summaryrefslogtreecommitdiffstats
path: root/modules/graceful/releasereopen/releasereopen.go
blob: de5b07c0a6c82db96ba3850bca9522742827af44 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package releasereopen

import (
	"errors"
	"sync"
)

type ReleaseReopener interface {
	ReleaseReopen() error
}

type Manager struct {
	mu      sync.Mutex
	counter int64

	releaseReopeners map[int64]ReleaseReopener
}

func (r *Manager) Register(rr ReleaseReopener) (cancel func()) {
	r.mu.Lock()
	defer r.mu.Unlock()

	r.counter++
	currentCounter := r.counter
	r.releaseReopeners[r.counter] = rr

	return func() {
		r.mu.Lock()
		defer r.mu.Unlock()

		delete(r.releaseReopeners, currentCounter)
	}
}

func (r *Manager) ReleaseReopen() error {
	r.mu.Lock()
	defer r.mu.Unlock()

	var errs []error
	for _, rr := range r.releaseReopeners {
		if err := rr.ReleaseReopen(); err != nil {
			errs = append(errs, err)
		}
	}
	return errors.Join(errs...)
}

func GetManager() *Manager {
	return manager
}

func NewManager() *Manager {
	return &Manager{
		releaseReopeners: make(map[int64]ReleaseReopener),
	}
}

var manager = NewManager()