-
Notifications
You must be signed in to change notification settings - Fork 6
/
object_list_dump.go
139 lines (124 loc) · 2.39 KB
/
object_list_dump.go
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package discover
import (
"context"
"fmt"
"os"
"sync"
"time"
)
type (
// objectList janitors the list.objects file used by the
// shell autocompletion.
objectList struct {
sync.RWMutex
// File is where the object list is dumped
File string
// Delay limits the rate of the dump file rewrites
Delay time.Duration
// m is a the reference data of the
// <var>/list.objects file content.
// On ObjectStatusUpdated, add the object path in the map.
// On ObjectStatusDeleted, del the object path from the map.
// If the top level map changes, dump to file.
m map[string]any
// q is used for dump request coalescing and
// rate limiting
q chan bool
// report write loop errors to the users (for logging, ...)
ErrC chan error
// report information to the users (for logging, ...)
InfoC chan string
ctx context.Context
}
)
func newObjectList(ctx context.Context, file string) *objectList {
t := objectList{
File: file,
Delay: time.Second,
m: make(map[string]any),
q: make(chan bool, 2),
ErrC: make(chan error, 2),
InfoC: make(chan string, 2),
ctx: ctx,
}
return &t
}
func (t *objectList) Loop() {
for {
select {
case <-t.ctx.Done():
return
case <-t.q:
if err := t.write(); err != nil {
select {
case <-t.ctx.Done():
return
case t.ErrC <- err:
default:
}
}
time.Sleep(time.Second)
}
}
}
func (t *objectList) requestWrite() bool {
select {
case <-t.ctx.Done():
return false
case t.q <- true:
return true
default:
return false
}
}
func (t *objectList) Add(l ...string) {
t.Lock()
defer t.Unlock()
var changed bool
for _, s := range l {
if _, ok := t.m[s]; ok {
continue
}
t.m[s] = nil
changed = true
}
if changed {
t.requestWrite()
}
}
func (t *objectList) Del(l ...string) {
t.Lock()
defer t.Unlock()
var changed bool
for _, s := range l {
if _, ok := t.m[s]; !ok {
continue
}
delete(t.m, s)
changed = true
}
if changed {
t.requestWrite()
}
}
func (t *objectList) write() error {
t.RLock()
defer t.RUnlock()
f, err := os.OpenFile(t.File, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, os.ModePerm)
if err != nil {
return err
}
defer f.Close()
for p := range t.m {
if _, err := fmt.Fprintf(f, "%s\n", p); err != nil {
return err
}
}
select {
case <-t.ctx.Done():
return t.ctx.Err()
case t.InfoC <- fmt.Sprintf("%s dumped", t.File):
default:
}
return nil
}