package outbox import ( "context" "encoding/json" "errors" "sync" "testing" "time" "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "github.com/stretchr/testify/require" ) func TestDispatcherPublishesAndMarksEvent(t *testing.T) { store := &storeStub{events: []model.OutboxEvent{{ID: "event-1", LeaseToken: "lease-1", Payload: testPayload()}}} publisher := &publisherStub{messageID: "1-0"} dispatcher := newTestDispatcher(t, store, publisher) published, err := dispatcher.DispatchOnce(context.Background()) require.NoError(t, err) require.Equal(t, 1, published) require.Equal(t, []string{"event-1:lease-1"}, store.marked) } func TestDispatcherRetriesSafelyAfterMarkFailure(t *testing.T) { event := model.OutboxEvent{ID: "event-1", LeaseToken: "lease-1", Payload: testPayload()} store := &storeStub{events: []model.OutboxEvent{event}, markErr: errors.New("database unavailable")} publisher := &publisherStub{messageID: "1-0"} dispatcher := newTestDispatcher(t, store, publisher) _, err := dispatcher.DispatchOnce(context.Background()) require.Error(t, err) require.Equal(t, 1, publisher.calls) store.markErr = nil store.events[0].LeaseToken = "lease-2" publisher.messageID = "2-0" published, err := dispatcher.DispatchOnce(context.Background()) require.NoError(t, err) require.Equal(t, 1, published) require.Equal(t, 2, publisher.calls) require.JSONEq(t, string(event.Payload), string(publisher.payloads[0])) require.JSONEq(t, string(publisher.payloads[0]), string(publisher.payloads[1])) require.Equal(t, []string{"event-1:lease-2"}, store.marked) } func TestDispatcherReleasesPublishFailure(t *testing.T) { store := &storeStub{events: []model.OutboxEvent{{ID: "event-1", LeaseToken: "lease-1", Payload: testPayload()}}} publisher := &publisherStub{err: errors.New("redis unavailable")} dispatcher := newTestDispatcher(t, store, publisher) dispatcher.now = func() time.Time { return time.Date(2026, 10, 22, 12, 0, 0, 0, time.UTC) } published, err := dispatcher.DispatchOnce(context.Background()) require.NoError(t, err) require.Zero(t, published) require.Equal(t, "event-1:lease-1:broker_publish_failed", store.released) require.Equal(t, dispatcher.now().Add(time.Second), store.nextAttemptAt) } func TestDispatcherRejectsStaleLeaseAfterPublish(t *testing.T) { store := &storeStub{ events: []model.OutboxEvent{{ID: "event-1", LeaseToken: "stale-lease", Payload: testPayload()}}, markLost: true, } dispatcher := newTestDispatcher(t, store, &publisherStub{messageID: "1-0"}) published, err := dispatcher.DispatchOnce(context.Background()) require.ErrorIs(t, err, errLeaseLost) require.Zero(t, published) } func TestDispatcherCleansPublishedEventsBeforeRetentionCutoff(t *testing.T) { store := &storeStub{deleted: 2} dispatcher := newTestDispatcher(t, store, &publisherStub{}) dispatcher.now = func() time.Time { return time.Date(2026, 10, 22, 12, 0, 0, 0, time.UTC) } deleted, err := dispatcher.CleanupPublished(context.Background()) require.NoError(t, err) require.Equal(t, 2, deleted) require.Equal(t, dispatcher.now().Add(-24*time.Hour), store.publishedBefore) require.Equal(t, 100, store.cleanupLimit) } func TestDispatcherStopsAfterCancellation(t *testing.T) { store := &storeStub{} publisher := &publisherStub{} dispatcher := newTestDispatcher(t, store, publisher) ctx, cancel := context.WithCancel(context.Background()) cancel() done := make(chan error, 1) go func() { done <- dispatcher.Run(ctx) }() select { case err := <-done: require.NoError(t, err) case <-time.After(time.Second): t.Fatal("dispatcher did not stop after cancellation") } } func newTestDispatcher(t *testing.T, store Store, publisher Publisher) *Dispatcher { t.Helper() dispatcher, err := New(store, publisher, nil, Config{ BatchSize: 10, LeaseDuration: time.Minute, PollInterval: time.Millisecond, RecoveryInterval: time.Second, RetryDelay: time.Second, Retention: 24 * time.Hour, CleanupInterval: time.Hour, CleanupBatchSize: 100, }) require.NoError(t, err) return dispatcher } func testPayload() json.RawMessage { return json.RawMessage(`{ "schema_version": 1, "job_id": "11111111-1111-4111-8111-111111111111", "type": "attachment.process.v1", "attachment_id": "22222222-2222-4222-8222-222222222222", "pipeline_version": 1, "attempt": 1, "created_at": "2026-10-22T12:00:00Z" }`) } type storeStub struct { mu sync.Mutex events []model.OutboxEvent markErr error markLost bool marked []string released string nextAttemptAt time.Time recoveredCalls int deleted int publishedBefore time.Time cleanupLimit int } func (s *storeStub) ClaimOutboxEvents(context.Context, int, time.Duration) ([]model.OutboxEvent, error) { s.mu.Lock() defer s.mu.Unlock() return append([]model.OutboxEvent(nil), s.events...), nil } func (s *storeStub) MarkOutboxPublished(_ context.Context, id, leaseToken string) (bool, error) { s.mu.Lock() defer s.mu.Unlock() if s.markErr != nil { return false, s.markErr } if s.markLost { return false, nil } s.marked = append(s.marked, id+":"+leaseToken) return true, nil } func (s *storeStub) ReleaseOutboxEvent( _ context.Context, id string, leaseToken string, code string, nextAttemptAt time.Time, ) (bool, error) { s.mu.Lock() defer s.mu.Unlock() s.released = id + ":" + leaseToken + ":" + code s.nextAttemptAt = nextAttemptAt return true, nil } func (s *storeStub) RecoverExpiredOutboxEvents(context.Context, time.Time) (int, error) { s.mu.Lock() defer s.mu.Unlock() s.recoveredCalls++ return 0, nil } func (s *storeStub) DeletePublishedOutboxEvents(_ context.Context, before time.Time, limit int) (int, error) { s.mu.Lock() defer s.mu.Unlock() s.publishedBefore = before s.cleanupLimit = limit return s.deleted, nil } type publisherStub struct { mu sync.Mutex messageID string err error calls int payloads [][]byte } func (p *publisherStub) PublishConfirmed(_ context.Context, payload []byte) (string, error) { p.mu.Lock() defer p.mu.Unlock() p.calls++ p.payloads = append(p.payloads, append([]byte(nil), payload...)) return p.messageID, p.err }