-
Notifications
You must be signed in to change notification settings - Fork 1
/
validator.go
105 lines (82 loc) · 2.08 KB
/
validator.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
package repository
import (
"context"
"fmt"
"log/slog"
"sync"
"time"
"github.com/ttab/elephantine"
"github.com/ttab/newsdoc"
"github.com/ttab/revisor"
)
type Validator struct {
m sync.RWMutex
val *revisor.Validator
}
type SchemaLoader interface {
GetActiveSchemas(ctx context.Context) ([]*Schema, error)
OnSchemaUpdate(ctx context.Context, ch chan SchemaEvent)
}
func NewValidator(
ctx context.Context, logger *slog.Logger, loader SchemaLoader,
) (*Validator, error) {
var v Validator
err := v.loadSchemas(ctx, loader)
if err != nil {
return nil, fmt.Errorf("failed to load schemas: %w", err)
}
go v.reloadLoop(ctx, logger, loader)
return &v, nil
}
func (v *Validator) reloadLoop(
ctx context.Context, logger *slog.Logger, loader SchemaLoader,
) {
recheckInterval := 5 * time.Minute
sub := make(chan SchemaEvent, 1)
loader.OnSchemaUpdate(ctx, sub)
for {
select {
case <-ctx.Done():
return
case <-time.After(recheckInterval):
case <-sub:
}
err := v.loadSchemas(ctx, loader)
if err != nil {
// TODO: add handler that reacts to LogKeyCountMetric
logger.ErrorContext(ctx, "failed to refresh schemas",
elephantine.LogKeyError, err,
elephantine.LogKeyCountMetric, "elephant_schema_refresh_failure_count")
}
}
}
func (v *Validator) loadSchemas(ctx context.Context, loader SchemaLoader) error {
schemas, err := loader.GetActiveSchemas(ctx)
if err != nil {
return fmt.Errorf("failed to get active schemas: %w", err)
}
var constraints []revisor.ConstraintSet
for _, schema := range schemas {
constraints = append(constraints, schema.Specification)
}
val, err := revisor.NewValidator(constraints...)
if err != nil {
return fmt.Errorf(
"failed to create a validator from the constraints: %w", err)
}
v.m.Lock()
v.val = val
v.m.Unlock()
return nil
}
func (v *Validator) ValidateDocument(document *newsdoc.Document) []revisor.ValidationResult {
v.m.RLock()
val := v.val
v.m.RUnlock()
return val.ValidateDocument(document)
}
func (v *Validator) GetValidator() *revisor.Validator {
v.m.RLock()
defer v.m.RUnlock()
return v.val
}