-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobserver_test.go
More file actions
393 lines (340 loc) · 11.4 KB
/
Copy pathobserver_test.go
File metadata and controls
393 lines (340 loc) · 11.4 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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package chat_test
import (
"context"
"errors"
"net/http"
"slices"
"sync"
"testing"
"time"
"github.com/coder/chat"
)
// recordingObserver captures Event calls and dispatch span open/close for
// assertions. It is the Observer test double called for in ADR 0010.
type recordingObserver struct {
mu sync.Mutex
events []recordedEvent
opened int
outcomes []chat.DispatchOutcome
attrs [][]chat.Attr
}
type recordedEvent struct {
name chat.ObservationName
attrs []chat.Attr
}
func (o *recordingObserver) Event(_ context.Context, name chat.ObservationName, attrs ...chat.Attr) {
o.mu.Lock()
defer o.mu.Unlock()
o.events = append(o.events, recordedEvent{name: name, attrs: append([]chat.Attr(nil), attrs...)})
}
func (o *recordingObserver) Dispatch(ctx context.Context, attrs ...chat.Attr) (context.Context, chat.DispatchSpan) {
o.mu.Lock()
o.opened++
o.mu.Unlock()
return ctx, &recordingSpan{observer: o, openAttrs: append([]chat.Attr(nil), attrs...)}
}
func (o *recordingObserver) eventNames() []chat.ObservationName {
o.mu.Lock()
defer o.mu.Unlock()
names := make([]chat.ObservationName, 0, len(o.events))
for _, e := range o.events {
names = append(names, e.name)
}
return names
}
func (o *recordingObserver) hasEvent(name chat.ObservationName) bool {
return slices.Contains(o.eventNames(), name)
}
func (o *recordingObserver) terminalOutcomes() []chat.DispatchOutcome {
o.mu.Lock()
defer o.mu.Unlock()
return append([]chat.DispatchOutcome(nil), o.outcomes...)
}
type recordingSpan struct {
observer *recordingObserver
openAttrs []chat.Attr
}
func (s *recordingSpan) End(outcome chat.DispatchOutcome, attrs ...chat.Attr) {
s.observer.mu.Lock()
defer s.observer.mu.Unlock()
s.observer.outcomes = append(s.observer.outcomes, outcome)
all := append(append([]chat.Attr(nil), s.openAttrs...), attrs...)
s.observer.attrs = append(s.observer.attrs, all)
}
func newObservedRuntime(t *testing.T, state chat.State, adapter chat.Adapter, observer chat.Observer) *chat.Chat {
t.Helper()
bot, err := chat.New(context.Background(),
chat.WithState(state),
chat.WithAdapter(adapter),
chat.WithObserver(observer),
chat.WithRuntimeOptions(chat.RuntimeOptions{
DedupeTTL: time.Hour,
ThreadLockTTL: time.Hour,
Concurrency: chat.ConcurrencyDrop,
}),
)
if err != nil {
t.Fatalf("new runtime: %v", err)
}
return bot
}
func TestObserverHandledDispatchOpensAndClosesOneSpan(t *testing.T) {
t.Parallel()
obs := &recordingObserver{}
bot := newObservedRuntime(t, newFakeState(), newFakeAdapter("fake"), obs)
bot.OnNewMention(func(ctx context.Context, ev *chat.MessageEvent) error {
return nil
})
if status := postEvent(t, bot, "fake", mentionEvent("h1", "fake:v1:thread-1")); status != http.StatusOK {
t.Fatalf("status = %d", status)
}
if obs.opened != 1 {
t.Fatalf("spans opened = %d, want 1", obs.opened)
}
if outcomes := obs.terminalOutcomes(); len(outcomes) != 1 || outcomes[0] != chat.OutcomeHandled {
t.Fatalf("outcomes = %#v, want [handled]", outcomes)
}
}
func TestObserverDuplicateLockConflictAndIgnoredReasons(t *testing.T) {
t.Parallel()
tests := []struct {
name string
setup func(t *testing.T, state *fakeState, bot *chat.Chat)
event chat.Event
wantEvent chat.ObservationName
wantOutcome chat.DispatchOutcome
}{
{
name: "non-message ignored",
event: chat.Event{ID: "ign-nonmsg", Adapter: "fake", Tenant: "tenant", ThreadID: "fake:v1:thread-1"},
wantEvent: chat.ObsIgnoredEvent,
wantOutcome: chat.OutcomeIgnored,
},
{
name: "unrouted ignored",
event: func() chat.Event {
e := mentionEvent("ign-unrouted", "fake:v1:thread-1")
e.Message.Mentioned = false
return e
}(),
wantEvent: chat.ObsIgnoredEvent,
wantOutcome: chat.OutcomeIgnored,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
obs := &recordingObserver{}
bot := newObservedRuntime(t, newFakeState(), newFakeAdapter("fake"), obs)
bot.OnSubscribedMessage(func(context.Context, *chat.MessageEvent) error { return nil })
if status := postEvent(t, bot, "fake", tc.event); status != http.StatusOK {
t.Fatalf("status = %d", status)
}
if !obs.hasEvent(tc.wantEvent) {
t.Fatalf("missing %q in %#v", tc.wantEvent, obs.eventNames())
}
if outcomes := obs.terminalOutcomes(); len(outcomes) != 1 || outcomes[0] != tc.wantOutcome {
t.Fatalf("outcomes = %#v, want [%s]", outcomes, tc.wantOutcome)
}
})
}
}
func TestObserverSelfMessageIgnoredReason(t *testing.T) {
t.Parallel()
obs := &recordingObserver{}
adapter := newFakeAdapter("fake")
bot := newObservedRuntime(t, newFakeState(), adapter, obs)
bot.OnNewMention(func(context.Context, *chat.MessageEvent) error { return nil })
self := mentionEvent("self", "fake:v1:thread-1")
self.Message.Author = adapter.BotActor()
if status := postEvent(t, bot, "fake", self); status != http.StatusOK {
t.Fatalf("status = %d", status)
}
assertReason(t, obs, "self-message")
if outcomes := obs.terminalOutcomes(); len(outcomes) != 1 || outcomes[0] != chat.OutcomeIgnored {
t.Fatalf("outcomes = %#v", outcomes)
}
}
func TestObserverDuplicate(t *testing.T) {
t.Parallel()
obs := &recordingObserver{}
bot := newObservedRuntime(t, newFakeState(), newFakeAdapter("fake"), obs)
bot.OnNewMention(func(context.Context, *chat.MessageEvent) error { return nil })
event := mentionEvent("dup", "fake:v1:thread-1")
postEvent(t, bot, "fake", event)
postEvent(t, bot, "fake", event)
if !obs.hasEvent(chat.ObsDedupeHit) {
t.Fatalf("missing dedupe hit in %#v", obs.eventNames())
}
outcomes := obs.terminalOutcomes()
if len(outcomes) != 2 || outcomes[1] != chat.OutcomeDuplicate {
t.Fatalf("outcomes = %#v, want second duplicate", outcomes)
}
}
func TestObserverLockConflict(t *testing.T) {
t.Parallel()
obs := &recordingObserver{}
state := newFakeState()
bot := newObservedRuntime(t, state, newFakeAdapter("fake"), obs)
bot.OnNewMention(func(context.Context, *chat.MessageEvent) error { return nil })
lease, _, err := state.AcquireLock(context.Background(), "fake:v1:thread-1", time.Hour)
if err != nil {
t.Fatalf("acquire: %v", err)
}
if status := postEvent(t, bot, "fake", mentionEvent("conflict", "fake:v1:thread-1")); status != http.StatusOK {
t.Fatalf("status = %d", status)
}
if _, err := state.ReleaseLock(context.Background(), lease); err != nil {
t.Fatalf("release: %v", err)
}
if !obs.hasEvent(chat.ObsLockConflict) {
t.Fatalf("missing lock conflict in %#v", obs.eventNames())
}
if outcomes := obs.terminalOutcomes(); len(outcomes) != 1 || outcomes[0] != chat.OutcomeDroppedLockConflict {
t.Fatalf("outcomes = %#v, want [dropped-lock-conflict]", outcomes)
}
}
func TestObserverHandlerError(t *testing.T) {
t.Parallel()
obs := &recordingObserver{}
bot := newObservedRuntime(t, newFakeState(), newFakeAdapter("fake"), obs)
bot.OnNewMention(func(context.Context, *chat.MessageEvent) error {
return errors.New("handler error")
})
if status := postEvent(t, bot, "fake", mentionEvent("err", "fake:v1:thread-1")); status != http.StatusOK {
t.Fatalf("status = %d", status)
}
if !obs.hasEvent(chat.ObsHandlerError) {
t.Fatalf("missing handler error in %#v", obs.eventNames())
}
if outcomes := obs.terminalOutcomes(); len(outcomes) != 1 || outcomes[0] != chat.OutcomeError {
t.Fatalf("outcomes = %#v, want [error]", outcomes)
}
}
func TestObserverCommandAndInteractionRoutes(t *testing.T) {
t.Parallel()
obs := &recordingObserver{}
bot := newObservedRuntime(t, newFakeState(), newFakeAdapter("fake"), obs)
bot.OnCommand(func(context.Context, *chat.CommandEvent) error { return nil })
bot.OnInteraction(func(context.Context, *chat.InteractionEvent) error { return nil })
postEvent(t, bot, "fake", commandEvent("c1", "fake:v1:thread-1"))
postEvent(t, bot, "fake", interactionEvent("i1", "fake:v1:thread-2"))
if outcomes := obs.terminalOutcomes(); len(outcomes) != 2 ||
outcomes[0] != chat.OutcomeHandled || outcomes[1] != chat.OutcomeHandled {
t.Fatalf("outcomes = %#v, want two handled", outcomes)
}
assertRoutePresent(t, obs, "command")
assertRoutePresent(t, obs, "interaction")
}
func TestDefaultNoOpObserverDoesNotChangeBehavior(t *testing.T) {
t.Parallel()
// No WithObserver: the no-op default must leave routing identical.
bot, err := chat.New(context.Background(),
chat.WithState(newFakeState()),
chat.WithAdapter(newFakeAdapter("fake")),
)
if err != nil {
t.Fatalf("new runtime: %v", err)
}
var calls int
bot.OnNewMention(func(context.Context, *chat.MessageEvent) error {
calls++
return nil
})
if status := postEvent(t, bot, "fake", mentionEvent("noop", "fake:v1:thread-1")); status != http.StatusOK {
t.Fatalf("status = %d", status)
}
if calls != 1 {
t.Fatalf("calls = %d", calls)
}
}
// panicObserver panics on every call; it must never fail an Accepted Event or
// alter acknowledgement.
type panicObserver struct{}
func (panicObserver) Event(context.Context, chat.ObservationName, ...chat.Attr) {
panic("observer event panic")
}
func (panicObserver) Dispatch(context.Context, ...chat.Attr) (context.Context, chat.DispatchSpan) {
panic("observer dispatch panic")
}
func TestPanickingObserverDoesNotAffectAck(t *testing.T) {
t.Parallel()
bot := newObservedRuntime(t, newFakeState(), newFakeAdapter("fake"), panicObserver{})
var calls int
bot.OnNewMention(func(context.Context, *chat.MessageEvent) error {
calls++
return nil
})
if status := postEvent(t, bot, "fake", mentionEvent("panic", "fake:v1:thread-1")); status != http.StatusOK {
t.Fatalf("status = %d, panicking observer must not change ack", status)
}
if calls != 1 {
t.Fatalf("calls = %d, want 1", calls)
}
}
func TestObserverAttributeHygiene(t *testing.T) {
t.Parallel()
obs := &recordingObserver{}
bot := newObservedRuntime(t, newFakeState(), newFakeAdapter("fake"), obs)
bot.OnNewMention(func(context.Context, *chat.MessageEvent) error { return nil })
threadID := "fake:v1:thread-1"
event := mentionEvent("hygiene", chat.ThreadID(threadID))
if status := postEvent(t, bot, "fake", event); status != http.StatusOK {
t.Fatalf("status = %d", status)
}
allowedKeys := map[string]bool{
chat.AttrAdapter: true,
chat.AttrRoute: true,
chat.AttrReason: true,
chat.AttrOutcome: true,
chat.AttrTenant: true,
}
obs.mu.Lock()
defer obs.mu.Unlock()
var attrSets [][]chat.Attr
for _, e := range obs.events {
attrSets = append(attrSets, e.attrs)
}
attrSets = append(attrSets, obs.attrs...)
for _, set := range attrSets {
for _, a := range set {
if !allowedKeys[a.Key] {
t.Fatalf("attribute key %q outside documented set", a.Key)
}
if a.Value == threadID {
t.Fatalf("thread id leaked into attribute %q", a.Key)
}
if a.Value == event.Message.Text || a.Value == event.Message.Author.ID {
t.Fatalf("message text or raw actor id leaked into attribute %q", a.Key)
}
}
}
}
func assertReason(t *testing.T, obs *recordingObserver, reason string) {
t.Helper()
obs.mu.Lock()
defer obs.mu.Unlock()
for _, e := range obs.events {
if e.name != chat.ObsIgnoredEvent {
continue
}
for _, a := range e.attrs {
if a.Key == chat.AttrReason && a.Value == reason {
return
}
}
}
t.Fatalf("ignored event with reason %q not found in %#v", reason, obs.events)
}
func assertRoutePresent(t *testing.T, obs *recordingObserver, route string) {
t.Helper()
obs.mu.Lock()
defer obs.mu.Unlock()
for _, set := range obs.attrs {
for _, a := range set {
if a.Key == chat.AttrRoute && a.Value == route {
return
}
}
}
t.Fatalf("route %q not present in span attrs %#v", route, obs.attrs)
}