-
Notifications
You must be signed in to change notification settings - Fork 413
feat: implement event bus subscription and dispatch pipeline #279
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| // Copyright (c) 2026 Lark Technologies Pte. Ltd. | ||
| // SPDX-License-Identifier: MIT | ||
|
|
||
| package event | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "io" | ||
| "path/filepath" | ||
| "sync" | ||
| "testing" | ||
| "time" | ||
| ) | ||
|
|
||
| func makeInboundEnvelopeWithEventID(eventID, eventType, eventJSON string) InboundEnvelope { | ||
| body := fmt.Sprintf(`{"schema":"2.0","header":{"event_id":"%s","event_type":"%s"},"event":%s}`, eventID, eventType, eventJSON) | ||
| return InboundEnvelope{ | ||
| Source: SourceWebSocket, | ||
| ReceivedAt: nowForTest(), | ||
| RawPayload: []byte(body), | ||
| } | ||
| } | ||
|
|
||
| func nowForTest() time.Time { | ||
| return time.Unix(1700000000, 0).UTC() | ||
| } | ||
|
|
||
| func TestOutputRouterWriteRecordConcurrent(t *testing.T) { | ||
| router := &outputRouter{ | ||
| defaultDir: filepath.Join(t.TempDir(), "events"), | ||
| seq: new(uint64), | ||
| writers: map[string]*dirRecordWriter{}, | ||
| } | ||
|
|
||
| const workers = 64 | ||
| var wg sync.WaitGroup | ||
| wg.Add(workers) | ||
| for i := 0; i < workers; i++ { | ||
| go func(i int) { | ||
| defer wg.Done() | ||
| if err := router.WriteRecord("im.message.receive_v1", map[string]interface{}{ | ||
| "event_type": "im.message.receive_v1", | ||
| "event_id": fmt.Sprintf("evt-%03d", i), | ||
| }); err != nil { | ||
| t.Errorf("WriteRecord() error = %v", err) | ||
| } | ||
| }(i) | ||
| } | ||
| wg.Wait() | ||
| } | ||
|
|
||
| func TestPipelineConcurrentProcessCountsAllDispatches(t *testing.T) { | ||
| registry := NewHandlerRegistry() | ||
| if err := registry.RegisterEventHandler(handlerFuncWith{ | ||
| id: "counting-handler", | ||
| eventType: "im.message.receive_v1", | ||
| fn: func(_ context.Context, evt *Event) HandlerResult { | ||
| return HandlerResult{Status: HandlerStatusHandled, Output: map[string]interface{}{"event_id": evt.EventID}} | ||
| }, | ||
| }); err != nil { | ||
| t.Fatalf("RegisterEventHandler() error = %v", err) | ||
| } | ||
|
|
||
| p := NewEventPipeline(registry, NewFilterChain(), PipelineConfig{Mode: TransformCompact}, io.Discard, io.Discard) | ||
|
|
||
| const workers = 64 | ||
| var wg sync.WaitGroup | ||
| wg.Add(workers) | ||
| for i := 0; i < workers; i++ { | ||
| go func(i int) { | ||
| defer wg.Done() | ||
| p.Process(context.Background(), makeInboundEnvelopeWithEventID( | ||
| fmt.Sprintf("evt-%03d", i), | ||
| "im.message.receive_v1", | ||
| fmt.Sprintf(`{"message":{"message_id":"om_%03d"}}`, i), | ||
| )) | ||
| }(i) | ||
| } | ||
| wg.Wait() | ||
|
|
||
| if got, want := p.EventCount(), int64(workers); got != want { | ||
| t.Fatalf("EventCount() = %d, want %d", got, want) | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| // Copyright (c) 2026 Lark Technologies Pte. Ltd. | ||
| // SPDX-License-Identifier: MIT | ||
|
|
||
| package event | ||
|
|
||
| import ( | ||
| "sync" | ||
| "sync/atomic" | ||
| "time" | ||
| ) | ||
|
|
||
| const deduperCleanupInterval = 64 | ||
|
|
||
| // Deduper suppresses repeated keys seen within a TTL window. | ||
| type Deduper struct { | ||
| ttl time.Duration | ||
| seen sync.Map // key -> time.Time | ||
| calls atomic.Uint64 | ||
| } | ||
|
|
||
| // NewDeduper creates a deduper with the provided TTL. | ||
| func NewDeduper(ttl time.Duration) *Deduper { | ||
| return &Deduper{ttl: ttl} | ||
| } | ||
|
|
||
| // Seen reports whether key has already been seen within ttl and records now. | ||
| func (d *Deduper) Seen(key string, now time.Time) bool { | ||
| if d == nil || key == "" || d.ttl <= 0 { | ||
| return false | ||
| } | ||
| if d.calls.Add(1)%deduperCleanupInterval == 0 { | ||
| d.cleanup(now) | ||
| } | ||
| if v, loaded := d.seen.LoadOrStore(key, now); loaded { | ||
| if ts, ok := v.(time.Time); ok && now.Sub(ts) < d.ttl { | ||
| return true | ||
| } | ||
| d.seen.Store(key, now) | ||
| } | ||
| return false | ||
| } | ||
|
Comment on lines
+14
to
+41
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🧩 Analysis chain🏁 Script executed: #!/bin/bash
# Check if Deduper cleanup is implemented elsewhere or if there's a bounded lifetime
rg -nP 'Deduper|Cleanup|cleanup' --type=go -C3Repository: larksuite/cli Length of output: 20673 🏁 Script executed: cat -n shortcuts/event/pipeline.go | head -100Repository: larksuite/cli Length of output: 3059 🏁 Script executed: # Check how Pipeline is created and used - search for NewPipeline and Pipeline instantiation
rg -n 'NewPipeline|Pipeline{' --type=go -B2 -A2 | head -60Repository: larksuite/cli Length of output: 162 🏁 Script executed: # Check event processing context - is it short-lived or long-running?
rg -n 'event\..*Pipeline\|pipeline.*Run\|pipeline.*Process' --type=go | head -30Repository: larksuite/cli Length of output: 39 🏁 Script executed: # Search for where EventPipeline is created and used
rg -n 'NewEventPipeline|\.Process\(' shortcuts/event/ --type=go -B2 -A2Repository: larksuite/cli Length of output: 8121 🏁 Script executed: # Check the broader context - where is event processing called from?
rg -n 'EventPipeline|event\.New' --type=go | grep -v test | head -40Repository: larksuite/cli Length of output: 1299 🏁 Script executed: # Look at the entire deduper.go to understand the implementation fully
cat -n shortcuts/event/deduper.goRepository: larksuite/cli Length of output: 1065 Memory accumulation in In the event subscription context (shortcuts/event/subscribe.go), the EventPipeline is created once and processes events continuously via WebSocket. The Deduper stores event identifiers indefinitely—entries older than the 5-minute TTL are never evicted, only overwritten if the same key reappears. For high-volume event streams with many unique identifiers, this can accumulate significant memory over time. Consider implementing periodic cleanup: ♻️ Cleanup approach// Cleanup removes entries older than TTL. Call periodically from a background goroutine.
func (d *Deduper) Cleanup(now time.Time) {
d.seen.Range(func(key, value interface{}) bool {
if ts, ok := value.(time.Time); ok && now.Sub(ts) >= d.ttl {
d.seen.Delete(key)
}
return true
})
}Then invoke it periodically (e.g., every 🤖 Prompt for AI Agents |
||
|
|
||
| func (d *Deduper) cleanup(now time.Time) { | ||
| d.seen.Range(func(key, value any) bool { | ||
| ts, ok := value.(time.Time) | ||
| if ok && now.Sub(ts) >= d.ttl { | ||
| d.seen.Delete(key) | ||
| } | ||
| return true | ||
| }) | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| // Copyright (c) 2026 Lark Technologies Pte. Ltd. | ||
| // SPDX-License-Identifier: MIT | ||
|
|
||
| package event | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "testing" | ||
| "time" | ||
| ) | ||
|
|
||
| func deduperHasKey(d *Deduper, key string) bool { | ||
| if d == nil { | ||
| return false | ||
| } | ||
| found := false | ||
| d.seen.Range(func(k, _ any) bool { | ||
| if k == key { | ||
| found = true | ||
| return false | ||
| } | ||
| return true | ||
| }) | ||
| return found | ||
| } | ||
|
|
||
| func TestDeduperEvictsExpiredKeysDuringSteadyState(t *testing.T) { | ||
| d := NewDeduper(time.Second) | ||
| now := time.Unix(100, 0).UTC() | ||
| if d.Seen("stale", now) { | ||
| t.Fatal("first observation of stale key should not dedupe") | ||
| } | ||
|
|
||
| later := now.Add(2 * time.Second) | ||
| for i := 0; i < 128; i++ { | ||
| if d.Seen(fmt.Sprintf("fresh-%03d", i), later) { | ||
| t.Fatalf("fresh key %d should not dedupe on first observation", i) | ||
| } | ||
| } | ||
|
|
||
| if deduperHasKey(d, "stale") { | ||
| t.Fatal("stale key should be evicted after periodic cleanup") | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| // Copyright (c) 2026 Lark Technologies Pte. Ltd. | ||
| // SPDX-License-Identifier: MIT | ||
|
|
||
| package event | ||
|
|
||
| import "context" | ||
|
|
||
| // Dispatcher routes normalized events to registered handlers. | ||
| type Dispatcher struct { | ||
| registry *HandlerRegistry | ||
| } | ||
|
|
||
| // NewDispatcher creates a dispatcher backed by the provided registry. | ||
| func NewDispatcher(registry *HandlerRegistry) *Dispatcher { | ||
| if registry == nil { | ||
| registry = NewHandlerRegistry() | ||
| } | ||
| return &Dispatcher{registry: registry} | ||
| } | ||
|
|
||
| // Dispatch runs matching event handlers first, then matching domain handlers. | ||
| // Fallback is only used when no direct handlers matched. | ||
| func (d *Dispatcher) Dispatch(ctx context.Context, evt *Event) DispatchResult { | ||
| if d == nil || d.registry == nil || evt == nil { | ||
| return DispatchResult{} | ||
| } | ||
|
|
||
| matched := append([]EventHandler{}, d.registry.EventHandlers(evt.EventType)...) | ||
| matched = append(matched, d.registry.DomainHandlers(evt.Domain)...) | ||
| if len(matched) == 0 { | ||
| if fallback := d.registry.FallbackHandler(); fallback != nil { | ||
| matched = append(matched, fallback) | ||
| } | ||
| } | ||
|
|
||
| result := DispatchResult{Results: make([]DispatchRecord, 0, len(matched))} | ||
| for _, handler := range matched { | ||
| handlerResult := handler.Handle(ctx, evt) | ||
| result.Results = append(result.Results, DispatchRecord{ | ||
| HandlerID: handler.ID(), | ||
| Status: handlerResult.Status, | ||
| Reason: handlerResult.Reason, | ||
| Err: handlerResult.Err, | ||
| Output: handlerResult.Output, | ||
| }) | ||
|
Comment on lines
+37
to
+45
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Recover handler panics inside the dispatch loop.
🤖 Prompt for AI Agents |
||
| } | ||
| return result | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.