refactor: testing from the beginning. a journey in 150k lines of tests to none
This commit is contained in:
651 files changed
-146443
No files matched your search
@@ -1,225 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
)
|
||||
|
||||
func newStoreForAccess(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
pool, _ := migrated(t)
|
||||
return New(pool)
|
||||
}
|
||||
|
||||
func TestAccessPolicyStore(t *testing.T) {
|
||||
s := newStoreForAccess(t)
|
||||
ctx := t.Context()
|
||||
|
||||
// PutPolicy stores one policy and reports a versioned level.
|
||||
p := access.Policy{
|
||||
ID: "test-policy", Level: access.LevelOrg, OrgID: "soc",
|
||||
Text: `permit(principal, action, resource) when { resource.kind == "binding" };`,
|
||||
}
|
||||
v1, err := s.PutPolicy(ctx, p)
|
||||
if err != nil {
|
||||
t.Fatalf("PutPolicy: %v", err)
|
||||
}
|
||||
if v1 != 2 { // the counter starts at 1; the first write bumps it
|
||||
t.Fatalf("PutPolicy version = %d, want 2", v1)
|
||||
}
|
||||
v2, err := s.PutPolicy(ctx, p)
|
||||
if err != nil {
|
||||
t.Fatalf("second PutPolicy: %v", err)
|
||||
}
|
||||
if v2 <= v1 {
|
||||
t.Fatalf("second PutPolicy version = %d, want > %d", v2, v1)
|
||||
}
|
||||
|
||||
// A malformed policy is refused by the store's own structural check.
|
||||
bad := access.Policy{ID: "bad", Level: access.LevelOrg, OrgID: "soc"}
|
||||
if _, err := s.PutPolicy(ctx, bad); !errors.Is(err, access.ErrInvalidPolicy) {
|
||||
t.Fatalf("PutPolicy(structurally invalid) = %v, want ErrInvalidPolicy", err)
|
||||
}
|
||||
|
||||
// ListPolicies round-trips the scope tuple.
|
||||
list, err := s.ListPolicies(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListPolicies: %v", err)
|
||||
}
|
||||
if len(list) != 1 {
|
||||
t.Fatalf("ListPolicies = %d policies, want 1", len(list))
|
||||
}
|
||||
if list[0].ID != "test-policy" || list[0].OrgID != "soc" {
|
||||
t.Fatalf("ListPolicies[0] = %+v, want the stored policy", list[0])
|
||||
}
|
||||
|
||||
// DeletePolicy removes it and reports an unknown key as a sentinel.
|
||||
if err := s.DeletePolicy(ctx, p); err != nil {
|
||||
t.Fatalf("DeletePolicy: %v", err)
|
||||
}
|
||||
if err := s.DeletePolicy(ctx, p); !errors.Is(err, access.ErrPolicyNotFound) {
|
||||
t.Fatalf("second DeletePolicy = %v, want ErrPolicyNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureShippedOrgPolicies(t *testing.T) {
|
||||
s := newStoreForAccess(t)
|
||||
ctx := t.Context()
|
||||
|
||||
if err := s.EnsureShippedOrgPolicies(ctx, "soc"); err != nil {
|
||||
t.Fatalf("EnsureShippedOrgPolicies: %v", err)
|
||||
}
|
||||
list, err := s.ListPolicies(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListPolicies: %v", err)
|
||||
}
|
||||
if len(list) != 4 {
|
||||
t.Fatalf("seeding produced %d policies, want the 4 shipped roles", len(list))
|
||||
}
|
||||
|
||||
// An edited role policy survives a re-seed: an org that already carries
|
||||
// the shipped IDs is left untouched.
|
||||
edited := list[0]
|
||||
edited.Text = `permit(principal, action, resource) when { resource.kind == "edited" };`
|
||||
if _, err := s.PutPolicy(ctx, edited); err != nil {
|
||||
t.Fatalf("PutPolicy(edit): %v", err)
|
||||
}
|
||||
if err := s.EnsureShippedOrgPolicies(ctx, "soc"); err != nil {
|
||||
t.Fatalf("re-seed: %v", err)
|
||||
}
|
||||
after, err := s.ListPolicies(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListPolicies after re-seed: %v", err)
|
||||
}
|
||||
for _, p := range after {
|
||||
if p.ID == edited.ID && p.Text != edited.Text {
|
||||
t.Fatalf("re-seed overwrote an edited role policy %s", p.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetPolicies(t *testing.T) {
|
||||
s := newStoreForAccess(t)
|
||||
ctx := t.Context()
|
||||
|
||||
if err := s.ResetOrgPolicies(ctx, "soc"); err != nil {
|
||||
t.Fatalf("ResetOrgPolicies: %v", err)
|
||||
}
|
||||
// An operator's custom org policy on top of the shipped set.
|
||||
custom := access.Policy{
|
||||
ID: "org-lockdown", Level: access.LevelOrg, OrgID: "soc",
|
||||
Text: `forbid(principal, action, resource) when { resource.kind == "source" };`,
|
||||
}
|
||||
if _, err := s.PutPolicy(ctx, custom); err != nil {
|
||||
t.Fatalf("PutPolicy(custom): %v", err)
|
||||
}
|
||||
// A workspace policy must survive an org reset.
|
||||
ws := access.Policy{
|
||||
ID: "ws-rule", Level: access.LevelWorkspace, OrgID: "soc", WorkspaceID: "net",
|
||||
Text: `permit(principal, action, resource) when { resource.kind == "binding" };`,
|
||||
}
|
||||
if _, err := s.PutPolicy(ctx, ws); err != nil {
|
||||
t.Fatalf("PutPolicy(ws): %v", err)
|
||||
}
|
||||
// And an instance policy must survive an org reset but not an instance
|
||||
// reset.
|
||||
instance := access.Policy{
|
||||
ID: "instance-rule", Level: access.LevelInstance,
|
||||
Text: `forbid(principal, action, resource) when { resource.kind == "secret" };`,
|
||||
}
|
||||
if _, err := s.PutPolicy(ctx, instance); err != nil {
|
||||
t.Fatalf("PutPolicy(instance): %v", err)
|
||||
}
|
||||
|
||||
if err := s.ResetOrgPolicies(ctx, "soc"); err != nil {
|
||||
t.Fatalf("org reset: %v", err)
|
||||
}
|
||||
after, err := s.ListPolicies(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListPolicies: %v", err)
|
||||
}
|
||||
orgPolicies := 0
|
||||
for _, p := range after {
|
||||
switch {
|
||||
case p.Level == access.LevelOrg && p.OrgID == "soc":
|
||||
orgPolicies++
|
||||
case p.Level == access.LevelOrg:
|
||||
t.Fatalf("org reset touched policy %s of another org", p.ID)
|
||||
}
|
||||
}
|
||||
if orgPolicies != 4 {
|
||||
t.Fatalf("org-level policies after reset = %d, want the 4 shipped roles", orgPolicies)
|
||||
}
|
||||
|
||||
if err := s.ResetInstancePolicies(ctx); err != nil {
|
||||
t.Fatalf("ResetInstancePolicies: %v", err)
|
||||
}
|
||||
after, err = s.ListPolicies(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListPolicies after instance reset: %v", err)
|
||||
}
|
||||
for _, p := range after {
|
||||
if p.Level == access.LevelInstance {
|
||||
t.Fatalf("instance reset left policy %s", p.ID)
|
||||
}
|
||||
}
|
||||
if len(after) == 0 {
|
||||
t.Fatal("instance reset removed non-instance policies")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDenialStore(t *testing.T) {
|
||||
s := newStoreForAccess(t)
|
||||
ctx := t.Context()
|
||||
|
||||
denial := access.Denial{
|
||||
Principal: identity.IdentityID("11111111-1111-5111-8111-111111111111"),
|
||||
Org: "soc", Action: access.ActionRead, Kind: access.KindBinding,
|
||||
ResourceID: "b1", Level: access.LevelOrg,
|
||||
Policies: []string{access.PolicyOrgRead, access.PolicyOrgEdit},
|
||||
}
|
||||
if err := s.RecordDenial(ctx, denial); err != nil {
|
||||
t.Fatalf("RecordDenial: %v", err)
|
||||
}
|
||||
if err := s.RecordDenial(ctx, denial); err != nil {
|
||||
t.Fatalf("repeat RecordDenial: %v", err)
|
||||
}
|
||||
// A different action is a separate row.
|
||||
other := denial
|
||||
other.Action = access.ActionDelete
|
||||
if err := s.RecordDenial(ctx, other); err != nil {
|
||||
t.Fatalf("RecordDenial(other action): %v", err)
|
||||
}
|
||||
|
||||
rows, err := s.ListDenials(ctx, "soc", 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListDenials: %v", err)
|
||||
}
|
||||
if len(rows) != 2 {
|
||||
t.Fatalf("ListDenials = %d rows, want 2", len(rows))
|
||||
}
|
||||
if rows[0].Action != access.ActionDelete {
|
||||
t.Fatalf("newest denial = %v, want the delete denial", rows[0].Action)
|
||||
}
|
||||
for _, r := range rows {
|
||||
if r.Action == access.ActionRead {
|
||||
if r.Count != 2 {
|
||||
t.Fatalf("repeated denial count = %d, want 2 (coalesced within the minute)", r.Count)
|
||||
}
|
||||
if len(r.Policies) != 2 {
|
||||
t.Fatalf("denial policies = %v, want the deciding policies", r.Policies)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Another org sees none of these.
|
||||
if rows, err := s.ListDenials(ctx, "other", 10); err != nil || len(rows) != 0 {
|
||||
t.Fatalf("ListDenials(other org) = %d rows %v, want none", len(rows), err)
|
||||
}
|
||||
// An org-less denial is refused at the producer.
|
||||
if err := s.RecordDenial(ctx, access.Denial{Action: access.ActionRead}); err == nil {
|
||||
t.Fatal("RecordDenial accepted a denial with no org or principal")
|
||||
}
|
||||
}
|
||||
@@ -1,366 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
task "github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
// CancelExecution is the one cancel path (docs/prds/execution-tree-state-machine.md,
|
||||
// "Cancellation"): one transaction cancels every non-terminal StepExecution of
|
||||
// the execution's current attempt and moves the execution to the status the
|
||||
// operator action names, with one event row per step transition and the
|
||||
// execution's own audit row in the same write.
|
||||
|
||||
func TestCancelExecutionCancelsTheAttemptsStepsAndTheExecution(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
stageID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "review",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep stage: %v", err)
|
||||
}
|
||||
childID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt,
|
||||
ParentID: stageID, Kind: task.StepKindAgent, Name: "review:1",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep child: %v", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stageID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded, Detail: "done",
|
||||
}); err != nil {
|
||||
t.Fatalf("FinishStep: %v", err)
|
||||
}
|
||||
|
||||
steps, err := s.CancelExecution(t.Context(), execution.ID, "stopped by operator", taskstate.Parked)
|
||||
if err != nil {
|
||||
t.Fatalf("CancelExecution: %v", err)
|
||||
}
|
||||
if len(steps) != 1 || steps[0] != childID {
|
||||
t.Fatalf("cancelled steps = %v, want only the non-terminal %d", steps, childID)
|
||||
}
|
||||
|
||||
// Every non-terminal step of the current attempt is cancelled; the one
|
||||
// that already finished is never rewritten.
|
||||
var statuses map[int64]string
|
||||
if err := s.pool.QueryRow(t.Context(),
|
||||
`SELECT jsonb_object_agg(id, status) FROM step_executions WHERE execution_id = $1`,
|
||||
execution.ID).Scan(&statuses); err != nil {
|
||||
t.Fatalf("read steps: %v", err)
|
||||
}
|
||||
if statuses[stageID] != string(taskstate.StepSucceeded) || statuses[childID] != string(taskstate.StepCancelled) {
|
||||
t.Fatalf("statuses = %v, want the finished step kept and the child cancelled", statuses)
|
||||
}
|
||||
|
||||
got, err := s.TaskByID(t.Context(), execution.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID: %+v %v", got, err)
|
||||
}
|
||||
if got.Status != taskstate.Parked || got.ParkReason != "stopped by operator" {
|
||||
t.Fatalf("execution after cancel = %s (%q), want parked with the reason", got.Status, got.ParkReason)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancelExecutionWritesOneEventPerCancelledStep(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
stageID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep: %v", err)
|
||||
}
|
||||
if _, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt,
|
||||
ParentID: stageID, Kind: task.StepKindAgent, Name: "implement",
|
||||
}); err != nil {
|
||||
t.Fatalf("StartStep child: %v", err)
|
||||
}
|
||||
|
||||
if _, err := s.CancelExecution(t.Context(), execution.ID, "stopped by operator", taskstate.Parked); err != nil {
|
||||
t.Fatalf("CancelExecution: %v", err)
|
||||
}
|
||||
evs, err := s.TaskEvents(t.Context(), execution.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskEvents: %v", err)
|
||||
}
|
||||
var cancelled []events.Event
|
||||
for _, e := range evs {
|
||||
if e.Data["cancelled"] == true {
|
||||
cancelled = append(cancelled, e)
|
||||
}
|
||||
}
|
||||
if len(cancelled) != 2 {
|
||||
t.Fatalf("cancel events = %d, want one per step the transaction cancelled", len(cancelled))
|
||||
}
|
||||
for _, e := range cancelled {
|
||||
if e.Kind != events.KindStageFinish || e.Attempt != execution.Attempt {
|
||||
t.Errorf("cancel event = %+v, want a stage_finish row attributed to the attempt", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancelExecutionLeavesEarlierAttemptsAlone(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
firstAttempt := execution.Attempt
|
||||
stepID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: firstAttempt, Kind: task.StepKindStage, Name: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep: %v", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stepID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded,
|
||||
}); err != nil {
|
||||
t.Fatalf("FinishStep: %v", err)
|
||||
}
|
||||
// A retry requeues and reclaims: attempt 2.
|
||||
if err := s.Requeue(t.Context(), execution.ID, taskstate.Running, "implement"); err != nil {
|
||||
t.Fatalf("Requeue: %v", err)
|
||||
}
|
||||
retried, err := s.ClaimNext(t.Context())
|
||||
if err != nil || retried == nil {
|
||||
t.Fatalf("ClaimNext: %+v %v", retried, err)
|
||||
}
|
||||
|
||||
if _, err := s.CancelExecution(t.Context(), execution.ID, "stopped by operator", taskstate.Parked); err != nil {
|
||||
t.Fatalf("CancelExecution: %v", err)
|
||||
}
|
||||
var firstAttemptStatuses []string
|
||||
if err := s.pool.QueryRow(t.Context(),
|
||||
`SELECT jsonb_agg(status) FROM step_executions WHERE execution_id = $1 AND attempt = $2`,
|
||||
execution.ID, firstAttempt).Scan(&firstAttemptStatuses); err != nil {
|
||||
t.Fatalf("read first attempt's steps: %v", err)
|
||||
}
|
||||
for _, status := range firstAttemptStatuses {
|
||||
if status != string(taskstate.StepSucceeded) {
|
||||
t.Errorf("an earlier attempt's step was rewritten to %q; history is never rewritten", status)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancelExecutionRefusesWhatTheTableForbids(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
target string
|
||||
want error
|
||||
}{
|
||||
{name: "a terminal execution", target: taskstate.Queued, want: storecontract.ErrIllegalTransition},
|
||||
{name: "an unroutable destination", target: "quantum", want: storecontract.ErrIllegalTransition},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
if tt.name == "a terminal execution" {
|
||||
// completed is terminal: the table routes nothing out of it.
|
||||
if err := s.Transition(t.Context(), execution.ID, taskstate.Running, taskstate.Completed, "done"); err != nil {
|
||||
t.Fatalf("seed completed: %v", err)
|
||||
}
|
||||
}
|
||||
if _, err := s.CancelExecution(t.Context(), execution.ID, "why", tt.target); !errors.Is(err, tt.want) {
|
||||
t.Fatalf("CancelExecution(to=%q) = %v, want %v", tt.target, err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
// A queued execution cancels fine: the table routes queued -> closed_wont_do.
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
if err := s.Transition(t.Context(), execution.ID, taskstate.Running, taskstate.Queued, "requeue"); err != nil {
|
||||
t.Fatalf("seed queued: %v", err)
|
||||
}
|
||||
if _, err := s.CancelExecution(t.Context(), execution.ID, "cancelled by operator", taskstate.Declined); err != nil {
|
||||
t.Fatalf("CancelExecution(queued -> closed_wont_do) = %v, want nil", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancelExecutionOnAMissingExecutionIsStale(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
if _, err := s.CancelExecution(t.Context(), 999999, "why", taskstate.Parked); !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("CancelExecution on a missing execution = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
}
|
||||
|
||||
// RecoverStale is the crash-recovery half of
|
||||
// docs/prds/execution-tree-state-machine.md: requeueing a running execution
|
||||
// moves the steps its interrupted attempt left running to the table's
|
||||
// interrupted outcome, through the step transition table (the pair pinned in
|
||||
// SQL, like the execution's own edge), with one event row per step transition
|
||||
// and the execution's audit row in the same transaction. Killing the daemon
|
||||
// mid-stage and restarting leaves that stage interrupted and the execution
|
||||
// queued with a fresh attempt for the next run.
|
||||
func TestRecoverStaleInterruptsRunningSteps(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
stageID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep stage: %v", err)
|
||||
}
|
||||
childID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt,
|
||||
ParentID: stageID, Kind: task.StepKindAgent, Name: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep child: %v", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stageID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded, Detail: "done",
|
||||
}); err != nil {
|
||||
t.Fatalf("FinishStep: %v", err)
|
||||
}
|
||||
|
||||
requeued, err := s.RecoverStale(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("RecoverStale: %v", err)
|
||||
}
|
||||
if requeued != 1 {
|
||||
t.Fatalf("RecoverStale requeued %d, want the one running execution", requeued)
|
||||
}
|
||||
|
||||
got, err := s.TaskByID(t.Context(), execution.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID: %+v %v", got, err)
|
||||
}
|
||||
if got.Status != taskstate.Queued {
|
||||
t.Fatalf("execution after recovery = %q, want queued for the next attempt", got.Status)
|
||||
}
|
||||
|
||||
var statuses map[int64]string
|
||||
if err := s.pool.QueryRow(t.Context(),
|
||||
`SELECT jsonb_object_agg(id, status) FROM step_executions WHERE execution_id = $1`,
|
||||
execution.ID).Scan(&statuses); err != nil {
|
||||
t.Fatalf("read steps: %v", err)
|
||||
}
|
||||
if statuses[stageID] != string(taskstate.StepSucceeded) {
|
||||
t.Errorf("the finished step was rewritten to %q; recovery only interrupts", statuses[stageID])
|
||||
}
|
||||
if statuses[childID] != string(taskstate.StepInterrupted) {
|
||||
t.Errorf("the step the crash left running = %q, want interrupted", statuses[childID])
|
||||
}
|
||||
|
||||
evs, err := s.TaskEvents(t.Context(), execution.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskEvents: %v", err)
|
||||
}
|
||||
var interrupted []events.Event
|
||||
for _, e := range evs {
|
||||
if e.Data["interrupted"] == true {
|
||||
interrupted = append(interrupted, e)
|
||||
}
|
||||
}
|
||||
if len(interrupted) != 1 {
|
||||
t.Fatalf("interrupted step events = %d, want exactly one for the step transition", len(interrupted))
|
||||
}
|
||||
if interrupted[0].Kind != events.KindStageFinish || interrupted[0].Stage != "implement" ||
|
||||
interrupted[0].Attempt != got.Attempt {
|
||||
t.Errorf("interrupted event = %+v, want a stage_finish row attributed to the interrupted attempt", interrupted[0])
|
||||
}
|
||||
}
|
||||
|
||||
// A wait:true call step is how the store knows the caller is still waiting on
|
||||
// its callee: it closes only when the callee ends, so a non-terminal call
|
||||
// step is a callee the caller waits on. Cancelling the caller sweeps each
|
||||
// such callee through its own CancelExecution -- the callee's own lifecycle
|
||||
// -- while a finished call step's callee (wait:false, or already ended) runs
|
||||
// on. Trees never cross runs: a call step naming a task that is not the
|
||||
// caller's callee cannot even be recorded (StartStep verifies the callee's
|
||||
// call_parent_task_id).
|
||||
func TestCancelExecutionCancelsTheCalleesTheCallerWaitsOn(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
caller := runningExecution(t, s)
|
||||
|
||||
// The callee: started through the call linkage the way a wait:true step
|
||||
// does (the store derives the callee from the caller's own row), running
|
||||
// under its own lifecycle, with a running step of its own.
|
||||
callee, err := s.StartCall(t.Context(), caller.ID, "implement", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("EnqueueCallTask: %v", err)
|
||||
}
|
||||
if _, err := s.ClaimNext(t.Context()); err != nil {
|
||||
t.Fatalf("ClaimNext callee: %v", err)
|
||||
}
|
||||
// The claim increments the attempt; read the row back the way the
|
||||
// container's own request carries it.
|
||||
callee, err = s.TaskByID(t.Context(), callee.ID)
|
||||
if err != nil || callee == nil {
|
||||
t.Fatalf("TaskByID(callee): %+v %v", callee, err)
|
||||
}
|
||||
if _, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: callee.ID, Attempt: callee.Attempt, Kind: task.StepKindStage, Name: "implement",
|
||||
}); err != nil {
|
||||
t.Fatalf("callee StartStep: %v", err)
|
||||
}
|
||||
|
||||
// The caller's wait:true call step names the callee and is still running.
|
||||
if _, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: caller.ID, Attempt: caller.Attempt, Kind: task.StepKindCall,
|
||||
Name: "workflow.call", CalledExecutionID: callee.ID,
|
||||
}); err != nil {
|
||||
t.Fatalf("call step: %v", err)
|
||||
}
|
||||
|
||||
// A wait:false call step's callee runs on: its call step already ended.
|
||||
unwaited, err := s.StartCall(t.Context(), caller.ID, "implement", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.ClaimNext(t.Context()); err != nil {
|
||||
t.Fatalf("ClaimNext no-wait callee: %v", err)
|
||||
}
|
||||
noWaitStep, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: caller.ID, Attempt: caller.Attempt, Kind: task.StepKindCall,
|
||||
Name: "workflow.call", CalledExecutionID: unwaited.ID,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("no-wait call step: %v", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: noWaitStep, ExecutionID: caller.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded, Detail: "started; no wait",
|
||||
}); err != nil {
|
||||
t.Fatalf("close the no-wait call step: %v", err)
|
||||
}
|
||||
|
||||
if _, err := s.CancelExecution(t.Context(), caller.ID, "stopped by operator", taskstate.Parked); err != nil {
|
||||
t.Fatalf("CancelExecution: %v", err)
|
||||
}
|
||||
|
||||
waited, err := s.TaskByID(t.Context(), callee.ID)
|
||||
if err != nil || waited == nil {
|
||||
t.Fatalf("TaskByID(callee): %+v %v", waited, err)
|
||||
}
|
||||
if waited.Status != taskstate.Parked {
|
||||
t.Fatalf("the waited-on callee = %q, want parked under its own lifecycle", waited.Status)
|
||||
}
|
||||
waitedSteps, err := s.TaskEvents(t.Context(), callee.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("callee TaskEvents: %v", err)
|
||||
}
|
||||
if len(waitedSteps) == 0 {
|
||||
t.Error("the callee's steps were not cancelled with their events")
|
||||
}
|
||||
|
||||
unwaitedAfter, err := s.TaskByID(t.Context(), unwaited.ID)
|
||||
if err != nil || unwaitedAfter == nil {
|
||||
t.Fatalf("TaskByID no-wait callee: %+v %v", unwaitedAfter, err)
|
||||
}
|
||||
if unwaitedAfter.Status != taskstate.Running {
|
||||
t.Errorf("the wait:false callee = %q, want it running on", unwaitedAfter.Status)
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
// ClearTerminalTasks deletes exactly the statuses taskstate.Terminal names, so
|
||||
// the SQL list cannot fall behind a new terminal status.
|
||||
func TestClearTerminalTasksMatchesTaskstate(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
statuses := taskstate.Statuses()
|
||||
for i, meta := range statuses {
|
||||
if _, err := s.EnqueueIssue(t.Context(), "acme", "widgets", i+1, "t", "b", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.pool.Exec(t.Context(), "UPDATE tasks SET status = $1 WHERE issue_number = $2", meta.ID, i+1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.ClearTerminalTasks(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, meta := range statuses {
|
||||
task, err := s.TaskByIssue(t.Context(), "acme", "widgets", i+1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if kept := task != nil; kept == taskstate.Terminal(meta.ID) {
|
||||
t.Errorf("status %q: kept = %v, want kept only when not terminal", meta.ID, kept)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,166 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// eventTypeFixture saves a type on source matching events whose "kind" equals kind.
|
||||
func eventTypeFixture(t *testing.T, s *EDA, source, kind string) string {
|
||||
t.Helper()
|
||||
id, err := s.InsertEventType(t.Context(), eventtype.EventType{
|
||||
Source: source, Name: kind,
|
||||
Rule: eventtype.Rule{Payload: []eventtype.PayloadCondition{{Path: "kind", Op: eventtype.OpEquals, Value: kind}}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEventType() error = %v", err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func armedBinding(t *testing.T, s *EDA, source, mappingID string) string {
|
||||
t.Helper()
|
||||
id, err := s.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "n", Matcher: binding.Matcher{Source: source}, MappingID: mappingID, Workflow: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding() error = %v", err)
|
||||
}
|
||||
if err := s.ApproveBinding(t.Context(), id); err != nil {
|
||||
t.Fatalf("ApproveBinding() error = %v", err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func captureOf(t *testing.T, s *EDA, source, body string) string {
|
||||
t.Helper()
|
||||
id, err := s.InsertCapture(t.Context(), storecontract.CapturedEvent{Source: source, Body: body}, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("InsertCapture() error = %v", err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func undispatchedIDs(t *testing.T, s *EDA, source string) map[string]bool {
|
||||
t.Helper()
|
||||
list, err := s.ListUndispatchedCaptures(t.Context(), []string{source}, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListUndispatchedCaptures() error = %v", err)
|
||||
}
|
||||
out := map[string]bool{}
|
||||
for _, c := range list {
|
||||
out[c.ID] = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestSeveralArmedBindingsShareASource(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
a := armedBinding(t, s, "github", "")
|
||||
b := armedBinding(t, s, "github", "")
|
||||
armed, err := s.ArmedBindingsForSource(t.Context(), "github")
|
||||
if err != nil {
|
||||
t.Fatalf("ArmedBindingsForSource() error = %v", err)
|
||||
}
|
||||
got := map[string]bool{}
|
||||
for _, x := range armed {
|
||||
got[x.ID] = true
|
||||
}
|
||||
if !got[a] || !got[b] || len(armed) != 2 {
|
||||
t.Fatalf("armed = %v, want both %s and %s", got, a, b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMappingAndBindingRoundTripEventTypeAndFilter(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
typeID := eventTypeFixture(t, s, "github", "push")
|
||||
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m", EventTypeID: typeID})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
m, err := s.GetMapping(t.Context(), mid)
|
||||
if err != nil || m.EventTypeID != typeID {
|
||||
t.Fatalf("GetMapping() event type = %q (err %v), want %q", m.EventTypeID, err, typeID)
|
||||
}
|
||||
bid, err := s.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "n", Matcher: binding.Matcher{Source: "github"}, MappingID: mid, Workflow: "implement",
|
||||
Filter: `kind == "push"`,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding() error = %v", err)
|
||||
}
|
||||
b, err := s.GetBinding(t.Context(), bid)
|
||||
if err != nil || b.Filter != `kind == "push"` {
|
||||
t.Fatalf("GetBinding() filter = %q (err %v)", b.Filter, err)
|
||||
}
|
||||
b.Filter = ""
|
||||
if err := s.UpdateBinding(t.Context(), *b); err != nil {
|
||||
t.Fatalf("UpdateBinding() error = %v", err)
|
||||
}
|
||||
if b, _ = s.GetBinding(t.Context(), bid); b.Filter != "" {
|
||||
t.Fatalf("filter after clearing = %q, want empty", b.Filter)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMappingMatchCountRisesOncePerEvent(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m"})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
before := time.Now().Add(-time.Minute)
|
||||
for _, capture := range []string{"c1", "c2", "c1"} {
|
||||
if err := s.RecordMappingMatch(t.Context(), mid, capture); err != nil {
|
||||
t.Fatalf("RecordMappingMatch(%s) error = %v", capture, err)
|
||||
}
|
||||
}
|
||||
list, err := s.ListMappings(t.Context())
|
||||
if err != nil || len(list) != 1 {
|
||||
t.Fatalf("ListMappings() = %d (err %v)", len(list), err)
|
||||
}
|
||||
if list[0].MatchCount != 2 {
|
||||
t.Errorf("MatchCount = %d, want 2 (one per distinct event)", list[0].MatchCount)
|
||||
}
|
||||
if !list[0].LastMatchedAt.After(before) {
|
||||
t.Errorf("LastMatchedAt = %v, want a recent time", list[0].LastMatchedAt)
|
||||
}
|
||||
got, _ := s.GetMapping(t.Context(), mid)
|
||||
if got.MatchCount != 2 {
|
||||
t.Errorf("GetMapping MatchCount = %d, want 2", got.MatchCount)
|
||||
}
|
||||
}
|
||||
|
||||
// A capture stays undispatched until every armed binding for its event type
|
||||
// has dispatched it; a binding for another event type does not hold it.
|
||||
func TestUndispatchedIsPerBinding(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
push := eventTypeFixture(t, s, "github", "push")
|
||||
issue := eventTypeFixture(t, s, "github", "issue")
|
||||
pushMap, _ := s.InsertMapping(t.Context(), mapping.Mapping{Name: "p", EventTypeID: push})
|
||||
issueMap, _ := s.InsertMapping(t.Context(), mapping.Mapping{Name: "i", EventTypeID: issue})
|
||||
a := armedBinding(t, s, "github", pushMap)
|
||||
b := armedBinding(t, s, "github", pushMap)
|
||||
c := armedBinding(t, s, "github", issueMap)
|
||||
|
||||
capture := captureOf(t, s, "github", `{"kind":"push"}`)
|
||||
if !undispatchedIDs(t, s, "github")[capture] {
|
||||
t.Fatal("new push capture not listed")
|
||||
}
|
||||
if err := s.RecordDispatch(t.Context(), a, 1, capture, 1); err != nil {
|
||||
t.Fatalf("RecordDispatch(a) error = %v", err)
|
||||
}
|
||||
if !undispatchedIDs(t, s, "github")[capture] {
|
||||
t.Fatal("capture dropped after one of two push bindings dispatched it")
|
||||
}
|
||||
if err := s.RecordDispatch(t.Context(), b, 1, capture, 2); err != nil {
|
||||
t.Fatalf("RecordDispatch(b) error = %v", err)
|
||||
}
|
||||
if undispatchedIDs(t, s, "github")[capture] {
|
||||
t.Fatalf("capture still listed after both push bindings dispatched it (issue binding %s must not hold it)", c)
|
||||
}
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
func githubType(name, event string) eventtype.EventType {
|
||||
return eventtype.EventType{
|
||||
Source: "gh", Name: name,
|
||||
Rule: eventtype.Rule{Headers: []eventtype.HeaderCondition{{Name: "X-GitHub-Event", Value: event}}},
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventTypeSaveRefusals(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
pushID, err := s.InsertEventType(t.Context(), githubType("push", "push"))
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEventType(push) error = %v", err)
|
||||
}
|
||||
prID, err := s.InsertEventType(t.Context(), githubType("pr", "pull_request"))
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEventType(pr) error = %v", err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
save func() error
|
||||
wantErr error
|
||||
}{
|
||||
{"insert overlapping rule", func() error {
|
||||
_, err := s.InsertEventType(t.Context(), githubType("push-again", "push"))
|
||||
return err
|
||||
}, eventtype.ErrOverlap},
|
||||
{"insert catch-all beside typed", func() error {
|
||||
_, err := s.InsertEventType(t.Context(), eventtype.EventType{Source: "gh", Name: "all"})
|
||||
return err
|
||||
}, eventtype.ErrOverlap},
|
||||
{"insert duplicate name", func() error {
|
||||
_, err := s.InsertEventType(t.Context(), githubType("push", "issues"))
|
||||
return err
|
||||
}, eventtype.ErrInvalid},
|
||||
{"insert without name", func() error {
|
||||
_, err := s.InsertEventType(t.Context(), githubType("", "issues"))
|
||||
return err
|
||||
}, eventtype.ErrInvalid},
|
||||
{"update into overlap", func() error {
|
||||
pr := githubType("pr", "push")
|
||||
pr.ID = prID
|
||||
return s.UpdateEventType(t.Context(), pr)
|
||||
}, eventtype.ErrOverlap},
|
||||
{"update missing", func() error {
|
||||
missing := githubType("x", "x")
|
||||
missing.ID = "missing"
|
||||
return s.UpdateEventType(t.Context(), missing)
|
||||
}, storecontract.ErrEventTypeNotFound},
|
||||
{"delete missing", func() error { return s.DeleteEventType(t.Context(), "missing") }, storecontract.ErrEventTypeNotFound},
|
||||
{"other source is independent", func() error {
|
||||
_, err := s.InsertEventType(t.Context(), eventtype.EventType{Source: "fw", Name: "all"})
|
||||
return err
|
||||
}, nil},
|
||||
{"update keeps itself out of the overlap check", func() error {
|
||||
push := githubType("push-renamed", "push")
|
||||
push.ID = pushID
|
||||
return s.UpdateEventType(t.Context(), push)
|
||||
}, nil},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := tt.save()
|
||||
if tt.wantErr == nil && err != nil {
|
||||
t.Fatalf("error = %v, want nil", err)
|
||||
}
|
||||
if tt.wantErr != nil && !errors.Is(err, tt.wantErr) {
|
||||
t.Fatalf("error = %v, want %v", err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
types, err := s.ListEventTypes(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("ListEventTypes() error = %v", err)
|
||||
}
|
||||
names := map[string]bool{}
|
||||
for _, et := range types {
|
||||
names[et.Source+"/"+et.Name] = true
|
||||
}
|
||||
for _, want := range []string{"gh/push-renamed", "gh/pr", "fw/all"} {
|
||||
if !names[want] {
|
||||
t.Errorf("ListEventTypes() lacks %s: %v", want, names)
|
||||
}
|
||||
}
|
||||
if len(types) != 3 {
|
||||
t.Errorf("ListEventTypes() = %d types, want 3", len(types))
|
||||
}
|
||||
}
|
||||
|
||||
// A type made from a pasted payload has that payload's schema, and a later
|
||||
// matching capture is identified as it and becomes dispatchable; a capture
|
||||
// matching no type stays unidentified and is never listed for dispatch.
|
||||
func TestPastedTypeIdentifiesLaterCaptures(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
pasted := eventtype.Sample{
|
||||
Headers: map[string]string{"X-GitHub-Event": "pull_request"},
|
||||
Body: []byte(`{"action":"opened","number":1}`),
|
||||
}
|
||||
id, err := s.InsertEventType(t.Context(), eventtype.FromExample("gh", "pull_request", pasted))
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEventType() error = %v", err)
|
||||
}
|
||||
types, err := s.ListEventTypes(t.Context())
|
||||
if err != nil || len(types) != 1 {
|
||||
t.Fatalf("ListEventTypes() = %v (err %v)", types, err)
|
||||
}
|
||||
if got := types[0].Schema; got["action"] != eventtype.TypeString || got["number"] != eventtype.TypeNumber {
|
||||
t.Fatalf("schema = %v, want the pasted payload's", got)
|
||||
}
|
||||
|
||||
for _, c := range []storecontract.CapturedEvent{
|
||||
{Source: "gh", Headers: `{"X-Github-Event":["pull_request"]}`, Body: `{"action":"closed","number":9}`},
|
||||
{Source: "gh", Headers: `{"X-Github-Event":["push"]}`, Body: `{"ref":"main"}`},
|
||||
} {
|
||||
if _, err := s.InsertCapture(t.Context(), c, 0, 0); err != nil {
|
||||
t.Fatalf("InsertCapture() error = %v", err)
|
||||
}
|
||||
}
|
||||
all, err := s.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures() error = %v", err)
|
||||
}
|
||||
byBody := map[string]string{}
|
||||
for _, c := range all {
|
||||
byBody[c.Body] = c.EventType
|
||||
}
|
||||
if byBody[`{"action":"closed","number":9}`] != id {
|
||||
t.Errorf("matching capture event type = %q, want %q", byBody[`{"action":"closed","number":9}`], id)
|
||||
}
|
||||
if byBody[`{"ref":"main"}`] != "" {
|
||||
t.Errorf("unmatched capture event type = %q, want unidentified", byBody[`{"ref":"main"}`])
|
||||
}
|
||||
|
||||
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m", EventTypeID: id})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
armedBinding(t, s, "gh", mid)
|
||||
undispatched, err := s.ListUndispatchedCaptures(t.Context(), []string{"gh"}, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListUndispatchedCaptures() error = %v", err)
|
||||
}
|
||||
if len(undispatched) != 1 || undispatched[0].EventType != id {
|
||||
t.Fatalf("ListUndispatchedCaptures() = %+v, want only the identified capture", undispatched)
|
||||
}
|
||||
}
|
||||
@@ -1,213 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/bindingcipher"
|
||||
)
|
||||
|
||||
const edaTestKey = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
|
||||
|
||||
// edaFor builds an EDA store over a migrated database, with no cipher.
|
||||
func edaFor(t *testing.T) *EDA {
|
||||
t.Helper()
|
||||
pool, _ := migrated(t)
|
||||
return NewEDA(pool, nil)
|
||||
}
|
||||
|
||||
func edaWithCipher(t *testing.T, cipher bindingcipher.BindingCipher) (*pgxpool.Pool, *EDA) {
|
||||
t.Helper()
|
||||
pool, _ := migrated(t)
|
||||
return pool, NewEDA(pool, cipher)
|
||||
}
|
||||
|
||||
func insertBinding(t *testing.T, s *EDA, source string) string {
|
||||
t.Helper()
|
||||
id, err := s.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "n", Matcher: binding.Matcher{Source: source}, Workflow: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding() error = %v", err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Hazard 2: unique-violation detection must be by SQLSTATE, not by grepping
|
||||
// the driver's error text. A Postgres error whose message happens to contain
|
||||
// "unique" but whose SQLSTATE is not 23505 must not be treated as one, and a
|
||||
// 23505 with a message lacking those words must be detected.
|
||||
func TestIsUniqueViolationDetectsBySQLState(t *testing.T) {
|
||||
if !isUniqueViolation(&pgconn.PgError{Code: "23505", Message: "duplicate key value"}) {
|
||||
t.Error("SQLSTATE 23505 was not detected as a unique violation")
|
||||
}
|
||||
if isUniqueViolation(&pgconn.PgError{Code: "23502", Message: "null value in column of a unique constraint"}) {
|
||||
t.Error("a non-23505 error whose text says unique was treated as a unique violation; SQLSTATE is authoritative")
|
||||
}
|
||||
if isUniqueViolation(errors.New("not a database error")) {
|
||||
t.Error("a non-Postgres error was treated as a unique violation")
|
||||
}
|
||||
}
|
||||
|
||||
// Hazard 2 (integration): the dispatch ledger is at-most-once, refused by the
|
||||
// schema and surfaced as ErrAlreadyDispatched.
|
||||
func TestRecordDispatchIsIdempotent(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
if err := s.RecordDispatch(t.Context(), "b1", 1, "c1", 42); err != nil {
|
||||
t.Fatalf("first RecordDispatch() error = %v", err)
|
||||
}
|
||||
if err := s.RecordDispatch(t.Context(), "b1", 1, "c1", 99); !errors.Is(err, storecontract.ErrAlreadyDispatched) {
|
||||
t.Errorf("second RecordDispatch() error = %v, want ErrAlreadyDispatched", err)
|
||||
}
|
||||
}
|
||||
|
||||
// binding_version is stored but deliberately not part of the unique key: a
|
||||
// version bump does not permit re-dispatching the same (binding, capture).
|
||||
func TestBindingDispatchVersionBumpDoesNotPermitRedispatch(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
if err := s.RecordDispatch(t.Context(), "b1", 1, "c1", 42); err != nil {
|
||||
t.Fatalf("first RecordDispatch() error = %v", err)
|
||||
}
|
||||
if err := s.RecordDispatch(t.Context(), "b1", 2, "c1", 99); !errors.Is(err, storecontract.ErrAlreadyDispatched) {
|
||||
t.Errorf("redispatch with a version bump = %v, want ErrAlreadyDispatched: binding_version is not part of the key", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlaybookDispatchIsIdempotent(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
if err := s.RecordPlaybookDispatch(t.Context(), "p1", "v1", "e1", "a1"); err != nil {
|
||||
t.Fatalf("first RecordPlaybookDispatch() error = %v", err)
|
||||
}
|
||||
if err := s.RecordPlaybookDispatch(t.Context(), "p1", "v1", "e1", "a1"); !errors.Is(err, storecontract.ErrAlreadyDispatched) {
|
||||
t.Errorf("second RecordPlaybookDispatch() error = %v, want ErrAlreadyDispatched", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The lifecycle gate survives the port: pending_approval -> armed, and only
|
||||
// from pending_approval.
|
||||
func TestBindingLifecycle(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
id := insertBinding(t, s, "src-lifecycle")
|
||||
|
||||
if err := s.ApproveBinding(t.Context(), id); err != nil {
|
||||
t.Fatalf("ApproveBinding(pending_approval) error = %v", err)
|
||||
}
|
||||
if err := s.ApproveBinding(t.Context(), id); !errors.Is(err, storecontract.ErrBindingTransition) {
|
||||
t.Errorf("re-approving an armed binding = %v, want ErrBindingTransition", err)
|
||||
}
|
||||
armed, err := s.ArmedBindingsForSource(t.Context(), "src-lifecycle")
|
||||
if err != nil || len(armed) != 1 {
|
||||
t.Fatalf("ArmedBindingsForSource() = %d bindings (err %v), want 1", len(armed), err)
|
||||
}
|
||||
}
|
||||
|
||||
// A capture round-trips its payload verbatim.
|
||||
func TestCaptureRoundTrip(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
body := `{"action":"created"}`
|
||||
if _, err := s.InsertCapture(t.Context(), storecontract.CapturedEvent{
|
||||
Source: "sentry", Body: body, Headers: `{"X-Hook":"1"}`, ContentType: "application/json",
|
||||
}, 0, 0); err != nil {
|
||||
t.Fatalf("InsertCapture() error = %v", err)
|
||||
}
|
||||
list, err := s.ListCaptures(t.Context(), 10)
|
||||
if err != nil || len(list) != 1 {
|
||||
t.Fatalf("ListCaptures() = %d (err %v), want 1", len(list), err)
|
||||
}
|
||||
if list[0].Body != body {
|
||||
t.Errorf("Body round-trip = %q, want %q", list[0].Body, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMappingCRUD(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
id, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "payload-map"})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
got, err := s.GetMapping(t.Context(), id)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("GetMapping() = %v (err %v), want the mapping", got, err)
|
||||
}
|
||||
if got.Name != "payload-map" {
|
||||
t.Errorf("Name = %q, want payload-map", got.Name)
|
||||
}
|
||||
got.Name = "renamed"
|
||||
if err := s.UpdateMapping(t.Context(), *got); err != nil {
|
||||
t.Fatalf("UpdateMapping() error = %v", err)
|
||||
}
|
||||
if err := s.DeleteMapping(t.Context(), id); err != nil {
|
||||
t.Fatalf("DeleteMapping() error = %v", err)
|
||||
}
|
||||
if err := s.DeleteMapping(t.Context(), id); !errors.Is(err, storecontract.ErrMappingNotFound) {
|
||||
t.Errorf("DeleteMapping(absent) = %v, want ErrMappingNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The Notify callback is an injected seam, not a LISTEN/NOTIFY path: a store
|
||||
// wired with one fires a change event per successful bindings/mappings write,
|
||||
// and one wired with none is a silent no-op.
|
||||
func TestNotifyCallbackIsAnInjectedSeam(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
var got []events.Event
|
||||
s.SetNotify(func(e events.Event) { got = append(got, e) })
|
||||
|
||||
id, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "wired"})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("notified %d times, want 1", len(got))
|
||||
}
|
||||
if got[0].Data["id"] != id || got[0].Data["action"] != "create" {
|
||||
t.Errorf("event data = %+v, want id=%q action=create", got[0].Data, id)
|
||||
}
|
||||
|
||||
// A store composed without a notifier is a silent no-op.
|
||||
s.SetNotify(nil)
|
||||
if _, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "silent"}); err != nil {
|
||||
t.Fatalf("InsertMapping(nil notifier) error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// tool_calls is an append-only transcript with no unique index: repeated rows
|
||||
// are distinct entries, and one task's calls never surface in another's.
|
||||
func TestToolCallRoundTrip(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
at := time.Date(2026, 9, 23, 1, 2, 3, 0, time.UTC)
|
||||
|
||||
for range 2 {
|
||||
if err := s.InsertToolCall(t.Context(), ToolCall{
|
||||
TaskID: 42, Attempt: 2, Tool: "shell", Result: "all checks passed", CalledAt: at,
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertToolCall() error = %v", err)
|
||||
}
|
||||
}
|
||||
if err := s.InsertToolCall(t.Context(), ToolCall{
|
||||
TaskID: 7, Attempt: 1, Tool: "read_file", Error: "no such file", CalledAt: at.Add(time.Second),
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertToolCall(other task) error = %v", err)
|
||||
}
|
||||
|
||||
got, err := s.TaskToolCalls(t.Context(), 42)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskToolCalls() error = %v", err)
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("TaskToolCalls() returned %d rows, want 2 (the transcript is append-only)", len(got))
|
||||
}
|
||||
if got[0].Result != "all checks passed" || got[0].Error != "" {
|
||||
t.Errorf("first row result/error = %q/%q, want the summary with no error", got[0].Result, got[0].Error)
|
||||
}
|
||||
if got[0].CalledAt.IsZero() {
|
||||
t.Error("called_at did not round-trip")
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
||||
)
|
||||
|
||||
// TestEventInsertsCommitInIDOrder pins the event-append lock: an insert
|
||||
// waits while another transaction holds an uncommitted event, so a reader
|
||||
// paging by (at, id) never sees a later id commit before an earlier one.
|
||||
func TestEventInsertsCommitInIDOrder(t *testing.T) {
|
||||
pool, _ := migrated(t)
|
||||
st := New(pool)
|
||||
|
||||
tx, err := pool.Begin(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("Begin: %v", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(t.Context()) }()
|
||||
firstID, err := insertEventQ(t.Context(), postgresdb.New(tx), events.Event{Kind: "first"})
|
||||
if err != nil {
|
||||
t.Fatalf("insert in tx: %v", err)
|
||||
}
|
||||
|
||||
type result struct {
|
||||
id int64
|
||||
err error
|
||||
}
|
||||
done := make(chan result, 1)
|
||||
go func() {
|
||||
id, err := st.InsertEvent(t.Context(), events.Event{Kind: "second"})
|
||||
done <- result{id, err}
|
||||
}()
|
||||
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for {
|
||||
var waiting int
|
||||
if err := pool.QueryRow(t.Context(),
|
||||
"SELECT count(*) FROM pg_locks WHERE locktype = 'advisory' AND NOT granted").Scan(&waiting); err != nil {
|
||||
t.Fatalf("pg_locks: %v", err)
|
||||
}
|
||||
if waiting > 0 {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case r := <-done:
|
||||
t.Fatalf("second insert returned (id %d, err %v) while the first was uncommitted; want it to wait", r.id, r.err)
|
||||
default:
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("second insert never waited on the event-append lock")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
|
||||
if visible, err := st.EventsSince(t.Context(), "", 10); err != nil || len(visible) != 0 {
|
||||
t.Fatalf("EventsSince while the first insert is uncommitted = %d events, %v; want none", len(visible), err)
|
||||
}
|
||||
if err := tx.Commit(t.Context()); err != nil {
|
||||
t.Fatalf("Commit: %v", err)
|
||||
}
|
||||
r := <-done
|
||||
if r.err != nil {
|
||||
t.Fatalf("second insert: %v", r.err)
|
||||
}
|
||||
if r.id <= firstID {
|
||||
t.Fatalf("second id %d, want greater than first id %d", r.id, firstID)
|
||||
}
|
||||
all, err := st.EventsSince(t.Context(), "", 10)
|
||||
if err != nil {
|
||||
t.Fatalf("EventsSince: %v", err)
|
||||
}
|
||||
if len(all) != 2 || all[0].Kind != "first" || all[1].Kind != "second" {
|
||||
t.Fatalf("EventsSince after both commit = %+v, want first then second", all)
|
||||
}
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/harnesssecret"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/bindingcipher"
|
||||
)
|
||||
|
||||
func readRawHarnessSecret(t *testing.T, pool *pgxpool.Pool, org, service string) string {
|
||||
t.Helper()
|
||||
var stored string
|
||||
err := pool.QueryRow(t.Context(), "SELECT secret_enc FROM harness_secrets WHERE org = $1 AND service = $2", org, service).Scan(&stored)
|
||||
if err != nil {
|
||||
t.Fatalf("read raw harness secret: %v", err)
|
||||
}
|
||||
return stored
|
||||
}
|
||||
|
||||
// A stored OAuth token set is a cipher envelope on disk and reads back as
|
||||
// plaintext, and the column never holds the raw access or refresh token.
|
||||
func TestHarnessSecretRoundTripEncrypts(t *testing.T) {
|
||||
cipher, err := bindingcipher.NewBindingCipher(edaTestKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher() error = %v", err)
|
||||
}
|
||||
pool, s := edaWithCipher(t, cipher)
|
||||
in := harnesssecret.Secret{
|
||||
Org: "org-1", Service: "claude-code",
|
||||
AccessToken: "at-0123456789abcdef", RefreshToken: "rt-0123456789abcdef",
|
||||
TokenType: "Bearer", ExpiresAt: time.Now().Add(time.Hour).UTC().Truncate(time.Second),
|
||||
Scopes: []string{"user:inference", "user:profile"},
|
||||
}
|
||||
if err := s.PutHarnessSecret(t.Context(), in); err != nil {
|
||||
t.Fatalf("PutHarnessSecret() error = %v", err)
|
||||
}
|
||||
raw := readRawHarnessSecret(t, pool, in.Org, in.Service)
|
||||
if raw == "" {
|
||||
t.Fatal("stored secret is empty")
|
||||
}
|
||||
for _, want := range []string{in.AccessToken, in.RefreshToken} {
|
||||
if strings.Contains(raw, want) {
|
||||
t.Fatalf("stored column contains a real token: %q", raw)
|
||||
}
|
||||
}
|
||||
got, err := s.GetHarnessSecret(t.Context(), in.Org, in.Service)
|
||||
if err != nil {
|
||||
t.Fatalf("GetHarnessSecret() error = %v", err)
|
||||
}
|
||||
if got.AccessToken != in.AccessToken || got.RefreshToken != in.RefreshToken ||
|
||||
got.TokenType != in.TokenType || !got.ExpiresAt.Equal(in.ExpiresAt) ||
|
||||
!slices.Equal(got.Scopes, in.Scopes) {
|
||||
t.Fatalf("GetHarnessSecret() = %+v, want %+v", got, in)
|
||||
}
|
||||
}
|
||||
|
||||
// A refresh (a second Put for the same org/service) overwrites the row
|
||||
// rather than accumulating one per token: exactly the upsert semantics the
|
||||
// egress proxy's every refresh depends on.
|
||||
func TestHarnessSecretPutOverwritesOnRefresh(t *testing.T) {
|
||||
cipher, err := bindingcipher.NewBindingCipher(edaTestKey, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, s := edaWithCipher(t, cipher)
|
||||
org, service := "org-1", "claude-code"
|
||||
first := harnesssecret.Secret{Org: org, Service: service, AccessToken: "at-first", RefreshToken: "rt-first"}
|
||||
if err := s.PutHarnessSecret(t.Context(), first); err != nil {
|
||||
t.Fatalf("PutHarnessSecret(first) error = %v", err)
|
||||
}
|
||||
second := harnesssecret.Secret{Org: org, Service: service, AccessToken: "at-second", RefreshToken: "rt-second"}
|
||||
if err := s.PutHarnessSecret(t.Context(), second); err != nil {
|
||||
t.Fatalf("PutHarnessSecret(second) error = %v", err)
|
||||
}
|
||||
got, err := s.GetHarnessSecret(t.Context(), org, service)
|
||||
if err != nil {
|
||||
t.Fatalf("GetHarnessSecret() error = %v", err)
|
||||
}
|
||||
if got.AccessToken != second.AccessToken {
|
||||
t.Fatalf("AccessToken = %q, want the refreshed value %q", got.AccessToken, second.AccessToken)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHarnessSecretNotFound(t *testing.T) {
|
||||
_, s := edaWithCipher(t, nil)
|
||||
_, err := s.GetHarnessSecret(t.Context(), "org-1", "no-such-service")
|
||||
if !errors.Is(err, storecontract.ErrHarnessSecretNotFound) {
|
||||
t.Fatalf("GetHarnessSecret() error = %v, want ErrHarnessSecretNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHarnessSecretPutRejectsIncomplete(t *testing.T) {
|
||||
_, s := edaWithCipher(t, nil)
|
||||
if err := s.PutHarnessSecret(t.Context(), harnesssecret.Secret{Org: "org-1"}); err == nil {
|
||||
t.Fatal("PutHarnessSecret() with no service or access token succeeded, want error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHarnessSecretRequiresEncryption(t *testing.T) {
|
||||
pool, store := edaWithCipher(t, nil)
|
||||
err := store.PutHarnessSecret(t.Context(), harnesssecret.Secret{Org: "org", Service: "service", AccessToken: "access"})
|
||||
if err == nil {
|
||||
t.Fatal("OAuth token stored without an encryption key")
|
||||
}
|
||||
var count int
|
||||
if err := pool.QueryRow(t.Context(), "SELECT count(*) FROM harness_secrets").Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Fatalf("stored %d rows without encryption", count)
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storepkg"
|
||||
)
|
||||
|
||||
func TestInstalledPackagesOrgPinsAndDependencies(t *testing.T) {
|
||||
pool, _ := migrated(t)
|
||||
s := NewInstalledPackages(pool)
|
||||
ctx := t.Context()
|
||||
const digest = "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||
base := storepkg.Descriptor{
|
||||
APIVersion: storepkg.APIVersion, DisplayName: "Kit", Version: "1",
|
||||
Contributes: storepkg.Contributions{Skills: []string{"skill"}},
|
||||
}
|
||||
kit := storepkg.Installed{OrgID: "org-a", Name: "kit", Reference: "localhost:5000/kit", Digest: digest, Descriptor: base, Layer: []byte("kit"), UpdatePolicy: "manual"}
|
||||
review := storepkg.Installed{OrgID: "org-a", Name: "review", Reference: "localhost:5000/review", Digest: digest, Descriptor: base, Layer: []byte("review"), UpdatePolicy: "manual"}
|
||||
review.Descriptor.Requires = []storepkg.PackageRef{{Name: "kit", Digest: digest}}
|
||||
|
||||
if err := s.Install(ctx, review); !errors.Is(err, storepkg.ErrNotFound) {
|
||||
t.Fatalf("missing dependency: %v", err)
|
||||
}
|
||||
if err := s.Install(ctx, kit); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Install(ctx, review); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Install(ctx, review); !errors.Is(err, storepkg.ErrInstalled) {
|
||||
t.Fatalf("duplicate install: %v", err)
|
||||
}
|
||||
if _, err := s.Get(ctx, "org-b", "kit"); !errors.Is(err, storepkg.ErrNotFound) {
|
||||
t.Fatalf("cross-org get: %v", err)
|
||||
}
|
||||
if list, err := s.List(ctx, "org-b"); err != nil || len(list) != 0 {
|
||||
t.Fatalf("cross-org list: %v, %v", list, err)
|
||||
}
|
||||
if err := s.Remove(ctx, "org-a", "kit"); !errors.Is(err, storepkg.ErrRequired) {
|
||||
t.Fatalf("remove required package: %v", err)
|
||||
}
|
||||
if err := s.Remove(ctx, "org-a", "review"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Remove(ctx, "org-a", "kit"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Remove(ctx, "org-a", "kit"); !errors.Is(err, storepkg.ErrNotFound) {
|
||||
t.Fatalf("remove missing: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1,302 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestLibpqTargetKeepsThePasswordOffTheCommandLine(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
url string
|
||||
wantDB string
|
||||
wantEnv []string
|
||||
leakFree string
|
||||
}{
|
||||
{
|
||||
name: "url with password",
|
||||
url: "postgres://archie:s3cret@db.example:5432/archie?sslmode=require",
|
||||
wantDB: "postgres://archie@db.example:5432/archie?sslmode=require",
|
||||
wantEnv: []string{"PGPASSWORD=s3cret"},
|
||||
leakFree: "s3cret",
|
||||
},
|
||||
{
|
||||
name: "url without password",
|
||||
url: "postgresql://archie@db.example/archie",
|
||||
wantDB: "postgresql://archie@db.example/archie",
|
||||
},
|
||||
{
|
||||
name: "key value connection string passes through",
|
||||
url: "host=db.example dbname=archie",
|
||||
wantDB: "host=db.example dbname=archie",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
db, env := libpqTarget(tt.url)
|
||||
if db != tt.wantDB {
|
||||
t.Errorf("dbname = %q, want %q", db, tt.wantDB)
|
||||
}
|
||||
if !slices.Equal(env, tt.wantEnv) {
|
||||
t.Errorf("env = %q, want %q", env, tt.wantEnv)
|
||||
}
|
||||
if tt.leakFree != "" && strings.Contains(db, tt.leakFree) {
|
||||
t.Errorf("dbname %q carries the password", db)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolArguments(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
got []string
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "dump is a whole-database custom-format archive",
|
||||
got: dumpArgs("postgres://h/db", "/tmp/out.dump"),
|
||||
want: []string{"--format=custom", "--no-password", "--file=/tmp/out.dump", "--dbname=postgres://h/db"},
|
||||
},
|
||||
{
|
||||
name: "restore cleans, stops on the first error and is atomic",
|
||||
got: restoreArgs("postgres://h/db", "/tmp/in.dump"),
|
||||
want: []string{"--clean", "--if-exists", "--single-transaction", "--exit-on-error", "--no-owner", "--no-password", "--dbname=postgres://h/db", "/tmp/in.dump"},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if !slices.Equal(tt.got, tt.want) {
|
||||
t.Errorf("args = %q, want %q", tt.got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotTablesReadsTheArchiveList(t *testing.T) {
|
||||
list := `;
|
||||
; Archive created at 2026-09-24 10:00:00 UTC
|
||||
;
|
||||
215; 1259 16390 TABLE public tasks archie
|
||||
216; 1259 16391 SEQUENCE public tasks_id_seq archie
|
||||
3401; 0 16390 TABLE DATA public tasks archie
|
||||
217; 1259 16400 TABLE public goose_db_version archie
|
||||
`
|
||||
got := snapshotTables(list)
|
||||
want := []string{"public.goose_db_version", "public.tasks"}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("snapshotTables = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func requireTools(t *testing.T) {
|
||||
t.Helper()
|
||||
for _, tool := range []string{"pg_dump", "pg_restore"} {
|
||||
if _, err := exec.LookPath(tool); err != nil {
|
||||
t.Skipf("%s is not on PATH; the integration test needs the PostgreSQL 18 client tools", tool)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// migratedURL is a migrated database and a pool on it.
|
||||
func migratedURL(t *testing.T) (string, *pgxpool.Pool) {
|
||||
t.Helper()
|
||||
url := pgtest.URL(t)
|
||||
pool := openPool(t, url)
|
||||
if err := Migrate(t.Context(), pool, Migrations()); err != nil {
|
||||
t.Fatalf("Migrate: %v", err)
|
||||
}
|
||||
return url, pool
|
||||
}
|
||||
|
||||
func titles(t *testing.T, pool *pgxpool.Pool) []string {
|
||||
t.Helper()
|
||||
rows, err := pool.Query(t.Context(), "SELECT title FROM tasks ORDER BY id")
|
||||
if err != nil {
|
||||
t.Fatalf("list tasks: %v", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []string
|
||||
for rows.Next() {
|
||||
var title string
|
||||
if err := rows.Scan(&title); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out = append(out, title)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func enqueue(t *testing.T, pool *pgxpool.Pool, title string) {
|
||||
t.Helper()
|
||||
if _, err := New(pool).EnqueueChatTask(t.Context(), "acme", "widget", title, "body", "implement", "", nil); err != nil {
|
||||
t.Fatalf("enqueue %q: %v", title, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A restore after a forward migration is the case restore exists for: the
|
||||
// tables the later migration added are not in the snapshot, so --clean alone
|
||||
// would leave them behind for the next upgrade to trip over.
|
||||
func TestBackupThenRestoreReturnsTheDatabaseToTheSnapshot(t *testing.T) {
|
||||
requireTools(t)
|
||||
url, pool := migratedURL(t)
|
||||
enqueue(t, pool, "before")
|
||||
before, err := SchemaVersion(t.Context(), pool)
|
||||
if err != nil {
|
||||
t.Fatalf("SchemaVersion: %v", err)
|
||||
}
|
||||
snapshot := filepath.Join(t.TempDir(), "snapshot.dump")
|
||||
if err := Backup(t.Context(), url, snapshot); err != nil {
|
||||
t.Fatalf("Backup: %v", err)
|
||||
}
|
||||
if leftovers, _ := filepath.Glob(snapshot + ".tmp*"); len(leftovers) != 0 {
|
||||
t.Errorf("backup left scratch files: %v", leftovers)
|
||||
}
|
||||
|
||||
enqueue(t, pool, "after")
|
||||
if _, err := pool.Exec(t.Context(), "CREATE TABLE later_migration (id bigint)"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(t.Context(), "INSERT INTO goose_db_version (version_id, is_applied) VALUES ($1, true)", before+1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := Restore(t.Context(), url, snapshot); err != nil {
|
||||
t.Fatalf("Restore: %v", err)
|
||||
}
|
||||
if got := titles(t, pool); !slices.Equal(got, []string{"before"}) {
|
||||
t.Errorf("tasks after restore = %q, want only the snapshot's", got)
|
||||
}
|
||||
var extra bool
|
||||
if err := pool.QueryRow(t.Context(), "SELECT to_regclass('public.later_migration') IS NOT NULL").Scan(&extra); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if extra {
|
||||
t.Error("restore left a table the snapshot does not contain")
|
||||
}
|
||||
if after, err := SchemaVersion(t.Context(), pool); err != nil || after != before {
|
||||
t.Errorf("schema version after restore = %d, %v; want %d", after, err, before)
|
||||
}
|
||||
enqueue(t, pool, "writable")
|
||||
}
|
||||
|
||||
func TestRestoreRefusesWhileAnyServiceIsServing(t *testing.T) {
|
||||
requireTools(t)
|
||||
for _, owner := range ServiceOwners {
|
||||
t.Run(owner, func(t *testing.T) {
|
||||
url, pool := migratedURL(t)
|
||||
enqueue(t, pool, "snapshot")
|
||||
snapshot := filepath.Join(t.TempDir(), "snapshot.dump")
|
||||
if err := Backup(t.Context(), url, snapshot); err != nil {
|
||||
t.Fatalf("Backup: %v", err)
|
||||
}
|
||||
enqueue(t, pool, "live")
|
||||
claimOther(t, url, owner, false, false)
|
||||
|
||||
err := Restore(t.Context(), url, snapshot)
|
||||
if !errors.Is(err, ErrOwned) {
|
||||
t.Fatalf("Restore with %s serving = %v, want ErrOwned", owner, err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), owner) {
|
||||
t.Errorf("refusal must name the serving role %q: %v", owner, err)
|
||||
}
|
||||
if got := titles(t, pool); !slices.Equal(got, []string{"snapshot", "live"}) {
|
||||
t.Errorf("refused restore changed the database: %q", got)
|
||||
}
|
||||
// Every claim the refused restore took is dropped again.
|
||||
for _, other := range ServiceOwners {
|
||||
if other == owner {
|
||||
continue
|
||||
}
|
||||
claim, err := AcquireOwnership(t.Context(), pool, other)
|
||||
if err != nil {
|
||||
t.Fatalf("%s still held after a refused restore: %v", other, err)
|
||||
}
|
||||
_ = claim.Release(t.Context())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreRefusesWhatItCannotCheck(t *testing.T) {
|
||||
requireTools(t)
|
||||
url, pool := migratedURL(t)
|
||||
snapshot := filepath.Join(t.TempDir(), "snapshot.dump")
|
||||
if err := Backup(t.Context(), url, snapshot); err != nil {
|
||||
t.Fatalf("Backup: %v", err)
|
||||
}
|
||||
notASnapshot := filepath.Join(t.TempDir(), "garbage.dump")
|
||||
if err := os.WriteFile(notASnapshot, []byte("not an archive"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
enqueue(t, pool, "live")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
url string
|
||||
from string
|
||||
}{
|
||||
{name: "unreachable server", url: "postgres://archie:archie@127.0.0.1:1/none?connect_timeout=2", from: snapshot},
|
||||
{name: "not a snapshot", url: url, from: notASnapshot},
|
||||
{name: "missing snapshot", url: url, from: filepath.Join(t.TempDir(), "absent.dump")},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if err := Restore(t.Context(), tt.url, tt.from); err == nil {
|
||||
t.Fatal("Restore succeeded, want refusal")
|
||||
}
|
||||
if got := titles(t, pool); !slices.Equal(got, []string{"live"}) {
|
||||
t.Errorf("refused restore changed the database: %q", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackupFailureKeepsThePreviousSnapshot(t *testing.T) {
|
||||
requireTools(t)
|
||||
out := filepath.Join(t.TempDir(), "snapshot.dump")
|
||||
if err := os.WriteFile(out, []byte("good snapshot"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := Backup(t.Context(), "postgres://archie:archie@127.0.0.1:1/none?connect_timeout=2", out); err == nil {
|
||||
t.Fatal("Backup of an unreachable database succeeded")
|
||||
}
|
||||
if data, _ := os.ReadFile(out); string(data) != "good snapshot" {
|
||||
t.Errorf("failed backup replaced the previous snapshot: %q", data)
|
||||
}
|
||||
if leftovers, _ := filepath.Glob(out + ".tmp*"); len(leftovers) != 0 {
|
||||
t.Errorf("failed backup left scratch files: %v", leftovers)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckSchemaVersion(t *testing.T) {
|
||||
supported := SupportedSchemaVersion()
|
||||
if supported < 4 {
|
||||
t.Fatalf("SupportedSchemaVersion = %d, want the highest embedded migration", supported)
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
version int64
|
||||
wantErr error
|
||||
}{
|
||||
{name: "current", version: supported},
|
||||
{name: "older is upgradable", version: 1},
|
||||
{name: "newer than this binary", version: supported + 1, wantErr: ErrSchemaTooNew},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if err := CheckSchemaVersion(tt.version); !errors.Is(err, tt.wantErr) {
|
||||
t.Fatalf("CheckSchemaVersion(%d) = %v, want %v", tt.version, err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func storeFor(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
pool := openPool(t, pgtest.URL(t))
|
||||
if err := Migrate(t.Context(), pool, Migrations()); err != nil {
|
||||
t.Fatalf("Migrate: %v", err)
|
||||
}
|
||||
return New(pool)
|
||||
}
|
||||
|
||||
// runningTask enqueues one issue and claims it, the state every park starts in.
|
||||
func runningTask(t *testing.T, s *Store) *workflow.Task {
|
||||
t.Helper()
|
||||
if _, err := s.EnqueueIssue(t.Context(), "acme", "widgets", 1, "t", "b", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := s.ClaimNext(t.Context())
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("ClaimNext = %v, %v", task, err)
|
||||
}
|
||||
return task
|
||||
}
|
||||
|
||||
type transitionRow struct{ from, to, detail string }
|
||||
|
||||
func transitions(t *testing.T, s *Store, taskID int64) []transitionRow {
|
||||
t.Helper()
|
||||
rows, err := s.pool.Query(t.Context(), "SELECT from_status, to_status, detail FROM transitions WHERE task_id = $1 ORDER BY id", taskID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []transitionRow
|
||||
for rows.Next() {
|
||||
var r transitionRow
|
||||
if err := rows.Scan(&r.from, &r.to, &r.detail); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Every free-text column the SQLite store clipped to 4000 bytes on a rune
|
||||
// boundary is clipped the same way here. The oversized value ends in a
|
||||
// multi-byte rune straddling the limit, so a byte cut would store invalid
|
||||
// UTF-8 and a missing clip would store all of it.
|
||||
func TestWritesClipFreeTextTo4000Bytes(t *testing.T) {
|
||||
oversized := strings.Repeat("x", 3999) + "é" + strings.Repeat("y", 1000)
|
||||
want := strings.Repeat("x", 3999)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
write func(t *testing.T, s *Store) string
|
||||
}{
|
||||
{name: "transition to parked: park reason and transition detail", write: func(t *testing.T, s *Store) string {
|
||||
task := runningTask(t, s)
|
||||
if err := s.Transition(t.Context(), task.ID, workflow.StatusRunning, workflow.StatusParked, oversized); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows := transitions(t, s, task.ID)
|
||||
if len(rows) == 0 || rows[len(rows)-1].detail != want {
|
||||
t.Errorf("transition detail not clipped: %d rows", len(rows))
|
||||
}
|
||||
got, _ := s.TaskByID(t.Context(), task.ID)
|
||||
return got.ParkReason
|
||||
}},
|
||||
{name: "park task: park reason and transition detail", write: func(t *testing.T, s *Store) string {
|
||||
task := runningTask(t, s)
|
||||
if err := s.ParkTask(t.Context(), task.ID, workflow.StatusRunning, oversized, "transient"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows := transitions(t, s, task.ID)
|
||||
if len(rows) == 0 || rows[len(rows)-1].detail != want {
|
||||
t.Errorf("transition detail not clipped: %d rows", len(rows))
|
||||
}
|
||||
got, _ := s.TaskByID(t.Context(), task.ID)
|
||||
return got.ParkReason
|
||||
}},
|
||||
{name: "update: park reason", write: func(t *testing.T, s *Store) string {
|
||||
task := runningTask(t, s)
|
||||
task.ParkReason = oversized
|
||||
if err := s.Update(t.Context(), task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ := s.TaskByID(t.Context(), task.ID)
|
||||
return got.ParkReason
|
||||
}},
|
||||
{name: "begin remediation: review payload", write: func(t *testing.T, s *Store) string {
|
||||
task := runningTask(t, s)
|
||||
if err := s.Transition(t.Context(), task.ID, workflow.StatusRunning, workflow.StatusPROpen, "pr"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.BeginRemediation(t.Context(), task.ID, oversized); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ := s.TaskByID(t.Context(), task.ID)
|
||||
return got.ReviewPayload
|
||||
}},
|
||||
{name: "update review payload", write: func(t *testing.T, s *Store) string {
|
||||
task := runningTask(t, s)
|
||||
if err := s.Transition(t.Context(), task.ID, workflow.StatusRunning, workflow.StatusPROpen, "pr"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.BeginRemediation(t.Context(), task.ID, "first"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.UpdateReviewPayload(t.Context(), task.ID, oversized); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ := s.TaskByID(t.Context(), task.ID)
|
||||
return got.ReviewPayload
|
||||
}},
|
||||
{name: "event detail", write: func(t *testing.T, s *Store) string {
|
||||
if _, err := s.InsertEvent(t.Context(), events.Event{Kind: events.KindLog, Detail: oversized}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := s.EventsSince(t.Context(), "", 1)
|
||||
if err != nil || len(got) != 1 {
|
||||
t.Fatalf("EventsSince = %d, %v", len(got), err)
|
||||
}
|
||||
return got[0].Detail
|
||||
}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := tt.write(t, storeFor(t))
|
||||
if got != want || !utf8.ValidString(got) {
|
||||
t.Errorf("stored %d bytes (valid UTF-8 %v), want the %d-byte rune-boundary clip", len(got), utf8.ValidString(got), len(want))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParkClassNormalisation(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
park func(ctx context.Context, s *Store, id int64) error
|
||||
want string
|
||||
}{
|
||||
{name: "generic transition to parked is needs_human", want: "needs_human", park: func(ctx context.Context, s *Store, id int64) error {
|
||||
return s.Transition(ctx, id, workflow.StatusRunning, workflow.StatusParked, "gate failed")
|
||||
}},
|
||||
{name: "known class is kept", want: "transient", park: func(ctx context.Context, s *Store, id int64) error {
|
||||
return s.ParkTask(ctx, id, workflow.StatusRunning, "container acquire failed", "transient")
|
||||
}},
|
||||
{name: "unknown class falls back to needs_human", want: "needs_human", park: func(ctx context.Context, s *Store, id int64) error {
|
||||
return s.ParkTask(ctx, id, workflow.StatusRunning, "x", "urgent")
|
||||
}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
task := runningTask(t, s)
|
||||
if err := tt.park(t.Context(), s, task.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ := s.TaskByID(t.Context(), task.ID)
|
||||
if got.Status != workflow.StatusParked || got.ParkClass != tt.want {
|
||||
t.Fatalf("status %q class %q, want parked %q", got.Status, got.ParkClass, tt.want)
|
||||
}
|
||||
// Requeue clears class and reason together: a stale class on a
|
||||
// queued task would group a live task with parked ones.
|
||||
if err := s.Requeue(t.Context(), task.ID, workflow.StatusParked, "implement"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ = s.TaskByID(t.Context(), task.ID)
|
||||
if got.ParkClass != "needs_human" || got.ParkReason != "" {
|
||||
t.Errorf("after requeue: class %q reason %q, want cleared", got.ParkClass, got.ParkReason)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A transition that leaves parked alone keeps the previous park fields, and
|
||||
// every guarded write leaves exactly one audit row in order.
|
||||
func TestTransitionsRecordEachMoveInOrder(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
task := runningTask(t, s)
|
||||
ctx := t.Context()
|
||||
if err := s.ParkTask(ctx, task.ID, workflow.StatusRunning, "why", "transient"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Requeue(ctx, task.ID, workflow.StatusParked, "implement"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A stale transition writes no audit row.
|
||||
if err := s.Transition(ctx, task.ID, workflow.StatusRunning, workflow.StatusPROpen, "stale"); err == nil {
|
||||
t.Fatal("stale Transition succeeded")
|
||||
}
|
||||
got := transitions(t, s, task.ID)
|
||||
want := []transitionRow{
|
||||
{workflow.StatusRunning, workflow.StatusParked, "why"},
|
||||
{workflow.StatusParked, workflow.StatusQueued, "requeued implement"},
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("transitions = %+v, want %+v", got, want)
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Errorf("transition %d = %+v, want %+v", i, got[i], want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
)
|
||||
|
||||
// newStoreForOrg is a migrated pool with the Store built over it.
|
||||
func newStoreForOrg(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
pool, _ := migrated(t)
|
||||
return New(pool)
|
||||
}
|
||||
|
||||
// seedAgent inserts one bot identity to assign.
|
||||
func seedAgent(t *testing.T, s *Store, name string) identity.Identity {
|
||||
t.Helper()
|
||||
value, err := identity.New(identity.StableID(name), identity.KindBot, name)
|
||||
if err != nil {
|
||||
t.Fatalf("identity.New(%s): %v", name, err)
|
||||
}
|
||||
created, err := s.Create(t.Context(), value, identity.Audit{
|
||||
ActorID: identity.SystemID, Source: "test", RequestID: "seed:" + name,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Create identity %s: %v", name, err)
|
||||
}
|
||||
return created
|
||||
}
|
||||
|
||||
func TestOrgRepository(t *testing.T) {
|
||||
s := newStoreForOrg(t)
|
||||
ctx := t.Context()
|
||||
|
||||
if _, err := s.CreateOrg(ctx, org.Org{ID: "soc", Name: "SOC"}); err != nil {
|
||||
t.Fatalf("CreateOrg: %v", err)
|
||||
}
|
||||
if _, err := s.CreateOrg(ctx, org.Org{ID: "soc", Name: "dup"}); !errors.Is(err, org.ErrOrgExists) {
|
||||
t.Fatalf("duplicate CreateOrg = %v, want ErrOrgExists", err)
|
||||
}
|
||||
if _, err := s.CreateOrg(ctx, org.Org{ID: "bad", Name: " "}); !errors.Is(err, org.ErrInvalidOrg) {
|
||||
t.Fatalf("blank-name CreateOrg = %v, want ErrInvalidOrg", err)
|
||||
}
|
||||
got, err := s.GetOrg(ctx, "soc")
|
||||
if err != nil {
|
||||
t.Fatalf("GetOrg: %v", err)
|
||||
}
|
||||
if got.Name != "SOC" {
|
||||
t.Fatalf("GetOrg = %+v, want name SOC", got)
|
||||
}
|
||||
if _, err := s.GetOrg(ctx, "missing"); !errors.Is(err, org.ErrOrgNotFound) {
|
||||
t.Fatalf("GetOrg(missing) = %v, want ErrOrgNotFound", err)
|
||||
}
|
||||
|
||||
ws, err := s.CreateWorkspace(ctx, org.Workspace{ID: "net", OrgID: "soc", Name: "networking-prd", Environment: "production"})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateWorkspace: %v", err)
|
||||
}
|
||||
if _, err := s.CreateWorkspace(ctx, ws); !errors.Is(err, org.ErrWorkspaceExists) {
|
||||
t.Fatalf("duplicate CreateWorkspace = %v, want ErrWorkspaceExists", err)
|
||||
}
|
||||
if _, err := s.CreateWorkspace(ctx, org.Workspace{ID: "x", OrgID: "missing", Name: "x"}); !errors.Is(err, org.ErrOrgNotFound) {
|
||||
t.Fatalf("CreateWorkspace(unknown org) = %v, want ErrOrgNotFound", err)
|
||||
}
|
||||
workspaces, err := s.ListWorkspaces(ctx, "soc")
|
||||
if err != nil || len(workspaces) != 1 || workspaces[0].ID != "net" {
|
||||
t.Fatalf("ListWorkspaces = %+v, %v; want one net", workspaces, err)
|
||||
}
|
||||
|
||||
member := seedAgent(t, s, "responder")
|
||||
if err := s.EnsureMembership(ctx, org.Membership{IdentityID: member.ID, OrgID: "soc", Role: org.RoleOwner}); err != nil {
|
||||
t.Fatalf("EnsureMembership: %v", err)
|
||||
}
|
||||
if err := s.EnsureMembership(ctx, org.Membership{IdentityID: member.ID, OrgID: "soc", Role: org.RoleOwner}); err != nil {
|
||||
t.Fatalf("repeated EnsureMembership: %v", err)
|
||||
}
|
||||
if err := s.EnsureMembership(ctx, org.Membership{OrgID: "soc", Role: org.RoleOwner}); !errors.Is(err, org.ErrInvalidMembership) {
|
||||
t.Fatalf("EnsureMembership(no identity) = %v, want ErrInvalidMembership", err)
|
||||
}
|
||||
missing := seedAgent(t, s, "ghost")
|
||||
if err := s.EnsureMembership(ctx, org.Membership{IdentityID: missing.ID, OrgID: "missing", Role: org.RoleOwner}); !errors.Is(err, org.ErrOrgNotFound) {
|
||||
t.Fatalf("EnsureMembership(unknown org) = %v, want ErrOrgNotFound", err)
|
||||
}
|
||||
|
||||
agent := seedAgent(t, s, "archie")
|
||||
if err := s.AssignAgent(ctx, org.AgentAssignment{IdentityID: agent.ID, OrgID: "soc"}); err != nil {
|
||||
t.Fatalf("AssignAgent: %v", err)
|
||||
}
|
||||
if err := s.AssignAgent(ctx, org.AgentAssignment{IdentityID: agent.ID, OrgID: "missing"}); !errors.Is(err, org.ErrOrgNotFound) {
|
||||
t.Fatalf("AssignAgent(unknown org) = %v, want ErrOrgNotFound", err)
|
||||
}
|
||||
resolved, err := s.OrgForIdentity(ctx, agent.ID)
|
||||
if err != nil || resolved != "soc" {
|
||||
t.Fatalf("OrgForIdentity(agent) = %s, %v; want soc", resolved, err)
|
||||
}
|
||||
|
||||
// An identity with only an org-wide membership resolves through it.
|
||||
// A person with only an org-wide membership resolves through it.
|
||||
person := seedAgent(t, s, "operator")
|
||||
if err := s.EnsureMembership(ctx, org.Membership{IdentityID: person.ID, OrgID: "soc", Role: org.RoleOwner}); err != nil {
|
||||
t.Fatalf("EnsureMembership: %v", err)
|
||||
}
|
||||
resolved, err = s.OrgForIdentity(ctx, person.ID)
|
||||
if err != nil || resolved != "soc" {
|
||||
t.Fatalf("OrgForIdentity(member) = %s, %v; want soc", resolved, err)
|
||||
}
|
||||
|
||||
// An identity in no org resolves to the default org.
|
||||
resolved, err = s.OrgForIdentity(ctx, "nobody")
|
||||
if err != nil || resolved != org.DefaultOrgID {
|
||||
t.Fatalf("OrgForIdentity(no org) = %s, %v; want default", resolved, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpgradeDefaultOrg(t *testing.T) {
|
||||
s := newStoreForOrg(t)
|
||||
ctx := t.Context()
|
||||
|
||||
// Records written before the upgrade: one with an empty org (the shape a
|
||||
// pre-column row lands in), one stamped by the default backfill.
|
||||
agent := seedAgent(t, s, "archie")
|
||||
if err := s.queries().InsertOrgUpgradePhase(ctx, "state_store"); err != nil {
|
||||
t.Fatalf("pre-insert ledger row: %v", err)
|
||||
}
|
||||
|
||||
// First run: completes both phases and is recorded.
|
||||
if err := s.UpgradeDefaultOrg(ctx); err != nil {
|
||||
t.Fatalf("UpgradeDefaultOrg: %v", err)
|
||||
}
|
||||
for _, phase := range []string{"state_store", "edastore"} {
|
||||
if _, err := s.queries().GetOrgUpgradePhase(ctx, phase); err != nil {
|
||||
t.Fatalf("phase %s not recorded: %v", phase, err)
|
||||
}
|
||||
}
|
||||
if _, err := s.GetOrg(ctx, org.DefaultOrgID); err != nil {
|
||||
t.Fatalf("default org missing after upgrade: %v", err)
|
||||
}
|
||||
workspaces, err := s.ListWorkspaces(ctx, org.DefaultOrgID)
|
||||
if err != nil || len(workspaces) != 1 || workspaces[0].ID != org.DefaultWorkspaceID {
|
||||
t.Fatalf("default workspace missing after upgrade: %+v, %v", workspaces, err)
|
||||
}
|
||||
resolved, err := s.OrgForIdentity(ctx, agent.ID)
|
||||
if err != nil || resolved != org.DefaultOrgID {
|
||||
t.Fatalf("agent org after upgrade = %s, %v; want default", resolved, err)
|
||||
}
|
||||
|
||||
// A second run is a no-op: recorded phases are never re-run.
|
||||
if err := s.UpgradeDefaultOrg(ctx); err != nil {
|
||||
t.Fatalf("second UpgradeDefaultOrg: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpgradeStampsEmptyOrg(t *testing.T) {
|
||||
pool, _ := migrated(t)
|
||||
s := New(pool)
|
||||
ctx := t.Context()
|
||||
|
||||
// Rows with an empty org, as a write between migration and upgrade would
|
||||
// leave them: one on each phase's side of the ledger.
|
||||
for _, stmt := range []string{
|
||||
"INSERT INTO resources (kind, value, version, updated_at, org_id) VALUES ('workflow:legacy', 'v', 1, now(), '')",
|
||||
"INSERT INTO bindings (id, name, source, secret) VALUES ('b1', 'b', 'src', '')",
|
||||
"UPDATE bindings SET org_id = '' WHERE id = 'b1'",
|
||||
} {
|
||||
if _, err := pool.Exec(ctx, stmt); err != nil {
|
||||
t.Fatalf("seed %q: %v", stmt, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.UpgradeDefaultOrg(ctx); err != nil {
|
||||
t.Fatalf("UpgradeDefaultOrg: %v", err)
|
||||
}
|
||||
var stamped string
|
||||
if err := pool.QueryRow(ctx, "SELECT org_id FROM resources WHERE kind = 'workflow:legacy'").Scan(&stamped); err != nil || stamped != "default" {
|
||||
t.Fatalf("resource org after upgrade = %q, %v; want default", stamped, err)
|
||||
}
|
||||
if err := pool.QueryRow(ctx, "SELECT org_id, workspace_id FROM bindings WHERE id = 'b1'").Scan(&stamped, &stamped); err != nil || stamped != "default" {
|
||||
t.Fatalf("binding org/workspace after upgrade = %q, %v; want default", stamped, err)
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func openPool(t *testing.T, url string) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
pool, err := Open(t.Context(), url)
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
return pool
|
||||
}
|
||||
|
||||
// claimOther takes name as another process would, then optionally releases it
|
||||
// or kills its backend.
|
||||
func claimOther(t *testing.T, url, name string, release, terminate bool) {
|
||||
t.Helper()
|
||||
other, err := AcquireOwnership(t.Context(), openPool(t, url), name)
|
||||
if err != nil {
|
||||
t.Fatalf("first claim: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = other.Release(t.Context()) })
|
||||
if release {
|
||||
if err := other.Release(t.Context()); err != nil {
|
||||
t.Fatalf("Release: %v", err)
|
||||
}
|
||||
}
|
||||
if terminate {
|
||||
if _, err := openPool(t, url).Exec(t.Context(), "SELECT pg_terminate_backend($1)", other.pid); err != nil {
|
||||
t.Fatalf("terminate: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcquireOwnership(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
// held is taken by another process before the claim under test.
|
||||
held string
|
||||
// release drops the other claim before the claim under test.
|
||||
release bool
|
||||
// terminate kills the other claim's backend, as a crash would.
|
||||
terminate bool
|
||||
want error
|
||||
}{
|
||||
{name: "state-store", want: nil},
|
||||
{name: "state-store", held: "state-store", want: ErrOwned},
|
||||
{name: "state-store", held: "state-store", release: true, want: nil},
|
||||
{name: "state-store", held: "state-store", terminate: true, want: nil},
|
||||
{name: "gateway", held: "state-store", want: nil},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name+"/held="+tt.held, func(t *testing.T) {
|
||||
url := pgtest.URL(t)
|
||||
if tt.held != "" {
|
||||
claimOther(t, url, tt.held, tt.release, tt.terminate)
|
||||
}
|
||||
got, err := AcquireOwnership(t.Context(), openPool(t, url), tt.name)
|
||||
if got != nil {
|
||||
t.Cleanup(func() { _ = got.Release(t.Context()) })
|
||||
}
|
||||
if !errors.Is(err, tt.want) {
|
||||
t.Fatalf("AcquireOwnership(%q) = %v, want %v", tt.name, err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"sync"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
|
||||
func TestCheckServerVersion(t *testing.T) {
|
||||
tests := []struct {
|
||||
num int
|
||||
want error
|
||||
}{
|
||||
{num: 180000},
|
||||
{num: 180006},
|
||||
{num: 190000},
|
||||
{num: 179999, want: ErrServerTooOld},
|
||||
{num: 170011, want: ErrServerTooOld},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if err := checkServerVersion(tt.num); !errors.Is(err, tt.want) {
|
||||
t.Errorf("checkServerVersion(%d) = %v, want %v", tt.num, err, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenConnectsToPostgres18(t *testing.T) {
|
||||
pool, err := Open(t.Context(), pgtest.URL(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
defer pool.Close()
|
||||
var one int
|
||||
if err := pool.QueryRow(t.Context(), "SELECT 1").Scan(&one); err != nil || one != 1 {
|
||||
t.Fatalf("SELECT 1 = %d, %v", one, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Each migration inserts one row, so the row count is the number of times
|
||||
// it was applied.
|
||||
var countingMigrations = fstest.MapFS{
|
||||
"00001_create.sql": {Data: []byte("-- +goose Up\nCREATE TABLE applied (n int);\nINSERT INTO applied VALUES (1);\n")},
|
||||
"00002_again.sql": {Data: []byte("-- +goose Up\nINSERT INTO applied VALUES (2);\n")},
|
||||
}
|
||||
|
||||
func TestMigrateAppliesEachMigrationOnce(t *testing.T) {
|
||||
pool, err := Open(t.Context(), pgtest.URL(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
// Two processes starting together, then a later restart.
|
||||
var wg sync.WaitGroup
|
||||
errs := make([]error, 2)
|
||||
for i := range errs {
|
||||
wg.Go(func() { errs[i] = Migrate(t.Context(), pool, countingMigrations) })
|
||||
}
|
||||
wg.Wait()
|
||||
for i, err := range errs {
|
||||
if err != nil {
|
||||
t.Fatalf("concurrent Migrate %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
if err := Migrate(t.Context(), pool, countingMigrations); err != nil {
|
||||
t.Fatalf("Migrate on restart: %v", err)
|
||||
}
|
||||
|
||||
var rows int
|
||||
if err := pool.QueryRow(t.Context(), "SELECT count(*) FROM applied").Scan(&rows); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rows != 2 {
|
||||
t.Fatalf("applied rows = %d, want 2 (each migration exactly once)", rows)
|
||||
}
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
)
|
||||
|
||||
// Tests for the review gate response write
|
||||
// (docs/prds/pr-review-operator-response.md, Decision 2): one guarded
|
||||
// requeue beside RetryTask/BeginRemediation. The rereview cap is enforced in
|
||||
// the row, so a race cannot spend a round the cap forbids.
|
||||
|
||||
// waitingTaskWithGate claims a task, runs it to waiting_human and writes a
|
||||
// gate document on it -- the state an operator's response acts on.
|
||||
func waitingTaskWithGate(t *testing.T, s *Store) *workflow.Task {
|
||||
t.Helper()
|
||||
execution := runningTask(t, s)
|
||||
if err := s.Transition(t.Context(), execution.ID, workflow.StatusRunning, workflow.StatusWaitingHuman, "awaiting operator review"); err != nil {
|
||||
t.Fatalf("Transition to waiting_human: %v", err)
|
||||
}
|
||||
if err := s.Update(t.Context(), &workflow.Task{
|
||||
ID: execution.ID, Workflow: execution.Workflow, ReviewGate: `{"findings":[{"title":"f0"}]}`,
|
||||
}); err != nil {
|
||||
t.Fatalf("write gate offer: %v", err)
|
||||
}
|
||||
refreshed, err := s.TaskByID(t.Context(), execution.ID)
|
||||
if err != nil || refreshed == nil {
|
||||
t.Fatalf("TaskByID = (%v, %v)", refreshed, err)
|
||||
}
|
||||
return refreshed
|
||||
}
|
||||
|
||||
func TestRespondReviewGateIncrementsOnlyForARereview(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
task := waitingTaskWithGate(t, s)
|
||||
|
||||
if err := s.RespondReviewGate(t.Context(), task.ID, workflow.StatusWaitingHuman, `{"outcome":"approve"}`, false, 2); err != nil {
|
||||
t.Fatalf("RespondReviewGate(approve): %v", err)
|
||||
}
|
||||
got, err := s.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%v, %v)", got, err)
|
||||
}
|
||||
if got.Status != workflow.StatusQueued {
|
||||
t.Fatalf("status after approve = %q, want %q: the response requeues", got.Status, workflow.StatusQueued)
|
||||
}
|
||||
if got.RereviewRounds != 0 {
|
||||
t.Fatalf("rereview_rounds after approve = %d, want 0: an approve counts no round", got.RereviewRounds)
|
||||
}
|
||||
if got.ReviewGate != `{"outcome":"approve"}` {
|
||||
t.Fatalf("review_gate after approve = %q, want the caller's document", got.ReviewGate)
|
||||
}
|
||||
if got.Workflow != task.Workflow {
|
||||
t.Fatalf("workflow after approve = %q, want %q (the wait resumes the workflow the wait names)", got.Workflow, task.Workflow)
|
||||
}
|
||||
|
||||
// Requeue again to waiting, then answer with a re-review: the counter moves.
|
||||
if err := s.Transition(t.Context(), task.ID, workflow.StatusQueued, workflow.StatusRunning, ""); err != nil {
|
||||
t.Fatalf("claim again: %v", err)
|
||||
}
|
||||
if err := s.Transition(t.Context(), task.ID, workflow.StatusRunning, workflow.StatusWaitingHuman, ""); err != nil {
|
||||
t.Fatalf("wait again: %v", err)
|
||||
}
|
||||
if err := s.RespondReviewGate(t.Context(), task.ID, workflow.StatusWaitingHuman, `{"outcome":"rereview","instructions":"look again"}`, true, 2); err != nil {
|
||||
t.Fatalf("RespondReviewGate(rereview): %v", err)
|
||||
}
|
||||
got, err = s.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%v, %v)", got, err)
|
||||
}
|
||||
if got.RereviewRounds != 1 {
|
||||
t.Fatalf("rereview_rounds after one re-review = %d, want 1 (and it must survive the store round trip)", got.RereviewRounds)
|
||||
}
|
||||
if got.Status != workflow.StatusQueued {
|
||||
t.Fatalf("status after re-review = %q, want %q", got.Status, workflow.StatusQueued)
|
||||
}
|
||||
if got.ReviewGate != `{"outcome":"rereview","instructions":"look again"}` {
|
||||
t.Fatalf("review_gate after re-review = %q, want the caller's document", got.ReviewGate)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRespondReviewGateAtCapRefusedAndStaysWaiting(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
task := waitingTaskWithGate(t, s)
|
||||
|
||||
// Spend both rounds: two waiting_human gates answered with re-reviews.
|
||||
for range 2 {
|
||||
if err := s.RespondReviewGate(t.Context(), task.ID, workflow.StatusWaitingHuman, `{"outcome":"rereview"}`, true, 2); err != nil {
|
||||
t.Fatalf("RespondReviewGate(reviewer round %d): %v", task.RereviewRounds, err)
|
||||
}
|
||||
if err := s.Transition(t.Context(), task.ID, workflow.StatusQueued, workflow.StatusRunning, ""); err != nil {
|
||||
t.Fatalf("claim again: %v", err)
|
||||
}
|
||||
if err := s.Transition(t.Context(), task.ID, workflow.StatusRunning, workflow.StatusWaitingHuman, ""); err != nil {
|
||||
t.Fatalf("wait again: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
before, err := s.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || before == nil {
|
||||
t.Fatalf("TaskByID = (%v, %v)", before, err)
|
||||
}
|
||||
err = s.RespondReviewGate(t.Context(), task.ID, workflow.StatusWaitingHuman, `{"outcome":"rereview"}`, true, 2)
|
||||
if !errors.Is(err, storecontract.ErrRereviewCapReached) {
|
||||
t.Fatalf("RespondReviewGate at cap = %v, want ErrRereviewCapReached", err)
|
||||
}
|
||||
after, err := s.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || after == nil {
|
||||
t.Fatalf("TaskByID = (%v, %v)", after, err)
|
||||
}
|
||||
if after.Status != workflow.StatusWaitingHuman {
|
||||
t.Fatalf("status after refused re-review = %q, want %q: the task stays waiting", after.Status, workflow.StatusWaitingHuman)
|
||||
}
|
||||
if after.RereviewRounds != before.RereviewRounds || after.ReviewGate != before.ReviewGate {
|
||||
t.Fatalf("refused re-review changed the row: rounds %d->%d, gate %q->%q",
|
||||
before.RereviewRounds, after.RereviewRounds, before.ReviewGate, after.ReviewGate)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRespondReviewGateStaleFromStatusWritesNothing(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
task := waitingTaskWithGate(t, s)
|
||||
|
||||
err := s.RespondReviewGate(t.Context(), task.ID, workflow.StatusParked, `{"outcome":"approve"}`, false, 2)
|
||||
if !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("RespondReviewGate from parked = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
got, err := s.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%v, %v)", got, err)
|
||||
}
|
||||
if got.Status != workflow.StatusWaitingHuman || got.ReviewGate != `{"findings":[{"title":"f0"}]}` {
|
||||
t.Fatalf("refused write changed the row: status=%q gate=%q", got.Status, got.ReviewGate)
|
||||
}
|
||||
}
|
||||
@@ -1,213 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/bindingcipher"
|
||||
)
|
||||
|
||||
func readRawSourceSecret(t *testing.T, pool *pgxpool.Pool, path string) string {
|
||||
t.Helper()
|
||||
var stored string
|
||||
if err := pool.QueryRow(t.Context(), "SELECT secret FROM sources WHERE path = $1", path).Scan(&stored); err != nil {
|
||||
t.Fatalf("read raw secret: %v", err)
|
||||
}
|
||||
return stored
|
||||
}
|
||||
|
||||
// A new source keeps its generated path, is signed, stores its secret as a
|
||||
// cipher envelope and reads it back as plaintext.
|
||||
func TestSourceRoundTripEncryptsSecret(t *testing.T) {
|
||||
cipher, err := bindingcipher.NewBindingCipher(edaTestKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher() error = %v", err)
|
||||
}
|
||||
pool, s := edaWithCipher(t, cipher)
|
||||
in, err := source.New("")
|
||||
if err != nil {
|
||||
t.Fatalf("source.New() error = %v", err)
|
||||
}
|
||||
if err := s.InsertSource(t.Context(), in); err != nil {
|
||||
t.Fatalf("InsertSource() error = %v", err)
|
||||
}
|
||||
if raw := readRawSourceSecret(t, pool, in.Path); raw == in.Secret || raw == "" {
|
||||
t.Fatalf("stored secret = %q, want a cipher envelope", raw)
|
||||
}
|
||||
got, err := s.GetSource(t.Context(), in.Path)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("GetSource() = %v, %v", got, err)
|
||||
}
|
||||
if got.Path != in.Path || got.Signing != source.SigningSigned || got.Secret != in.Secret {
|
||||
t.Fatalf("GetSource() = %+v, want path %q signed with the plaintext secret", got, in.Path)
|
||||
}
|
||||
list, err := s.ListSources(t.Context())
|
||||
if err != nil || len(list) != 1 || list[0].Secret != in.Secret {
|
||||
t.Fatalf("ListSources() = %+v, %v", list, err)
|
||||
}
|
||||
}
|
||||
|
||||
// sourceUnder inserts a new source through a store sealing with cipher.
|
||||
func sourceUnder(t *testing.T, cipher bindingcipher.BindingCipher) (*pgxpool.Pool, source.Source) {
|
||||
t.Helper()
|
||||
pool, s := edaWithCipher(t, cipher)
|
||||
in, err := source.New("")
|
||||
if err != nil {
|
||||
t.Fatalf("source.New() error = %v", err)
|
||||
}
|
||||
if err := s.InsertSource(t.Context(), in); err != nil {
|
||||
t.Fatalf("InsertSource() error = %v", err)
|
||||
}
|
||||
return pool, in
|
||||
}
|
||||
|
||||
// A deployment with no configured key stores plaintext.
|
||||
func TestSourceNoCipherKeepsPlaintext(t *testing.T) {
|
||||
pool, in := sourceUnder(t, nil)
|
||||
if raw := readRawSourceSecret(t, pool, in.Path); raw != in.Secret {
|
||||
t.Errorf("stored secret = %q, want the plaintext with no cipher configured", raw)
|
||||
}
|
||||
}
|
||||
|
||||
// A secret written under the previous key stays readable once a new active
|
||||
// key is installed; otherwise rotation bricks every signed source.
|
||||
func TestSourceRotatedKeyStillReadsOldRows(t *testing.T) {
|
||||
const oldKey = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"
|
||||
oldCipher, err := bindingcipher.NewBindingCipher(oldKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher(old) error = %v", err)
|
||||
}
|
||||
pool, in := sourceUnder(t, oldCipher)
|
||||
rotated, err := bindingcipher.NewBindingCipher(edaTestKey, []string{oldKey})
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher(rotated) error = %v", err)
|
||||
}
|
||||
got, err := NewEDA(pool, rotated).GetSource(t.Context(), in.Path)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("GetSource() after rotation = %v, %v", got, err)
|
||||
}
|
||||
if got.Secret != in.Secret {
|
||||
t.Errorf("Secret after rotation = %q: the previous key must still decrypt", got.Secret)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceWritesRefuseBadState(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
taken := source.Source{Path: "sentry", Signing: source.SigningSigned, Secret: "k"}
|
||||
if err := s.InsertSource(t.Context(), taken); err != nil {
|
||||
t.Fatalf("InsertSource() error = %v", err)
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
write func() error
|
||||
want error
|
||||
}{
|
||||
{"taken custom path", func() error { return s.InsertSource(t.Context(), taken) }, storecontract.ErrSourcePathTaken},
|
||||
{"stale signing", func() error {
|
||||
return s.SetSourceSigning(t.Context(), "sentry", source.SigningUnsignedPending, source.SigningUnsigned)
|
||||
}, storecontract.ErrSourceSigningStale},
|
||||
{"signing on unknown path", func() error {
|
||||
return s.SetSourceSigning(t.Context(), "nope", source.SigningSigned, source.SigningUnsignedPending)
|
||||
}, storecontract.ErrSourceNotFound},
|
||||
{"secret on unknown path", func() error { return s.SetSourceSecret(t.Context(), "nope", "k") }, storecontract.ErrSourceNotFound},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if err := tt.write(); !errors.Is(err, tt.want) {
|
||||
t.Fatalf("error = %v, want %v", err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
got, err := s.GetSource(t.Context(), "nope")
|
||||
if err != nil || got != nil {
|
||||
t.Fatalf("GetSource(unknown) = %v, %v; want nil, nil", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceSigningAndSecretWrites(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
if err := s.InsertSource(t.Context(), source.Source{Path: "fw", Signing: source.SigningSigned}); err != nil {
|
||||
t.Fatalf("InsertSource() error = %v", err)
|
||||
}
|
||||
if err := s.SetSourceSigning(t.Context(), "fw", source.SigningSigned, source.SigningUnsignedPending); err != nil {
|
||||
t.Fatalf("SetSourceSigning() error = %v", err)
|
||||
}
|
||||
if err := s.SetSourceSecret(t.Context(), "fw", "newsecret"); err != nil {
|
||||
t.Fatalf("SetSourceSecret() error = %v", err)
|
||||
}
|
||||
got, err := s.GetSource(t.Context(), "fw")
|
||||
if err != nil || got.Signing != source.SigningUnsignedPending || got.Secret != "newsecret" {
|
||||
t.Fatalf("GetSource() = %+v, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureUnsignedRoundTrip(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
// Only an identified capture with an armed binding for its type is listed
|
||||
// for dispatch; a catch-all type identifies every event on the source.
|
||||
etID, err := s.InsertEventType(t.Context(), eventtype.EventType{Source: "fw", Name: "any"})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEventType() error = %v", err)
|
||||
}
|
||||
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m", EventTypeID: etID})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
armedBinding(t, s, "fw", mid)
|
||||
if _, err := s.InsertCapture(t.Context(), storecontract.CapturedEvent{Source: "fw", Unsigned: true}, 0, 0); err != nil {
|
||||
t.Fatalf("InsertCapture() error = %v", err)
|
||||
}
|
||||
for name, list := range map[string]func() ([]storecontract.CapturedEvent, error){
|
||||
"ListCaptures": func() ([]storecontract.CapturedEvent, error) { return s.ListCaptures(t.Context(), 10) },
|
||||
"ListUndispatchedCaptures": func() ([]storecontract.CapturedEvent, error) {
|
||||
return s.ListUndispatchedCaptures(t.Context(), []string{"fw"}, 10)
|
||||
},
|
||||
} {
|
||||
got, err := list()
|
||||
if err != nil || len(got) != 1 || !got[0].Unsigned {
|
||||
t.Errorf("%s() = %+v, %v; want one unsigned capture", name, got, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Existing source strings become sources: a bound source takes its binding's
|
||||
// secret, a capture-only source gets none, and an existing source is kept.
|
||||
func TestDeriveSourcesFromExistingRows(t *testing.T) {
|
||||
pool, q := migrated(t)
|
||||
ctx := t.Context()
|
||||
for _, stmt := range []string{
|
||||
`INSERT INTO bindings (id, name, source, secret) VALUES ('b1', 'n', 'sentry', 'envelope')`,
|
||||
`INSERT INTO captures (id, source, received_at) VALUES ('c1', 'sentry', now()), ('c2', 'firewall', now()), ('c3', 'kept', now())`,
|
||||
`INSERT INTO sources (path, signing, secret) VALUES ('kept', 'unsigned', 'x')`,
|
||||
} {
|
||||
if _, err := pool.Exec(ctx, stmt); err != nil {
|
||||
t.Fatalf("%s: %v", stmt, err)
|
||||
}
|
||||
}
|
||||
if err := q.DeriveSources(ctx); err != nil {
|
||||
t.Fatalf("DeriveSources() error = %v", err)
|
||||
}
|
||||
want := map[string][2]string{
|
||||
"sentry": {"signed", "envelope"},
|
||||
"firewall": {"signed", ""},
|
||||
"kept": {"unsigned", "x"},
|
||||
}
|
||||
rows, err := q.ListSources(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListSources() error = %v", err)
|
||||
}
|
||||
if len(rows) != len(want) {
|
||||
t.Fatalf("derived %d sources, want %d: %+v", len(rows), len(want), rows)
|
||||
}
|
||||
for _, r := range rows {
|
||||
if w := want[r.Path]; w != [2]string{r.Signing, r.Secret} {
|
||||
t.Errorf("source %q = (%s, %q), want %v", r.Path, r.Signing, r.Secret, w)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,540 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
||||
)
|
||||
|
||||
// syntheticIssueBase mirrors the store's chat issue-number seed. It is the
|
||||
// fallback for a repo's first chat task, not the number that lands: the
|
||||
// allocator adds one to it.
|
||||
const syntheticIssueBase = 1_000_000_000_000_000
|
||||
|
||||
// migrated is a pool with the State Store schema applied, and its queries.
|
||||
func migrated(t *testing.T) (*pgxpool.Pool, *postgresdb.Queries) {
|
||||
t.Helper()
|
||||
pool, err := Open(t.Context(), pgtest.URL(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
if err := Migrate(t.Context(), pool, Migrations()); err != nil {
|
||||
t.Fatalf("Migrate: %v", err)
|
||||
}
|
||||
return pool, postgresdb.New(pool)
|
||||
}
|
||||
|
||||
// queriesFor is migrated's queries without the pool, for tests that only read
|
||||
// and write through sqlc.
|
||||
func queriesFor(t *testing.T) *postgresdb.Queries {
|
||||
t.Helper()
|
||||
_, q := migrated(t)
|
||||
return q
|
||||
}
|
||||
|
||||
func resourcesFor(t *testing.T) *Resources {
|
||||
t.Helper()
|
||||
pool, _ := migrated(t)
|
||||
return NewResources(pool)
|
||||
}
|
||||
|
||||
// insertChatTask queues one chat-sourced task.
|
||||
func insertChatTask(t *testing.T, q *postgresdb.Queries) postgresdb.Task {
|
||||
t.Helper()
|
||||
task, err := q.InsertChatTask(t.Context(), postgresdb.InsertChatTaskParams{
|
||||
Owner: "acme", Repo: "widget", Title: "t", Body: "b",
|
||||
Workflow: "tdd", Identity: "bot",
|
||||
FallbackIssueNumber: syntheticIssueBase,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertChatTask: %v", err)
|
||||
}
|
||||
return task
|
||||
}
|
||||
|
||||
func TestSchemaAppliesAndTasksRoundTrip(t *testing.T) {
|
||||
q := queriesFor(t)
|
||||
|
||||
task := insertChatTask(t, q)
|
||||
if task.Status != "queued" {
|
||||
t.Fatalf("new task status = %q, want queued", task.Status)
|
||||
}
|
||||
if task.CreatedAt.IsZero() || task.UpdatedAt.IsZero() {
|
||||
t.Error("created_at/updated_at were not populated")
|
||||
}
|
||||
if task.IssueNumber != syntheticIssueBase+1 {
|
||||
t.Fatalf("first chat task issue number = %d, want %d", task.IssueNumber, syntheticIssueBase+1)
|
||||
}
|
||||
|
||||
got, err := q.TaskByIssue(t.Context(), postgresdb.TaskByIssueParams{
|
||||
Owner: task.Owner, Repo: task.Repo, IssueNumber: task.IssueNumber,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("TaskByIssue: %v", err)
|
||||
}
|
||||
if got.ID != task.ID {
|
||||
t.Fatalf("TaskByIssue = %d, want %d", got.ID, task.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// The chat allocator hands out the next number per repo, so two chat tasks in
|
||||
// one repo never share an issue number.
|
||||
func TestChatIssueNumberAllocatorIsPerRepo(t *testing.T) {
|
||||
q := queriesFor(t)
|
||||
|
||||
first := insertChatTask(t, q)
|
||||
second := insertChatTask(t, q)
|
||||
if second.IssueNumber != first.IssueNumber+1 {
|
||||
t.Fatalf("second chat issue number = %d, want %d", second.IssueNumber, first.IssueNumber+1)
|
||||
}
|
||||
}
|
||||
|
||||
// Task uniqueness follows the record's identity: the same owner/repo/issue
|
||||
// under the same org and identity is refused, and the constraint that carries
|
||||
// that rule survives the move.
|
||||
func TestTaskIssueNumberIsUnique(t *testing.T) {
|
||||
pool, q := migrated(t)
|
||||
task := insertChatTask(t, q)
|
||||
|
||||
_, err := pool.Exec(t.Context(), `
|
||||
INSERT INTO tasks (owner, repo, issue_number, identity, org_id)
|
||||
VALUES ($1, $2, $3, $4, 'default')`,
|
||||
task.Owner, task.Repo, task.IssueNumber, task.Identity)
|
||||
if err == nil {
|
||||
t.Fatal("a second task for the same org/identity/owner/repo/issue was accepted, want the unique constraint refused it")
|
||||
}
|
||||
|
||||
// A different identity may work the same issue: that is its own record.
|
||||
if task.Identity != "other" {
|
||||
_, err = pool.Exec(t.Context(), `
|
||||
INSERT INTO tasks (owner, repo, issue_number, identity, org_id)
|
||||
VALUES ($1, $2, $3, 'other', 'default')`,
|
||||
task.Owner, task.Repo, task.IssueNumber)
|
||||
if err != nil {
|
||||
t.Fatalf("a second task under another identity was refused: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Claiming takes the oldest queued task, in id order, and counts the attempt.
|
||||
func TestClaimNextTakesTheOldestAndCountsTheAttempt(t *testing.T) {
|
||||
q := queriesFor(t)
|
||||
first := insertChatTask(t, q)
|
||||
second := insertChatTask(t, q)
|
||||
|
||||
claimed, err := q.ClaimNextTask(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("ClaimNextTask: %v", err)
|
||||
}
|
||||
if claimed.ID != first.ID || claimed.Status != "running" || claimed.Attempt != 1 {
|
||||
t.Fatalf("first claim = {id:%d status:%q attempt:%d}, want {id:%d running 1}", claimed.ID, claimed.Status, claimed.Attempt, first.ID)
|
||||
}
|
||||
|
||||
claimed, err = q.ClaimNextTask(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("second ClaimNextTask: %v", err)
|
||||
}
|
||||
if claimed.ID != second.ID {
|
||||
t.Fatalf("second claim = %d, want %d", claimed.ID, second.ID)
|
||||
}
|
||||
|
||||
if _, err := q.ClaimNextTask(t.Context()); !errors.Is(err, pgx.ErrNoRows) {
|
||||
t.Fatalf("claim on an empty queue = %v, want pgx.ErrNoRows", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A claimer must not wait behind a row another transaction holds: it takes the
|
||||
// next one. This is what FOR UPDATE SKIP LOCKED buys over the SQLite version,
|
||||
// where a second claimer could only ever have blocked on the writer lock.
|
||||
func TestClaimSkipsARowAnotherTransactionHolds(t *testing.T) {
|
||||
pool, q := migrated(t)
|
||||
held := insertChatTask(t, q)
|
||||
free := insertChatTask(t, q)
|
||||
|
||||
tx, err := pool.Begin(t.Context())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(t.Context()) }()
|
||||
var lockedID int64
|
||||
if err := tx.QueryRow(t.Context(),
|
||||
`SELECT id FROM tasks WHERE status = 'queued' ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1`,
|
||||
).Scan(&lockedID); err != nil {
|
||||
t.Fatalf("lock the oldest queued row: %v", err)
|
||||
}
|
||||
if lockedID != held.ID {
|
||||
t.Fatalf("locked row %d, want the oldest queued row %d", lockedID, held.ID)
|
||||
}
|
||||
|
||||
claimed, err := q.ClaimNextTask(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("ClaimNextTask while a row is held: %v", err)
|
||||
}
|
||||
if claimed.ID != free.ID {
|
||||
t.Fatalf("claimed %d while %d was held, want the skipped-to row %d", claimed.ID, free.ID, held.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// A control-plane resource write is optimistic and idempotent: a retry returns
|
||||
// the audited original, while a different request based on a stale revision is
|
||||
// refused. The history remains the audit trail, newest first.
|
||||
func TestResourceWritesPreserveOptimisticAndIdempotentSemantics(t *testing.T) {
|
||||
resources := resourcesFor(t)
|
||||
firstAt := time.Date(2026, 9, 24, 1, 0, 0, 0, time.UTC)
|
||||
first, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "settings", Value: []byte(`{"v":1}`), Actor: "operator", Source: "archie-ui",
|
||||
RequestID: "r1", ExpectedVersion: 0, At: firstAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("first PutResource: %v", err)
|
||||
}
|
||||
if first.Version != 1 || first.CurrentVersion != 0 {
|
||||
t.Fatalf("first write = %+v, want version 1 from version 0", first)
|
||||
}
|
||||
|
||||
replay, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "settings", Value: []byte(`{"v":999}`), Actor: "other", Source: "retry",
|
||||
RequestID: "r1", ExpectedVersion: 0, At: firstAt.Add(time.Minute),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("replay PutResource: %v", err)
|
||||
}
|
||||
if replay.Version != first.Version || string(replay.Value) != string(first.Value) || replay.Actor != first.Actor {
|
||||
t.Fatalf("replay = %+v, want original %+v", replay, first)
|
||||
}
|
||||
|
||||
if _, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "settings", Value: []byte(`{"v":2}`), Actor: "operator", Source: "archie-ui",
|
||||
RequestID: "r2", ExpectedVersion: 0, At: firstAt.Add(2 * time.Minute),
|
||||
}); !errors.Is(err, storecontract.ErrResourceVersionConflict) {
|
||||
t.Fatalf("stale PutResource = %v, want ErrResourceVersionConflict", err)
|
||||
}
|
||||
|
||||
second, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "settings", Value: []byte(`{"v":2}`), Actor: "operator", Source: "messaging",
|
||||
RequestID: "r2", ExpectedVersion: 1, At: firstAt.Add(3 * time.Minute),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("second PutResource: %v", err)
|
||||
}
|
||||
if second.Version != 2 || second.CurrentVersion != 1 {
|
||||
t.Fatalf("second write = %+v, want version 2 from version 1", second)
|
||||
}
|
||||
lateReplay, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "settings", Value: []byte(`{"v":999}`), Actor: "other", Source: "retry",
|
||||
RequestID: "r1", ExpectedVersion: 0, At: firstAt.Add(4 * time.Minute),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("late replay PutResource: %v", err)
|
||||
}
|
||||
if lateReplay.Version != first.Version || string(lateReplay.Value) != string(first.Value) {
|
||||
t.Fatalf("late replay = %+v, want original %+v", lateReplay, first)
|
||||
}
|
||||
live, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, "settings")
|
||||
if err != nil {
|
||||
t.Fatalf("Resource: %v", err)
|
||||
}
|
||||
if live.Version != second.Version || string(live.Value) != string(second.Value) {
|
||||
t.Fatalf("live resource after replay = %+v, want second write %+v", live, second)
|
||||
}
|
||||
|
||||
history, err := resources.ResourceHistory(t.Context(), storecontract.DefaultOrgID, "settings", 1)
|
||||
if err != nil {
|
||||
t.Fatalf("ResourceHistory: %v", err)
|
||||
}
|
||||
if len(history) != 1 || history[0].Version != 2 || history[0].Source != "messaging" {
|
||||
t.Fatalf("limited history = %+v, want newest revision only", history)
|
||||
}
|
||||
history, err = resources.ResourceHistory(t.Context(), storecontract.DefaultOrgID, "settings", 0)
|
||||
if err != nil {
|
||||
t.Fatalf("unlimited ResourceHistory: %v", err)
|
||||
}
|
||||
if len(history) != 2 {
|
||||
t.Fatalf("history after late replay = %+v, want two revisions", history)
|
||||
}
|
||||
if _, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, "missing"); !errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
t.Fatalf("missing Resource = %v, want ErrResourceNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A write is idempotent per request ID, and the ledger holding those IDs
|
||||
// outlives the row it describes. So a replay whose resource is gone must
|
||||
// re-create it: answering with the ledger's revision alone reports a version for
|
||||
// a kind the store does not hold, and a caller cannot tell that apart from a
|
||||
// resource that is there. An operator removing a resource and restarting the
|
||||
// process that seeds it is the shape this repairs.
|
||||
func TestResourceReplayRecreatesARemovedResource(t *testing.T) {
|
||||
pool, _ := migrated(t)
|
||||
resources := NewResources(pool)
|
||||
at := time.Date(2026, 9, 27, 9, 0, 0, 0, time.UTC)
|
||||
write := storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "workflow-definitions", Value: []byte(`{"definitions":[]}`), Actor: "system:migration",
|
||||
Source: "legacy-config", RequestID: "import:workflow-definitions", ExpectedVersion: 0, At: at,
|
||||
}
|
||||
seeded, err := resources.PutResource(t.Context(), write)
|
||||
if err != nil {
|
||||
t.Fatalf("seed PutResource: %v", err)
|
||||
}
|
||||
|
||||
if _, err := pool.Exec(t.Context(), `DELETE FROM resources WHERE kind = $1`, write.Kind); err != nil {
|
||||
t.Fatalf("remove the resource: %v", err)
|
||||
}
|
||||
if _, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, write.Kind); !errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
t.Fatalf("resource after the removal = %v, want ErrResourceNotFound", err)
|
||||
}
|
||||
|
||||
replayed, err := resources.PutResource(t.Context(), write)
|
||||
if err != nil {
|
||||
t.Fatalf("replay PutResource: %v", err)
|
||||
}
|
||||
if replayed.Version != seeded.Version || string(replayed.Value) != string(seeded.Value) {
|
||||
t.Fatalf("replay = %+v, want the revision the ledger records, %+v", replayed, seeded)
|
||||
}
|
||||
live, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, write.Kind)
|
||||
if err != nil {
|
||||
t.Fatalf("the replay did not re-create the resource: %v", err)
|
||||
}
|
||||
if live.Version != seeded.Version || string(live.Value) != string(seeded.Value) {
|
||||
t.Fatalf("live resource after the replay = %+v, want the restored %+v", live, seeded)
|
||||
}
|
||||
// The repair re-creates the row the write produced; it does not append a
|
||||
// second ledger entry, which idx_resource_history_kind_request would refuse.
|
||||
history, err := resources.ResourceHistory(t.Context(), storecontract.DefaultOrgID, write.Kind, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("ResourceHistory: %v", err)
|
||||
}
|
||||
if len(history) != 1 {
|
||||
t.Fatalf("history after the replay = %d revisions, want the one the write made", len(history))
|
||||
}
|
||||
|
||||
// A resource the store still holds is answered from the ledger, unchanged:
|
||||
// the idempotent replay the index exists for.
|
||||
again, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: write.Kind, Value: []byte(`{"definitions":[{"id":"different"}]}`), Actor: "other",
|
||||
Source: "retry", RequestID: write.RequestID, ExpectedVersion: 0, At: at.Add(time.Minute),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("second replay: %v", err)
|
||||
}
|
||||
if again.Version != seeded.Version || string(again.Value) != string(seeded.Value) {
|
||||
t.Fatalf("second replay = %+v, want the original %+v", again, seeded)
|
||||
}
|
||||
}
|
||||
|
||||
// A request ID is idempotent per kind: the store API, the resource_history
|
||||
// UNIQUE(kind, request_id) index and every production caller treat it as one,
|
||||
// so a caller that mints one request ID for two different kinds must get two
|
||||
// writes -- the second kind's own revision -- and not the first kind's history
|
||||
// row replayed under the second kind's name.
|
||||
func TestResourceRequestIDIsIdempotentPerKind(t *testing.T) {
|
||||
resources := resourcesFor(t)
|
||||
at := time.Date(2026, 9, 26, 12, 0, 0, 0, time.UTC)
|
||||
first, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "provider-settings", Value: []byte(`{"v":1}`), Actor: "operator", Source: "import",
|
||||
RequestID: "shared", ExpectedVersion: 0, At: at,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("first PutResource: %v", err)
|
||||
}
|
||||
second, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "scheduling-policy", Value: []byte(`{"v":2}`), Actor: "operator", Source: "import",
|
||||
RequestID: "shared", ExpectedVersion: 0, At: at,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("second PutResource with the same request ID: %v", err)
|
||||
}
|
||||
if second.Kind != "scheduling-policy" || string(second.Value) != `{"v":2}` || second.Version != 1 {
|
||||
t.Fatalf("second write = %+v, want scheduling-policy's own revision, not a replay of %+v", second, first)
|
||||
}
|
||||
|
||||
replay, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "scheduling-policy", Value: []byte(`{"v":999}`), Actor: "other", Source: "retry",
|
||||
RequestID: "shared", ExpectedVersion: 0, At: at.Add(time.Minute),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("replay PutResource: %v", err)
|
||||
}
|
||||
if replay.Version != second.Version || string(replay.Value) != string(second.Value) || replay.Actor != second.Actor {
|
||||
t.Fatalf("replay = %+v, want scheduling-policy's original %+v", replay, second)
|
||||
}
|
||||
|
||||
live, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, "scheduling-policy")
|
||||
if err != nil {
|
||||
t.Fatalf("Resource: %v", err)
|
||||
}
|
||||
if live.Version != second.Version || string(live.Value) != string(second.Value) {
|
||||
t.Fatalf("live scheduling-policy = %+v, want second write %+v", live, second)
|
||||
}
|
||||
}
|
||||
|
||||
// PostgreSQL admits concurrent writers, unlike SQLite's single writer. The
|
||||
// resource lock keeps the expected-version comparison and audit append one
|
||||
// serialized operation.
|
||||
func TestConcurrentResourceWritesAcceptOnlyOneExpectedVersion(t *testing.T) {
|
||||
resources := resourcesFor(t)
|
||||
type result struct{ err error }
|
||||
start := make(chan struct{})
|
||||
results := make(chan result, 2)
|
||||
for _, requestID := range []string{"first", "second"} {
|
||||
go func() {
|
||||
<-start
|
||||
_, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "settings", Value: []byte(`{"v":1}`), Actor: "operator", Source: "test",
|
||||
RequestID: requestID, ExpectedVersion: 0,
|
||||
})
|
||||
results <- result{err: err}
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
|
||||
var succeeded, conflicted int
|
||||
for range 2 {
|
||||
outcome := <-results
|
||||
switch {
|
||||
case outcome.err == nil:
|
||||
succeeded++
|
||||
case errors.Is(outcome.err, storecontract.ErrResourceVersionConflict):
|
||||
conflicted++
|
||||
default:
|
||||
t.Fatalf("concurrent PutResource: %v", outcome.err)
|
||||
}
|
||||
}
|
||||
if succeeded != 1 || conflicted != 1 {
|
||||
t.Fatalf("concurrent writes = %d succeeded, %d conflicted; want 1 each", succeeded, conflicted)
|
||||
}
|
||||
|
||||
history, err := resources.ResourceHistory(t.Context(), storecontract.DefaultOrgID, "settings", 0)
|
||||
if err != nil {
|
||||
t.Fatalf("ResourceHistory: %v", err)
|
||||
}
|
||||
if len(history) != 1 || history[0].Version != 1 {
|
||||
t.Fatalf("history after race = %+v, want exactly one version 1", history)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResourceWritesRecordFieldLevelAudit: each write records one sys_audit row
|
||||
// per field it changed, newest first, and a replayed write records nothing.
|
||||
func TestResourceWritesRecordFieldLevelAudit(t *testing.T) {
|
||||
resources := resourcesFor(t)
|
||||
put := func(value string, expected int64, request string) {
|
||||
t.Helper()
|
||||
if _, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "settings", Value: []byte(value), Actor: "sam", Source: "archie-ui",
|
||||
RequestID: request, ExpectedVersion: expected,
|
||||
}); err != nil {
|
||||
t.Fatalf("PutResource(%s): %v", value, err)
|
||||
}
|
||||
}
|
||||
put(`{"a":1,"b":2}`, 0, "r1")
|
||||
put(`{"a":1,"b":3,"c":4}`, 1, "r2")
|
||||
put(`{"a":1,"b":3,"c":4}`, 1, "r2")
|
||||
|
||||
audit, err := resources.Audit(t.Context(), storecontract.AuditTableResources, []string{"settings"}, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("ResourceAudit: %v", err)
|
||||
}
|
||||
got := make([]string, 0, len(audit))
|
||||
for _, entry := range audit {
|
||||
got = append(got, fmt.Sprintf("v%d %s %s->%s by %s", entry.Version, entry.Field, entry.OldValue, entry.NewValue, entry.Actor))
|
||||
}
|
||||
want := []string{
|
||||
"v2 c ->4 by sam", "v2 b 2->3 by sam",
|
||||
"v1 b ->2 by sam", "v1 a ->1 by sam",
|
||||
}
|
||||
if strings.Join(got, "; ") != strings.Join(want, "; ") {
|
||||
t.Fatalf("audit =\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
|
||||
}
|
||||
}
|
||||
|
||||
// A kind is one document per org: two orgs write the same kind under the same
|
||||
// request ID and each keeps its own value, revision, history and audit trail.
|
||||
func TestResourcesAreIndependentPerOrg(t *testing.T) {
|
||||
resources := resourcesFor(t)
|
||||
at := time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC)
|
||||
put := func(orgID, value string, expected int64) storecontract.Resource {
|
||||
t.Helper()
|
||||
got, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: orgID, Kind: "workflow-definitions", Value: []byte(value), Actor: "operator",
|
||||
Source: "test", RequestID: "shared-" + value, ExpectedVersion: expected, At: at,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("PutResource(%s): %v", orgID, err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
put("acme", `{"v":"a1"}`, 0)
|
||||
acme := put("acme", `{"v":"a2"}`, 1)
|
||||
globex := put("globex", `{"v":"g1"}`, 0)
|
||||
if acme.Version != 2 || globex.Version != 1 {
|
||||
t.Fatalf("versions acme=%d globex=%d, want 2 and 1: orgs must not share a revision counter", acme.Version, globex.Version)
|
||||
}
|
||||
if _, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: "globex", Kind: "workflow-definitions", Value: []byte(`{}`), Actor: "operator",
|
||||
Source: "test", RequestID: "stale", ExpectedVersion: 2, At: at,
|
||||
}); !errors.Is(err, storecontract.ErrResourceVersionConflict) {
|
||||
t.Fatalf("globex write expecting acme's version = %v, want ErrResourceVersionConflict", err)
|
||||
}
|
||||
|
||||
live, err := resources.Resource(t.Context(), "globex", "workflow-definitions")
|
||||
if err != nil || string(live.Value) != `{"v":"g1"}` || live.OrgID != "globex" {
|
||||
t.Fatalf("globex Resource = %+v, %v", live, err)
|
||||
}
|
||||
if _, err := resources.Resource(t.Context(), "initech", "workflow-definitions"); !errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
t.Fatalf("an org that never wrote the kind reads %v, want ErrResourceNotFound", err)
|
||||
}
|
||||
history, err := resources.ResourceHistory(t.Context(), "acme", "workflow-definitions", 0)
|
||||
if err != nil || len(history) != 2 {
|
||||
t.Fatalf("acme history = %d entries, %v; want its own 2", len(history), err)
|
||||
}
|
||||
audit, err := resources.Audit(t.Context(), storecontract.AuditTableResources,
|
||||
[]string{storecontract.ResourceAuditKey("globex", "workflow-definitions")}, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("Audit: %v", err)
|
||||
}
|
||||
for _, entry := range audit {
|
||||
if entry.Version != 1 {
|
||||
t.Fatalf("globex audit entry at version %d: acme's revisions leaked into its trail", entry.Version)
|
||||
}
|
||||
}
|
||||
if len(audit) == 0 {
|
||||
t.Fatal("globex audit is empty, want its first write")
|
||||
}
|
||||
}
|
||||
|
||||
// A key the audit record key could not tell apart from another, or one naming
|
||||
// no org, is refused on both paths rather than reading as an absent resource.
|
||||
func TestResourceKeysAreValidated(t *testing.T) {
|
||||
resources := resourcesFor(t)
|
||||
for _, key := range [][2]string{{"", "settings"}, {"acme", ""}, {"a/b", "settings"}, {"a", "b/settings"}} {
|
||||
if _, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: key[0], Kind: key[1], Value: []byte(`{}`), Actor: "operator", Source: "test", RequestID: "r",
|
||||
}); err == nil {
|
||||
t.Errorf("write %q/%q accepted", key[0], key[1])
|
||||
}
|
||||
if _, err := resources.Resource(t.Context(), key[0], key[1]); errors.Is(err, storecontract.ErrResourceNotFound) || err == nil {
|
||||
t.Errorf("read %q/%q = %v, want a key error, not not-found", key[0], key[1], err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,314 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
task "github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
// The step-execution writes (docs/prds/execution-tree-state-machine.md): each
|
||||
// of StartStep and FinishStep is one transaction -- guarded row write plus the
|
||||
// domain event row -- under the step transition table, with the execution's
|
||||
// own status gating whether a step may run at all.
|
||||
|
||||
// runningExecution enqueues and claims one task, the state a step runs in.
|
||||
func runningExecution(t *testing.T, s *Store) *workflow.Task {
|
||||
t.Helper()
|
||||
seed, err := s.EnqueueChatTask(t.Context(), "acme", "widgets", "t", "b", "implement", "", nil)
|
||||
if err != nil || seed == nil {
|
||||
t.Fatalf("EnqueueChatTask: %+v %v", seed, err)
|
||||
}
|
||||
claimed, err := s.ClaimNext(t.Context())
|
||||
if err != nil || claimed == nil {
|
||||
t.Fatalf("ClaimNext: %+v %v", claimed, err)
|
||||
}
|
||||
return claimed
|
||||
}
|
||||
|
||||
func TestStartStepRecordsAStageEnteringRunning(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
stepID, startEvent, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep: %v", err)
|
||||
}
|
||||
if startEvent.Kind != events.KindStageStart || startEvent.Stage != "implement" ||
|
||||
startEvent.TaskID != execution.ID || startEvent.Attempt != execution.Attempt ||
|
||||
startEvent.Repo != "acme/widgets" || startEvent.ID == 0 {
|
||||
t.Fatalf("stage_start event = %+v, want the transition's row", startEvent)
|
||||
}
|
||||
|
||||
eventsForTask, err := s.TaskEvents(t.Context(), execution.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskEvents: %v", err)
|
||||
}
|
||||
if n := len(eventsForTask); n != 1 {
|
||||
t.Fatalf("events after StartStep = %d, want exactly the one the transition wrote", n)
|
||||
}
|
||||
|
||||
step, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stepID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded, Detail: "implemented",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("FinishStep: %v", err)
|
||||
}
|
||||
if step.Kind != events.KindStageFinish || step.Stage != "implement" || step.ID == 0 {
|
||||
t.Fatalf("stage_finish event = %+v, want the transition's row", step)
|
||||
}
|
||||
if _, ok := step.Data["duration_ms"]; !ok {
|
||||
t.Errorf("stage_finish data = %v, want duration_ms: the stage statistics read it", step.Data)
|
||||
}
|
||||
if _, has := step.Data["error"]; has {
|
||||
t.Errorf("stage_finish data = %v, want no error key for a succeeded step", step.Data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinishStepFailedCarriesTheErrorTheDashboardRenders(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
stepID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "review",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep: %v", err)
|
||||
}
|
||||
step, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stepID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepFailed, Detail: "review found 3 findings",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("FinishStep: %v", err)
|
||||
}
|
||||
if step.Data["error"] != "review found 3 findings" {
|
||||
t.Errorf("stage_finish data = %v, want the error text stageOutcome renders", step.Data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartStepRefusesWhatTheStateMachineForbids(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
seed func(s *Store, taskID int64) error
|
||||
start task.StepStart
|
||||
want error
|
||||
}{
|
||||
{
|
||||
name: "an execution that is not running",
|
||||
start: task.StepStart{Kind: task.StepKindStage, Name: "plan", Attempt: 1},
|
||||
want: storecontract.ErrIllegalTransition,
|
||||
},
|
||||
{
|
||||
name: "an execution that does not exist",
|
||||
start: task.StepStart{Kind: task.StepKindStage, Name: "plan", Attempt: 1},
|
||||
want: storecontract.ErrStaleTransition,
|
||||
},
|
||||
{
|
||||
name: "an attempt the execution no longer runs",
|
||||
start: task.StepStart{Kind: task.StepKindStage, Name: "plan", Attempt: 99},
|
||||
want: storecontract.ErrStaleTransition,
|
||||
},
|
||||
{
|
||||
name: "an unknown step kind",
|
||||
start: task.StepStart{Kind: "quantum", Name: "plan", Attempt: 1},
|
||||
want: storecontract.ErrInvalidStep,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
if tt.name == "an execution that is not running" {
|
||||
// Back on the queue: nothing may run under it. The seed rides
|
||||
// the legal running->queued edge, not a hand-written pair.
|
||||
if err := s.Transition(t.Context(), execution.ID, taskstate.Running, taskstate.Queued, "requeue"); err != nil {
|
||||
t.Fatalf("seed queued: %v", err)
|
||||
}
|
||||
}
|
||||
start := tt.start
|
||||
start.ExecutionID = execution.ID
|
||||
if tt.name == "an execution that does not exist" {
|
||||
start.ExecutionID = execution.ID + 999999
|
||||
}
|
||||
if _, _, err := s.StartStep(t.Context(), start); !errors.Is(err, tt.want) {
|
||||
t.Fatalf("StartStep = %v, want %v", err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartStepUnderATerminalParentIsIllegal(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
parentID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "review",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep parent: %v", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: parentID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded, Detail: "done",
|
||||
}); err != nil {
|
||||
t.Fatalf("FinishStep parent: %v", err)
|
||||
}
|
||||
|
||||
_, _, err = s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt,
|
||||
ParentID: parentID, Kind: task.StepKindAgent, Name: "review:2",
|
||||
})
|
||||
if !errors.Is(err, storecontract.ErrIllegalTransition) {
|
||||
t.Fatalf("StartStep under a terminal parent = %v, want ErrIllegalTransition", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStepDepthIsDerivedFromTheParent(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
parentID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep stage: %v", err)
|
||||
}
|
||||
childID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt,
|
||||
ParentID: parentID, Kind: task.StepKindAgent, Name: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep agent child: %v", err)
|
||||
}
|
||||
var depths map[int64]int
|
||||
if err := s.pool.QueryRow(t.Context(),
|
||||
`SELECT jsonb_object_agg(id, depth) FROM step_executions WHERE execution_id = $1`,
|
||||
execution.ID).Scan(&depths); err != nil {
|
||||
t.Fatalf("read depths: %v", err)
|
||||
}
|
||||
if depths[parentID] != 0 || depths[childID] != 1 {
|
||||
t.Fatalf("depths = %v, want the stage at 0 and its child at 1", depths)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinishStepRefusesStaleAndForeign(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
other := runningExecution(t, s)
|
||||
|
||||
stepID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "plan",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep: %v", err)
|
||||
}
|
||||
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stepID, ExecutionID: other.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded,
|
||||
}); !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("FinishStep naming another execution = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stepID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepSucceeded, To: taskstate.StepFailed,
|
||||
}); !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("FinishStep with an untruthful from = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stepID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepPending,
|
||||
}); !errors.Is(err, storecontract.ErrIllegalTransition) {
|
||||
t.Fatalf("FinishStep off-table pair = %v, want ErrIllegalTransition", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stepID + 999999, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded,
|
||||
}); !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("FinishStep on a missing step = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestListStepsOrdersByAttemptThenID is the dashboard run detail's
|
||||
// authoritative read (docs/prds/execution-tree-state-machine.md): every
|
||||
// attempt in one call when attempt is 0, one attempt's steps when it names
|
||||
// one, both ordered oldest first.
|
||||
func TestListStepsOrdersByAttemptThenID(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
firstStepID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "plan",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep: %v", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: firstStepID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded, Detail: "planned", TokensUsed: 42,
|
||||
}); err != nil {
|
||||
t.Fatalf("FinishStep: %v", err)
|
||||
}
|
||||
secondStepID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep: %v", err)
|
||||
}
|
||||
|
||||
steps, err := s.ListSteps(t.Context(), execution.ID, execution.Attempt)
|
||||
if err != nil {
|
||||
t.Fatalf("ListSteps: %v", err)
|
||||
}
|
||||
if len(steps) != 2 {
|
||||
t.Fatalf("ListSteps len = %d, want 2", len(steps))
|
||||
}
|
||||
if steps[0].ID != firstStepID || steps[0].Name != "plan" || steps[0].Status != taskstate.StepSucceeded ||
|
||||
steps[0].Detail != "planned" || steps[0].TokensUsed != 42 || steps[0].StartedAt.IsZero() || steps[0].FinishedAt.IsZero() {
|
||||
t.Fatalf("steps[0] = %+v, want the finished plan step", steps[0])
|
||||
}
|
||||
if steps[1].ID != secondStepID || steps[1].Name != "implement" || steps[1].Status != taskstate.StepRunning ||
|
||||
steps[1].StartedAt.IsZero() || !steps[1].FinishedAt.IsZero() {
|
||||
t.Fatalf("steps[1] = %+v, want the still-running implement step", steps[1])
|
||||
}
|
||||
|
||||
// attempt 0 lists every attempt; there is only one here, so the result is
|
||||
// the same, proving the "list everything" branch is reachable and correct
|
||||
// rather than coincidentally equal to a hardcoded attempt.
|
||||
all, err := s.ListSteps(t.Context(), execution.ID, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("ListSteps(attempt=0): %v", err)
|
||||
}
|
||||
if len(all) != 2 {
|
||||
t.Fatalf("ListSteps(attempt=0) len = %d, want 2", len(all))
|
||||
}
|
||||
|
||||
// A different execution's steps never appear, however queried.
|
||||
other := runningExecution(t, s)
|
||||
otherSteps, err := s.ListSteps(t.Context(), other.ID, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("ListSteps other execution: %v", err)
|
||||
}
|
||||
if len(otherSteps) != 0 {
|
||||
t.Fatalf("ListSteps other execution = %+v, want none", otherSteps)
|
||||
}
|
||||
}
|
||||
|
||||
// A late FinishStep for a step another path already finished is stale, the
|
||||
// PRD's named wire behaviour: errors.Is matches on the client too.
|
||||
func TestFinishStepOffTablePairIsIllegalOverTheTable(t *testing.T) {
|
||||
if !taskstate.CanStepTransition(taskstate.StepPending, taskstate.StepRunning) {
|
||||
t.Fatal("pending -> running must be in the step transition table")
|
||||
}
|
||||
if taskstate.CanStepTransition(taskstate.StepSucceeded, taskstate.StepRunning) {
|
||||
t.Fatal("succeeded -> running must not be in the step transition table: terminal is terminal")
|
||||
}
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
// Declared workflow outputs on the task row: the attempt-scoped structured
|
||||
// results a run writes (docs/prds/workflow-call-outputs.md, "Storage and
|
||||
// wire").
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
)
|
||||
|
||||
// newStoreForOutputs is a migrated pool with the Store built over it.
|
||||
func newStoreForOutputs(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
pool, _ := migrated(t)
|
||||
return New(pool)
|
||||
}
|
||||
|
||||
// TestTaskOutputs pins the task row half of the outputs model:
|
||||
//
|
||||
// - Update persists the run's written set, decoded exactly on the way out;
|
||||
// - an encoded set past the structured-payload bound is refused, not
|
||||
// clipped (clipped JSON does not parse);
|
||||
// - a claim starts the next attempt with an empty set, so nothing a
|
||||
// retried attempt does not rewrite survives.
|
||||
func TestTaskOutputs(t *testing.T) {
|
||||
t.Run("Update persists the run's outputs and TaskByID reads them back", func(t *testing.T) {
|
||||
st := newStoreForOutputs(t)
|
||||
ctx := t.Context()
|
||||
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "callee", "body", "w", "", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.ClaimNext(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
row, err := st.TaskByID(ctx, task.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
row.Outputs = map[string]any{"contained": true, "n": "3"}
|
||||
if err := st.Update(ctx, row); err != nil {
|
||||
t.Fatalf("Update: %v", err)
|
||||
}
|
||||
back, err := st.TaskByID(ctx, task.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if back.Outputs["contained"] != true || back.Outputs["n"] != "3" {
|
||||
t.Fatalf("row outputs = %+v, want the written set read back", back.Outputs)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an encoded set past the structured-payload bound is refused", func(t *testing.T) {
|
||||
st := newStoreForOutputs(t)
|
||||
ctx := t.Context()
|
||||
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "callee", "body", "w", "", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.ClaimNext(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
row, err := st.TaskByID(ctx, task.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
row.Outputs = map[string]any{"summary": strings.Repeat("x", 5000)}
|
||||
err = st.Update(ctx, row)
|
||||
if err == nil {
|
||||
t.Fatal("Update accepted a set past the structured-payload bound; it must be refused, not clipped")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "outputs") {
|
||||
t.Fatalf("refusal = %v, want it to name the outputs", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a retried attempt starts with an empty set", func(t *testing.T) {
|
||||
st := newStoreForOutputs(t)
|
||||
ctx := t.Context()
|
||||
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "callee", "body", "w", "", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := st.ClaimNext(ctx)
|
||||
if err != nil || first == nil {
|
||||
t.Fatalf("first claim: (%+v, %v)", first, err)
|
||||
}
|
||||
if first.Outputs != nil {
|
||||
t.Fatalf("first claim outputs = %+v, want the empty set the fresh attempt starts with", first.Outputs)
|
||||
}
|
||||
row, err := st.TaskByID(ctx, task.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
row.Outputs = map[string]any{"contained": true}
|
||||
if err := st.Update(ctx, row); err != nil {
|
||||
t.Fatalf("Update: %v", err)
|
||||
}
|
||||
back, err := st.TaskByID(ctx, task.ID)
|
||||
if err != nil || back.Outputs["contained"] != true {
|
||||
t.Fatalf("setup: the attempt's outputs did not reach the row: (%+v, %v)", back.Outputs, err)
|
||||
}
|
||||
if err := st.Transition(ctx, task.ID, workflow.StatusRunning, workflow.StatusParked, "needs a look"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := st.RetryTask(ctx, task.ID, workflow.StatusParked, "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := st.ClaimNext(ctx)
|
||||
if err != nil || second == nil {
|
||||
t.Fatalf("retried claim: (%+v, %v)", second, err)
|
||||
}
|
||||
if task.ID != second.ID {
|
||||
t.Skipf("another queued task claimed first; the idempotent queue handed out %d", second.ID)
|
||||
}
|
||||
if second.Outputs != nil {
|
||||
t.Fatalf("retried attempt outputs = %+v, want the empty set", second.Outputs)
|
||||
}
|
||||
final, err := st.TaskByID(ctx, task.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, still := final.Outputs["contained"]; still {
|
||||
t.Fatalf("row outputs = %+v, want the emptiness the new attempt starts with", final.Outputs)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate/taskstatetest"
|
||||
)
|
||||
|
||||
// Enforcement of the shared transition table (docs/prds/execution-tree-state-machine.md):
|
||||
// a status write whose from->to pair the table does not route is refused with
|
||||
// ErrIllegalTransition, leaves the row untouched and writes no audit row --
|
||||
// the same three guarantees a stale from already had under ErrStaleTransition.
|
||||
|
||||
// TestIllegalTransitionsAreRejected drives every caller-supplied status write
|
||||
// through an illegal pair and asserts the refusal is total: sentinel, status,
|
||||
// audit trail.
|
||||
func TestIllegalTransitionsAreRejected(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
seed string // status the task is parked in before the write
|
||||
write func(s *Store, taskID int64) error
|
||||
}{
|
||||
{name: "transition queued->parked", seed: taskstate.Queued, write: func(s *Store, taskID int64) error {
|
||||
return s.Transition(t.Context(), taskID, taskstate.Queued, taskstate.Parked, "why")
|
||||
}},
|
||||
{name: "transition running->merged", seed: taskstate.Running, write: func(s *Store, taskID int64) error {
|
||||
return s.Transition(t.Context(), taskID, taskstate.Running, taskstate.Merged, "why")
|
||||
}},
|
||||
{name: "transition running->rejected", seed: taskstate.Running, write: func(s *Store, taskID int64) error {
|
||||
return s.Transition(t.Context(), taskID, taskstate.Running, taskstate.Rejected, "why")
|
||||
}},
|
||||
{name: "transition parked->running", seed: taskstate.Parked, write: func(s *Store, taskID int64) error {
|
||||
return s.Transition(t.Context(), taskID, taskstate.Parked, taskstate.Running, "why")
|
||||
}},
|
||||
{name: "transition waiting_human->pr_open", seed: taskstate.WaitingHuman, write: func(s *Store, taskID int64) error {
|
||||
return s.Transition(t.Context(), taskID, taskstate.WaitingHuman, taskstate.PROpen, "why")
|
||||
}},
|
||||
{name: "transition out of terminal merged", seed: taskstate.Merged, write: func(s *Store, taskID int64) error {
|
||||
return s.Transition(t.Context(), taskID, taskstate.Merged, taskstate.Queued, "why")
|
||||
}},
|
||||
{name: "park from queued", seed: taskstate.Queued, write: func(s *Store, taskID int64) error {
|
||||
return s.ParkTask(t.Context(), taskID, taskstate.Queued, "why", taskstate.ParkTransient)
|
||||
}},
|
||||
{name: "park from pr_open", seed: taskstate.PROpen, write: func(s *Store, taskID int64) error {
|
||||
return s.ParkTask(t.Context(), taskID, taskstate.PROpen, "why", taskstate.ParkTransient)
|
||||
}},
|
||||
{name: "requeue from terminal merged", seed: taskstate.Merged, write: func(s *Store, taskID int64) error {
|
||||
return s.Requeue(t.Context(), taskID, taskstate.Merged, "implement")
|
||||
}},
|
||||
{name: "retry from terminal merged", seed: taskstate.Merged, write: func(s *Store, taskID int64) error {
|
||||
return s.RetryTask(t.Context(), taskID, taskstate.Merged, "implement", "")
|
||||
}},
|
||||
{name: "retry from queued self-pair", seed: taskstate.Queued, write: func(s *Store, taskID int64) error {
|
||||
return s.RetryTask(t.Context(), taskID, taskstate.Queued, "implement", "")
|
||||
}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
task, err := s.EnqueueChatTask(t.Context(), "acme", "widgets", "t", "b", "implement", "", nil)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("EnqueueChatTask: %+v %v", task, err)
|
||||
}
|
||||
taskstatetest.Seed(t.Context(), t, s, task.ID, taskstate.Queued, tt.seed, "seed")
|
||||
before := len(transitions(t, s, task.ID))
|
||||
|
||||
err = tt.write(s, task.ID)
|
||||
if !errors.Is(err, storecontract.ErrIllegalTransition) {
|
||||
t.Fatalf("illegal write = %v, want ErrIllegalTransition", err)
|
||||
}
|
||||
got, err := s.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID: %+v %v", got, err)
|
||||
}
|
||||
if got.Status != tt.seed {
|
||||
t.Fatalf("status after refused write = %q, want %q", got.Status, tt.seed)
|
||||
}
|
||||
if n := len(transitions(t, s, task.ID)); n != before {
|
||||
t.Fatalf("refused write added %d audit row(s), want none", n-before)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Staleness still wins when the from is both untruthful and illegal: the
|
||||
// row's own status is the ground truth a caller first has to be right about
|
||||
// (a queued->merged write against a running task is stale, as the wire
|
||||
// conformance battery has always asserted).
|
||||
func TestStaleFromBeatsIllegalPair(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
task, err := s.EnqueueChatTask(t.Context(), "acme", "widgets", "t", "b", "implement", "", nil)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("EnqueueChatTask: %+v %v", task, err)
|
||||
}
|
||||
taskstatetest.Seed(t.Context(), t, s, task.ID, taskstate.Queued, taskstate.Running, "claim")
|
||||
err = s.Transition(t.Context(), task.ID, taskstate.Queued, taskstate.Merged, "why")
|
||||
if !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("untruthful from = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A legal pair still lands: the guard must not reject what the table routes,
|
||||
// and the audit row is written as before.
|
||||
func TestLegalTransitionStillWrites(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
task, err := s.EnqueueChatTask(t.Context(), "acme", "widgets", "t", "b", "implement", "", nil)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("EnqueueChatTask: %+v %v", task, err)
|
||||
}
|
||||
taskstatetest.Seed(t.Context(), t, s, task.ID, taskstate.Queued, taskstate.Running, "claim")
|
||||
if err := s.Transition(t.Context(), task.ID, taskstate.Running, taskstate.Completed, "done"); err != nil {
|
||||
t.Fatalf("legal transition running->completed = %v, want nil", err)
|
||||
}
|
||||
got, err := s.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID: %+v %v", got, err)
|
||||
}
|
||||
if got.Status != taskstate.Completed {
|
||||
t.Fatalf("status = %q, want %q", got.Status, taskstate.Completed)
|
||||
}
|
||||
rows := transitions(t, s, task.ID)
|
||||
if n := len(rows); n == 0 || rows[n-1] != (transitionRow{taskstate.Running, taskstate.Completed, "done"}) {
|
||||
t.Fatalf("last audit row = %+v, want the running->completed edge", rows)
|
||||
}
|
||||
}
|
||||
|
||||
// The status-changing methods whose from/to is pinned in SQL rather than
|
||||
// supplied by a caller (claim, BeginRemediation, RecoverStale) can only write
|
||||
// the pairs asserted here. Pinning them to the shared table keeps a query
|
||||
// edit from moving a write off the table without this file failing.
|
||||
// The step edge RecoverStale writes is table-routed too: the sweep's WHERE
|
||||
// clause pins status = 'running' and writes 'interrupted', so the pair must
|
||||
// stay legal on the STEP table for a query edit to stay on it. The step table
|
||||
// is a different table from the execution's, so it is pinned beside it rather
|
||||
// than mixed into the execution pairs above.
|
||||
func TestSQLPinnedStepTransitionsAreTableLegal(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
from, to taskstate.StepStatus
|
||||
}{{name: "crash recovery pins step running->interrupted", from: taskstate.StepRunning, to: taskstate.StepInterrupted}} {
|
||||
if !taskstate.CanStepTransition(tc.from, tc.to) {
|
||||
t.Errorf("%s: %s -> %s is not in the shared step transition table", tc.name, tc.from, tc.to)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSQLPinnedTransitionsAreTableLegal(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
from, to string
|
||||
}{
|
||||
{name: "claim pins queued->running", from: taskstate.Queued, to: taskstate.Running},
|
||||
{name: "begin remediation pins pr_open->queued", from: taskstate.PROpen, to: taskstate.Queued},
|
||||
{name: "crash recovery pins running->queued", from: taskstate.Running, to: taskstate.Queued},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if !taskstate.CanTransition(tt.from, tt.to) {
|
||||
t.Errorf("%s: %s -> %s is not in the shared transition table", tt.name, tt.from, tt.to)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate/taskstatetest"
|
||||
)
|
||||
|
||||
// TestWorkflowStatsCountsCompletedRuns pins the per-workflow count the
|
||||
// transition table made reachable: a run that finishes with no pull request
|
||||
// (a no-change build, a triage that needed no code) ends in taskstate.Completed,
|
||||
// so the workflows page has to be able to see those runs at all. The count is a
|
||||
// status filter in SQL, which fails silently when it is wrong -- a typo'd or
|
||||
// missing filter reads as zero, not as an error -- so it is asserted against the
|
||||
// store rather than left to the dashboard to notice.
|
||||
func TestWorkflowStatsCountsCompletedRuns(t *testing.T) {
|
||||
pool, q := migrated(t)
|
||||
store := New(pool)
|
||||
|
||||
finished := insertChatTask(t, q)
|
||||
merged := insertChatTask(t, q)
|
||||
finish := func(id int64, to string) {
|
||||
t.Helper()
|
||||
// Seeded along the table's edges: a merged task is merged on an open
|
||||
// pull request, and the fixture used to write running -> merged.
|
||||
taskstatetest.Seed(t.Context(), t, store, id, taskstate.Queued, to, "")
|
||||
}
|
||||
finish(finished.ID, taskstate.Completed)
|
||||
finish(merged.ID, taskstate.Merged)
|
||||
|
||||
stats, err := store.WorkflowStats(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("WorkflowStats: %v", err)
|
||||
}
|
||||
if len(stats) != 1 {
|
||||
t.Fatalf("WorkflowStats = %+v, want one row for %q", stats, finished.Workflow)
|
||||
}
|
||||
got := stats[0]
|
||||
if got.Workflow != merged.Workflow {
|
||||
t.Fatalf("WorkflowStats row is %q, want %q", got.Workflow, merged.Workflow)
|
||||
}
|
||||
if got.Runs != 2 || got.Completed != 1 || got.Merged != 1 {
|
||||
t.Errorf("WorkflowStats = %+v, want runs 2, completed 1, merged 1: the completed count has to be its own status, not a share of merged", got)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user