-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcloser.go
More file actions
114 lines (102 loc) · 2.16 KB
/
closer.go
File metadata and controls
114 lines (102 loc) · 2.16 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package otk
import (
"context"
"os"
"os/signal"
"sync"
"time"
"go.oneofone.dev/genh"
"go.oneofone.dev/oerrs"
)
func NewCloser(onClose func(name string, took time.Duration)) *Closer {
ctx, cfn := context.WithCancel(context.Background())
if onClose == nil {
onClose = func(name string, took time.Duration) {}
}
return &Closer{
ctx: ctx,
cfn: cfn,
onClose: onClose,
}
}
type closerFn struct {
fn func() error
name string
}
type Closer struct {
ctx context.Context
cfn func()
onClose func(name string, took time.Duration)
fns []closerFn
fnsSync []closerFn
mux sync.Mutex
}
func (c *Closer) Add(name string, fn func() error, sync bool) error {
c.mux.Lock()
defer c.mux.Unlock()
if c.cfn == nil {
return os.ErrClosed
}
if sync {
c.fnsSync = append(c.fnsSync, closerFn{name: name, fn: fn})
} else {
c.fns = append(c.fns, closerFn{name: name, fn: fn})
}
return nil
}
func (c *Closer) Delete(name string) error {
c.mux.Lock()
defer c.mux.Unlock()
if c.cfn == nil {
return os.ErrClosed
}
c.fns = genh.Filter(c.fns, func(cfn closerFn) (keep bool) {
return cfn.name != name
}, true)
c.fnsSync = genh.Filter(c.fns, func(cfn closerFn) (keep bool) {
return cfn.name != name
}, true)
return nil
}
func (c *Closer) Close() error {
c.mux.Lock()
defer c.mux.Unlock()
if c.cfn == nil {
return os.ErrClosed
}
c.cfn()
c.cfn = nil
var wg sync.WaitGroup
errs := oerrs.NewSafeList(false)
for _, cfn := range c.fnsSync {
start := time.Now()
if err := cfn.fn(); err != nil {
errs.Errorf("error closing %s: %v", cfn.name, err)
}
c.onClose(cfn.name, time.Since(start))
}
for _, cfn := range c.fns {
wg.Add(1)
go func(cfn closerFn) {
defer wg.Done()
start := time.Now()
if err := cfn.fn(); err != nil {
errs.Errorf("error closing %s: %v", cfn.name, err)
}
c.onClose(cfn.name, time.Since(start))
}(cfn)
}
wg.Wait()
return errs.Err()
}
func (c *Closer) WaitSignal(signals ...os.Signal) error {
ctx, _ := signal.NotifyContext(c.ctx, signals...)
return c.Wait(ctx)
}
func (c *Closer) Wait(ctx context.Context) error {
select {
case <-ctx.Done():
case <-c.ctx.Done():
}
return c.Close()
}