diff --git a/submitqueue/entity/request_log.go b/submitqueue/entity/request_log.go index ea29018f6..b76022d45 100644 --- a/submitqueue/entity/request_log.go +++ b/submitqueue/entity/request_log.go @@ -18,6 +18,10 @@ import ( "time" ) +// RequestLogMetadataKeyResent marks a terminal request log that repeats a status +// already written. It stays on the log in History but never reaches a summary. +const RequestLogMetadataKeyResent = "resent" + // RequestStatus is where a request is in the pipeline. It is customer-friendly and can be displayed to the user. // It is different from the request state, which is internal and used to implement a state machine. Request statuses can be // generally added freely by the system without breaking the state machine. diff --git a/submitqueue/gateway/README.md b/submitqueue/gateway/README.md index 8b171f74d..0228158b8 100644 --- a/submitqueue/gateway/README.md +++ b/submitqueue/gateway/README.md @@ -25,6 +25,8 @@ The gateway owns the request log read model and is the only service that reads i The materializer appends every audit event, selects the current authoritative winner, and repairs the queue projection. The normal orchestrator pipeline does not read or write the request-log store directly. +A finished status keeps the reason and metadata it was first recorded with. When the orchestrator repairs a request already in that state it resends the terminal log marked `resent`, with whatever details the repairing path knows, which may differ from the original's or be none. So a log restating the summary's finished status and request version only fills details the summary lacks, whichever copy arrives first, and the `resent` marker stays in History, never in the summary. + ## Request hook events The materializer publishes SubmitQueue's request hook events (`submitqueue/core/hookevent`) to the `submitqueue-hook` topic, which the orchestrator pipeline's hook stage consumes, one event per change of the request. The update that takes the summary out of `accepting` announces `request.received`, once. That is normally `Land`, and a later log only when `Land` failed to record `accepted`; a failed receipt publish is only counted on `request_hook.publish_errors` and never repeated. Every delivery of a log that restates a `landed`, `error` or `cancelled` summary announces `request.landed`, `request.failed` or `request.cancelled`, so a failed publish is returned and the log's redelivery repairs it; a copy that arrives after the queue has forgotten the event id reaches hooks twice. Events therefore follow the summary users see, including a request whose start failed before the orchestrator saved it, and a stale or unfinished log publishes nothing. diff --git a/submitqueue/gateway/core/request/materializer.go b/submitqueue/gateway/core/request/materializer.go index e6b4b3168..854b6c7d8 100644 --- a/submitqueue/gateway/core/request/materializer.go +++ b/submitqueue/gateway/core/request/materializer.go @@ -94,16 +94,9 @@ func (m *Materializer) PersistLog(ctx context.Context, log entity.RequestLog) er } beforeUpdate, updatedSummary := summary, false - if logWins(log, summary) { + if updated, ok := projectLog(log, summary); ok { oldVersion := summary.Version newVersion := oldVersion + 1 - updated := summary - updated.Status = log.Status - updated.RequestVersion = log.RequestVersion - updated.StatusTimestampMs = log.TimestampMs - updated.LastError = log.LastError - updated.Metadata = cloneMetadata(log.Metadata) - if err := summaries.Update(ctx, updated, oldVersion, newVersion); err != nil { if errors.Is(err, basestorage.ErrVersionMismatch) { continue @@ -206,6 +199,55 @@ func logRestatesSummary(log entity.RequestLog, summary entity.RequestSummary) bo return log.Type == entity.RequestLogTypeStatus && log.Status == summary.Status && log.RequestVersion == summary.RequestVersion } +// projectLog returns the summary log projects onto, and false when it changes +// nothing. A winning log replaces the status and its details. A log restating a +// finished status and version only fills details the summary lacks, whatever its +// timestamp: a resend carries none of the original's and can reach the gateway +// before it, and the announced finish must keep describing the same failure. +func projectLog(log entity.RequestLog, summary entity.RequestSummary) (entity.RequestSummary, bool) { + restatesFinish := isTerminalStatus(log.Status) && logRestatesSummary(log, summary) + updated := summary + switch { + case logWins(log, summary): + updated.Status = log.Status + updated.RequestVersion = log.RequestVersion + updated.StatusTimestampMs = log.TimestampMs + updated.LastError, updated.Metadata = log.LastError, summaryMetadata(log.Metadata) + if restatesFinish { + updated.LastError, updated.Metadata = fillFinishedDetails(log, summary) + } + return updated, true + case restatesFinish: + updated.LastError, updated.Metadata = fillFinishedDetails(log, summary) + return updated, updated.LastError != summary.LastError || !maps.Equal(updated.Metadata, summary.Metadata) + default: + return summary, false + } +} + +// fillFinishedDetails keeps the summary's reason and metadata and adds what log has that they lack. +func fillFinishedDetails(log entity.RequestLog, summary entity.RequestSummary) (string, map[string]string) { + lastError := summary.LastError + if lastError == "" { + lastError = log.LastError + } + metadata := summaryMetadata(summary.Metadata) + for key, value := range summaryMetadata(log.Metadata) { + if _, ok := metadata[key]; !ok { + metadata[key] = value + } + } + return lastError, metadata +} + +// summaryMetadata copies a log's metadata for a summary, without the resent +// marker: it describes one log, not the request. +func summaryMetadata(metadata map[string]string) map[string]string { + summary := cloneMetadata(metadata) + delete(summary, entity.RequestLogMetadataKeyResent) + return summary +} + func isTerminalStatus(status entity.RequestStatus) bool { return entity.IsRequestStateTerminal(entity.RequestState(status)) } diff --git a/submitqueue/gateway/core/request/materializer_test.go b/submitqueue/gateway/core/request/materializer_test.go index f19448d52..4f0b4ef8c 100644 --- a/submitqueue/gateway/core/request/materializer_test.go +++ b/submitqueue/gateway/core/request/materializer_test.go @@ -167,6 +167,100 @@ func TestMaterializer_RecordsLifecycleMetrics(t *testing.T) { } } +func TestMaterializer_KeepsFinishedDetails(t *testing.T) { + failed := testRequestSummary() + failed.Status, failed.RequestVersion, failed.StatusTimestampMs, failed.Version = entity.RequestStatusError, 2, 20, 4 + failed.LastError, failed.Metadata = "build failed", map[string]string{"batch_id": "b1"} + started := testRequestSummary() + started.Status, started.RequestVersion, started.StatusTimestampMs, started.Version = entity.RequestStatusStarted, 1, 15, 3 + failedByResend := failed + failedByResend.StatusTimestampMs, failedByResend.LastError, failedByResend.Metadata = 30, "", map[string]string{} + resend := entity.RequestLog{Queue: "q", RequestID: "1", Type: entity.RequestLogTypeStatus, Status: entity.RequestStatusError, RequestVersion: 2, TimestampMs: 30, LastError: "dead lettered", Metadata: map[string]string{"batch_id": "b9", "dlq.failure_count": "3", "resent": "true"}} + bareResend := resend + bareResend.LastError, bareResend.Metadata = "", map[string]string{"resent": "true"} + original := entity.RequestLog{Queue: "q", RequestID: "1", Type: entity.RequestLogTypeStatus, Status: entity.RequestStatusError, RequestVersion: 2, TimestampMs: 20, LastError: "build failed", Metadata: map[string]string{"batch_id": "b1"}} + laterVersion := original + laterVersion.RequestVersion, laterVersion.TimestampMs, laterVersion.LastError, laterVersion.Metadata = 3, 40, "land failed", map[string]string{"batch_id": "b2"} + + tests := []struct { + name string + before entity.RequestSummary + log entity.RequestLog + wantUpdate bool + wantLastError string + wantMetadata map[string]string + }{ + { + name: "a resend after the original keeps its details and only fills what they lack", + before: failed, + log: resend, + wantUpdate: true, + wantLastError: "build failed", + wantMetadata: map[string]string{"batch_id": "b1", "dlq.failure_count": "3"}, + }, + { + name: "a resend without details after the original keeps them", + before: failed, + log: bareResend, + wantUpdate: true, + wantLastError: "build failed", + wantMetadata: map[string]string{"batch_id": "b1"}, + }, + { + name: "a resend whose original never arrived records its details without the resent marker", + before: started, + log: resend, + wantUpdate: true, + wantLastError: "dead lettered", + wantMetadata: map[string]string{"batch_id": "b9", "dlq.failure_count": "3"}, + }, + { + name: "the original after a bare resend fills the missing reason despite its older timestamp", + before: failedByResend, + log: original, + wantUpdate: true, + wantLastError: "build failed", + wantMetadata: map[string]string{"batch_id": "b1"}, + }, + { + name: "a redelivered original changes nothing", + before: failed, + log: original, + }, + { + name: "a later finished version replaces the details", + before: failed, + log: laterVersion, + wantUpdate: true, + wantLastError: "land failed", + wantMetadata: map[string]string{"batch_id": "b2"}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f := newMaterializerReceiptFixture(gomock.NewController(t)) + f.logs.EXPECT().Insert(gomock.Any(), tt.log).Return(nil) + f.summaries.EXPECT().Get(gomock.Any(), tt.before.RequestID).Return(tt.before, nil) + var got entity.RequestSummary + if tt.wantUpdate { + f.summaries.EXPECT().Update(gomock.Any(), gomock.Any(), tt.before.Version, tt.before.Version+1).DoAndReturn(func(_ context.Context, updated entity.RequestSummary, _, _ int32) error { + got = updated + return nil + }) + } + f.uris.EXPECT().Create(gomock.Any(), gomock.Any()).Return(nil).AnyTimes() + f.receipts.EXPECT().Create(gomock.Any(), gomock.Any()).Return(nil).AnyTimes() + + require.NoError(t, f.materializer.PersistLog(context.Background(), tt.log)) + + if tt.wantUpdate { + assert.Equal(t, tt.wantLastError, got.LastError) + assert.Equal(t, tt.wantMetadata, got.Metadata) + } + }) + } +} + func TestMaterializer_PublishesRequestHookEvents(t *testing.T) { accepting := testRequestSummary() accepted := accepting diff --git a/submitqueue/orchestrator/controller/cancel/cancel.go b/submitqueue/orchestrator/controller/cancel/cancel.go index 4cc794e6d..0c16104f3 100644 --- a/submitqueue/orchestrator/controller/cancel/cancel.go +++ b/submitqueue/orchestrator/controller/cancel/cancel.go @@ -149,7 +149,7 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er // The cancellation may be terminal even though its final log was never published. if request.State == entity.RequestStateCancelled { - return corerequest.ResendTerminalRequestLog(ctx, c.registry, request) + return corerequest.ResendTerminalRequestLog(ctx, c.registry, request, "", cancelMetadata(cancelReq.Reason)) } // Other terminal outcomes belong to their winning writer and are left untouched. @@ -264,11 +264,7 @@ func (c *Controller) findBatches(ctx context.Context, store orchstorage.Storage, // reports TerminationDiverged and we simply ack — the other writer owns the // terminal log for the state it wrote. func (c *Controller) cancelRequest(ctx context.Context, store orchstorage.Storage, request entity.Request, reason string) error { - metadata := map[string]string{} - if reason != "" { - metadata["reason"] = reason - } - res, err := corerequest.TerminateRequest(ctx, store, c.registry, request.ID, entity.RequestStateCancelled, "", metadata) + res, err := corerequest.TerminateRequest(ctx, store, c.registry, request.ID, entity.RequestStateCancelled, "", cancelMetadata(reason)) if err != nil { metrics.NamedCounter(c.metricsScope, opName, "request_terminate_errors", 1, metrics.TagsFromContext(ctx)...) return fmt.Errorf("failed to cancel request %s: %w", request.ID, err) @@ -385,3 +381,12 @@ func (c *Controller) TopicKey() consumer.TopicKey { func (c *Controller) ConsumerGroup() string { return c.consumerGroup } + +// cancelMetadata is the cancelled request log's metadata: the caller's reason, when given. +func cancelMetadata(reason string) map[string]string { + metadata := map[string]string{} + if reason != "" { + metadata["reason"] = reason + } + return metadata +} diff --git a/submitqueue/orchestrator/controller/cancel/cancel_test.go b/submitqueue/orchestrator/controller/cancel/cancel_test.go index f7dcbb9c6..b6ba75915 100644 --- a/submitqueue/orchestrator/controller/cancel/cancel_test.go +++ b/submitqueue/orchestrator/controller/cancel/cancel_test.go @@ -166,6 +166,48 @@ func TestProcess_AlreadyTerminal_NoOp(t *testing.T) { require.NoError(t, err) } +func TestProcess_AlreadyCancelled_ResendsTerminalLog(t *testing.T) { + tests := []struct { + name string + reason string + wantMetadata map[string]string + }{ + {name: "with the cancel reason", reason: "user asked", wantMetadata: map[string]string{"reason": "user asked", entity.RequestLogMetadataKeyResent: "true"}}, + {name: "without a reason", wantMetadata: map[string]string{entity.RequestLogMetadataKeyResent: "true"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + registry, pub := newRegistry(t, ctrl) + var logs []entity.RequestLog + pub.EXPECT().Publish(gomock.Any(), "log", gomock.Any()).DoAndReturn( + func(_ context.Context, _ string, msg entityqueue.Message) error { + logEntry, err := sqmq.UnmarshalRequestLog(msg.Payload) + require.NoError(t, err) + logs = append(logs, logEntry) + return nil + }, + ) + + reqStore := storagemock.NewMockRequestStore(ctrl) + reqStore.EXPECT().Get(gomock.Any(), "1").Return(entity.Request{ + ID: "1", Queue: "q", State: entity.RequestStateCancelled, Version: 5, + }, nil) + store := orchstoragemock.NewMockStorage(ctrl) + store.EXPECT().GetQueueBatchStateStore().Return(newQueueBatchStateStore(ctrl)).AnyTimes() + store.EXPECT().GetRequestStore().Return(reqStore).AnyTimes() + + controller := newController(t, store, registry) + require.NoError(t, controller.Process(context.Background(), newDelivery(t, ctrl, cancelPayload(t, "1", tt.reason), "1"))) + + require.Len(t, logs, 1) + assert.Equal(t, entity.RequestStatusCancelled, logs[0].Status) + assert.Equal(t, int32(5), logs[0].RequestVersion) + assert.Equal(t, tt.wantMetadata, logs[0].Metadata) + }) + } +} + func TestProcess_RequestNotFound_Retryable(t *testing.T) { ctrl := gomock.NewController(t) registry, _ := newRegistry(t, ctrl) diff --git a/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal.go b/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal.go index a3d26bb3b..20e2389cc 100644 --- a/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal.go +++ b/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal.go @@ -114,9 +114,14 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er "partition_key", msg.PartitionKey, ) - // The failed conflict check may be terminal even though its final log was never published. + // The failed conflict check may be terminal even though its final log was never + // published. A redelivered failure carries the same result, so the resend can say why. if request.State == entity.RequestStateError { - return corerequest.ResendTerminalRequestLog(ctx, c.registry, request) + var reason string + if result.Outcome != runwaypb.Outcome_SUCCEEDED { + reason = result.Reason + } + return corerequest.ResendTerminalRequestLog(ctx, c.registry, request, reason, nil) } if entity.IsRequestStateHalted(request.State) { diff --git a/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal_test.go b/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal_test.go index 368f4fe06..4626014b5 100644 --- a/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal_test.go +++ b/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal_test.go @@ -244,3 +244,59 @@ func TestProcess_HaltedRequestSkips(t *testing.T) { msg := entityqueue.NewMessage(testRequestID, resultPayload(t, res), testQueue, nil) require.NoError(t, controller.Process(context.Background(), newDelivery(ctrl, msg))) } + +func TestProcess_ErrorRequestResendsTerminalLog(t *testing.T) { + tests := []struct { + name string + result runwaymq.MergeResult + wantLastError string + }{ + { + name: "a redelivered failure says why", + result: runwaymq.MergeResult{Id: testRequestID, Outcome: runwaypb.Outcome_FAILED, Reason: "conflict in foo.go"}, + wantLastError: "conflict in foo.go", + }, + { + name: "a success cannot say why the request failed", + result: runwaymq.MergeResult{Id: testRequestID, Outcome: runwaypb.Outcome_SUCCEEDED}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + reqStore := storagemock.NewMockRequestStore(ctrl) + reqStore.EXPECT().Get(gomock.Any(), testRequestID).Return( + entity.Request{ID: testRequestID, Queue: testQueue, State: entity.RequestStateError, Version: 2}, nil) + store := orchstoragemock.NewMockStorage(ctrl) + store.EXPECT().GetRequestStore().Return(reqStore).AnyTimes() + + var logs []entity.RequestLog + pub := queuemock.NewMockPublisher(ctrl) + pub.EXPECT().Publish(gomock.Any(), "log", gomock.Any()).DoAndReturn( + func(_ context.Context, _ string, msg entityqueue.Message) error { + logEntry, err := sqmq.UnmarshalRequestLog(msg.Payload) + require.NoError(t, err) + logs = append(logs, logEntry) + return nil + }, + ) + q := queuemock.NewMockQueue(ctrl) + q.EXPECT().Publisher().Return(pub).AnyTimes() + registry, err := consumer.NewTopicRegistry([]consumer.TopicConfig{{Key: topickey.TopicKeyLog, Name: "log", Queue: q}}) + require.NoError(t, err) + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + controller := NewController(zaptest.NewLogger(t).Sugar(), tally.NoopScope, storageFactory, registry, + runwaymq.TopicKeyMergeConflictCheckSignal, "orchestrator-landconflictsignal") + + msg := entityqueue.NewMessage(testRequestID, resultPayload(t, tt.result), testQueue, nil) + require.NoError(t, controller.Process(context.Background(), newDelivery(ctrl, msg))) + + require.Len(t, logs, 1) + assert.Equal(t, entity.RequestStatusError, logs[0].Status) + assert.Equal(t, int32(2), logs[0].RequestVersion) + assert.Equal(t, tt.wantLastError, logs[0].LastError) + assert.Equal(t, "true", logs[0].Metadata[entity.RequestLogMetadataKeyResent]) + }) + } +} diff --git a/submitqueue/orchestrator/controller/validate/validate.go b/submitqueue/orchestrator/controller/validate/validate.go index 63633053e..c624f8395 100644 --- a/submitqueue/orchestrator/controller/validate/validate.go +++ b/submitqueue/orchestrator/controller/validate/validate.go @@ -134,8 +134,9 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er ) // The rejection may be terminal even though its final log was never published. + // This delivery cannot tell why the request was rejected, so the resend has no reason. if request.State == entity.RequestStateError { - return corerequest.ResendTerminalRequestLog(ctx, c.registry, request) + return corerequest.ResendTerminalRequestLog(ctx, c.registry, request, "", nil) } // Cancellation intent halts forward progress even before the terminal outcome. diff --git a/submitqueue/orchestrator/core/request/terminal_log.go b/submitqueue/orchestrator/core/request/terminal_log.go index 0a81b33a0..b5cb36bf4 100644 --- a/submitqueue/orchestrator/core/request/terminal_log.go +++ b/submitqueue/orchestrator/core/request/terminal_log.go @@ -17,19 +17,29 @@ package request import ( "context" "fmt" + "maps" "github.com/uber/submitqueue/platform/consumer" "github.com/uber/submitqueue/submitqueue/entity" ) -// ResendTerminalRequestLog resends the request's terminal status without another state write. -// The log identifies the resend; original diagnostics may be unavailable. -func ResendTerminalRequestLog(ctx context.Context, registry consumer.TopicRegistry, request entity.Request) error { +// resentTerminalLogMetadata copies metadata and marks the copy resent. +func resentTerminalLogMetadata(metadata map[string]string) map[string]string { + resent := make(map[string]string, len(metadata)+1) + maps.Copy(resent, metadata) + resent[entity.RequestLogMetadataKeyResent] = "true" + return resent +} + +// ResendTerminalRequestLog resends the request's terminal status without another state write, marked resent. +// lastError and metadata are what the caller knows of the finish, empty when it knows nothing. The gateway +// keeps the details that reached it first and only fills those it lacks, so a resend never rewrites them. +func ResendTerminalRequestLog(ctx context.Context, registry consumer.TopicRegistry, request entity.Request, lastError string, metadata map[string]string) error { status, err := terminalStateToStatus(request.State) if err != nil { return err } - logEntry := entity.NewRequestStatusLog(request.Queue, request.ID, status, request.Version, "terminal status resent for consistency; original details may not have been retained", nil) + logEntry := entity.NewRequestStatusLog(request.Queue, request.ID, status, request.Version, lastError, resentTerminalLogMetadata(metadata)) if err := PublishLog(ctx, registry, logEntry, request.ID, ""); err != nil { return fmt.Errorf("failed to publish request log for %s: %w", request.ID, err) } diff --git a/submitqueue/orchestrator/core/request/terminate.go b/submitqueue/orchestrator/core/request/terminate.go index 72e976efc..eaca3034c 100644 --- a/submitqueue/orchestrator/core/request/terminate.go +++ b/submitqueue/orchestrator/core/request/terminate.go @@ -86,7 +86,9 @@ type TerminationResult struct { // - the request is not found: nothing is done (TerminationOutcomeNotFound). // // The caller owns all logging and metrics — TerminationResult carries the state context needed to do so. -// lastError and metadata describe the first transition; same-state repair reports unavailable original details. +// lastError and metadata describe the transition. A same-state repair sends them marked resent: when the original +// log was never published they are the only account of the finish, and the gateway keeps an original that did +// arrive, filling only the details it lacks. // // A storage.ErrVersionMismatch from the conditional write is returned as-is (it is // intrinsically retryable) so the caller's next attempt re-reads and re-evaluates. @@ -123,7 +125,7 @@ func TerminateRequest( // Idempotent retry: a prior attempt already wrote the terminal state. // Skip the CAS and fall through to re-publish the terminal log. outcome = TerminationOutcomeAlreadyInTargetState - lastError, metadata = "terminal status resent for consistency; original details may not have been retained", nil + metadata = resentTerminalLogMetadata(metadata) case entity.IsRequestStateTerminal(request.State): // Divergent terminal state — a concurrent path reached terminal first // and owns the terminal log entry for the state it actually wrote. diff --git a/submitqueue/orchestrator/core/request/terminate_test.go b/submitqueue/orchestrator/core/request/terminate_test.go index 87b483189..779ab66e5 100644 --- a/submitqueue/orchestrator/core/request/terminate_test.go +++ b/submitqueue/orchestrator/core/request/terminate_test.go @@ -17,6 +17,7 @@ package request import ( "context" "fmt" + "maps" "testing" "github.com/stretchr/testify/assert" @@ -123,8 +124,10 @@ func TestTerminateRequest(t *testing.T) { assert.Equal(t, "validate", log.Metadata["source"]) }, }, - "already in target terminal state republishes log": { + "already in target terminal state republishes log with the caller's details marked resent": { targetState: entity.RequestStateError, + lastError: "boom", + metadata: map[string]string{"source": "dlq"}, mockFunc: func(rs *storagemock.MockRequestStore) { already := entity.Request{ID: requestID, Queue: "q", State: entity.RequestStateError, Version: 5} rs.EXPECT().Get(gomock.Any(), requestID).Return(already, nil) @@ -137,6 +140,8 @@ func TestTerminateRequest(t *testing.T) { wantLog: func(t *testing.T, log entity.RequestLog) { assert.Equal(t, entity.RequestStatusError, log.Status) assert.Equal(t, int32(5), log.RequestVersion) + assert.Equal(t, "boom", log.LastError) + assert.Equal(t, map[string]string{"source": "dlq", entity.RequestLogMetadataKeyResent: "true"}, log.Metadata) }, }, "already in target terminal state returns republish error": { @@ -215,3 +220,47 @@ func TestTerminateRequest(t *testing.T) { }) } } + +func TestResendTerminalRequestLog(t *testing.T) { + tests := []struct { + name string + state entity.RequestState + lastError string + metadata map[string]string + wantStatus entity.RequestStatus + wantMetadata map[string]string + wantErr bool + }{ + { + name: "error with the caller's details", state: entity.RequestStateError, lastError: "conflict", metadata: map[string]string{"k": "v"}, + wantStatus: entity.RequestStatusError, wantMetadata: map[string]string{"k": "v", entity.RequestLogMetadataKeyResent: "true"}, + }, + { + name: "landed without details", state: entity.RequestStateLanded, + wantStatus: entity.RequestStatusLanded, wantMetadata: map[string]string{entity.RequestLogMetadataKeyResent: "true"}, + }, + {name: "non-terminal state rejected", state: entity.RequestStateValidated, wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + registry, logs := recordingRegistry(t, gomock.NewController(t), nil) + metadata := maps.Clone(tt.metadata) + + err := ResendTerminalRequestLog(context.Background(), registry, entity.Request{ID: "1", Queue: "q", State: tt.state, Version: 5}, tt.lastError, metadata) + + if tt.wantErr { + require.Error(t, err) + assert.Empty(t, *logs) + return + } + require.NoError(t, err) + require.Len(t, *logs, 1) + log := (*logs)[0] + assert.Equal(t, tt.wantStatus, log.Status) + assert.Equal(t, int32(5), log.RequestVersion) + assert.Equal(t, tt.lastError, log.LastError) + assert.Equal(t, tt.wantMetadata, log.Metadata) + assert.Equal(t, tt.metadata, metadata, "the caller's metadata is not modified") + }) + } +}