-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeychain.go
More file actions
357 lines (324 loc) · 8.12 KB
/
Copy pathkeychain.go
File metadata and controls
357 lines (324 loc) · 8.12 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
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
package keycheck
import "fmt"
type (
ErrInvalidBitwiseID BitwiseID
ErrNoValidatorExist struct{}
ErrNilReceiver struct{}
)
func (err ErrInvalidBitwiseID) Error() string {
return fmt.Sprintf("keycheck: invalid bitwise operator ID %d", uint8(err))
}
func (err ErrNoValidatorExist) Error() string {
return "keycheck: no validators registered"
}
func (err ErrNilReceiver) Error() string {
return "keycheck: nil receiver"
}
type BitwiseID uint8 // Bitwise Operator ID
const (
NOT BitwiseID = iota // Bitwise NOT
AND // Bitwise AND
OR // Bitwise OR
XOR // Bitwise XOR (exclusive OR)
)
type (
StatusGetter interface {
Clone() Status
GetDetails() string
GetID() string
Marshal(f func(v any) ([]byte, error)) ([]byte, error)
}
StatusSetter interface {
SetDetails(details string)
SetID(id string)
Unmarshal(f func(data []byte, v any) error, b []byte) error
Reset()
}
StatusGetSetter interface {
StatusGetter
StatusSetter
}
)
type Status struct {
ID string `json:"id,omitempty"`
Details string `json:"details,omitempty"`
}
func (s Status) Clone() Status {
return Status{
ID: s.ID,
Details: s.Details,
}
}
func (s *Status) GetID() string {
return s.ID
}
func (s *Status) SetID(id string) {
s.ID = id
}
func (s *Status) GetDetails() string {
return s.Details
}
func (s *Status) SetDetails(details string) {
s.Details = details
}
func (s *Status) Marshal(f func(v any) ([]byte, error)) ([]byte, error) {
return f(s)
}
func (s *Status) Unmarshal(f func(data []byte, v any) error, b []byte) error {
return f(b, s)
}
func (s *Status) Reset() {
if s == nil {
return
}
s.Details = ""
s.ID = ""
}
var (
SUCCESS StatusGetter = &Status{ID: "SUCCESS"}
FAIL StatusGetter = &Status{ID: "FAIL"}
INVALID StatusGetter = &Status{ID: "INVALID"}
CUSTOM StatusGetter = &Status{ID: "CUSTOM"}
RETRY StatusGetter = &Status{ID: "RETRY"}
BAN StatusGetter = &Status{ID: "BAN"}
NONE StatusGetter = &Status{ID: "NONE"}
)
var emptyStatus = &Status{}
// IsValid checks if the BitwiseID is a defined operator.
func (bid BitwiseID) IsValid() bool {
return bid <= XOR
}
type KeyChain[T any] interface {
DelValidator(label string) error
GetValidator(label string) (Status, func(a T) (bool, error), error)
Reset()
SetCondition(condition BitwiseID) error
SetValidator(status Status, fn func(a T) (bool, error)) error
Validate(data T, defaultStatus StatusGetter) (StatusGetter, bool, []error)
}
type keyChain[T any] struct {
validators validatorsMap[T]
condition BitwiseID
}
// NewKeyChain creates and returns a new KeyChain instance with a specified
// bitwise condition for validation logic. It returns an error if the
// condition is invalid.
func NewKeyChain[T any](condition BitwiseID) (KeyChain[T], error) {
if !condition.IsValid() {
return nil, ErrInvalidBitwiseID(condition)
}
return &keyChain[T]{
validators: validatorsMap[T]{index: map[string]int{}},
condition: condition,
}, nil
}
// DelValidator removes a validator function, identified by its label,
// from the keychain.
func (kc *keyChain[T]) DelValidator(label string) error {
if kc == nil {
return ErrNilReceiver{}
}
if kc.validators.index == nil {
return ErrNoValidatorExist{}
}
kc.validators.Del(label)
return nil
}
// GetValidator retrieves a validator function by its label. It returns
// the status, the function and a nil error if found, otherwise zero
// Status, nil function, and nil error (for compatibility with previous behaviour).
func (kc *keyChain[T]) GetValidator(id string) (Status, func(a T) (bool, error), error) {
if kc == nil {
return Status{}, nil, ErrNilReceiver{}
}
if kc.validators.index == nil {
return Status{}, nil, ErrNoValidatorExist{}
}
status, fn, _ := kc.validators.Get(id)
return status, fn, nil
}
// SetValidator adds or updates a validator function for a given status.
// It also maintains the order in which validators were added.
func (kc *keyChain[T]) SetValidator(status Status, fn func(a T) (bool, error)) error {
if kc == nil {
return ErrNilReceiver{}
}
if kc.validators.index == nil {
kc.validators = validatorsMap[T]{index: map[string]int{}}
}
kc.validators.Set(status, fn)
return nil
}
// SetCondition updates the bitwise condition (e.g., AND, OR) that
// governs the overall validation logic.
func (kc *keyChain[T]) SetCondition(condition BitwiseID) error {
if kc == nil {
return ErrNilReceiver{}
}
if !condition.IsValid() {
return ErrInvalidBitwiseID(condition)
}
kc.condition = condition
return nil
}
// Validate processes the given data against all registered validators according
// to the set bitwise condition (NOT, AND, OR, XOR). It returns the resulting
// Status, a boolean indicating overall success, and a slice of any errors
// encountered.
func (kc *keyChain[T]) Validate(data T, defaultStatus StatusGetter) (StatusGetter, bool, []error) {
if kc == nil {
return nil, false, []error{ErrNilReceiver{}}
}
if kc.validators.index == nil {
return defaultStatus, false, nil
}
var (
ok bool
err error
errs []error
)
switch kc.condition {
case NOT:
var lbl StatusGetter
for i := range kc.validators.entries {
entry := &kc.validators.entries[i]
fn := entry.validator
if fn == nil {
continue
}
if ok, _ = fn(data); !ok {
lbl = &entry.status
continue
}
return defaultStatus, false, errs
}
if lbl == nil {
lbl = emptyStatus
}
return lbl, true, nil
case AND:
lbl := StatusGetter(emptyStatus)
for i := range kc.validators.entries {
entry := &kc.validators.entries[i]
fn := entry.validator
if fn == nil {
continue
}
ok, err = fn(data)
if !ok {
if err != nil {
errs = append(errs, err)
}
return defaultStatus, false, errs
}
lbl = &entry.status
}
return lbl, ok, nil
case OR:
return kc.validateOR(data, defaultStatus)
case XOR:
return kc.validateXOR(data, defaultStatus)
}
return defaultStatus, false, nil
}
func (kc *keyChain[T]) validateOR(data T, defaultStatus StatusGetter) (StatusGetter, bool, []error) {
entries := kc.validators.entries
var (
bufErrs [32]error
heapErrs []error
errCount int
usedHeap bool
)
for i := range entries {
entry := &entries[i]
fn := entry.validator
if fn == nil {
continue
}
ok, err := fn(data)
if ok {
return &entry.status, true, nil
}
if err != nil {
if !usedHeap && errCount < len(bufErrs) {
bufErrs[errCount] = err
} else {
if !usedHeap {
heapErrs = make([]error, errCount, errCount+len(entries)-i)
copy(heapErrs, bufErrs[:errCount])
usedHeap = true
}
heapErrs = append(heapErrs, err)
}
errCount++
}
}
if errCount == 0 {
return defaultStatus, false, nil
}
if usedHeap {
return defaultStatus, false, heapErrs
}
errs := make([]error, errCount)
copy(errs, bufErrs[:errCount])
return defaultStatus, false, errs
}
func (kc *keyChain[T]) validateXOR(data T, defaultStatus StatusGetter) (StatusGetter, bool, []error) {
var trueCount uint
lbl := StatusGetter(emptyStatus)
entries := kc.validators.entries
var (
bufErrs [32]error
heapErrs []error
errCount int
usedHeap bool
)
for i := range entries {
entry := &entries[i]
fn := entry.validator
if fn == nil {
continue
}
ok, err := fn(data)
if ok {
trueCount++
if trueCount > 1 {
return defaultStatus, false, nil
}
lbl = &entry.status
} else if err != nil {
if !usedHeap && errCount < len(bufErrs) {
bufErrs[errCount] = err
} else {
if !usedHeap {
heapErrs = make([]error, errCount, errCount+len(entries)-i)
copy(heapErrs, bufErrs[:errCount])
usedHeap = true
}
heapErrs = append(heapErrs, err)
}
errCount++
}
}
if trueCount == 1 {
return lbl, true, nil
}
if errCount == 0 {
return defaultStatus, false, nil
}
if usedHeap {
return defaultStatus, false, heapErrs
}
errs := make([]error, errCount)
copy(errs, bufErrs[:errCount])
return defaultStatus, false, errs
}
// Reset clears all validators, the validation order, and the bitwise
// condition, restoring the keychain to its initial empty state.
func (kc *keyChain[T]) Reset() {
if kc == nil {
return
}
kc.condition = 0
kc.validators = validatorsMap[T]{}
}