-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmulti_lookup.go
307 lines (251 loc) ยท 9.3 KB
/
multi_lookup.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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
package tempura
import (
"context"
"fmt"
"log/slog"
"strings"
)
// =================================================================================
// Prefix types for MultiLookup keys
// =================================================================================
type Prefix interface {
Match(string) bool
Strip(string) string
}
type DotPrefix string
func (p DotPrefix) Match(s string) bool {
return strings.HasPrefix(s, fmt.Sprintf("%s.", p))
}
func (p DotPrefix) Strip(s string) string {
return strings.TrimPrefix(s, fmt.Sprintf("%s.", p))
}
type SlashPrefix string
func (p SlashPrefix) Match(s string) bool {
return strings.HasPrefix(s, fmt.Sprintf("%s/", p))
}
func (p SlashPrefix) Strip(s string) string {
return strings.TrimPrefix(s, fmt.Sprintf("%s/", p))
}
// =================================================================================
// Function types for MultiLookup values
// =================================================================================
type LookupAny func(val string) (any, bool)
type LookupAnyWithError func(val string) (any, bool, error)
type LookupAnyWithContext func(ctx context.Context, val string) (any, bool)
type LookupAnyWithContextError func(ctx context.Context, val string) (any, bool, error)
func Func[R any](fn func(val string) (R, bool)) LookupAny {
return func(val string) (any, bool) {
return fn(val)
}
}
func FuncWithError[R any](fn func(val string) (R, bool, error)) LookupAnyWithError {
return func(val string) (any, bool, error) {
return fn(val)
}
}
func FuncWithContext[R any](fn func(ctx context.Context, val string) (R, bool)) LookupAnyWithContext {
return func(ctx context.Context, val string) (any, bool) {
return fn(ctx, val)
}
}
func FuncWithContextError[R any](fn func(ctx context.Context, val string) (R, bool, error)) LookupAnyWithContextError {
return func(ctx context.Context, val string) (any, bool, error) {
return fn(ctx, val)
}
}
// LookupFunc ใฏใMultiLookup ใซ็ป้ฒใใๅใ
้ขๆฐใงใprefixใๅใ้คใใใญใผใๆๅญๅใจใใฆๅใๅใฃใฆไฝใใใใฎๅคใ่ฟใๅฟ
่ฆใใใใพใใ
// LookupFunc ใคใณใฟใใงใผในใๆบใใใซใฏใ tempura.FuncXXXX ็ต็ฑใง LookupAnyXXXX ๅใ็ๆใใใใจใๆจๅฅจใใใพใใ
// tempura.FuncXXXX ใง็ปๅ ดใใใธใงใใชใใฏๅๅถ็ดใฏanyใงใใใ template ใใใฑใผใธใๅฆ็ใงใใชใๅใๅฉ็จใใใจๅฎ่กๆใจใฉใผใซใชใๅฏ่ฝๆงใใใใพใใ
//
// LookupFunc represents individual functions registered in MultiLookup, which receive the key as a string, with the prefix removed, and return some value.
// It is recommended to generate a LookupAnyXXXX type through tempura.FuncXXXX to satisfy the LookupFunc interface.
// The generic type constraint in tempura.FuncXXXX is 'any', but using types that the template package cannot process might result in runtime errors.
type LookupFunc interface {
_isSupportedLookupFunc()
}
func (fn LookupAny) _isSupportedLookupFunc() {}
func (fn LookupAnyWithError) _isSupportedLookupFunc() {}
func (fn LookupAnyWithContext) _isSupportedLookupFunc() {}
func (fn LookupAnyWithContextError) _isSupportedLookupFunc() {}
// MultiLookup ใฏใ1ใคใพใใฏ่คๆฐใฎๆๅญๅใๅผๆฐใจใใฆๅใๅใใขใฏใทใงใณใซใใใฆใๅผๆฐใฎใใฌใใฃใใฏในใซๅฟใใฆ็ฐใชใๆข็ดข้ขๆฐใๅฎ่กใใใใใฎๆฉๆงใงใใ
// ใใ ใ context.Context ใๅใๅใ้ขๆฐใๅฉ็จใใๅ ดๅใฏใ BindContext(ctx) ใๅผใณๅบใใฆ MultiLookupContext ใ็ๆใใๅฟ
่ฆใใใใพใใ
//
// MultiLookup is a mechanism for executing different lookup functions depending on the prefix of the arguments in actions that take one or more strings as arguments.
// NOTE: If you want to use a function that takes context.Context, you need to call BindContext(ctx) to generate MultiLookupContext.
type MultiLookup map[Prefix]LookupFunc
func (m MultiLookup) Validate() error {
if len(m) == 0 {
return ErrNoFunctionRegistered
}
for k, v := range m {
switch v.(type) {
case LookupAny, LookupAnyWithError:
slog.Debug(
fmt.Sprintf("valid function of MultiLookup: %s", k),
slog.Any("name", fmt.Sprintf("%s", v)),
slog.Any("type", fmt.Sprintf("%T", v)),
)
case LookupAnyWithContext, LookupAnyWithContextError:
err := InvalidFunctionError{Type: "MultiLookup", Prefix: k, Func: v}
return fmt.Errorf("consider calling BindContext(ctx) to generate MultiLookupContext: %w", err)
default:
return InvalidFunctionError{Type: "MultiLookup", Prefix: k, Func: v}
}
}
return nil
}
func (m MultiLookup) FuncMapValue(args ...string) (any, error) {
matched := false
for _, arg := range args {
for prefix, fn := range m {
if !prefix.Match(arg) {
continue
}
matched = true
suffix := prefix.Strip(arg)
switch fn := fn.(type) {
case LookupAny:
slog.Debug(fmt.Sprintf("executing LookupAny for %s", arg))
val, ok := fn(suffix)
if ok {
return val, nil
}
case LookupAnyWithError:
slog.Debug(fmt.Sprintf("executing LookupAnyWithError for %s", arg))
val, ok, err := fn(suffix)
if err != nil {
return nil, err
}
if ok {
return val, nil
}
default:
err := InvalidFunctionError{Type: "MultiLookup", Prefix: prefix, Func: fn}
return nil, fmt.Errorf("consider calling Validate() to check the functions: %w", err)
}
}
}
if !matched {
return nil, ErrMatchFailed
}
return nil, ErrNotFound
}
func (m MultiLookup) BindContext(ctx context.Context) *MultiLookupContext {
return &MultiLookupContext{
MultiLookup: m,
Ctx: ctx,
}
}
// MultiLookupContext ใฏ context.Context ใๅใๅใ้ขๆฐใๅฉ็จใงใใ MultiLookup ใงใใ BindContext(ctx) ใๅผใณๅบใใฆ็ๆใใฆใใ ใใใ
//
// MultiLookupContext is a MultiLookup that can use functions that accept context.Context. Generate it by calling BindContext(ctx).
type MultiLookupContext struct {
MultiLookup MultiLookup
Ctx context.Context
}
func (m *MultiLookupContext) Validate() error {
if m.Ctx == nil {
return fmt.Errorf("consider calling BindContext(ctx): %w", ErrContextUntypedNil)
}
if len(m.MultiLookup) == 0 {
return ErrNoFunctionRegistered
}
for prefix, fn := range m.MultiLookup {
switch fn.(type) {
case LookupAny, LookupAnyWithError, LookupAnyWithContext, LookupAnyWithContextError:
slog.Debug(
fmt.Sprintf("valid function of MultiLookupContext: %s", prefix),
slog.Any("name", fmt.Sprintf("%s", fn)),
slog.Any("type", fmt.Sprintf("%T", fn)),
)
default:
return InvalidFunctionError{Type: "MultiLookupContext", Prefix: prefix, Func: fn}
}
}
return nil
}
func (m *MultiLookupContext) FuncMapValue(args ...string) (any, error) {
type result struct {
val any
ok bool
err error
}
results := make([]chan result, 0, len(args))
for range args {
results = append(results, make(chan result, 1))
}
ctx, cancel := context.WithCancel(m.Ctx)
defer cancel()
// ้ๅๆๅฆ็ใฎ็บ็ซใพใใฏๅๆๅฆ็ๅฎ่ก
// en: Fire asynchronous processing or execute synchronous processing
matched := false
for index, arg := range args {
promise := results[index]
for prefix, fn := range m.MultiLookup {
if !prefix.Match(arg) {
continue
}
matched = true
suffix := prefix.Strip(arg)
switch fn := fn.(type) {
case LookupAny:
slog.DebugContext(ctx, fmt.Sprintf("executing LookupAny for %s", arg))
val, ok := fn(suffix)
promise <- result{val: val, ok: ok, err: nil}
close(promise)
case LookupAnyWithError:
slog.DebugContext(ctx, fmt.Sprintf("executing LookupAnyWithError for %s", arg))
val, ok, err := fn(suffix)
promise <- result{val: val, ok: ok, err: err}
close(promise)
case LookupAnyWithContext:
slog.DebugContext(ctx, fmt.Sprintf("executing LookupAnyWithContext for %s", arg))
go func() {
val, ok := fn(ctx, suffix)
promise <- result{val: val, ok: ok, err: nil}
close(promise)
}()
case LookupAnyWithContextError:
slog.DebugContext(ctx, fmt.Sprintf("executing LookupAnyWithContextError for %s", arg))
go func() {
val, ok, err := fn(ctx, suffix)
promise <- result{val: val, ok: ok, err: err}
close(promise)
}()
default:
err := InvalidFunctionError{Type: "MultiLookupContext", Prefix: prefix, Func: fn}
return nil, fmt.Errorf("unexpected error! it might be a bug: %w", err)
}
}
}
if !matched {
return nil, ErrMatchFailed
}
for _, promise := range results {
select {
case res := <-promise:
if res.err != nil {
return nil, res.err
}
if res.ok {
return res.val, nil
}
}
}
return nil, ErrNotFound
}
// =================================================================================
// Defined errors that you can handle with errors.Is / errors.As
// =================================================================================
var ErrNoFunctionRegistered = fmt.Errorf("no function registered")
var ErrContextUntypedNil = fmt.Errorf("context.Context is untyped nil")
var ErrMatchFailed = fmt.Errorf("failed to match between args and prefixes")
var ErrNotFound = fmt.Errorf("not found: none of the lookup functions returned true as the second return value")
type InvalidFunctionError struct {
Type string
Prefix Prefix
Func any
}
func (e InvalidFunctionError) Error() string {
return fmt.Sprintf("invalid function of %s: %+v with type %T", e.Type, e.Prefix, e.Func)
}