package app import ( "bytes" "context" "errors" "os" "path/filepath" "testing" "time" "gitea.maximumdirect.net/eric/narratio/internal/artifacts" "gitea.maximumdirect.net/eric/narratio/internal/config" "gitea.maximumdirect.net/eric/narratio/internal/manifest" "gitea.maximumdirect.net/eric/narratio/internal/stage" "go.maximumdirect.net/commandkit" ) type observedWorkspaceStore struct { artifacts.Store entering chan struct{} acquired chan struct{} proceed <-chan struct{} } func (s *observedWorkspaceStore) AcquireWorkspaceLockContext(ctx context.Context) (*artifacts.LockHandle, error) { if s.entering != nil { lock, err := s.Store.AcquireWorkspaceLock() if !errors.Is(err, artifacts.ErrLockConflict) { return lock, err } close(s.entering) } lock, err := s.Store.AcquireWorkspaceLockContext(ctx) if err == nil && s.acquired != nil { close(s.acquired) <-s.proceed } return lock, err } type waitingPrepare struct { entered chan struct{} release <-chan struct{} } func (s waitingPrepare) Name() string { return "prepare" } func (s waitingPrepare) Run(ctx context.Context, _ *stage.Env, _ *manifest.Manifest) (*stage.StageResult, error) { close(s.entered) select { case <-s.release: return &stage.StageResult{}, nil case <-ctx.Done(): return nil, ctx.Err() } } func TestManualCleanWaitsForActiveInvocation(t *testing.T) { for _, all := range []bool{false, true} { t.Run(map[bool]string{false: "session", true: "all"}[all], func(t *testing.T) { root := t.TempDir() pipeline, campaign, session := writeValidConfigFiles(t, root) cfg, err := config.Load(pipeline, campaign, session) if err != nil { t.Fatal(err) } entered, release := make(chan struct{}), make(chan struct{}) running := make(chan error, 1) go func() { _, err := executePlan(context.Background(), cfg, BoundedPlan{stages: []stage.Stage{waitingPrepare{entered, release}}}, RunOptions{}) running <- err }() select { case <-entered: case err := <-running: t.Fatalf("runner stopped: %v", err) case <-time.After(5 * time.Second): t.Fatal("runner did not enter") } work := artifacts.SessionWorkDirForCampaign(root, cfg.Session.Campaign, cfg.Session.SessionID) attempted := make(chan struct{}) deps := commandDependencies{newWorkspaceStore: func(root string) artifacts.Store { return &observedWorkspaceStore{Store: artifacts.NewLocalStore(root), entering: attempted} }} app, err := newApplication(deps, executePlan) if err != nil { t.Fatal(err) } args := []string{"session", "clean", cfg.Session.SessionID, "--config", pipeline, "--campaign-file", campaign, "--session-file", session} if all { args = []string{"session", "clean", "--all", "--config", pipeline} } ctx, cancel := context.WithCancel(context.Background()) result := make(chan commandkit.Outcome, 1) go func() { result <- app.Execute(ctx, args, commandkit.Streams{Out: &bytes.Buffer{}, Err: &bytes.Buffer{}}) }() select { case <-attempted: case <-time.After(5 * time.Second): t.Fatal("cleanup did not attempt lock") } if _, err := os.Stat(work); err != nil { t.Fatalf("active work removed: %v", err) } cancel() select { case out := <-result: if out.Status == 0 { t.Fatal("cancelled clean succeeded") } case <-time.After(5 * time.Second): t.Fatal("cleanup did not cancel") } if _, err := os.Stat(work); err != nil { t.Fatalf("cancelled clean removed work: %v", err) } attemptedAgain := make(chan struct{}) retryApp, err := newApplication(commandDependencies{newWorkspaceStore: func(root string) artifacts.Store { return &observedWorkspaceStore{Store: artifacts.NewLocalStore(root), entering: attemptedAgain} }}, executePlan) if err != nil { t.Fatal(err) } retry := make(chan commandkit.Outcome, 1) go func() { retry <- retryApp.Execute(context.Background(), args, commandkit.Streams{Out: &bytes.Buffer{}, Err: &bytes.Buffer{}}) }() select { case <-attemptedAgain: case <-time.After(5 * time.Second): t.Fatal("cleanup retry did not wait for lock") } close(release) if err := <-running; err != nil { t.Fatal(err) } if outcome := <-retry; outcome.Status != 0 { t.Fatalf("cleanup failed: status %d", outcome.Status) } if _, err := os.Stat(work); !errors.Is(err, os.ErrNotExist) { t.Fatalf("work remains: %v", err) } }) } } func TestCleanAllBlocksNewSessionAdmission(t *testing.T) { root := t.TempDir() pipeline, campaign, session := writeValidConfigFiles(t, root) cfg, err := config.Load(pipeline, campaign, session) if err != nil { t.Fatal(err) } cfg.Session.SessionID = "new-session" acquired, release := make(chan struct{}), make(chan struct{}) deps := commandDependencies{newWorkspaceStore: func(root string) artifacts.Store { return &observedWorkspaceStore{Store: artifacts.NewLocalStore(root), acquired: acquired, proceed: release} }} app, err := newApplication(deps, executePlan) if err != nil { t.Fatal(err) } done := make(chan commandkit.Outcome, 1) go func() { done <- app.Execute(context.Background(), []string{"session", "clean", "--all", "--config", pipeline}, commandkit.Streams{Out: &bytes.Buffer{}, Err: &bytes.Buffer{}}) }() select { case <-acquired: case <-time.After(5 * time.Second): t.Fatal("cleanup did not acquire lock") } ctx, cancel := context.WithCancel(context.Background()) attempted := make(chan struct{}) result := make(chan error, 1) store := &observedWorkspaceStore{Store: artifacts.NewLocalStore(root), entering: attempted} go func() { _, err := executeStages(ctx, cfg, nil, RunOptions{Env: &Env{ArtifactStore: store}}) result <- err }() select { case <-attempted: case <-time.After(5 * time.Second): t.Fatal("new invocation did not attempt lock") } cancel() err = <-result if !errors.Is(err, context.Canceled) { t.Fatalf("new invocation: %v", err) } if _, err := os.Stat(filepath.Join(root, "work")); !errors.Is(err, os.ErrNotExist) { t.Fatalf("new session created work: %v", err) } close(release) if out := <-done; out.Status != 0 { t.Fatalf("clean status = %d", out.Status) } } func TestSessionInitWaitsWhenOutputIsManaged(t *testing.T) { root := t.TempDir() pipeline, campaign, _ := writeValidConfigFiles(t, root) store := artifacts.NewLocalStore(root) lock, err := store.AcquireWorkspaceLock() if err != nil { t.Fatal(err) } defer store.ReleaseWorkspaceLock(lock) attempted := make(chan struct{}) deps := commandDependencies{newWorkspaceStore: func(root string) artifacts.Store { return &observedWorkspaceStore{Store: artifacts.NewLocalStore(root), entering: attempted} }} app, err := newApplication(deps, executePlan) if err != nil { t.Fatal(err) } output := filepath.Join(root, "work", "sample-campaign", "new", "session.yml") ctx, cancel := context.WithCancel(context.Background()) done := make(chan commandkit.Outcome, 1) go func() { done <- app.Execute(ctx, []string{"session", "init", "2026-06-07", "--config", pipeline, "--campaign-file", campaign, "--output", output}, commandkit.Streams{Out: &bytes.Buffer{}, Err: &bytes.Buffer{}}) }() select { case <-attempted: case <-time.After(5 * time.Second): t.Fatal("initialization did not attempt lock") } cancel() if out := <-done; out.Status == 0 { t.Fatal("cancelled initialization succeeded") } if _, err := os.Stat(output); !errors.Is(err, os.ErrNotExist) { t.Fatalf("output created: %v", err) } }