-
Notifications
You must be signed in to change notification settings - Fork 21
/
substation.go
85 lines (68 loc) · 1.94 KB
/
substation.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
package substation
import (
"context"
_ "embed"
"encoding/json"
"fmt"
"github.com/brexhq/substation/v2/config"
"github.com/brexhq/substation/v2/message"
"github.com/brexhq/substation/v2/transform"
)
//go:embed substation.libsonnet
var Library string
var errNoTransforms = fmt.Errorf("no transforms configured")
// Config is the core configuration for the application. Custom applications
// should embed this and add additional configuration options.
type Config struct {
// Transforms contains a list of data transformatons that are executed.
Transforms []config.Config `json:"transforms"`
}
// Substation provides access to data transformation functions.
type Substation struct {
cfg Config
factory transform.Factory
tforms []transform.Transformer
}
// New returns a new Substation instance.
func New(ctx context.Context, cfg Config, opts ...func(*Substation)) (*Substation, error) {
if cfg.Transforms == nil {
return nil, errNoTransforms
}
sub := &Substation{
cfg: cfg,
factory: transform.New,
}
for _, o := range opts {
o(sub)
}
// Create transforms from the configuration.
for _, c := range cfg.Transforms {
t, err := sub.factory(ctx, c)
if err != nil {
return nil, err
}
sub.tforms = append(sub.tforms, t)
}
return sub, nil
}
// WithTransformFactory implements a custom transform factory.
func WithTransformFactory(fac transform.Factory) func(*Substation) {
return func(s *Substation) {
s.factory = fac
}
}
// Transform runs the configured data transformation functions on the
// provided messages.
//
// This is safe to use concurrently.
func (s *Substation) Transform(ctx context.Context, msg ...*message.Message) ([]*message.Message, error) {
return transform.Apply(ctx, s.tforms, msg...)
}
// String returns a JSON representation of the configuration.
func (s *Substation) String() string {
b, err := json.Marshal(s.cfg)
if err != nil {
return fmt.Sprintf("substation: %v", err)
}
return string(b)
}