/
actor.go
226 lines (205 loc) · 4.54 KB
/
actor.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
package hz
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"runtime"
"github.com/google/uuid"
"github.com/nats-io/nats.go"
)
type Actioner interface {
Action() string
}
type Action[T Objecter] interface {
Actioner
Do(context.Context, T) (T, error)
}
type ActorOption[T Objecter] func(*actorOption[T])
func WithActorActioner[T Objecter](
actioner Action[T],
) ActorOption[T] {
return func(ro *actorOption[T]) {
ro.actioners = append(ro.actioners, actioner)
}
}
func WithActorLabels[T Objecter](
labels map[string]string,
) ActorOption[T] {
return func(ro *actorOption[T]) {
ro.labels = labels
}
}
type actorOption[T Objecter] struct {
actioners []Action[T]
forObject T
labels map[string]string
}
func StartActor[T Objecter](
ctx context.Context,
nc *nats.Conn,
opts ...ActorOption[T],
) (*Actor[T], error) {
a := Actor[T]{
nc: nc,
}
if err := a.Start(ctx, opts...); err != nil {
return nil, fmt.Errorf("start: %w", err)
}
return &a, nil
}
type Actor[T Objecter] struct {
nc *nats.Conn
subscriptions []*nats.Subscription
}
func (a *Actor[T]) Start(ctx context.Context, opts ...ActorOption[T]) error {
opt := actorOption[T]{}
for _, o := range opts {
o(&opt)
}
// Setup common labels.
if err := a.addCommonLabels(&opt); err != nil {
return fmt.Errorf("add common labels: %w", err)
}
id := uuid.New()
for _, actioner := range opt.actioners {
if err := a.startActioner(ctx, actioner, opt, id); err != nil {
return fmt.Errorf("start actioner: %w", err)
}
}
return nil
}
func (a *Actor[T]) addCommonLabels(opt *actorOption[T]) error {
hostname, err := os.Hostname()
if err != nil {
return fmt.Errorf("getting hostname: %w", err)
}
if opt.labels == nil {
opt.labels = make(map[string]string)
}
opt.labels["hostname"] = hostname
opt.labels["os"] = runtime.GOOS
opt.labels["arch"] = runtime.GOARCH
return nil
}
func (a *Actor[T]) startActioner(
ctx context.Context,
actioner Action[T],
opt actorOption[T],
id uuid.UUID,
) error {
group := opt.forObject.ObjectGroup()
version := opt.forObject.ObjectVersion()
kind := opt.forObject.ObjectKind()
action := actioner.Action()
advertiseSubject := fmt.Sprintf(
SubjectActorAdvertise,
group,
version,
kind,
action,
)
runSubject := fmt.Sprintf(SubjectActorRun, group, version, kind, action, id)
adSub, err := a.nc.Subscribe(
advertiseSubject,
func(msg *nats.Msg) {
var adMsg AdvertiseMsg
if err := json.Unmarshal(msg.Data, &adMsg); err != nil {
slog.Error("unmarshal advertise message", "error", err)
_ = RespondError(
msg,
&Error{
Status: http.StatusBadRequest,
Message: fmt.Sprintf(
"unmarshal advertise message: %s",
err,
),
},
)
return
}
// If the label selector doesn't match, ignore the message and don't
// respond.
if !adMsg.LabelSelector.Matches(opt.labels) {
return
}
if err := RespondOK(msg, []byte(id.String())); err != nil {
slog.Error("responding to advertise message", "error", err)
}
},
)
if err != nil {
return fmt.Errorf("subscribe advertiser: %w", err)
}
a.subscriptions = append(a.subscriptions, adSub)
slog.Info("subscribed to advertise", "subject", advertiseSubject)
doSub, err := a.nc.Subscribe(
runSubject,
func(msg *nats.Msg) {
var t T
if err := json.Unmarshal(msg.Data, &t); err != nil {
slog.Error("unmarshalling msg data", "error", err)
_ = RespondError(
msg,
&Error{
Status: http.StatusBadRequest,
Message: fmt.Sprintf(
"unmarshalling msg data: %s",
err,
),
},
)
return
}
resp, err := actioner.Do(ctx, t)
if err != nil {
_ = RespondError(
msg,
&Error{
Status: http.StatusInternalServerError,
Message: fmt.Sprintf(
"running action: %s",
err,
),
},
)
return
}
b, err := json.Marshal(resp)
if err != nil {
slog.Error("marshalling response", "error", err)
_ = RespondError(
msg,
&Error{
Status: http.StatusInternalServerError,
Message: fmt.Sprintf(
"marshalling response: %s",
err,
),
},
)
return
}
_ = RespondOK(msg, b)
},
)
if err != nil {
return fmt.Errorf("subscribe action handler: %w", err)
}
a.subscriptions = append(a.subscriptions, doSub)
slog.Info("subscribed to run", "subject", runSubject)
return nil
}
func (a *Actor[T]) Stop() error {
var errs error
for _, sub := range a.subscriptions {
err := sub.Unsubscribe()
if err != nil {
errs = errors.Join(errs, err)
}
}
return errs
}