Debian Codegraph @

docstore/driver/util.go

raw
1 // Copyright 2019 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package driver
16
17 import (
18 "reflect"
19 "sort"
20 "sync"
21
22 "github.com/google/uuid"
23 )
24
25 // UniqueString generates a string that is unique with high probability.
26 // Driver implementations can use it to generate keys for Create actions.
27 func UniqueString() string { return uuid.New().String() }
28
29 // SplitActions divides the actions slice into sub-slices much like strings.Split.
30 // The split function should report whether two consecutive actions should be split,
31 // that is, should be in different sub-slices. The first argument to split is the
32 // last action of the sub-slice currently under construction; the second argument is
33 // the action being considered for addition to that sub-slice.
34 // SplitActions doesn't change the order of the input slice.
35 func SplitActions(actions []*Action, split func(a, b *Action) bool) [][]*Action {
36 var (
37 groups [][]*Action // the actions, split; the return value
38 cur []*Action // the group currently being constructed
39 )
40 collect := func() { // called when the current group is known to be finished
41 if len(cur) > 0 {
42 groups = append(groups, cur)
43 cur = nil
44 }
45 }
46 for _, a := range actions {
47 if len(cur) > 0 && split(cur[len(cur)-1], a) {
48 collect()
49 }
50 cur = append(cur, a)
51 }
52 collect()
53 return groups
54 }
55
56 // GroupActions separates actions into four sets: writes, gets that must happen before the writes,
57 // gets that must happen after the writes, and gets that can happen concurrently with the writes.
58 func GroupActions(actions []*Action) (beforeGets, getList, writeList, writesTxList, afterGets []*Action) {
59 // maps from key to action
60 bgets := map[any]*Action{}
61 agets := map[any]*Action{}
62 cgets := map[any]*Action{}
63 writes := map[any]*Action{}
64 writesTx := map[any]*Action{}
65 var nilkeys []*Action
66 for _, a := range actions {
67 if a.Key == nil {
68 // Probably a Create.
69 nilkeys = append(nilkeys, a)
70 } else if a.Kind == Get {
71 // If there was a prior write with this key, make sure this get
72 // happens after the writes.
73 if _, ok := writes[a.Key]; ok {
74 agets[a.Key] = a
75 } else if _, ok := writesTx[a.Key]; ok {
76 agets[a.Key] = a
77 } else {
78 cgets[a.Key] = a
79 }
80 } else {
81 // This is a write. A prior get on the same key was put into cgets; move
82 // it to bgets because it has to happen before writes.
83 if g, ok := cgets[a.Key]; ok {
84 delete(cgets, a.Key)
85 bgets[a.Key] = g
86 }
87 if a.InAtomicWrite {
88 writesTx[a.Key] = a
89 } else {
90 writes[a.Key] = a
91 }
92 }
93 }
94
95 vals := func(m map[any]*Action) []*Action {
96 var as []*Action
97 for _, v := range m {
98 as = append(as, v)
99 }
100 // Sort so the order is always the same for replay.
101 sort.Slice(as, func(i, j int) bool { return as[i].Index < as[j].Index })
102 return as
103 }
104
105 return vals(bgets), vals(cgets), append(vals(writes), nilkeys...), vals(writesTx), vals(agets)
106 }
107
108 // AsFunc creates and returns an "as function" that behaves as follows:
109 // If its argument is a pointer to the same type as val, the argument is set to val
110 // and the function returns true. Otherwise, the function returns false.
111 func AsFunc(val any) func(any) bool {
112 rval := reflect.ValueOf(val)
113 wantType := reflect.PtrTo(rval.Type())
114 return func(i any) bool {
115 if i == nil {
116 return false
117 }
118 ri := reflect.ValueOf(i)
119 if ri.Type() != wantType {
120 return false
121 }
122 ri.Elem().Set(rval)
123 return true
124 }
125 }
126
127 // GroupByFieldPath collect the Get actions into groups with the same set of
128 // field paths.
129 func GroupByFieldPath(gets []*Action) [][]*Action {
130 // This is quadratic in the worst case, but it's unlikely that there would be
131 // many Gets with different field paths.
132 var groups [][]*Action
133 seen := map[*Action]bool{}
134 for len(seen) < len(gets) {
135 var g []*Action
136 for _, a := range gets {
137 if !seen[a] {
138 if len(g) == 0 || fpsEqual(g[0].FieldPaths, a.FieldPaths) {
139 g = append(g, a)
140 seen[a] = true
141 }
142 }
143 }
144 groups = append(groups, g)
145 }
146 return groups
147 }
148
149 // Report whether two lists of field paths are equal.
150 func fpsEqual(fps1, fps2 [][]string) bool {
151 // TODO?: We really care about sets of field paths, but that's too tedious to determine.
152 if len(fps1) != len(fps2) {
153 return false
154 }
155 for i, fp1 := range fps1 {
156 if !FieldPathsEqual(fp1, fps2[i]) {
157 return false
158 }
159 }
160 return true
161 }
162
163 // FieldPathsEqual reports whether two field paths are equal.
164 func FieldPathsEqual(fp1, fp2 []string) bool {
165 if len(fp1) != len(fp2) {
166 return false
167 }
168 for i, s1 := range fp1 {
169 if s1 != fp2[i] {
170 return false
171 }
172 }
173 return true
174 }
175
176 // FieldPathEqualsField reports whether a field path equals a field.
177 // This is a convenience for FieldPathsEqual(fp, []string{s}).
178 func FieldPathEqualsField(fp []string, s string) bool {
179 return len(fp) == 1 && fp[0] == s
180 }
181
182 // Throttle is used to limit the number of outstanding activities, like RPCs.
183 // It acts like a combination of a semaphore and a WaitGroup.
184 type Throttle struct {
185 c chan struct{} // token semaphore
186 wg sync.WaitGroup
187 }
188
189 // NewThrottle returns a Throttle that will allow max calls to Acquire that
190 // are not matched with Release calls before blocking.
191 // If max is <= 0, there is no throttling: Acquire always returns immediately.
192 func NewThrottle(max int) *Throttle {
193 t := &Throttle{}
194 if max > 0 {
195 t.c = make(chan struct{}, max)
196 }
197 return t
198 }
199
200 // Acquire blocks until a token is available, then acquires it and returns.
201 // Acquire is deliberately not sensitive to context.Context, because it assumes
202 // that whatever acquires a token will be context-sensitive, and thus will release
203 // the token when the context is done.
204 func (t *Throttle) Acquire() {
205 t.wg.Add(1)
206 if t.c != nil {
207 t.c <- struct{}{}
208 }
209 }
210
211 // Release releases a token obtained by Acquire.
212 func (t *Throttle) Release() {
213 if t.c != nil {
214 <-t.c
215 }
216 t.wg.Done()
217 }
218
219 // Wait blocks goroutine until the number of calls to Release matches the number of
220 // calls to Acquire.
221 func (t *Throttle) Wait() {
222 t.wg.Wait()
223 }