Keep one verified copy of session audio
This commit is contained in:
@@ -636,6 +636,13 @@ creating a parallel orchestration harness.
|
|||||||
|
|
||||||
## Stage 17 — Simplify audio acquisition to one retained session copy
|
## Stage 17 — Simplify audio acquisition to one retained session copy
|
||||||
|
|
||||||
|
**Complete.** Commit: `Keep one verified copy of session audio`.
|
||||||
|
Verification: focused audio, prepare, resume, cleanup, and command tests passed,
|
||||||
|
including reuse, changed or missing sources, corrupt bytes, failed download and
|
||||||
|
retry, and preservation of historical storage. All packages compile with
|
||||||
|
`go test ./... -run '^$'` using Go 1.27.4. Restore integration and remaining old
|
||||||
|
fixtures are reconciled in the subsequent restore and test cutover stages.
|
||||||
|
|
||||||
**Read:** roadmap “Audio acquisition”; current audio and restore contracts.
|
**Read:** roadmap “Audio acquisition”; current audio and restore contracts.
|
||||||
Entry points: `internal/audio`, prepare audio handling, artifact spool/cache
|
Entry points: `internal/audio`, prepare audio handling, artifact spool/cache
|
||||||
helpers, configuration, and manifest local-path bookkeeping.
|
helpers, configuration, and manifest local-path bookkeeping.
|
||||||
|
|||||||
@@ -1,43 +1,5 @@
|
|||||||
package app
|
package app
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
func cleanableRootChildren(root, policy string) (string, []string, error) {
|
|
||||||
rootAbs, exists, err := validateCleanRoot(root, policy)
|
|
||||||
if err != nil {
|
|
||||||
return "", nil, err
|
|
||||||
}
|
|
||||||
if !exists {
|
|
||||||
return rootAbs, nil, nil
|
|
||||||
}
|
|
||||||
entries, err := os.ReadDir(rootAbs)
|
|
||||||
if err != nil {
|
|
||||||
return "", nil, fmt.Errorf("cleanup policy %s: read root %q: %w", policy, rootAbs, err)
|
|
||||||
}
|
|
||||||
out := make([]string, 0, len(entries))
|
|
||||||
for _, entry := range entries {
|
|
||||||
path := filepath.Join(rootAbs, entry.Name())
|
|
||||||
info, err := os.Lstat(path)
|
|
||||||
if err != nil {
|
|
||||||
return "", nil, fmt.Errorf("cleanup policy %s: stat child %q: %w", policy, path, err)
|
|
||||||
}
|
|
||||||
if info.Mode()&os.ModeSymlink != 0 {
|
|
||||||
return "", nil, fmt.Errorf("cleanup policy %s: refusing to delete symlink path %q", policy, path)
|
|
||||||
}
|
|
||||||
out = append(out, path)
|
|
||||||
}
|
|
||||||
return rootAbs, out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func validateScopedFile(root, target, policy string) (scopedDir, error) {
|
func validateScopedFile(root, target, policy string) (scopedDir, error) {
|
||||||
return validateScopedTarget(root, target, policy, false)
|
return validateScopedTarget(root, target, policy, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
func cleanIsFlac(path string) bool {
|
|
||||||
return strings.EqualFold(filepath.Ext(path), ".flac")
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
||||||
@@ -14,9 +13,9 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type cleanCommandInput struct {
|
type cleanCommandInput struct {
|
||||||
Selection configurationSelection
|
Selection configurationSelection
|
||||||
PreviousSession commandkit.Supplied[string]
|
PreviousSession commandkit.Supplied[string]
|
||||||
All, DryRun, ClearCache bool
|
All, DryRun bool
|
||||||
}
|
}
|
||||||
type cleanCommandReport struct {
|
type cleanCommandReport struct {
|
||||||
Campaign string `json:"campaign,omitempty"`
|
Campaign string `json:"campaign,omitempty"`
|
||||||
@@ -24,7 +23,6 @@ type cleanCommandReport struct {
|
|||||||
All bool `json:"all"`
|
All bool `json:"all"`
|
||||||
DryRun bool `json:"dry_run"`
|
DryRun bool `json:"dry_run"`
|
||||||
Complete bool `json:"complete"`
|
Complete bool `json:"complete"`
|
||||||
Cache string `json:"cache"`
|
|
||||||
Actions []cleanAction `json:"actions"`
|
Actions []cleanAction `json:"actions"`
|
||||||
Error string `json:"error,omitempty"`
|
Error string `json:"error,omitempty"`
|
||||||
}
|
}
|
||||||
@@ -50,12 +48,11 @@ func checkCleanInput(input *cleanCommandInput) error {
|
|||||||
|
|
||||||
func cleanCommand(deps commandDependencies) commandkit.Command {
|
func cleanCommand(deps commandDependencies) commandkit.Command {
|
||||||
common := newConfigurationFlags(func(input **cleanCommandInput) *configurationSelection { return &(*input).Selection })
|
common := newConfigurationFlags(func(input **cleanCommandInput) *configurationSelection { return &(*input).Selection })
|
||||||
return commandkit.NewCommand(commandkit.CommandSpec[*cleanCommandInput]{Name: "clean", Summary: "Remove selected local session data, preserving cache unless requested.", NewInput: func() *cleanCommandInput { return &cleanCommandInput{} },
|
return commandkit.NewCommand(commandkit.CommandSpec[*cleanCommandInput]{Name: "clean", Summary: "Remove selected local session data.", NewInput: func() *cleanCommandInput { return &cleanCommandInput{} },
|
||||||
Flags: []commandkit.Flag[*cleanCommandInput]{common.Config, common.Overlay, common.Campaign, common.CampaignFile, common.SessionFile, common.PartyFile,
|
Flags: []commandkit.Flag[*cleanCommandInput]{common.Config, common.Overlay, common.Campaign, common.CampaignFile, common.SessionFile, common.PartyFile,
|
||||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "previous-session-id", Usage: "Assert the previous session identity."}, nil, stringValue, func(input **cleanCommandInput, value commandkit.Supplied[string]) { (*input).PreviousSession = value }),
|
commandkit.ValueFlag(commandkit.FlagMeta{Name: "previous-session-id", Usage: "Assert the previous session identity."}, nil, stringValue, func(input **cleanCommandInput, value commandkit.Supplied[string]) { (*input).PreviousSession = value }),
|
||||||
commandkit.BoolFlag(commandkit.FlagMeta{Name: "all", Usage: "Clean all local session workspace and spool entries."}, false, func(input **cleanCommandInput, value commandkit.Supplied[bool]) { (*input).All = value.Value }),
|
commandkit.BoolFlag(commandkit.FlagMeta{Name: "all", Usage: "Clean all local session workspace entries."}, false, func(input **cleanCommandInput, value commandkit.Supplied[bool]) { (*input).All = value.Value }),
|
||||||
commandkit.BoolFlag(commandkit.FlagMeta{Name: "dry-run", Usage: "Preview exact paths without deleting them."}, false, func(input **cleanCommandInput, value commandkit.Supplied[bool]) { (*input).DryRun = value.Value }),
|
commandkit.BoolFlag(commandkit.FlagMeta{Name: "dry-run", Usage: "Preview exact paths without deleting them."}, false, func(input **cleanCommandInput, value commandkit.Supplied[bool]) { (*input).DryRun = value.Value }),
|
||||||
commandkit.BoolFlag(commandkit.FlagMeta{Name: "clear-cache", Usage: "Also remove the selected S3 audio cache entries."}, false, func(input **cleanCommandInput, value commandkit.Supplied[bool]) { (*input).ClearCache = value.Value }),
|
|
||||||
},
|
},
|
||||||
Arguments: []commandkit.Argument[*cleanCommandInput]{commandkit.ValueArgument(commandkit.ArgumentMeta{Name: "SESSION", Usage: "Session identity, omitted with --all."}, false, stringValue, func(input **cleanCommandInput, value commandkit.Supplied[string]) { (*input).Selection.Session = value })},
|
Arguments: []commandkit.Argument[*cleanCommandInput]{commandkit.ValueArgument(commandkit.ArgumentMeta{Name: "SESSION", Usage: "Session identity, omitted with --all."}, false, stringValue, func(input **cleanCommandInput, value commandkit.Supplied[string]) { (*input).Selection.Session = value })},
|
||||||
CheckInput: checkCleanInput,
|
CheckInput: checkCleanInput,
|
||||||
@@ -82,10 +79,7 @@ func cleanSelectedSession(ctx context.Context, input *cleanCommandInput, deps co
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
report = &cleanCommandReport{All: input.All, DryRun: input.DryRun, Cache: "preserved", Actions: []cleanAction{}}
|
report = &cleanCommandReport{All: input.All, DryRun: input.DryRun, Actions: []cleanAction{}}
|
||||||
if input.ClearCache {
|
|
||||||
report.Cache = "requested"
|
|
||||||
}
|
|
||||||
pipeline, err := acquired.Pipeline(ctx)
|
pipeline, err := acquired.Pipeline(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return report, err
|
return report, err
|
||||||
@@ -102,24 +96,6 @@ func cleanSelectedSession(ctx context.Context, input *cleanCommandInput, deps co
|
|||||||
if err := appendTarget(pipeline.Workspace.Root, filepath.Join(pipeline.Workspace.Root, config.PathWorkDirSegment), "clean.workspace.all", true); err != nil {
|
if err := appendTarget(pipeline.Workspace.Root, filepath.Join(pipeline.Workspace.Root, config.PathWorkDirSegment), "clean.workspace.all", true); err != nil {
|
||||||
return report, err
|
return report, err
|
||||||
}
|
}
|
||||||
actions, err := cleanRootChildren(ctx, pipeline.Spool.Root, "clean.spool.all", input.DryRun)
|
|
||||||
report.Actions = append(report.Actions, actions...)
|
|
||||||
if err != nil {
|
|
||||||
return report, err
|
|
||||||
}
|
|
||||||
if input.ClearCache {
|
|
||||||
if pipeline.Storage.S3 == nil || strings.TrimSpace(pipeline.Storage.S3.Bucket) == "" {
|
|
||||||
return report, fmt.Errorf("clear cache requires pipeline.storage.s3.bucket")
|
|
||||||
}
|
|
||||||
namespace, err := artifacts.S3AudioCacheNamespaceDir(pipeline.Cache.Root, pipeline.Storage.S3.Bucket, pipeline.Storage.S3.RootPrefix)
|
|
||||||
if err != nil {
|
|
||||||
return report, err
|
|
||||||
}
|
|
||||||
if err := appendTarget(pipeline.Cache.Root, namespace, "clean.cache.all", true); err != nil {
|
|
||||||
return report, err
|
|
||||||
}
|
|
||||||
report.Cache = "processed"
|
|
||||||
}
|
|
||||||
return report, nil
|
return report, nil
|
||||||
}
|
}
|
||||||
cfg, err := acquired.Domain(ctx)
|
cfg, err := acquired.Domain(ctx)
|
||||||
@@ -129,25 +105,9 @@ func cleanSelectedSession(ctx context.Context, input *cleanCommandInput, deps co
|
|||||||
report.Campaign = cfg.Session.Campaign
|
report.Campaign = cfg.Session.Campaign
|
||||||
report.SessionID = cfg.Session.SessionID
|
report.SessionID = cfg.Session.SessionID
|
||||||
work := artifacts.SessionWorkDirForCampaign(pipeline.Workspace.Root, report.Campaign, report.SessionID)
|
work := artifacts.SessionWorkDirForCampaign(pipeline.Workspace.Root, report.Campaign, report.SessionID)
|
||||||
spool := artifacts.SessionSpoolDir(pipeline.Spool.Root, report.Campaign, report.SessionID)
|
|
||||||
if err := appendTarget(pipeline.Workspace.Root, work, "clean.workspace.session", true); err != nil {
|
if err := appendTarget(pipeline.Workspace.Root, work, "clean.workspace.session", true); err != nil {
|
||||||
return report, err
|
return report, err
|
||||||
}
|
}
|
||||||
if err := appendTarget(pipeline.Spool.Root, spool, "clean.spool.session", true); err != nil {
|
|
||||||
return report, err
|
|
||||||
}
|
|
||||||
if input.ClearCache {
|
|
||||||
if cfg.Session.Inputs.AudioS3 == nil {
|
|
||||||
report.Cache = "not_applicable"
|
|
||||||
return report, nil
|
|
||||||
}
|
|
||||||
actions, err := cleanSessionCache(ctx, cfg, input.DryRun, deps)
|
|
||||||
report.Actions = append(report.Actions, actions...)
|
|
||||||
if err != nil {
|
|
||||||
return report, err
|
|
||||||
}
|
|
||||||
report.Cache = "processed"
|
|
||||||
}
|
|
||||||
return report, nil
|
return report, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -174,66 +134,3 @@ func cleanScopedTarget(root, target, policy string, directory, dryRun bool) (cle
|
|||||||
action.Status = "deleted"
|
action.Status = "deleted"
|
||||||
return action, nil
|
return action, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func cleanRootChildren(ctx context.Context, root, policy string, dryRun bool) ([]cleanAction, error) {
|
|
||||||
rootAbs, entries, err := cleanableRootChildren(root, policy)
|
|
||||||
if err != nil {
|
|
||||||
return []cleanAction{{Path: root, Status: "failed", Error: err.Error()}}, err
|
|
||||||
}
|
|
||||||
if len(entries) == 0 {
|
|
||||||
return []cleanAction{{Path: rootAbs, Status: "empty"}}, nil
|
|
||||||
}
|
|
||||||
actions := make([]cleanAction, 0, len(entries))
|
|
||||||
for _, entry := range entries {
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return actions, err
|
|
||||||
}
|
|
||||||
action := cleanAction{Path: entry, Status: "would_delete"}
|
|
||||||
if !dryRun {
|
|
||||||
if err := fileops.RemoveAllUnderRoot(rootAbs, entry); err != nil {
|
|
||||||
action.Status = "failed"
|
|
||||||
action.Error = err.Error()
|
|
||||||
return append(actions, action), fmt.Errorf("cleanup policy %s: remove %q: %w", policy, entry, err)
|
|
||||||
}
|
|
||||||
action.Status = "deleted"
|
|
||||||
}
|
|
||||||
actions = append(actions, action)
|
|
||||||
}
|
|
||||||
return actions, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func cleanSessionCache(ctx context.Context, cfg *config.Config, dryRun bool, deps commandDependencies) ([]cleanAction, error) {
|
|
||||||
if cfg.Pipeline.Storage.S3 == nil || strings.TrimSpace(cfg.Pipeline.Storage.S3.Bucket) == "" {
|
|
||||||
return nil, fmt.Errorf("clear cache requires pipeline.storage.s3.bucket")
|
|
||||||
}
|
|
||||||
store, err := newCommandObjectStoreWithDependencies(ctx, cfg, deps)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("initialize object store for cache cleanup: %w", err)
|
|
||||||
}
|
|
||||||
prefix := artifacts.S3SessionPrefix(cfg.Pipeline.Storage.S3.RootPrefix, cfg.Session.Campaign, cfg.Session.SessionID)
|
|
||||||
audioPrefix := artifacts.S3AudioPrefix(prefix, cfg.Session.Inputs.AudioS3.Prefix)
|
|
||||||
objects, err := store.List(ctx, audioPrefix)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("list s3 audio objects under %q: %w", audioPrefix, err)
|
|
||||||
}
|
|
||||||
actions := []cleanAction{}
|
|
||||||
for _, object := range objects {
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return actions, err
|
|
||||||
}
|
|
||||||
key := strings.TrimSpace(object.Key)
|
|
||||||
if key == "" || strings.HasSuffix(key, "/") || !cleanIsFlac(key) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
cache, err := artifacts.S3AudioCachePath(cfg.Pipeline.Cache.Root, cfg.Pipeline.Storage.S3.Bucket, key)
|
|
||||||
if err != nil {
|
|
||||||
return actions, err
|
|
||||||
}
|
|
||||||
action, err := cleanScopedTarget(cfg.Pipeline.Cache.Root, cache, "clean.cache.session", false, dryRun)
|
|
||||||
actions = append(actions, action)
|
|
||||||
if err != nil {
|
|
||||||
return actions, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return actions, nil
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -4,47 +4,14 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"os"
|
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
||||||
"go.maximumdirect.net/commandkit"
|
"go.maximumdirect.net/commandkit"
|
||||||
configkit "go.maximumdirect.net/configkit"
|
configkit "go.maximumdirect.net/configkit"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestCleanCommandReportsCompletedActionsBeforeLaterFailure(t *testing.T) {
|
|
||||||
workspace := t.TempDir()
|
|
||||||
pipeline, campaign, session := writeValidConfigFiles(t, workspace)
|
|
||||||
work := artifacts.SessionWorkDirForCampaign(workspace, "sample-campaign", "2026-05-03")
|
|
||||||
mustWriteTestFile(t, filepath.Join(work, "manifest.json"), "{}")
|
|
||||||
spool := artifacts.SessionSpoolDir(filepath.Join(workspace, "spool"), "sample-campaign", "2026-05-03")
|
|
||||||
if err := os.MkdirAll(filepath.Dir(spool), 0755); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
outside := t.TempDir()
|
|
||||||
sentinel := filepath.Join(outside, "retained")
|
|
||||||
mustWriteTestFile(t, sentinel, "retained")
|
|
||||||
if err := os.Symlink(outside, spool); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
var out, diagnostic bytes.Buffer
|
|
||||||
outcome := Execute(context.Background(), []string{"session", "clean", "2026-05-03", "--config", pipeline, "--campaign-file", campaign, "--session-file", session, "--format", "json"}, commandkit.Streams{Out: &out, Err: &diagnostic})
|
|
||||||
if outcome.Status != 1 {
|
|
||||||
t.Fatalf("status=%d diagnostics=%s", outcome.Status, diagnostic.String())
|
|
||||||
}
|
|
||||||
var report cleanCommandReport
|
|
||||||
if err := json.Unmarshal(out.Bytes(), &report); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if report.Complete || len(report.Actions) != 2 || report.Actions[0].Status != "deleted" || report.Actions[1].Status != "failed" || report.Error == "" {
|
|
||||||
t.Fatalf("partial report=%#v", report)
|
|
||||||
}
|
|
||||||
cleanAssertMissing(t, work)
|
|
||||||
cleanAssertExists(t, sentinel)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCleanCommandChecksAllSelectionBeforeBootstrap(t *testing.T) {
|
func TestCleanCommandChecksAllSelectionBeforeBootstrap(t *testing.T) {
|
||||||
app, err := newApplication(commandDependencies{
|
app, err := newApplication(commandDependencies{
|
||||||
preparePipelineSource: func(configkit.Source) (*configkit.SecretsReport, configkit.Source, error) {
|
preparePipelineSource: func(configkit.Source) (*configkit.SecretsReport, configkit.Source, error) {
|
||||||
@@ -80,7 +47,7 @@ func TestCleanCommandChecksAllSelectionBeforeBootstrap(t *testing.T) {
|
|||||||
func TestCleanAllCommandNeedsOnlyPipelineConfiguration(t *testing.T) {
|
func TestCleanAllCommandNeedsOnlyPipelineConfiguration(t *testing.T) {
|
||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
pipeline := filepath.Join(root, "pipeline.yml")
|
pipeline := filepath.Join(root, "pipeline.yml")
|
||||||
mustWriteTestFile(t, pipeline, "workspace: {root: ./workspace}\nspool: {root: ./spool}\nwhisperx: {transcribe_url: https://transcription.example.test/transcribe}\n")
|
mustWriteTestFile(t, pipeline, "workspace: {root: ./workspace}\nwhisperx: {transcribe_url: https://transcription.example.test/transcribe}\n")
|
||||||
var out, diagnostic bytes.Buffer
|
var out, diagnostic bytes.Buffer
|
||||||
outcome := Execute(context.Background(), []string{"session", "clean", "--all", "--dry-run", "--config", pipeline, "--format", "json"}, commandkit.Streams{Out: &out, Err: &diagnostic})
|
outcome := Execute(context.Background(), []string{"session", "clean", "--all", "--dry-run", "--config", pipeline, "--format", "json"}, commandkit.Streams{Out: &out, Err: &diagnostic})
|
||||||
if outcome.Status != 0 {
|
if outcome.Status != 0 {
|
||||||
@@ -90,7 +57,7 @@ func TestCleanAllCommandNeedsOnlyPipelineConfiguration(t *testing.T) {
|
|||||||
if err := json.Unmarshal(out.Bytes(), &report); err != nil {
|
if err := json.Unmarshal(out.Bytes(), &report); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if !report.All || !report.DryRun || report.Complete || report.Campaign != "" || report.Cache != "preserved" {
|
if !report.All || !report.DryRun || report.Complete || report.Campaign != "" {
|
||||||
t.Fatalf("report=%#v", report)
|
t.Fatalf("report=%#v", report)
|
||||||
}
|
}
|
||||||
cleanAssertMissing(t, filepath.Join(root, "workspace"))
|
cleanAssertMissing(t, filepath.Join(root, "workspace"))
|
||||||
|
|||||||
@@ -7,42 +7,32 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
|
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestExecuteCleanSessionDeletesWorkAndSpoolButPreservesCache(t *testing.T) {
|
func TestExecuteCleanSessionPreservesHistoricalAudioStorage(t *testing.T) {
|
||||||
workspaceRoot := t.TempDir()
|
root := t.TempDir()
|
||||||
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
|
pipeline, campaign, session := writeValidConfigFiles(t, root)
|
||||||
workDir := artifacts.SessionWorkDirForCampaign(workspaceRoot, "sample-campaign", "2026-05-03")
|
work := artifacts.SessionWorkDirForCampaign(root, "sample-campaign", "2026-05-03")
|
||||||
spoolDir := artifacts.SessionSpoolDir(filepath.Join(workspaceRoot, "spool"), "sample-campaign", "2026-05-03")
|
historical := filepath.Join(root, "spool", "sample-campaign", "2026-05-03", "audio.flac")
|
||||||
cachePath, err := artifacts.S3AudioCachePath(filepath.Join(workspaceRoot, "cache"), "test-bucket", "dnd/campaigns/sample-campaign/sessions/2026-05-03/audio/alice.flac")
|
cache := filepath.Join(root, "cache", "old.flac")
|
||||||
if err != nil {
|
mustWriteTestFile(t, filepath.Join(work, "manifest.json"), "{}")
|
||||||
t.Fatalf("S3AudioCachePath() error = %v", err)
|
mustWriteTestFile(t, historical, "recording")
|
||||||
}
|
mustWriteTestFile(t, cache, "cached")
|
||||||
mustWriteTestFile(t, filepath.Join(workDir, "manifest.json"), "{}")
|
var stdout, stderr bytes.Buffer
|
||||||
mustWriteTestFile(t, filepath.Join(spoolDir, "run-1", "audio", "alice.flac"), "audio")
|
if code := executeForTest([]string{"session", "clean", "2026-05-03", "--config", pipeline, "--campaign-file", campaign, "--session-file", session}, &stdout, &stderr); code != 0 {
|
||||||
mustWriteTestFile(t, cachePath, "cached-audio")
|
t.Fatalf("exit=%d stderr=%s", code, stderr.String())
|
||||||
|
|
||||||
var stdout bytes.Buffer
|
|
||||||
var stderr bytes.Buffer
|
|
||||||
code := executeForTest([]string{"session", "clean", "2026-05-03", "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath}, &stdout, &stderr)
|
|
||||||
if code != 0 {
|
|
||||||
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
|
|
||||||
}
|
|
||||||
cleanAssertMissing(t, workDir)
|
|
||||||
cleanAssertMissing(t, spoolDir)
|
|
||||||
cleanAssertExists(t, cachePath)
|
|
||||||
if !strings.Contains(stdout.String(), "cache: preserved") {
|
|
||||||
t.Fatalf("stdout = %q, want cache preserved", stdout.String())
|
|
||||||
}
|
}
|
||||||
|
cleanAssertMissing(t, work)
|
||||||
|
cleanAssertExists(t, historical)
|
||||||
|
cleanAssertExists(t, cache)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestExecuteCleanSessionDryRunDeletesNothing(t *testing.T) {
|
func TestExecuteCleanSessionDryRunDeletesNothing(t *testing.T) {
|
||||||
workspaceRoot := t.TempDir()
|
workspaceRoot := t.TempDir()
|
||||||
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
|
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
|
||||||
workDir := artifacts.SessionWorkDirForCampaign(workspaceRoot, "sample-campaign", "2026-05-03")
|
workDir := artifacts.SessionWorkDirForCampaign(workspaceRoot, "sample-campaign", "2026-05-03")
|
||||||
spoolDir := artifacts.SessionSpoolDir(filepath.Join(workspaceRoot, "spool"), "sample-campaign", "2026-05-03")
|
spoolDir := filepath.Join(workspaceRoot, "spool", "sample-campaign", "2026-05-03")
|
||||||
mustWriteTestFile(t, filepath.Join(workDir, "manifest.json"), "{}")
|
mustWriteTestFile(t, filepath.Join(workDir, "manifest.json"), "{}")
|
||||||
mustWriteTestFile(t, filepath.Join(spoolDir, "run-1", "audio", "alice.flac"), "audio")
|
mustWriteTestFile(t, filepath.Join(spoolDir, "run-1", "audio", "alice.flac"), "audio")
|
||||||
|
|
||||||
@@ -74,64 +64,7 @@ func TestExecuteCleanMissingSessionPathsSucceeds(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestExecuteCleanSessionClearCacheRemovesOnlyS3AudioCache(t *testing.T) {
|
func TestExecuteCleanAllPreservesHistoricalAudioStorage(t *testing.T) {
|
||||||
workspaceRoot := t.TempDir()
|
|
||||||
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
|
|
||||||
if err := os.WriteFile(sessionPath, []byte(`session_id: 2026-05-03
|
|
||||||
inputs:
|
|
||||||
audio_s3:
|
|
||||||
prefix: audio/
|
|
||||||
`), 0o644); err != nil {
|
|
||||||
t.Fatalf("write session: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
audioKey := "dnd/campaigns/sample-campaign/sessions/2026-05-03/audio/alice.flac"
|
|
||||||
fake := &storage.FakeBackend{}
|
|
||||||
fake.SeedObject(storage.FakeObject{Key: audioKey, Data: []byte("audio")})
|
|
||||||
var storeInitCalls int
|
|
||||||
deps := fakeCommandDependencies(fake, &storeInitCalls)
|
|
||||||
|
|
||||||
cacheRoot := filepath.Join(workspaceRoot, "cache")
|
|
||||||
cachePath, err := artifacts.S3AudioCachePath(cacheRoot, "test-bucket", audioKey)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("S3AudioCachePath() error = %v", err)
|
|
||||||
}
|
|
||||||
otherCachePath, err := artifacts.S3AudioCachePath(cacheRoot, "test-bucket", "dnd/campaigns/other/sessions/2026-05-03/audio/bob.flac")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("S3AudioCachePath() error = %v", err)
|
|
||||||
}
|
|
||||||
mustWriteTestFile(t, cachePath, "cached-audio")
|
|
||||||
mustWriteTestFile(t, otherCachePath, "other-audio")
|
|
||||||
|
|
||||||
var stdout bytes.Buffer
|
|
||||||
var stderr bytes.Buffer
|
|
||||||
code := executeWithDependencies([]string{"session", "clean", "2026-05-03", "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath, "--clear-cache"}, &stdout, &stderr, deps, executePlan)
|
|
||||||
if code != 0 {
|
|
||||||
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
|
|
||||||
}
|
|
||||||
cleanAssertMissing(t, cachePath)
|
|
||||||
cleanAssertExists(t, otherCachePath)
|
|
||||||
if storeInitCalls != 1 {
|
|
||||||
t.Fatalf("object store init calls = %d, want 1", storeInitCalls)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestExecuteCleanLocalAudioClearCacheIsNoop(t *testing.T) {
|
|
||||||
workspaceRoot := t.TempDir()
|
|
||||||
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
|
|
||||||
|
|
||||||
var stdout bytes.Buffer
|
|
||||||
var stderr bytes.Buffer
|
|
||||||
code := executeForTest([]string{"session", "clean", "2026-05-03", "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath, "--clear-cache"}, &stdout, &stderr)
|
|
||||||
if code != 0 {
|
|
||||||
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
|
|
||||||
}
|
|
||||||
if !strings.Contains(stdout.String(), "cache: not_applicable") {
|
|
||||||
t.Fatalf("stdout = %q, want local audio cache no-op", stdout.String())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestExecuteCleanAllDeletesWorkAndSpoolContentsButPreservesCache(t *testing.T) {
|
|
||||||
workspaceRoot := t.TempDir()
|
workspaceRoot := t.TempDir()
|
||||||
pipelinePath, _, _ := writeValidConfigFiles(t, workspaceRoot)
|
pipelinePath, _, _ := writeValidConfigFiles(t, workspaceRoot)
|
||||||
workRoot := filepath.Join(workspaceRoot, "work")
|
workRoot := filepath.Join(workspaceRoot, "work")
|
||||||
@@ -149,35 +82,10 @@ func TestExecuteCleanAllDeletesWorkAndSpoolContentsButPreservesCache(t *testing.
|
|||||||
}
|
}
|
||||||
cleanAssertMissing(t, workRoot)
|
cleanAssertMissing(t, workRoot)
|
||||||
cleanAssertExists(t, spoolRoot)
|
cleanAssertExists(t, spoolRoot)
|
||||||
cleanAssertMissing(t, filepath.Join(spoolRoot, "sample-campaign"))
|
cleanAssertExists(t, filepath.Join(spoolRoot, "sample-campaign"))
|
||||||
cleanAssertExists(t, cachePath)
|
cleanAssertExists(t, cachePath)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestExecuteCleanAllClearCacheRemovesS3AudioNamespaceOnly(t *testing.T) {
|
|
||||||
workspaceRoot := t.TempDir()
|
|
||||||
pipelinePath, _, _ := writeValidConfigFiles(t, workspaceRoot)
|
|
||||||
cacheRoot := filepath.Join(workspaceRoot, "cache")
|
|
||||||
audioCachePath, err := artifacts.S3AudioCachePath(cacheRoot, "test-bucket", "dnd/campaigns/sample-campaign/sessions/2026-05-03/audio/alice.flac")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("S3AudioCachePath() error = %v", err)
|
|
||||||
}
|
|
||||||
otherCachePath, err := artifacts.S3AudioCachePath(cacheRoot, "test-bucket", "other-root/campaigns/sample-campaign/sessions/2026-05-03/audio/alice.flac")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("S3AudioCachePath() error = %v", err)
|
|
||||||
}
|
|
||||||
mustWriteTestFile(t, audioCachePath, "cached-audio")
|
|
||||||
mustWriteTestFile(t, otherCachePath, "other-cache")
|
|
||||||
|
|
||||||
var stdout bytes.Buffer
|
|
||||||
var stderr bytes.Buffer
|
|
||||||
code := executeForTest([]string{"session", "clean", "--config", pipelinePath, "--all", "--clear-cache"}, &stdout, &stderr)
|
|
||||||
if code != 0 {
|
|
||||||
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
|
|
||||||
}
|
|
||||||
cleanAssertMissing(t, audioCachePath)
|
|
||||||
cleanAssertExists(t, otherCachePath)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestExecuteCleanAllRejectsSessionScopedFlags(t *testing.T) {
|
func TestExecuteCleanAllRejectsSessionScopedFlags(t *testing.T) {
|
||||||
workspaceRoot := t.TempDir()
|
workspaceRoot := t.TempDir()
|
||||||
pipelinePath, campaignPath, _ := writeValidConfigFiles(t, workspaceRoot)
|
pipelinePath, campaignPath, _ := writeValidConfigFiles(t, workspaceRoot)
|
||||||
|
|||||||
@@ -21,8 +21,8 @@ import (
|
|||||||
const cleanupOrchestrationRunID = "20260905T010203Z-a1b2c3d4"
|
const cleanupOrchestrationRunID = "20260905T010203Z-a1b2c3d4"
|
||||||
|
|
||||||
type cleanupPublishEvidenceStage struct {
|
type cleanupPublishEvidenceStage struct {
|
||||||
runs *int
|
runs *int
|
||||||
skipSpoolTarget bool
|
invalidRetention bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cleanupPublishEvidenceStage) Name() string { return "publish" }
|
func (cleanupPublishEvidenceStage) Name() string { return "publish" }
|
||||||
@@ -31,19 +31,19 @@ func (s cleanupPublishEvidenceStage) Run(_ context.Context, env *stage.Env, m *m
|
|||||||
if s.runs != nil {
|
if s.runs != nil {
|
||||||
*s.runs++
|
*s.runs++
|
||||||
}
|
}
|
||||||
if !s.skipSpoolTarget {
|
|
||||||
spoolTarget := artifacts.SessionSpoolAudioDir(env.Config.Pipeline.Spool.Root, m.Campaign, m.SessionID, m.RunID)
|
|
||||||
if err := os.MkdirAll(spoolTarget, 0o755); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if err := os.WriteFile(filepath.Join(spoolTarget, "audio.flac"), []byte("audio"), 0o644); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
workspaceTarget := artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, m.Campaign, m.SessionID, m.RunID)
|
workspaceTarget := artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, m.Campaign, m.SessionID, m.RunID)
|
||||||
if err := os.MkdirAll(workspaceTarget, 0o755); err != nil {
|
if err := os.MkdirAll(workspaceTarget, 0o755); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if s.invalidRetention {
|
||||||
|
extract := filepath.Join(workspaceTarget, "extract")
|
||||||
|
if err := os.MkdirAll(extract, 0755); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(extract, "notarius-retention.json"), []byte("invalid"), 0644); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
return &stage.StageResult{Metadata: cleanupPublishMetadata(m)}, nil
|
return &stage.StageResult{Metadata: cleanupPublishMetadata(m)}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,15 +105,10 @@ func TestCleanupStopsAtPublishAndNotifyFailureBoundaries(t *testing.T) {
|
|||||||
|
|
||||||
func TestCleanupFailurePreservesPublishAndRetriesWithoutRepublishing(t *testing.T) {
|
func TestCleanupFailurePreservesPublishAndRetriesWithoutRepublishing(t *testing.T) {
|
||||||
cfg, remote := cleanupOrchestrationConfig(t)
|
cfg, remote := cleanupOrchestrationConfig(t)
|
||||||
badSpoolRoot := filepath.Join(t.TempDir(), "spool-file")
|
|
||||||
if err := os.WriteFile(badSpoolRoot, []byte("not a directory"), 0o644); err != nil {
|
|
||||||
t.Fatalf("write invalid spool root: %v", err)
|
|
||||||
}
|
|
||||||
cfg.Pipeline.Spool.Root = badSpoolRoot
|
|
||||||
remote.SeedObject(storage.FakeObject{Key: "sentinel/remote-state", Data: []byte("unchanged")})
|
remote.SeedObject(storage.FakeObject{Key: "sentinel/remote-state", Data: []byte("unchanged")})
|
||||||
publishRuns := 0
|
publishRuns := 0
|
||||||
plan := BoundedPlan{stages: []stage.Stage{
|
plan := BoundedPlan{stages: []stage.Stage{
|
||||||
cleanupPublishEvidenceStage{runs: &publishRuns, skipSpoolTarget: true},
|
cleanupPublishEvidenceStage{runs: &publishRuns, invalidRetention: true},
|
||||||
resultStage{name: "notify"},
|
resultStage{name: "notify"},
|
||||||
selectedCleanupStage(t),
|
selectedCleanupStage(t),
|
||||||
}}
|
}}
|
||||||
@@ -139,10 +134,8 @@ func TestCleanupFailurePreservesPublishAndRetriesWithoutRepublishing(t *testing.
|
|||||||
}
|
}
|
||||||
|
|
||||||
workspaceTarget := artifacts.SessionRunRootForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID, cleanupOrchestrationRunID)
|
workspaceTarget := artifacts.SessionRunRootForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID, cleanupOrchestrationRunID)
|
||||||
cfg.Pipeline.Spool.Root = t.TempDir()
|
if err := os.Remove(filepath.Join(workspaceTarget, "extract", "notarius-retention.json")); err != nil {
|
||||||
spoolTarget := artifacts.SessionSpoolAudioDir(cfg.Pipeline.Spool.Root, cfg.Session.Campaign, cfg.Session.SessionID, cleanupOrchestrationRunID)
|
t.Fatal(err)
|
||||||
if err := os.MkdirAll(spoolTarget, 0o755); err != nil {
|
|
||||||
t.Fatalf("create retry spool target: %v", err)
|
|
||||||
}
|
}
|
||||||
summary, err := executePlanWithDependencies(
|
summary, err := executePlanWithDependencies(
|
||||||
context.Background(), cfg, plan, RunOptions{Env: &Env{ObjectStore: remote}}, cleanupOrchestrationDependencies(),
|
context.Background(), cfg, plan, RunOptions{Env: &Env{ObjectStore: remote}}, cleanupOrchestrationDependencies(),
|
||||||
@@ -159,9 +152,7 @@ func TestCleanupFailurePreservesPublishAndRetriesWithoutRepublishing(t *testing.
|
|||||||
if _, statErr := os.Lstat(workspaceTarget); !errors.Is(statErr, os.ErrNotExist) {
|
if _, statErr := os.Lstat(workspaceTarget); !errors.Is(statErr, os.ErrNotExist) {
|
||||||
t.Fatalf("workspace target stat error = %v, want absent", statErr)
|
t.Fatalf("workspace target stat error = %v, want absent", statErr)
|
||||||
}
|
}
|
||||||
if _, statErr := os.Lstat(spoolTarget); !errors.Is(statErr, os.ErrNotExist) {
|
|
||||||
t.Fatalf("spool target stat error = %v, want absent", statErr)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestRunSingleStageCleanupUsesPublishEvidenceAndFailsClosedWithoutIt(t *testing.T) {
|
func TestRunSingleStageCleanupUsesPublishEvidenceAndFailsClosedWithoutIt(t *testing.T) {
|
||||||
@@ -185,8 +176,7 @@ func TestRunSingleStageCleanupUsesPublishEvidenceAndFailsClosedWithoutIt(t *test
|
|||||||
t.Fatalf("save publication evidence: %v", err)
|
t.Fatalf("save publication evidence: %v", err)
|
||||||
}
|
}
|
||||||
workspaceTarget := artifacts.SessionRunRootForCampaign(cfg.Pipeline.Workspace.Root, m.Campaign, m.SessionID, publishedRunID)
|
workspaceTarget := artifacts.SessionRunRootForCampaign(cfg.Pipeline.Workspace.Root, m.Campaign, m.SessionID, publishedRunID)
|
||||||
spoolTarget := artifacts.SessionSpoolAudioDir(cfg.Pipeline.Spool.Root, m.Campaign, m.SessionID, publishedRunID)
|
for _, target := range []string{workspaceTarget} {
|
||||||
for _, target := range []string{workspaceTarget, spoolTarget} {
|
|
||||||
if err := os.MkdirAll(target, 0o755); err != nil {
|
if err := os.MkdirAll(target, 0o755); err != nil {
|
||||||
t.Fatalf("create cleanup target: %v", err)
|
t.Fatalf("create cleanup target: %v", err)
|
||||||
}
|
}
|
||||||
@@ -203,7 +193,7 @@ func TestRunSingleStageCleanupUsesPublishEvidenceAndFailsClosedWithoutIt(t *test
|
|||||||
if !runCountsMatch(t, output.Bytes(), 1, 0, "cleanup") {
|
if !runCountsMatch(t, output.Bytes(), 1, 0, "cleanup") {
|
||||||
t.Fatalf("output = %q, want direct cleanup execution", output.String())
|
t.Fatalf("output = %q, want direct cleanup execution", output.String())
|
||||||
}
|
}
|
||||||
for _, target := range []string{workspaceTarget, spoolTarget} {
|
for _, target := range []string{workspaceTarget} {
|
||||||
if _, statErr := os.Lstat(target); !errors.Is(statErr, os.ErrNotExist) {
|
if _, statErr := os.Lstat(target); !errors.Is(statErr, os.ErrNotExist) {
|
||||||
t.Fatalf("cleanup target %q stat error = %v, want absent", target, statErr)
|
t.Fatalf("cleanup target %q stat error = %v, want absent", target, statErr)
|
||||||
}
|
}
|
||||||
@@ -235,7 +225,6 @@ func enableCleanupForCommandTest(t *testing.T, pipelinePath string) {
|
|||||||
t.Fatalf("read pipeline config: %v", err)
|
t.Fatalf("read pipeline config: %v", err)
|
||||||
}
|
}
|
||||||
content := strings.Replace(string(data), "workspace:\n root: ", "workspace:\n cleanup_after_publish: true\n root: ", 1)
|
content := strings.Replace(string(data), "workspace:\n root: ", "workspace:\n cleanup_after_publish: true\n root: ", 1)
|
||||||
content = strings.Replace(content, "spool:\n root: ", "spool:\n delete_audio_after_publish: true\n root: ", 1)
|
|
||||||
content = strings.Replace(content, " upload_run: false", " upload_run: true", 1)
|
content = strings.Replace(content, " upload_run: false", " upload_run: true", 1)
|
||||||
if err := os.WriteFile(pipelinePath, []byte(content), 0o644); err != nil {
|
if err := os.WriteFile(pipelinePath, []byte(content), 0o644); err != nil {
|
||||||
t.Fatalf("write cleanup config: %v", err)
|
t.Fatalf("write cleanup config: %v", err)
|
||||||
@@ -245,8 +234,6 @@ func enableCleanupForCommandTest(t *testing.T, pipelinePath string) {
|
|||||||
func cleanupOrchestrationConfig(t *testing.T) (*config.Config, *storage.FakeBackend) {
|
func cleanupOrchestrationConfig(t *testing.T) (*config.Config, *storage.FakeBackend) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
cfg := testConfig(t)
|
cfg := testConfig(t)
|
||||||
cfg.Pipeline.Spool.Root = t.TempDir()
|
|
||||||
cfg.Pipeline.Spool.DeleteAudioAfterPublish = true
|
|
||||||
cfg.Pipeline.Workspace.CleanupAfterPublish = true
|
cfg.Pipeline.Workspace.CleanupAfterPublish = true
|
||||||
cfg.Pipeline.Publish = &config.PublishConfig{Enabled: boolPtr(true), UploadRun: boolPtr(true)}
|
cfg.Pipeline.Publish = &config.PublishConfig{Enabled: boolPtr(true), UploadRun: boolPtr(true)}
|
||||||
cfg.Pipeline.Storage.Backend = config.StorageBackendS3
|
cfg.Pipeline.Storage.Backend = config.StorageBackendS3
|
||||||
|
|||||||
@@ -65,22 +65,6 @@ func TestCleanValidateScopedTargetSafetyRules(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCleanableRootChildrenRejectsSymlinkChild(t *testing.T) {
|
|
||||||
root := t.TempDir()
|
|
||||||
realChild := filepath.Join(root, "runs")
|
|
||||||
if err := os.MkdirAll(realChild, 0o755); err != nil {
|
|
||||||
t.Fatalf("MkdirAll(realChild) error = %v", err)
|
|
||||||
}
|
|
||||||
if err := os.Symlink(realChild, filepath.Join(root, "link")); err != nil {
|
|
||||||
t.Fatalf("Symlink() error = %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
_, _, err := cleanableRootChildren(root, "test.root.children")
|
|
||||||
if err == nil || !strings.Contains(err.Error(), "refusing to delete symlink path") {
|
|
||||||
t.Fatalf("cleanableRootChildren() error = %v, want symlink rejection", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCleanValidateScopedTargetMissing(t *testing.T) {
|
func TestCleanValidateScopedTargetMissing(t *testing.T) {
|
||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
missingDir := filepath.Join(root, "runs", "missing")
|
missingDir := filepath.Join(root, "runs", "missing")
|
||||||
|
|||||||
@@ -297,9 +297,6 @@ func TestCommittedRestoreRejectsChangedAudioBeforeInstall(t *testing.T) {
|
|||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
t.Run(test.name, func(t *testing.T) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
cfg := restorePlanConfig(t)
|
cfg := restorePlanConfig(t)
|
||||||
cfg.Pipeline.Spool.Root = filepath.Join(t.TempDir(), "spool")
|
|
||||||
cacheDisabled := false
|
|
||||||
cfg.Pipeline.Cache.S3Audio = &cacheDisabled
|
|
||||||
fake := &storage.FakeBackend{}
|
fake := &storage.FakeBackend{}
|
||||||
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
|
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
|
||||||
"audio/alice.flac": []byte("original-audio"),
|
"audio/alice.flac": []byte("original-audio"),
|
||||||
|
|||||||
@@ -341,8 +341,6 @@ func executeRestoreAudioAction(
|
|||||||
if cfg == nil || cfg.Pipeline == nil || cfg.Pipeline.Storage.S3 == nil || cfg.Session == nil {
|
if cfg == nil || cfg.Pipeline == nil || cfg.Pipeline.Storage.S3 == nil || cfg.Session == nil {
|
||||||
return fmt.Errorf("resolved s3 config and session are required")
|
return fmt.Errorf("resolved s3 config and session are required")
|
||||||
}
|
}
|
||||||
spoolDir := artifacts.SessionSpoolRestoreAudioDir(cfg.Pipeline.Spool.Root, cfg.Session.Campaign, cfg.Session.SessionID)
|
|
||||||
spoolPath := filepath.Join(spoolDir, filepath.Base(safeLocalPath))
|
|
||||||
temporary, err := os.CreateTemp(filepath.Dir(safeLocalPath), "."+filepath.Base(safeLocalPath)+".restore-*")
|
temporary, err := os.CreateTemp(filepath.Dir(safeLocalPath), "."+filepath.Base(safeLocalPath)+".restore-*")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("create sibling audio staging file: %w", err)
|
return fmt.Errorf("create sibling audio staging file: %w", err)
|
||||||
@@ -354,7 +352,6 @@ func executeRestoreAudioAction(
|
|||||||
}
|
}
|
||||||
defer func() { _ = os.Remove(temporaryPath) }()
|
defer func() { _ = os.Remove(temporaryPath) }()
|
||||||
|
|
||||||
cacheEnabled := cfg.Pipeline.Cache.S3Audio == nil || *cfg.Pipeline.Cache.S3Audio
|
|
||||||
_, err = audio.MaterializeS3Audio(ctx, audio.S3MaterializeRequest{
|
_, err = audio.MaterializeS3Audio(ctx, audio.S3MaterializeRequest{
|
||||||
Store: store,
|
Store: store,
|
||||||
Object: storage.ObjectInfo{
|
Object: storage.ObjectInfo{
|
||||||
@@ -362,11 +359,8 @@ func executeRestoreAudioAction(
|
|||||||
Size: action.Size,
|
Size: action.Size,
|
||||||
ETag: action.ETag,
|
ETag: action.ETag,
|
||||||
},
|
},
|
||||||
Bucket: strings.TrimSpace(cfg.Pipeline.Storage.S3.Bucket),
|
Bucket: strings.TrimSpace(cfg.Pipeline.Storage.S3.Bucket),
|
||||||
CacheRoot: strings.TrimSpace(cfg.Pipeline.Cache.Root),
|
DestPath: temporaryPath,
|
||||||
CacheEnabled: cacheEnabled,
|
|
||||||
SpoolPath: spoolPath,
|
|
||||||
DestPath: temporaryPath,
|
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("materialize audio: %w", err)
|
return fmt.Errorf("materialize audio: %w", err)
|
||||||
|
|||||||
@@ -262,7 +262,7 @@ func TestExecuteRestoreIncludeAudioRestoresAudio(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestExecuteRestoreIncludeAudioUsesCacheAfterWorkspaceDeletion(t *testing.T) {
|
func TestExecuteRestoreIncludeAudioDownloadsAfterWorkspaceDeletion(t *testing.T) {
|
||||||
workspaceRoot := t.TempDir()
|
workspaceRoot := t.TempDir()
|
||||||
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
|
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
|
||||||
|
|
||||||
@@ -295,8 +295,8 @@ func TestExecuteRestoreIncludeAudioUsesCacheAfterWorkspaceDeletion(t *testing.T)
|
|||||||
if code != 0 {
|
if code != 0 {
|
||||||
t.Fatalf("second restore exit code = %d, want 0; stderr=%q", code, stderr.String())
|
t.Fatalf("second restore exit code = %d, want 0; stderr=%q", code, stderr.String())
|
||||||
}
|
}
|
||||||
if got := fakeDownloadCount(fake, committedAudioKey); got != 1 {
|
if got := fakeDownloadCount(fake, committedAudioKey); got != 2 {
|
||||||
t.Fatalf("audio downloads after cached restore = %d, want still 1", got)
|
t.Fatalf("audio downloads after restored session was removed = %d, want 2", got)
|
||||||
}
|
}
|
||||||
mustReadEquals(t, filepath.Join(sessionRoot, "audio", "alice.flac"), "remote-audio")
|
mustReadEquals(t, filepath.Join(sessionRoot, "audio", "alice.flac"), "remote-audio")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -86,10 +86,6 @@ func rebaseRestoredManifestPaths(cfg *config.Config, m *manifest.Manifest, desti
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
m.Inputs[i].Path = value
|
m.Inputs[i].Path = value
|
||||||
// Spool and cache locations are host-local implementation details. They
|
|
||||||
// are deliberately not authoritative after a restore.
|
|
||||||
m.Inputs[i].SpoolPath = ""
|
|
||||||
m.Inputs[i].CachePath = ""
|
|
||||||
}
|
}
|
||||||
for i := range m.Artifacts {
|
for i := range m.Artifacts {
|
||||||
value, err := rebase("artifacts.local_path", m.Artifacts[i].LocalPath)
|
value, err := rebase("artifacts.local_path", m.Artifacts[i].LocalPath)
|
||||||
@@ -121,7 +117,6 @@ func rebaseRestoredManifestPaths(cfg *config.Config, m *manifest.Manifest, desti
|
|||||||
} else {
|
} else {
|
||||||
m.LocalWorkDir = destinationRoot
|
m.LocalWorkDir = destinationRoot
|
||||||
}
|
}
|
||||||
m.LocalSpoolDir = ""
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -423,7 +423,6 @@ type invocationIdentity struct {
|
|||||||
SessionID string
|
SessionID string
|
||||||
RunID string
|
RunID string
|
||||||
LocalWorkDir string
|
LocalWorkDir string
|
||||||
LocalSpoolDir string
|
|
||||||
S3Bucket string
|
S3Bucket string
|
||||||
S3SessionPrefix string
|
S3SessionPrefix string
|
||||||
S3RunPrefix string
|
S3RunPrefix string
|
||||||
@@ -461,9 +460,6 @@ func resolveInvocationIdentity(cfg *config.Config, runID string) (invocationIden
|
|||||||
RunID: runID,
|
RunID: runID,
|
||||||
LocalWorkDir: artifacts.SessionRunRootForCampaign(cfg.Pipeline.Workspace.Root, campaign, sessionID, runID),
|
LocalWorkDir: artifacts.SessionRunRootForCampaign(cfg.Pipeline.Workspace.Root, campaign, sessionID, runID),
|
||||||
}
|
}
|
||||||
if spoolRoot := strings.TrimSpace(cfg.Pipeline.Spool.Root); spoolRoot != "" {
|
|
||||||
identity.LocalSpoolDir = artifacts.SessionSpoolAudioDir(spoolRoot, campaign, sessionID, runID)
|
|
||||||
}
|
|
||||||
if s3 := cfg.Pipeline.Storage.S3; s3 != nil {
|
if s3 := cfg.Pipeline.Storage.S3; s3 != nil {
|
||||||
identity.S3Bucket = strings.TrimSpace(s3.Bucket)
|
identity.S3Bucket = strings.TrimSpace(s3.Bucket)
|
||||||
identity.S3SessionPrefix = artifacts.S3SessionPrefix(s3.RootPrefix, campaign, sessionID)
|
identity.S3SessionPrefix = artifacts.S3SessionPrefix(s3.RootPrefix, campaign, sessionID)
|
||||||
@@ -493,7 +489,6 @@ func (identity invocationIdentity) applyToSessionManifest(m *manifest.Manifest)
|
|||||||
m.Campaign = identity.Campaign
|
m.Campaign = identity.Campaign
|
||||||
m.RunID = identity.RunID
|
m.RunID = identity.RunID
|
||||||
m.LocalWorkDir = identity.LocalWorkDir
|
m.LocalWorkDir = identity.LocalWorkDir
|
||||||
m.LocalSpoolDir = identity.LocalSpoolDir
|
|
||||||
m.S3Bucket = identity.S3Bucket
|
m.S3Bucket = identity.S3Bucket
|
||||||
m.S3SessionPrefix = identity.S3SessionPrefix
|
m.S3SessionPrefix = identity.S3SessionPrefix
|
||||||
m.S3RunPrefix = identity.S3RunPrefix
|
m.S3RunPrefix = identity.S3RunPrefix
|
||||||
|
|||||||
@@ -976,7 +976,6 @@ func TestExecuteStagesLoadsExistingManifest(t *testing.T) {
|
|||||||
|
|
||||||
func TestExecuteStagesCreatesRunDirectoryForEachExecutedInvocation(t *testing.T) {
|
func TestExecuteStagesCreatesRunDirectoryForEachExecutedInvocation(t *testing.T) {
|
||||||
cfg := testConfig(t)
|
cfg := testConfig(t)
|
||||||
cfg.Pipeline.Spool.Root = t.TempDir()
|
|
||||||
cfg.Pipeline.Storage.S3 = &config.StorageS3Config{
|
cfg.Pipeline.Storage.S3 = &config.StorageS3Config{
|
||||||
Bucket: "archive-bucket",
|
Bucket: "archive-bucket",
|
||||||
RootPrefix: "narratio",
|
RootPrefix: "narratio",
|
||||||
|
|||||||
@@ -308,7 +308,7 @@ func TestExecuteCleanAcceptsPositionalSessionID(t *testing.T) {
|
|||||||
workspaceRoot := t.TempDir()
|
workspaceRoot := t.TempDir()
|
||||||
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
|
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
|
||||||
workDir := artifacts.SessionWorkDirForCampaign(workspaceRoot, "sample-campaign", "2026-05-03")
|
workDir := artifacts.SessionWorkDirForCampaign(workspaceRoot, "sample-campaign", "2026-05-03")
|
||||||
spoolDir := artifacts.SessionSpoolDir(filepath.Join(workspaceRoot, "spool"), "sample-campaign", "2026-05-03")
|
spoolDir := filepath.Join(workspaceRoot, "spool", "sample-campaign", "2026-05-03")
|
||||||
mustWriteTestFile(t, filepath.Join(workDir, "manifest.json"), "{}")
|
mustWriteTestFile(t, filepath.Join(workDir, "manifest.json"), "{}")
|
||||||
mustWriteTestFile(t, filepath.Join(spoolDir, "run-1", "audio", "alice.flac"), "audio")
|
mustWriteTestFile(t, filepath.Join(spoolDir, "run-1", "audio", "alice.flac"), "audio")
|
||||||
|
|
||||||
@@ -319,5 +319,5 @@ func TestExecuteCleanAcceptsPositionalSessionID(t *testing.T) {
|
|||||||
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
|
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
|
||||||
}
|
}
|
||||||
cleanAssertMissing(t, workDir)
|
cleanAssertMissing(t, workDir)
|
||||||
cleanAssertMissing(t, spoolDir)
|
cleanAssertExists(t, spoolDir)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package artifacts
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"path"
|
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -189,65 +188,6 @@ func SessionNotariusBundleDirForCampaign(rootDir, campaign, sessionID, runID str
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SessionSpoolAudioDir returns the campaign/session/run scoped local spool audio path.
|
|
||||||
func SessionSpoolAudioDir(spoolRoot, campaign, sessionID, runID string) string {
|
|
||||||
return filepath.Join(spoolRoot, campaign, sessionID, runID, config.PathAudioDirSegment)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SessionSpoolDir returns the campaign/session scoped local spool root.
|
|
||||||
func SessionSpoolDir(spoolRoot, campaign, sessionID string) string {
|
|
||||||
return filepath.Join(spoolRoot, campaign, sessionID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SessionSpoolRestoreAudioDir returns the local spool audio path for restore downloads.
|
|
||||||
func SessionSpoolRestoreAudioDir(spoolRoot, campaign, sessionID string) string {
|
|
||||||
return filepath.Join(SessionSpoolDir(spoolRoot, campaign, sessionID), "restore", config.PathAudioDirSegment)
|
|
||||||
}
|
|
||||||
|
|
||||||
// S3AudioCachePath returns the durable local cache path for one S3 audio object.
|
|
||||||
func S3AudioCachePath(cacheRoot, bucket, key string) (string, error) {
|
|
||||||
root := filepath.Clean(strings.TrimSpace(cacheRoot))
|
|
||||||
if root == "." || root == "" {
|
|
||||||
return "", fmt.Errorf("cache root is required")
|
|
||||||
}
|
|
||||||
bucket = strings.Trim(strings.TrimSpace(bucket), "/")
|
|
||||||
if bucket == "" || bucket == "." || bucket == ".." || strings.Contains(bucket, "/") || strings.Contains(bucket, `\`) {
|
|
||||||
return "", fmt.Errorf("bucket is required and must be a single path segment")
|
|
||||||
}
|
|
||||||
rawKey := strings.ReplaceAll(strings.TrimSpace(key), `\`, "/")
|
|
||||||
if strings.HasPrefix(rawKey, "/") {
|
|
||||||
return "", fmt.Errorf("s3 key must not be absolute")
|
|
||||||
}
|
|
||||||
cleanKey := cleanCacheS3Key(rawKey)
|
|
||||||
if cleanKey == "" {
|
|
||||||
return "", fmt.Errorf("s3 key is required")
|
|
||||||
}
|
|
||||||
if cleanKey == ".." || strings.HasPrefix(cleanKey, "../") || strings.HasPrefix(cleanKey, "/") {
|
|
||||||
return "", fmt.Errorf("s3 key must not escape cache root")
|
|
||||||
}
|
|
||||||
return filepath.Join(root, "s3", bucket, filepath.FromSlash(cleanKey)), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// S3AudioCacheNamespaceDir returns the durable local cache namespace for all
|
|
||||||
// Narratio S3 audio objects under one bucket/root prefix.
|
|
||||||
func S3AudioCacheNamespaceDir(cacheRoot, bucket, rootPrefix string) (string, error) {
|
|
||||||
sentinelKey := path.Join(cleanS3PathPart(rootPrefix), config.S3CampaignsSegment, ".narratio-cache-sentinel")
|
|
||||||
sentinelPath, err := S3AudioCachePath(cacheRoot, bucket, sentinelKey)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return filepath.Dir(sentinelPath), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func cleanCacheS3Key(key string) string {
|
|
||||||
normalized := strings.ReplaceAll(strings.TrimSpace(key), `\`, "/")
|
|
||||||
normalized = strings.Trim(normalized, "/")
|
|
||||||
if normalized == "" {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return path.Clean(normalized)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SessionPreviousDir returns the previous-session state directory for already-resolved session paths.
|
// SessionPreviousDir returns the previous-session state directory for already-resolved session paths.
|
||||||
func SessionPreviousDir(paths SessionPaths) string {
|
func SessionPreviousDir(paths SessionPaths) string {
|
||||||
return paths.PreviousDir
|
return paths.PreviousDir
|
||||||
|
|||||||
@@ -189,75 +189,3 @@ func TestSessionPreviousPathsFromSessionPaths(t *testing.T) {
|
|||||||
t.Fatalf("SessionPreviousArtifactPath(previous-relative) = %q, want %q", got, want)
|
t.Fatalf("SessionPreviousArtifactPath(previous-relative) = %q, want %q", got, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSessionSpoolAudioDir(t *testing.T) {
|
|
||||||
root := "/var/spool/narratio"
|
|
||||||
got := SessionSpoolAudioDir(root, "forsaken", "2026-04-19", "20260515T031522Z-a1b2c3d4")
|
|
||||||
want := filepath.Join(root, "forsaken", "2026-04-19", "20260515T031522Z-a1b2c3d4", "audio")
|
|
||||||
if got != want {
|
|
||||||
t.Fatalf("SessionSpoolAudioDir() = %q, want %q", got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSessionSpoolDir(t *testing.T) {
|
|
||||||
root := "/var/spool/narratio"
|
|
||||||
got := SessionSpoolDir(root, "forsaken", "2026-04-19")
|
|
||||||
want := filepath.Join(root, "forsaken", "2026-04-19")
|
|
||||||
if got != want {
|
|
||||||
t.Fatalf("SessionSpoolDir() = %q, want %q", got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSessionSpoolRestoreAudioDir(t *testing.T) {
|
|
||||||
root := "/var/spool/narratio"
|
|
||||||
got := SessionSpoolRestoreAudioDir(root, "forsaken", "2026-04-19")
|
|
||||||
want := filepath.Join(root, "forsaken", "2026-04-19", "restore", "audio")
|
|
||||||
if got != want {
|
|
||||||
t.Fatalf("SessionSpoolRestoreAudioDir() = %q, want %q", got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestS3AudioCachePath(t *testing.T) {
|
|
||||||
got, err := S3AudioCachePath("/var/cache/narratio", "my-dnd-archive", "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("S3AudioCachePath() error = %v", err)
|
|
||||||
}
|
|
||||||
want := filepath.Join("/var/cache/narratio", "s3", "my-dnd-archive", "dnd", "campaigns", "forsaken", "sessions", "2026-04-19", "audio", "alice.flac")
|
|
||||||
if got != want {
|
|
||||||
t.Fatalf("S3AudioCachePath() = %q, want %q", got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestS3AudioCacheNamespaceDir(t *testing.T) {
|
|
||||||
got, err := S3AudioCacheNamespaceDir("/var/cache/narratio", "my-dnd-archive", "dnd")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("S3AudioCacheNamespaceDir() error = %v", err)
|
|
||||||
}
|
|
||||||
want := filepath.Join("/var/cache/narratio", "s3", "my-dnd-archive", "dnd", "campaigns")
|
|
||||||
if got != want {
|
|
||||||
t.Fatalf("S3AudioCacheNamespaceDir() = %q, want %q", got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestS3AudioCachePathRejectsUnsafeInputs(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
root string
|
|
||||||
bucket string
|
|
||||||
key string
|
|
||||||
}{
|
|
||||||
{name: "empty root", root: "", bucket: "bucket", key: "audio/a.flac"},
|
|
||||||
{name: "empty bucket", root: "/cache", bucket: "", key: "audio/a.flac"},
|
|
||||||
{name: "bucket slash", root: "/cache", bucket: "bad/bucket", key: "audio/a.flac"},
|
|
||||||
{name: "empty key", root: "/cache", bucket: "bucket", key: ""},
|
|
||||||
{name: "escaping key", root: "/cache", bucket: "bucket", key: "../audio/a.flac"},
|
|
||||||
{name: "absolute key", root: "/cache", bucket: "bucket", key: "/audio/a.flac"},
|
|
||||||
}
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
if got, err := S3AudioCachePath(tt.root, tt.bucket, tt.key); err == nil {
|
|
||||||
t.Fatalf("S3AudioCachePath() = %q, want error", got)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,176 +0,0 @@
|
|||||||
package audio
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"crypto/sha256"
|
|
||||||
"encoding/hex"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
|
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/pathsafe"
|
|
||||||
)
|
|
||||||
|
|
||||||
const audioCacheIdentityVersion = 1
|
|
||||||
|
|
||||||
type audioCacheIdentity struct {
|
|
||||||
Version int `json:"version"`
|
|
||||||
Bucket string `json:"bucket"`
|
|
||||||
ObjectKey string `json:"object_key"`
|
|
||||||
Generation string `json:"generation"`
|
|
||||||
Size int64 `json:"size"`
|
|
||||||
SHA256 string `json:"sha256"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func cacheIdentityPath(cachePath string) string {
|
|
||||||
return cachePath + ".identity.json"
|
|
||||||
}
|
|
||||||
|
|
||||||
func cacheIdentityForRequest(req S3MaterializeRequest, checksum string) audioCacheIdentity {
|
|
||||||
return audioCacheIdentity{
|
|
||||||
Version: audioCacheIdentityVersion,
|
|
||||||
Bucket: strings.TrimSpace(req.Bucket),
|
|
||||||
ObjectKey: strings.TrimSpace(req.Object.Key),
|
|
||||||
Generation: strings.TrimSpace(req.Object.ETag),
|
|
||||||
Size: req.Object.Size,
|
|
||||||
SHA256: strings.ToLower(strings.TrimSpace(checksum)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (identity audioCacheIdentity) matchesRequest(req S3MaterializeRequest) bool {
|
|
||||||
return identity.Version == audioCacheIdentityVersion &&
|
|
||||||
identity.Bucket == strings.TrimSpace(req.Bucket) &&
|
|
||||||
identity.ObjectKey == strings.TrimSpace(req.Object.Key) &&
|
|
||||||
identity.Generation != "" && identity.Generation == strings.TrimSpace(req.Object.ETag) &&
|
|
||||||
identity.Size > 0 && identity.Size == req.Object.Size &&
|
|
||||||
validSHA256(identity.SHA256)
|
|
||||||
}
|
|
||||||
|
|
||||||
func cacheIdentityEligible(req S3MaterializeRequest) bool {
|
|
||||||
return strings.TrimSpace(req.Object.Key) != "" && strings.TrimSpace(req.Bucket) != "" &&
|
|
||||||
strings.TrimSpace(req.Object.ETag) != "" && req.Object.Size > 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func loadAudioCacheIdentity(path string) (audioCacheIdentity, bool, error) {
|
|
||||||
data, err := fileops.ReadFileBounded(path, 64*1024)
|
|
||||||
if os.IsNotExist(err) {
|
|
||||||
return audioCacheIdentity{}, false, nil
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return audioCacheIdentity{}, false, nil
|
|
||||||
}
|
|
||||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
|
||||||
decoder.DisallowUnknownFields()
|
|
||||||
var identity audioCacheIdentity
|
|
||||||
if err := decoder.Decode(&identity); err != nil {
|
|
||||||
return audioCacheIdentity{}, false, nil
|
|
||||||
}
|
|
||||||
if err := decoder.Decode(&struct{}{}); err != io.EOF || !validSHA256(identity.SHA256) {
|
|
||||||
return audioCacheIdentity{}, false, nil
|
|
||||||
}
|
|
||||||
return identity, true, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeAudioCacheIdentity(path string, identity audioCacheIdentity) error {
|
|
||||||
data, err := json.Marshal(identity)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("encode audio cache identity: %w", err)
|
|
||||||
}
|
|
||||||
if err := fileops.WriteFileAtomic(path, data, fileops.WorkspaceFileMode); err != nil {
|
|
||||||
return fmt.Errorf("write audio cache identity: %w", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func materializeVerifiedCachedAudio(ctx context.Context, req S3MaterializeRequest, cachePath string) (string, bool, error) {
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return "", false, err
|
|
||||||
}
|
|
||||||
identity, ok, err := loadAudioCacheIdentity(cacheIdentityPath(cachePath))
|
|
||||||
if err != nil {
|
|
||||||
return "", false, err
|
|
||||||
}
|
|
||||||
if !ok || !identity.matchesRequest(req) {
|
|
||||||
return "", false, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
source, err := os.Open(cachePath)
|
|
||||||
if err != nil {
|
|
||||||
return "", false, nil
|
|
||||||
}
|
|
||||||
defer func() { _ = source.Close() }()
|
|
||||||
info, err := source.Stat()
|
|
||||||
if err != nil {
|
|
||||||
return "", false, fmt.Errorf("inspect cached audio: %w", err)
|
|
||||||
}
|
|
||||||
if !info.Mode().IsRegular() || info.Size() != identity.Size {
|
|
||||||
return "", false, nil
|
|
||||||
}
|
|
||||||
if err := fileops.EnsureWorkspaceDirectory(filepath.Dir(req.DestPath)); err != nil {
|
|
||||||
return "", false, fmt.Errorf("create audio destination directory: %w", err)
|
|
||||||
}
|
|
||||||
temporaryPath, err := writeAudioTemp(req.DestPath, func(destination io.Writer) error {
|
|
||||||
_, err := io.Copy(destination, source)
|
|
||||||
return err
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return "", false, fmt.Errorf("copy verified cached audio: %w", err)
|
|
||||||
}
|
|
||||||
defer func() { _ = os.Remove(temporaryPath) }()
|
|
||||||
checksum, size, err := checksumAudioTemp(temporaryPath)
|
|
||||||
if err != nil {
|
|
||||||
return "", false, err
|
|
||||||
}
|
|
||||||
if err := validateLocalAudio(temporaryPath, identity.Size); err != nil {
|
|
||||||
return "", false, nil
|
|
||||||
}
|
|
||||||
if size != identity.Size || checksum != identity.SHA256 {
|
|
||||||
return "", false, nil
|
|
||||||
}
|
|
||||||
if err := fileops.InstallSiblingTempFile(temporaryPath, req.DestPath, fileops.WorkspaceFileMode); err != nil {
|
|
||||||
return "", false, fmt.Errorf("install verified cached audio: %w", err)
|
|
||||||
}
|
|
||||||
return checksum, true, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func cacheRelativePath(cacheRoot, cachePath string) (string, error) {
|
|
||||||
relativePath, err := filepath.Rel(filepath.Clean(cacheRoot), filepath.Clean(cachePath))
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("resolve audio cache path: %w", err)
|
|
||||||
}
|
|
||||||
normalized, err := pathsafe.NormalizeRelativeDestination(filepath.ToSlash(relativePath))
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("audio cache path escapes cache root: %w", err)
|
|
||||||
}
|
|
||||||
return normalized, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func checksumAudioTemp(path string) (string, int64, error) {
|
|
||||||
file, err := os.Open(path)
|
|
||||||
if err != nil {
|
|
||||||
return "", 0, fmt.Errorf("open cached audio copy: %w", err)
|
|
||||||
}
|
|
||||||
digest := sha256.New()
|
|
||||||
size, copyErr := io.Copy(digest, file)
|
|
||||||
closeErr := file.Close()
|
|
||||||
if copyErr != nil {
|
|
||||||
return "", 0, fmt.Errorf("checksum cached audio copy: %w", copyErr)
|
|
||||||
}
|
|
||||||
if closeErr != nil {
|
|
||||||
return "", 0, fmt.Errorf("close cached audio copy: %w", closeErr)
|
|
||||||
}
|
|
||||||
return hex.EncodeToString(digest.Sum(nil)), size, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func validSHA256(value string) bool {
|
|
||||||
if len(value) != sha256.Size*2 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
_, err := hex.DecodeString(value)
|
|
||||||
return err == nil
|
|
||||||
}
|
|
||||||
@@ -12,31 +12,26 @@ import (
|
|||||||
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
|
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/logging"
|
"gitea.maximumdirect.net/eric/narratio/internal/logging"
|
||||||
|
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
|
||||||
)
|
)
|
||||||
|
|
||||||
// S3MaterializeRequest describes one S3-backed audio materialization.
|
// S3MaterializeRequest describes one S3-backed audio materialization.
|
||||||
type S3MaterializeRequest struct {
|
type S3MaterializeRequest struct {
|
||||||
Reporter logging.Reporter
|
Reporter logging.Reporter
|
||||||
Store storage.ObjectStore
|
Store storage.ObjectStore
|
||||||
Object storage.ObjectInfo
|
Object storage.ObjectInfo
|
||||||
Bucket string
|
Bucket string
|
||||||
CacheRoot string
|
DestPath string
|
||||||
CacheEnabled bool
|
Prior *manifest.InputRecord
|
||||||
SpoolPath string
|
|
||||||
DestPath string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// S3MaterializeResult captures local materialization provenance.
|
|
||||||
type S3MaterializeResult struct {
|
type S3MaterializeResult struct {
|
||||||
Checksum string
|
Checksum string
|
||||||
CachePath string
|
Reused bool
|
||||||
SpoolPath string
|
|
||||||
CacheHit bool
|
|
||||||
Downloaded bool
|
Downloaded bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// MaterializeS3Audio installs one S3 audio object into the destination path,
|
// MaterializeS3Audio verifies the recorded prepared copy or installs a fresh download.
|
||||||
// reusing and refreshing the durable local cache when enabled.
|
|
||||||
func MaterializeS3Audio(ctx context.Context, req S3MaterializeRequest) (S3MaterializeResult, error) {
|
func MaterializeS3Audio(ctx context.Context, req S3MaterializeRequest) (S3MaterializeResult, error) {
|
||||||
if err := ctx.Err(); err != nil {
|
if err := ctx.Err(); err != nil {
|
||||||
return S3MaterializeResult{}, err
|
return S3MaterializeResult{}, err
|
||||||
@@ -51,59 +46,33 @@ func MaterializeS3Audio(ctx context.Context, req S3MaterializeRequest) (S3Materi
|
|||||||
if strings.TrimSpace(req.DestPath) == "" {
|
if strings.TrimSpace(req.DestPath) == "" {
|
||||||
return S3MaterializeResult{}, fmt.Errorf("destination path is required")
|
return S3MaterializeResult{}, fmt.Errorf("destination path is required")
|
||||||
}
|
}
|
||||||
|
|
||||||
if req.Reporter != nil {
|
if req.Reporter != nil {
|
||||||
req.Reporter.Info("selected audio source", "bucket", req.Bucket, "key", key, "destination", req.DestPath)
|
req.Reporter.Info("selected audio source", "bucket", req.Bucket, "key", key, "destination", req.DestPath)
|
||||||
}
|
}
|
||||||
result := S3MaterializeResult{}
|
prior := req.Prior
|
||||||
if req.CacheEnabled && cacheIdentityEligible(req) {
|
if prior != nil && prior.Kind == "audio" && prior.Source == "s3" && filepath.Clean(prior.Path) == filepath.Clean(req.DestPath) &&
|
||||||
cachePath, err := artifacts.S3AudioCachePath(req.CacheRoot, req.Bucket, key)
|
strings.TrimSpace(req.Bucket) != "" && prior.S3Bucket == strings.TrimSpace(req.Bucket) && prior.S3Key == key &&
|
||||||
if err != nil {
|
strings.TrimSpace(req.Object.ETag) != "" && strings.TrimSpace(prior.S3ETag) == strings.TrimSpace(req.Object.ETag) &&
|
||||||
return S3MaterializeResult{}, fmt.Errorf("resolve audio cache path: %w", err)
|
req.Object.Size > 0 && prior.S3Size == req.Object.Size && strings.TrimSpace(prior.Checksum) != "" {
|
||||||
}
|
info, err := os.Lstat(req.DestPath)
|
||||||
result.CachePath = cachePath
|
if err == nil && info.Mode().IsRegular() && info.Size() == req.Object.Size {
|
||||||
if checksum, ok, err := materializeVerifiedCachedAudio(ctx, req, cachePath); err != nil {
|
checksum, err := artifacts.SHA256File(req.DestPath)
|
||||||
return S3MaterializeResult{}, err
|
if err == nil && strings.EqualFold(checksum, prior.Checksum) {
|
||||||
} else if ok {
|
if req.Reporter != nil {
|
||||||
result.Checksum = checksum
|
req.Reporter.Progress("reusing prepared audio", "audio", filepath.Base(req.DestPath))
|
||||||
result.CacheHit = true
|
}
|
||||||
if req.Reporter != nil {
|
return S3MaterializeResult{Checksum: checksum, Reused: true}, nil
|
||||||
req.Reporter.Progress("reusing cached audio", "audio", filepath.Base(req.DestPath))
|
|
||||||
}
|
}
|
||||||
return result, nil
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if err := downloadObjectAtomic(ctx, req.Store, key, req.DestPath, req.Object.Size, req.Reporter); err != nil {
|
||||||
spoolPath := strings.TrimSpace(req.SpoolPath)
|
|
||||||
if spoolPath == "" {
|
|
||||||
return S3MaterializeResult{}, fmt.Errorf("spool path is required for s3 audio download")
|
|
||||||
}
|
|
||||||
if err := downloadObjectAtomic(ctx, req.Store, key, spoolPath, req.Object.Size, req.Reporter); err != nil {
|
|
||||||
return S3MaterializeResult{}, fmt.Errorf("download s3 audio object %q: %w", key, err)
|
return S3MaterializeResult{}, fmt.Errorf("download s3 audio object %q: %w", key, err)
|
||||||
}
|
}
|
||||||
|
checksum, err := artifacts.SHA256File(req.DestPath)
|
||||||
checksum, err := fileops.CopyFileAtomicWithChecksum(spoolPath, req.DestPath, fileops.WorkspaceFileMode)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return S3MaterializeResult{}, fmt.Errorf("materialize downloaded audio %q: %w", filepath.Base(req.DestPath), err)
|
return S3MaterializeResult{}, fmt.Errorf("checksum downloaded audio: %w", err)
|
||||||
}
|
}
|
||||||
result.Checksum = checksum
|
return S3MaterializeResult{Checksum: checksum, Downloaded: true}, nil
|
||||||
result.SpoolPath = spoolPath
|
|
||||||
result.Downloaded = true
|
|
||||||
|
|
||||||
if result.CachePath != "" {
|
|
||||||
cacheChecksum, err := fileops.CopyFileAtomicWithChecksum(spoolPath, result.CachePath, fileops.WorkspaceFileMode)
|
|
||||||
if err != nil {
|
|
||||||
return S3MaterializeResult{}, fmt.Errorf("populate audio cache %q: %w", result.CachePath, err)
|
|
||||||
}
|
|
||||||
if cacheChecksum != result.Checksum {
|
|
||||||
return S3MaterializeResult{}, fmt.Errorf("audio cache checksum differs from downloaded audio")
|
|
||||||
}
|
|
||||||
if err := writeAudioCacheIdentity(cacheIdentityPath(result.CachePath), cacheIdentityForRequest(req, cacheChecksum)); err != nil {
|
|
||||||
return S3MaterializeResult{}, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return result, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func validateLocalAudio(path string, expectedSize int64) error {
|
func validateLocalAudio(path string, expectedSize int64) error {
|
||||||
@@ -137,6 +106,9 @@ func downloadObjectAtomic(ctx context.Context, store storage.ObjectStore, key, d
|
|||||||
if err := validateLocalAudio(temporaryPath, expectedSize); err != nil {
|
if err := validateLocalAudio(temporaryPath, expectedSize); err != nil {
|
||||||
return fmt.Errorf("validate downloaded audio: %w", err)
|
return fmt.Errorf("validate downloaded audio: %w", err)
|
||||||
}
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
if err := fileops.InstallSiblingTempFile(temporaryPath, destPath, fileops.WorkspaceFileMode); err != nil {
|
if err := fileops.InstallSiblingTempFile(temporaryPath, destPath, fileops.WorkspaceFileMode); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,360 +4,110 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
|
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestMaterializeS3AudioCacheMissDownloadsAndPopulatesCache(t *testing.T) {
|
func TestMaterializeS3AudioUsesVerifiedPreparedCopy(t *testing.T) {
|
||||||
root := t.TempDir()
|
for _, tc := range []struct {
|
||||||
fake := &storage.FakeBackend{}
|
name string
|
||||||
key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac"
|
change func(*testing.T, *S3MaterializeRequest)
|
||||||
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("audio")})
|
reuse bool
|
||||||
req := testMaterializeRequest(t, root, fake, key, int64(len("audio")))
|
}{
|
||||||
|
{"current", nil, true},
|
||||||
result, err := MaterializeS3Audio(context.Background(), req)
|
{"changed generation", func(_ *testing.T, r *S3MaterializeRequest) { r.Object.ETag = "new" }, false},
|
||||||
if err != nil {
|
{"missing identity", func(_ *testing.T, r *S3MaterializeRequest) { r.Prior = nil }, false},
|
||||||
t.Fatalf("MaterializeS3Audio() error = %v", err)
|
{"unknown size", func(_ *testing.T, r *S3MaterializeRequest) { r.Object.Size = 0 }, false},
|
||||||
}
|
{"missing copy", func(t *testing.T, r *S3MaterializeRequest) {
|
||||||
if !result.Downloaded || result.CacheHit {
|
if err := os.Remove(r.DestPath); err != nil {
|
||||||
t.Fatalf("result = %#v, want downloaded miss", result)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if len(fake.Downloads) != 1 {
|
}, false},
|
||||||
t.Fatalf("downloads = %d, want 1", len(fake.Downloads))
|
{"corrupt copy", func(t *testing.T, r *S3MaterializeRequest) {
|
||||||
}
|
if err := os.WriteFile(r.DestPath, []byte("stale"), 0600); err != nil {
|
||||||
assertFileEquals(t, req.DestPath, "audio")
|
t.Fatal(err)
|
||||||
assertFileEquals(t, req.SpoolPath, "audio")
|
}
|
||||||
assertFileEquals(t, result.CachePath, "audio")
|
}, false},
|
||||||
if result.Checksum == "" {
|
} {
|
||||||
t.Fatalf("checksum is empty")
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
fake := &storage.FakeBackend{}
|
||||||
|
key := "audio/alice.flac"
|
||||||
|
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("audio"), ETag: "generation"})
|
||||||
|
req := S3MaterializeRequest{Store: fake, Object: storage.ObjectInfo{Key: key, Size: 5, ETag: "generation"}, Bucket: "bucket", DestPath: filepath.Join(root, "audio", "alice.flac")}
|
||||||
|
first, err := MaterializeS3Audio(context.Background(), req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
req.Prior = &manifest.InputRecord{Kind: "audio", Source: "s3", Path: req.DestPath, Checksum: first.Checksum, S3Bucket: req.Bucket, S3Key: key, S3Size: 5, S3ETag: "generation"}
|
||||||
|
if tc.change != nil {
|
||||||
|
tc.change(t, &req)
|
||||||
|
}
|
||||||
|
result, err := MaterializeS3Audio(context.Background(), req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if result.Reused != tc.reuse || result.Downloaded == tc.reuse {
|
||||||
|
t.Fatalf("result = %#v", result)
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(req.DestPath)
|
||||||
|
if err != nil || string(data) != "audio" {
|
||||||
|
t.Fatalf("audio = %q, %v", data, err)
|
||||||
|
}
|
||||||
|
entries, err := os.ReadDir(filepath.Dir(req.DestPath))
|
||||||
|
if err != nil || len(entries) != 1 {
|
||||||
|
t.Fatalf("audio directory = %v, %v", entries, err)
|
||||||
|
}
|
||||||
|
entries, err = os.ReadDir(root)
|
||||||
|
if err != nil || len(entries) != 1 || entries[0].Name() != "audio" {
|
||||||
|
t.Fatalf("root directory = %v, %v", entries, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestMaterializeS3AudioCacheHitSkipsDownload(t *testing.T) {
|
func TestMaterializeS3AudioFailedDownloadPreservesDestination(t *testing.T) {
|
||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
fake := &storage.FakeBackend{}
|
fake := &storage.FakeBackend{}
|
||||||
key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac"
|
fake.SeedObject(storage.FakeObject{Key: "audio/a.flac", Data: []byte("short")})
|
||||||
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("audio")})
|
dest := filepath.Join(root, "a.flac")
|
||||||
req := testMaterializeRequest(t, root, fake, key, int64(len("audio")))
|
if err := os.WriteFile(dest, []byte("original"), 0600); err != nil {
|
||||||
if _, err := MaterializeS3Audio(context.Background(), req); err != nil {
|
t.Fatal(err)
|
||||||
t.Fatalf("populate cache: %v", err)
|
|
||||||
}
|
}
|
||||||
|
req := S3MaterializeRequest{Store: fake, Object: storage.ObjectInfo{Key: "audio/a.flac", Size: 100}, DestPath: dest}
|
||||||
result, err := MaterializeS3Audio(context.Background(), req)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("MaterializeS3Audio() error = %v", err)
|
|
||||||
}
|
|
||||||
if !result.CacheHit || result.Downloaded {
|
|
||||||
t.Fatalf("result = %#v, want cache hit", result)
|
|
||||||
}
|
|
||||||
if len(fake.Downloads) != 1 {
|
|
||||||
t.Fatalf("downloads = %d, want only the initial population download", len(fake.Downloads))
|
|
||||||
}
|
|
||||||
assertFileEquals(t, req.DestPath, "audio")
|
|
||||||
if result.SpoolPath != "" {
|
|
||||||
t.Fatalf("spool path = %q, want empty on cache hit", result.SpoolPath)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMaterializeS3AudioRefreshesSameSizeChangedGeneration(t *testing.T) {
|
|
||||||
root := t.TempDir()
|
|
||||||
fake := &storage.FakeBackend{}
|
|
||||||
key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac"
|
|
||||||
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("audio-one"), ETag: "generation-one"})
|
|
||||||
req := testMaterializeRequest(t, root, fake, key, int64(len("audio-one")))
|
|
||||||
req.Object.ETag = "generation-one"
|
|
||||||
if _, err := MaterializeS3Audio(context.Background(), req); err != nil {
|
|
||||||
t.Fatalf("initial MaterializeS3Audio() error = %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("audio-two"), ETag: "generation-two"})
|
|
||||||
req.Object.ETag = "generation-two"
|
|
||||||
result, err := MaterializeS3Audio(context.Background(), req)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("refreshed MaterializeS3Audio() error = %v", err)
|
|
||||||
}
|
|
||||||
if !result.Downloaded || result.CacheHit || len(fake.Downloads) != 2 {
|
|
||||||
t.Fatalf("result=%#v downloads=%d, want refreshed download", result, len(fake.Downloads))
|
|
||||||
}
|
|
||||||
assertFileEquals(t, req.DestPath, "audio-two")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMaterializeS3AudioRefreshesCorruptedSameSizeCache(t *testing.T) {
|
|
||||||
root := t.TempDir()
|
|
||||||
fake := &storage.FakeBackend{}
|
|
||||||
key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac"
|
|
||||||
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("fresh-audio"), ETag: "generation"})
|
|
||||||
req := testMaterializeRequest(t, root, fake, key, int64(len("fresh-audio")))
|
|
||||||
req.Object.ETag = "generation"
|
|
||||||
if _, err := MaterializeS3Audio(context.Background(), req); err != nil {
|
|
||||||
t.Fatalf("initial MaterializeS3Audio() error = %v", err)
|
|
||||||
}
|
|
||||||
writeAudioTestFile(t, cachePathForTest(t, req), "stale-audio")
|
|
||||||
|
|
||||||
result, err := MaterializeS3Audio(context.Background(), req)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("refreshed MaterializeS3Audio() error = %v", err)
|
|
||||||
}
|
|
||||||
if !result.Downloaded || result.CacheHit || len(fake.Downloads) != 2 {
|
|
||||||
t.Fatalf("result=%#v downloads=%d, want refreshed download", result, len(fake.Downloads))
|
|
||||||
}
|
|
||||||
assertFileEquals(t, req.DestPath, "fresh-audio")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMaterializeS3AudioMissingIdentityDoesNotReuseCache(t *testing.T) {
|
|
||||||
root := t.TempDir()
|
|
||||||
fake := &storage.FakeBackend{}
|
|
||||||
key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac"
|
|
||||||
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("fresh-audio"), ETag: "generation"})
|
|
||||||
req := testMaterializeRequest(t, root, fake, key, int64(len("fresh-audio")))
|
|
||||||
req.Object.ETag = "generation"
|
|
||||||
writeAudioTestFile(t, cachePathForTest(t, req), "stale-audio")
|
|
||||||
|
|
||||||
result, err := MaterializeS3Audio(context.Background(), req)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("MaterializeS3Audio() error = %v", err)
|
|
||||||
}
|
|
||||||
if !result.Downloaded || result.CacheHit || len(fake.Downloads) != 1 {
|
|
||||||
t.Fatalf("result=%#v downloads=%d, want cache refresh", result, len(fake.Downloads))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMaterializeS3AudioTreatsMultipartETagAsGeneration(t *testing.T) {
|
|
||||||
root := t.TempDir()
|
|
||||||
fake := &storage.FakeBackend{}
|
|
||||||
key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac"
|
|
||||||
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("fresh-audio"), ETag: "not-a-checksum-2"})
|
|
||||||
req := testMaterializeRequest(t, root, fake, key, int64(len("fresh-audio")))
|
|
||||||
req.Object.ETag = "not-a-checksum-2"
|
|
||||||
if _, err := MaterializeS3Audio(context.Background(), req); err != nil {
|
|
||||||
t.Fatalf("populate cache: %v", err)
|
|
||||||
}
|
|
||||||
result, err := MaterializeS3Audio(context.Background(), req)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("reuse cache: %v", err)
|
|
||||||
}
|
|
||||||
if !result.CacheHit || result.Downloaded || len(fake.Downloads) != 1 {
|
|
||||||
t.Fatalf("result=%#v downloads=%d, want verified cache hit", result, len(fake.Downloads))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMaterializeS3AudioUnknownRemoteSizeDoesNotReuseCache(t *testing.T) {
|
|
||||||
root := t.TempDir()
|
|
||||||
fake := &storage.FakeBackend{}
|
|
||||||
key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac"
|
|
||||||
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("fresh-audio"), ETag: "generation"})
|
|
||||||
req := testMaterializeRequest(t, root, fake, key, 0)
|
|
||||||
req.Object.ETag = "generation"
|
|
||||||
if _, err := MaterializeS3Audio(context.Background(), req); err != nil {
|
|
||||||
t.Fatalf("first MaterializeS3Audio() error = %v", err)
|
|
||||||
}
|
|
||||||
result, err := MaterializeS3Audio(context.Background(), req)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("second MaterializeS3Audio() error = %v", err)
|
|
||||||
}
|
|
||||||
if !result.Downloaded || result.CacheHit || len(fake.Downloads) != 2 {
|
|
||||||
t.Fatalf("result=%#v downloads=%d, want refresh without identity evidence", result, len(fake.Downloads))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMaterializeS3AudioSymlinkedCacheRefreshesWithoutFollowingLink(t *testing.T) {
|
|
||||||
root := t.TempDir()
|
|
||||||
fake := &storage.FakeBackend{}
|
|
||||||
key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac"
|
|
||||||
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("fresh-audio"), ETag: "generation"})
|
|
||||||
req := testMaterializeRequest(t, root, fake, key, int64(len("fresh-audio")))
|
|
||||||
req.Object.ETag = "generation"
|
|
||||||
if _, err := MaterializeS3Audio(context.Background(), req); err != nil {
|
|
||||||
t.Fatalf("populate cache: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
cachePath := cachePathForTest(t, req)
|
|
||||||
outsidePath := filepath.Join(root, "outside-audio")
|
|
||||||
writeAudioTestFile(t, outsidePath, "untrusted-audio")
|
|
||||||
if err := os.Remove(cachePath); err != nil {
|
|
||||||
t.Fatalf("remove cache file: %v", err)
|
|
||||||
}
|
|
||||||
if err := os.Symlink(outsidePath, cachePath); err != nil {
|
|
||||||
t.Fatalf("create cache symlink: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
result, err := MaterializeS3Audio(context.Background(), req)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("refresh symlinked cache: %v", err)
|
|
||||||
}
|
|
||||||
if !result.Downloaded || result.CacheHit || len(fake.Downloads) != 2 {
|
|
||||||
t.Fatalf("result=%#v downloads=%d, want safe refresh", result, len(fake.Downloads))
|
|
||||||
}
|
|
||||||
assertFileEquals(t, outsidePath, "untrusted-audio")
|
|
||||||
assertFileEquals(t, req.DestPath, "fresh-audio")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMaterializeS3AudioNonRegularCacheFailsClearly(t *testing.T) {
|
|
||||||
root := t.TempDir()
|
|
||||||
fake := &storage.FakeBackend{}
|
|
||||||
key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac"
|
|
||||||
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("fresh-audio"), ETag: "generation"})
|
|
||||||
req := testMaterializeRequest(t, root, fake, key, int64(len("fresh-audio")))
|
|
||||||
req.Object.ETag = "generation"
|
|
||||||
if _, err := MaterializeS3Audio(context.Background(), req); err != nil {
|
|
||||||
t.Fatalf("populate cache: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
cachePath := cachePathForTest(t, req)
|
|
||||||
if err := os.Remove(cachePath); err != nil {
|
|
||||||
t.Fatalf("remove cache file: %v", err)
|
|
||||||
}
|
|
||||||
if err := os.Mkdir(cachePath, 0o755); err != nil {
|
|
||||||
t.Fatalf("create cache directory: %v", err)
|
|
||||||
}
|
|
||||||
_, err := MaterializeS3Audio(context.Background(), req)
|
|
||||||
if err == nil || !strings.Contains(err.Error(), "populate audio cache") {
|
|
||||||
t.Fatalf("error = %v, want clear cache refresh error", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMaterializeS3AudioInterruptedRefreshCanRetry(t *testing.T) {
|
|
||||||
root := t.TempDir()
|
|
||||||
fake := &storage.FakeBackend{}
|
|
||||||
key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac"
|
|
||||||
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("audio-one"), ETag: "generation-one"})
|
|
||||||
req := testMaterializeRequest(t, root, fake, key, int64(len("audio-one")))
|
|
||||||
req.Object.ETag = "generation-one"
|
|
||||||
if _, err := MaterializeS3Audio(context.Background(), req); err != nil {
|
|
||||||
t.Fatalf("populate cache: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("audio-two"), ETag: "generation-two"})
|
|
||||||
req.Object.ETag = "generation-two"
|
|
||||||
fake.DownloadErr = os.ErrPermission
|
|
||||||
if _, err := MaterializeS3Audio(context.Background(), req); err == nil {
|
if _, err := MaterializeS3Audio(context.Background(), req); err == nil {
|
||||||
t.Fatal("MaterializeS3Audio() error = nil, want interrupted refresh failure")
|
t.Fatal("expected size mismatch")
|
||||||
}
|
}
|
||||||
fake.DownloadErr = nil
|
data, err := os.ReadFile(dest)
|
||||||
|
if err != nil || string(data) != "original" {
|
||||||
result, err := MaterializeS3Audio(context.Background(), req)
|
t.Fatalf("destination = %q, %v", data, err)
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("retry refresh: %v", err)
|
|
||||||
}
|
}
|
||||||
if !result.Downloaded || result.CacheHit {
|
entries, err := os.ReadDir(root)
|
||||||
t.Fatalf("result = %#v, want refreshed download after retry", result)
|
if err != nil || len(entries) != 1 {
|
||||||
|
t.Fatalf("entries = %v, %v", entries, err)
|
||||||
|
}
|
||||||
|
req.Object.Size = 5
|
||||||
|
if _, err := MaterializeS3Audio(context.Background(), req); err != nil {
|
||||||
|
t.Fatalf("retry: %v", err)
|
||||||
}
|
}
|
||||||
assertFileEquals(t, req.DestPath, "audio-two")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestMaterializeS3AudioInvalidCacheRefreshesFromS3(t *testing.T) {
|
func TestMaterializeS3AudioCanceledRequestCanRetry(t *testing.T) {
|
||||||
root := t.TempDir()
|
|
||||||
fake := &storage.FakeBackend{}
|
fake := &storage.FakeBackend{}
|
||||||
key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac"
|
fake.SeedObject(storage.FakeObject{Key: "audio/a.flac", Data: []byte("audio")})
|
||||||
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("fresh-audio")})
|
dest := filepath.Join(t.TempDir(), "a.flac")
|
||||||
req := testMaterializeRequest(t, root, fake, key, int64(len("fresh-audio")))
|
req := S3MaterializeRequest{Store: fake, Object: storage.ObjectInfo{Key: "audio/a.flac", Size: 5}, DestPath: dest}
|
||||||
cachePath, err := artifacts.S3AudioCachePath(req.CacheRoot, req.Bucket, key)
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
if err != nil {
|
cancel()
|
||||||
t.Fatalf("cache path: %v", err)
|
if _, err := MaterializeS3Audio(ctx, req); err == nil {
|
||||||
|
t.Fatal("expected cancellation")
|
||||||
}
|
}
|
||||||
writeAudioTestFile(t, cachePath, "stale")
|
if _, err := os.Stat(dest); !os.IsNotExist(err) {
|
||||||
|
t.Fatalf("destination after cancellation: %v", err)
|
||||||
result, err := MaterializeS3Audio(context.Background(), req)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("MaterializeS3Audio() error = %v", err)
|
|
||||||
}
|
}
|
||||||
if !result.Downloaded || result.CacheHit {
|
if _, err := MaterializeS3Audio(context.Background(), req); err != nil {
|
||||||
t.Fatalf("result = %#v, want refreshed miss", result)
|
t.Fatalf("retry: %v", err)
|
||||||
}
|
|
||||||
if len(fake.Downloads) != 1 {
|
|
||||||
t.Fatalf("downloads = %d, want 1", len(fake.Downloads))
|
|
||||||
}
|
|
||||||
assertFileEquals(t, req.DestPath, "fresh-audio")
|
|
||||||
assertFileEquals(t, cachePath, "fresh-audio")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMaterializeS3AudioDownloadFailureLeavesDestinationMissing(t *testing.T) {
|
|
||||||
root := t.TempDir()
|
|
||||||
fake := &storage.FakeBackend{DownloadErr: os.ErrPermission}
|
|
||||||
key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac"
|
|
||||||
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("audio")})
|
|
||||||
req := testMaterializeRequest(t, root, fake, key, int64(len("audio")))
|
|
||||||
|
|
||||||
_, err := MaterializeS3Audio(context.Background(), req)
|
|
||||||
if err == nil || !strings.Contains(err.Error(), "download s3 audio object") {
|
|
||||||
t.Fatalf("error = %v, want download error", err)
|
|
||||||
}
|
|
||||||
assertMissing(t, req.DestPath)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMaterializeS3AudioRejectsSizeMismatchBeforeReplacingSpool(t *testing.T) {
|
|
||||||
root := t.TempDir()
|
|
||||||
fake := &storage.FakeBackend{}
|
|
||||||
key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac"
|
|
||||||
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("audio")})
|
|
||||||
req := testMaterializeRequest(t, root, fake, key, int64(len("audio")+1))
|
|
||||||
writeAudioTestFile(t, req.SpoolPath, "existing-audio")
|
|
||||||
|
|
||||||
_, err := MaterializeS3Audio(context.Background(), req)
|
|
||||||
if err == nil || !strings.Contains(err.Error(), "size") {
|
|
||||||
t.Fatalf("error = %v, want size validation failure", err)
|
|
||||||
}
|
|
||||||
assertFileEquals(t, req.SpoolPath, "existing-audio")
|
|
||||||
entries, err := os.ReadDir(filepath.Dir(req.SpoolPath))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("read spool directory: %v", err)
|
|
||||||
}
|
|
||||||
for _, entry := range entries {
|
|
||||||
if strings.HasPrefix(entry.Name(), ".alice.flac.tmp-") {
|
|
||||||
t.Fatalf("unexpected temporary file residue: %q", entry.Name())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func testMaterializeRequest(t *testing.T, root string, fake *storage.FakeBackend, key string, size int64) S3MaterializeRequest {
|
|
||||||
t.Helper()
|
|
||||||
return S3MaterializeRequest{
|
|
||||||
Store: fake,
|
|
||||||
Object: storage.ObjectInfo{Key: key, Size: size, ETag: "etag"},
|
|
||||||
Bucket: "my-dnd-archive",
|
|
||||||
CacheRoot: filepath.Join(root, "cache"),
|
|
||||||
CacheEnabled: true,
|
|
||||||
SpoolPath: filepath.Join(root, "spool", "alice.flac"),
|
|
||||||
DestPath: filepath.Join(root, "work", "audio", "alice.flac"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func cachePathForTest(t *testing.T, req S3MaterializeRequest) string {
|
|
||||||
t.Helper()
|
|
||||||
cachePath, err := artifacts.S3AudioCachePath(req.CacheRoot, req.Bucket, req.Object.Key)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("cache path: %v", err)
|
|
||||||
}
|
|
||||||
return cachePath
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeAudioTestFile(t *testing.T, path, contents string) {
|
|
||||||
t.Helper()
|
|
||||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
|
||||||
t.Fatalf("mkdir %q: %v", path, err)
|
|
||||||
}
|
|
||||||
if err := os.WriteFile(path, []byte(contents), 0o644); err != nil {
|
|
||||||
t.Fatalf("write %q: %v", path, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func assertFileEquals(t *testing.T, path, want string) {
|
|
||||||
t.Helper()
|
|
||||||
data, err := os.ReadFile(path)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("read %q: %v", path, err)
|
|
||||||
}
|
|
||||||
if string(data) != want {
|
|
||||||
t.Fatalf("%q = %q, want %q", path, string(data), want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func assertMissing(t *testing.T, path string) {
|
|
||||||
t.Helper()
|
|
||||||
if _, err := os.Stat(path); !os.IsNotExist(err) {
|
|
||||||
t.Fatalf("stat %q = %v, want not exists", path, err)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,57 +5,14 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestCacheDefaults(t *testing.T) {
|
func TestRetiredAudioCacheAndSpoolSettingsAreRejected(t *testing.T) {
|
||||||
pipelinePath, sessionPath := writeConfigFiles(t, `workspace:
|
for _, field := range []string{"cache", "spool"} {
|
||||||
root: /tmp/narratio
|
t.Run(field, func(t *testing.T) {
|
||||||
whisperx:
|
pipeline, session := writeConfigFiles(t, "workspace:\n root: /tmp/narratio\n"+field+":\n root: /tmp/old\n", "session_id: 2026-05-03\ninputs:\n audio_dir: ./audio\n")
|
||||||
transcribe_url: https://example.com/transcribe
|
_, err := Load(pipeline, session)
|
||||||
notification:
|
if err == nil || !strings.Contains(configurationErrorText(err), "decode.unknown_field") {
|
||||||
mode: noop
|
t.Fatalf("Load() = %v, want unknown field error", err)
|
||||||
`, `session_id: 2026-05-03
|
}
|
||||||
inputs:
|
})
|
||||||
audio_dir: ./audio
|
|
||||||
`)
|
|
||||||
cfg, err := Load(pipelinePath, sessionPath)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Load() error = %v", err)
|
|
||||||
}
|
|
||||||
if cfg.Pipeline.Cache.Root != DefaultCacheRoot {
|
|
||||||
t.Fatalf("cache.root = %q, want %q", cfg.Pipeline.Cache.Root, DefaultCacheRoot)
|
|
||||||
}
|
|
||||||
if cfg.Pipeline.Cache.S3Audio == nil || *cfg.Pipeline.Cache.S3Audio != DefaultCacheS3Audio {
|
|
||||||
t.Fatalf("cache.s3_audio = %v, want %v", cfg.Pipeline.Cache.S3Audio, DefaultCacheS3Audio)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCacheStrictDecodeRejectsUnknownFields(t *testing.T) {
|
|
||||||
pipelinePath, sessionPath := writeConfigFiles(t, `workspace:
|
|
||||||
root: /tmp/narratio
|
|
||||||
cache:
|
|
||||||
root: /var/cache/narratio
|
|
||||||
unknown: true
|
|
||||||
`, `session_id: 2026-05-03
|
|
||||||
inputs:
|
|
||||||
audio_dir: ./audio
|
|
||||||
`)
|
|
||||||
_, err := Load(pipelinePath, sessionPath)
|
|
||||||
if err == nil || !strings.Contains(configurationErrorText(err), "decode.unknown_field") {
|
|
||||||
t.Fatalf("Load() error = %v, want strict decode failed", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCacheValidationRequiresRootWhenS3AudioEnabled(t *testing.T) {
|
|
||||||
pipelinePath, sessionPath := writeConfigFiles(t, `workspace:
|
|
||||||
root: /tmp/narratio
|
|
||||||
cache:
|
|
||||||
root: " "
|
|
||||||
s3_audio: true
|
|
||||||
`, `session_id: 2026-05-03
|
|
||||||
inputs:
|
|
||||||
audio_dir: ./audio
|
|
||||||
`)
|
|
||||||
_, err := Load(pipelinePath, sessionPath)
|
|
||||||
if err == nil || !strings.Contains(configurationErrorText(err), "pipeline.cache.root is required") {
|
|
||||||
t.Fatalf("Load() error = %v, want cache root error", err)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,8 +49,6 @@ type PipelineConfig struct {
|
|||||||
Workspace WorkspaceConfig `yaml:"workspace" json:"workspace"`
|
Workspace WorkspaceConfig `yaml:"workspace" json:"workspace"`
|
||||||
Campaigns CampaignsConfig `yaml:"campaigns" json:"campaigns"`
|
Campaigns CampaignsConfig `yaml:"campaigns" json:"campaigns"`
|
||||||
Storage StorageConfig `yaml:"storage" json:"storage"`
|
Storage StorageConfig `yaml:"storage" json:"storage"`
|
||||||
Spool SpoolConfig `yaml:"spool" json:"spool"`
|
|
||||||
Cache CacheConfig `yaml:"cache" json:"cache"`
|
|
||||||
Publish *PublishConfig `yaml:"publish" json:"publish"`
|
Publish *PublishConfig `yaml:"publish" json:"publish"`
|
||||||
WhisperX WhisperXConfig `yaml:"whisperx" json:"whisperx"`
|
WhisperX WhisperXConfig `yaml:"whisperx" json:"whisperx"`
|
||||||
Seriatim SeriatimConfig `yaml:"seriatim" json:"seriatim"`
|
Seriatim SeriatimConfig `yaml:"seriatim" json:"seriatim"`
|
||||||
@@ -186,18 +184,6 @@ type StorageS3Config struct {
|
|||||||
SecretAccessKey *configkit.Secret `yaml:"secret_access_key,omitempty" json:"secret_access_key,omitempty"`
|
SecretAccessKey *configkit.Secret `yaml:"secret_access_key,omitempty" json:"secret_access_key,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// SpoolConfig configures local spool storage for staged data.
|
|
||||||
type SpoolConfig struct {
|
|
||||||
Root string `yaml:"root" json:"root"`
|
|
||||||
DeleteAudioAfterPublish bool `yaml:"delete_audio_after_publish" json:"delete_audio_after_publish"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// CacheConfig configures durable local caches for reusable remote inputs.
|
|
||||||
type CacheConfig struct {
|
|
||||||
Root string `yaml:"root" json:"root"`
|
|
||||||
S3Audio *bool `yaml:"s3_audio" json:"s3_audio"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// PublishConfig configures publish behavior and source-based output uploads.
|
// PublishConfig configures publish behavior and source-based output uploads.
|
||||||
type PublishConfig struct {
|
type PublishConfig struct {
|
||||||
Enabled *bool `yaml:"enabled" json:"enabled"`
|
Enabled *bool `yaml:"enabled" json:"enabled"`
|
||||||
|
|||||||
@@ -10,9 +10,6 @@ const (
|
|||||||
DefaultStorageS3RootPrefix = "dnd"
|
DefaultStorageS3RootPrefix = "dnd"
|
||||||
DefaultWorkspaceRoot = "/var/lib/narratio"
|
DefaultWorkspaceRoot = "/var/lib/narratio"
|
||||||
DefaultCampaignsRoot = "/usr/local/share/narratio/campaigns"
|
DefaultCampaignsRoot = "/usr/local/share/narratio/campaigns"
|
||||||
DefaultSpoolRoot = "/var/spool/narratio"
|
|
||||||
DefaultCacheRoot = "/var/cache/narratio"
|
|
||||||
DefaultCacheS3Audio = true
|
|
||||||
|
|
||||||
DefaultWhisperXLanguage = "en"
|
DefaultWhisperXLanguage = "en"
|
||||||
DefaultWhisperXTimeout = "30m"
|
DefaultWhisperXTimeout = "30m"
|
||||||
|
|||||||
@@ -12,8 +12,6 @@ type effectivePipelineProjection struct {
|
|||||||
Workspace WorkspaceConfig `yaml:"workspace" json:"workspace"`
|
Workspace WorkspaceConfig `yaml:"workspace" json:"workspace"`
|
||||||
Campaigns CampaignsConfig `yaml:"campaigns" json:"campaigns"`
|
Campaigns CampaignsConfig `yaml:"campaigns" json:"campaigns"`
|
||||||
Storage effectiveStorageConfig `yaml:"storage" json:"storage"`
|
Storage effectiveStorageConfig `yaml:"storage" json:"storage"`
|
||||||
Spool SpoolConfig `yaml:"spool" json:"spool"`
|
|
||||||
Cache CacheConfig `yaml:"cache" json:"cache"`
|
|
||||||
Publish *PublishConfig `yaml:"publish" json:"publish"`
|
Publish *PublishConfig `yaml:"publish" json:"publish"`
|
||||||
WhisperX WhisperXConfig `yaml:"whisperx" json:"whisperx"`
|
WhisperX WhisperXConfig `yaml:"whisperx" json:"whisperx"`
|
||||||
Seriatim SeriatimConfig `yaml:"seriatim" json:"seriatim"`
|
Seriatim SeriatimConfig `yaml:"seriatim" json:"seriatim"`
|
||||||
@@ -80,7 +78,7 @@ func projectEffectivePipeline(cfg *PipelineConfig) effectivePipelineProjection {
|
|||||||
projection := effectivePipelineProjection{
|
projection := effectivePipelineProjection{
|
||||||
ReferenceCatalog: cfg.ReferenceCatalog,
|
ReferenceCatalog: cfg.ReferenceCatalog,
|
||||||
Workspace: cfg.Workspace, Campaigns: cfg.Campaigns, Storage: effectiveStorageConfig{Backend: cfg.Storage.Backend},
|
Workspace: cfg.Workspace, Campaigns: cfg.Campaigns, Storage: effectiveStorageConfig{Backend: cfg.Storage.Backend},
|
||||||
Spool: cfg.Spool, Cache: cfg.Cache, Publish: cfg.Publish,
|
Publish: cfg.Publish,
|
||||||
WhisperX: cfg.WhisperX, Seriatim: cfg.Seriatim,
|
WhisperX: cfg.WhisperX, Seriatim: cfg.Seriatim,
|
||||||
Normalize: cfg.Normalize, Trim: cfg.Trim, Render: cfg.Render,
|
Normalize: cfg.Normalize, Trim: cfg.Trim, Render: cfg.Render,
|
||||||
Notification: cfg.Notification,
|
Notification: cfg.Notification,
|
||||||
|
|||||||
@@ -77,8 +77,6 @@ func pipelineConfigDefaults() PipelineConfig {
|
|||||||
Workspace: WorkspaceConfig{Root: DefaultWorkspaceRoot},
|
Workspace: WorkspaceConfig{Root: DefaultWorkspaceRoot},
|
||||||
Campaigns: CampaignsConfig{Root: DefaultCampaignsRoot},
|
Campaigns: CampaignsConfig{Root: DefaultCampaignsRoot},
|
||||||
Storage: StorageConfig{Backend: StorageBackendLocal},
|
Storage: StorageConfig{Backend: StorageBackendLocal},
|
||||||
Spool: SpoolConfig{Root: DefaultSpoolRoot},
|
|
||||||
Cache: CacheConfig{Root: DefaultCacheRoot, S3Audio: boolPtr(DefaultCacheS3Audio)},
|
|
||||||
Publish: &PublishConfig{
|
Publish: &PublishConfig{
|
||||||
Enabled: boolPtr(DefaultArchiveEnabled), UploadRun: boolPtr(DefaultArchiveUploadRun),
|
Enabled: boolPtr(DefaultArchiveEnabled), UploadRun: boolPtr(DefaultArchiveUploadRun),
|
||||||
Outputs: defaultPublishOutputs(),
|
Outputs: defaultPublishOutputs(),
|
||||||
@@ -140,8 +138,6 @@ func resolvePipelineConfig(cfg *PipelineConfig, resolution *configkit.Resolution
|
|||||||
resolveHostResource(resolution, configkit.Keys("workspace", "root"), &cfg.Workspace.Root, invocationDir)
|
resolveHostResource(resolution, configkit.Keys("workspace", "root"), &cfg.Workspace.Root, invocationDir)
|
||||||
resolveHostResource(resolution, configkit.Keys("campaigns", "root"), &cfg.Campaigns.Root, invocationDir)
|
resolveHostResource(resolution, configkit.Keys("campaigns", "root"), &cfg.Campaigns.Root, invocationDir)
|
||||||
resolveHostResource(resolution, configkit.Keys("campaigns", "session_template_file"), &cfg.Campaigns.SessionTemplateFile, invocationDir)
|
resolveHostResource(resolution, configkit.Keys("campaigns", "session_template_file"), &cfg.Campaigns.SessionTemplateFile, invocationDir)
|
||||||
resolveHostResource(resolution, configkit.Keys("spool", "root"), &cfg.Spool.Root, invocationDir)
|
|
||||||
resolveHostResource(resolution, configkit.Keys("cache", "root"), &cfg.Cache.Root, invocationDir)
|
|
||||||
resolveHostResource(resolution, configkit.Keys("audita", "config_path"), &cfg.Audita.ConfigPath, invocationDir)
|
resolveHostResource(resolution, configkit.Keys("audita", "config_path"), &cfg.Audita.ConfigPath, invocationDir)
|
||||||
if cfg.Scriptorium != nil {
|
if cfg.Scriptorium != nil {
|
||||||
resolveHostResource(resolution, configkit.Keys("scriptorium", "config_path"), &cfg.Scriptorium.ConfigPath, invocationDir)
|
resolveHostResource(resolution, configkit.Keys("scriptorium", "config_path"), &cfg.Scriptorium.ConfigPath, invocationDir)
|
||||||
|
|||||||
@@ -16,8 +16,6 @@ func TestPipelineResourcePathsFollowEffectiveSources(t *testing.T) {
|
|||||||
workspace: {root: root-work}
|
workspace: {root: root-work}
|
||||||
`)
|
`)
|
||||||
writePipelineFixture(t, dir, "fragments/shared.yml", `campaigns: {root: campaigns}
|
writePipelineFixture(t, dir, "fragments/shared.yml", `campaigns: {root: campaigns}
|
||||||
spool: {root: /absolute/spool}
|
|
||||||
cache: {root: cache}
|
|
||||||
audita: {config_path: config/tool.yml}
|
audita: {config_path: config/tool.yml}
|
||||||
scriptorium: {extends: audita}
|
scriptorium: {extends: audita}
|
||||||
notarius:
|
notarius:
|
||||||
@@ -36,7 +34,7 @@ notarius:
|
|||||||
if base.Audita.ConfigPath != wantConfig || base.Scriptorium.ConfigPath != wantConfig || base.Notarius.ConfigPath != wantConfig {
|
if base.Audita.ConfigPath != wantConfig || base.Scriptorium.ConfigPath != wantConfig || base.Notarius.ConfigPath != wantConfig {
|
||||||
t.Fatalf("resource paths: audita=%q scriptorium=%q notarius=%q", base.Audita.ConfigPath, base.Scriptorium.ConfigPath, base.Notarius.ConfigPath)
|
t.Fatalf("resource paths: audita=%q scriptorium=%q notarius=%q", base.Audita.ConfigPath, base.Scriptorium.ConfigPath, base.Notarius.ConfigPath)
|
||||||
}
|
}
|
||||||
if base.Notarius.WorkingDirectory != filepath.Dir(wantConfig) || base.Workspace.Root != filepath.Join(dir, "root-work") || base.Campaigns.Root != filepath.Join(dir, "fragments", "campaigns") || base.Cache.Root != filepath.Join(dir, "fragments", "cache") || base.Spool.Root != "/absolute/spool" {
|
if base.Notarius.WorkingDirectory != filepath.Dir(wantConfig) || base.Workspace.Root != filepath.Join(dir, "root-work") || base.Campaigns.Root != filepath.Join(dir, "fragments", "campaigns") {
|
||||||
t.Fatalf("resolved paths: %#v", base)
|
t.Fatalf("resolved paths: %#v", base)
|
||||||
}
|
}
|
||||||
overlay := "testing"
|
overlay := "testing"
|
||||||
|
|||||||
@@ -285,7 +285,7 @@ inputs:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSpoolAndPublishDefaults(t *testing.T) {
|
func TestPublishDefaults(t *testing.T) {
|
||||||
pipelinePath, sessionPath := writeConfigFiles(t, testPipelineBaseYAML, testSessionBaseYAML)
|
pipelinePath, sessionPath := writeConfigFiles(t, testPipelineBaseYAML, testSessionBaseYAML)
|
||||||
|
|
||||||
cfg, err := Load(pipelinePath, sessionPath)
|
cfg, err := Load(pipelinePath, sessionPath)
|
||||||
@@ -293,12 +293,6 @@ func TestSpoolAndPublishDefaults(t *testing.T) {
|
|||||||
t.Fatalf("Load() error = %v", err)
|
t.Fatalf("Load() error = %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if cfg.Pipeline.Spool.Root != "/var/spool/narratio" {
|
|
||||||
t.Fatalf("spool.root = %q, want /var/spool/narratio", cfg.Pipeline.Spool.Root)
|
|
||||||
}
|
|
||||||
if cfg.Pipeline.Spool.DeleteAudioAfterPublish {
|
|
||||||
t.Fatalf("spool.delete_audio_after_publish = true, want false")
|
|
||||||
}
|
|
||||||
if cfg.Pipeline.Workspace.CleanupAfterPublish {
|
if cfg.Pipeline.Workspace.CleanupAfterPublish {
|
||||||
t.Fatalf("workspace.cleanup_after_publish = true, want false")
|
t.Fatalf("workspace.cleanup_after_publish = true, want false")
|
||||||
}
|
}
|
||||||
@@ -340,17 +334,13 @@ func TestSpoolAndPublishDefaults(t *testing.T) {
|
|||||||
func TestCleanupPoliciesRequireEnabledRunPublication(t *testing.T) {
|
func TestCleanupPoliciesRequireEnabledRunPublication(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
spoolCleanup bool
|
|
||||||
workspaceCleanup bool
|
workspaceCleanup bool
|
||||||
publishEnabled bool
|
publishEnabled bool
|
||||||
uploadRun bool
|
uploadRun bool
|
||||||
wantError bool
|
wantError bool
|
||||||
}{
|
}{
|
||||||
{name: "spool cleanup rejects disabled publish", spoolCleanup: true, uploadRun: true, wantError: true},
|
|
||||||
{name: "workspace cleanup rejects disabled publish", workspaceCleanup: true, uploadRun: true, wantError: true},
|
{name: "workspace cleanup rejects disabled publish", workspaceCleanup: true, uploadRun: true, wantError: true},
|
||||||
{name: "spool cleanup rejects disabled run upload", spoolCleanup: true, publishEnabled: true, wantError: true},
|
|
||||||
{name: "workspace cleanup rejects disabled run upload", workspaceCleanup: true, publishEnabled: true, wantError: true},
|
{name: "workspace cleanup rejects disabled run upload", workspaceCleanup: true, publishEnabled: true, wantError: true},
|
||||||
{name: "spool cleanup accepts enabled run publication", spoolCleanup: true, publishEnabled: true, uploadRun: true},
|
|
||||||
{name: "workspace cleanup accepts enabled run publication", workspaceCleanup: true, publishEnabled: true, uploadRun: true},
|
{name: "workspace cleanup accepts enabled run publication", workspaceCleanup: true, publishEnabled: true, uploadRun: true},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -361,7 +351,6 @@ func TestCleanupPoliciesRequireEnabledRunPublication(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load() error = %v", err)
|
t.Fatalf("Load() error = %v", err)
|
||||||
}
|
}
|
||||||
cfg.Pipeline.Spool.DeleteAudioAfterPublish = test.spoolCleanup
|
|
||||||
cfg.Pipeline.Workspace.CleanupAfterPublish = test.workspaceCleanup
|
cfg.Pipeline.Workspace.CleanupAfterPublish = test.workspaceCleanup
|
||||||
cfg.Pipeline.Publish.Enabled = &test.publishEnabled
|
cfg.Pipeline.Publish.Enabled = &test.publishEnabled
|
||||||
cfg.Pipeline.Publish.UploadRun = &test.uploadRun
|
cfg.Pipeline.Publish.UploadRun = &test.uploadRun
|
||||||
|
|||||||
@@ -85,8 +85,6 @@ func pipelineConfigurationIssues(cfg *PipelineConfig) []pipelineConfigurationIss
|
|||||||
{[]string{"workspace", "root"}, workspaceErr},
|
{[]string{"workspace", "root"}, workspaceErr},
|
||||||
{[]string{"campaigns", "default_campaign_id"}, campaignErr},
|
{[]string{"campaigns", "default_campaign_id"}, campaignErr},
|
||||||
{[]string{"storage"}, validateStorage(cfg.Storage)},
|
{[]string{"storage"}, validateStorage(cfg.Storage)},
|
||||||
{[]string{"spool"}, validateSpool(cfg.Spool)},
|
|
||||||
{[]string{"cache"}, validateCache(cfg.Cache)},
|
|
||||||
{[]string{"notarius"}, validateNotarius(cfg.Notarius, cfg.Scriptorium)},
|
{[]string{"notarius"}, validateNotarius(cfg.Notarius, cfg.Scriptorium)},
|
||||||
{[]string{"publish"}, validateCleanupPublishPolicy(cfg)},
|
{[]string{"publish"}, validateCleanupPublishPolicy(cfg)},
|
||||||
{[]string{"whisperx"}, validateWhisperX(cfg.WhisperX)},
|
{[]string{"whisperx"}, validateWhisperX(cfg.WhisperX)},
|
||||||
|
|||||||
@@ -33,17 +33,6 @@ func campaignConfigurationError(cfg *CampaignConfig) (configkit.Path, error) {
|
|||||||
return configkit.Keys(), nil
|
return configkit.Keys(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func validateSpool(cfg SpoolConfig) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func validateCache(cfg CacheConfig) error {
|
|
||||||
if cfg.S3Audio != nil && *cfg.S3Audio && strings.TrimSpace(cfg.Root) == "" {
|
|
||||||
return fmt.Errorf("pipeline.cache.root is required when pipeline.cache.s3_audio is true")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func validateSession(cfg *SessionConfig) error {
|
func validateSession(cfg *SessionConfig) error {
|
||||||
_, err := sessionConfigurationError(cfg)
|
_, err := sessionConfigurationError(cfg)
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -104,7 +104,7 @@ func validatePublishedOutputs(outputs []PublishOutputRule, configuredOutputs map
|
|||||||
}
|
}
|
||||||
|
|
||||||
func validateCleanupPublishPolicy(cfg *PipelineConfig) error {
|
func validateCleanupPublishPolicy(cfg *PipelineConfig) error {
|
||||||
if cfg == nil || (!cfg.Spool.DeleteAudioAfterPublish && !cfg.Workspace.CleanupAfterPublish) {
|
if cfg == nil || !cfg.Workspace.CleanupAfterPublish {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if cfg.Publish == nil || (cfg.Publish.Enabled != nil && !*cfg.Publish.Enabled) {
|
if cfg.Publish == nil || (cfg.Publish.Enabled != nil && !*cfg.Publish.Enabled) {
|
||||||
|
|||||||
@@ -31,8 +31,6 @@ type InputRecord struct {
|
|||||||
S3Key string `json:"s3_key,omitempty"`
|
S3Key string `json:"s3_key,omitempty"`
|
||||||
S3Size int64 `json:"s3_size,omitempty"`
|
S3Size int64 `json:"s3_size,omitempty"`
|
||||||
S3ETag string `json:"s3_etag,omitempty"`
|
S3ETag string `json:"s3_etag,omitempty"`
|
||||||
SpoolPath string `json:"spool_path,omitempty"`
|
|
||||||
CachePath string `json:"cache_path,omitempty"`
|
|
||||||
Dependencies []string `json:"dependencies,omitempty"`
|
Dependencies []string `json:"dependencies,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,7 +90,6 @@ type Manifest struct {
|
|||||||
Campaign string `json:"campaign,omitempty"`
|
Campaign string `json:"campaign,omitempty"`
|
||||||
RunID string `json:"run_id,omitempty"`
|
RunID string `json:"run_id,omitempty"`
|
||||||
LocalWorkDir string `json:"local_workdir,omitempty"`
|
LocalWorkDir string `json:"local_workdir,omitempty"`
|
||||||
LocalSpoolDir string `json:"local_spool_dir,omitempty"`
|
|
||||||
S3Bucket string `json:"s3_bucket,omitempty"`
|
S3Bucket string `json:"s3_bucket,omitempty"`
|
||||||
S3SessionPrefix string `json:"s3_session_prefix,omitempty"`
|
S3SessionPrefix string `json:"s3_session_prefix,omitempty"`
|
||||||
S3RunPrefix string `json:"s3_run_prefix,omitempty"`
|
S3RunPrefix string `json:"s3_run_prefix,omitempty"`
|
||||||
|
|||||||
@@ -29,7 +29,6 @@ func TestLocalStoreCreateSaveLoadRoundTrip(t *testing.T) {
|
|||||||
m.Campaign = "forsaken"
|
m.Campaign = "forsaken"
|
||||||
m.RunID = "20260515T031522Z-a1b2c3d4"
|
m.RunID = "20260515T031522Z-a1b2c3d4"
|
||||||
m.LocalWorkDir = "/var/lib/narratio/work/forsaken/2026-05-03/20260515T031522Z-a1b2c3d4"
|
m.LocalWorkDir = "/var/lib/narratio/work/forsaken/2026-05-03/20260515T031522Z-a1b2c3d4"
|
||||||
m.LocalSpoolDir = "/var/spool/narratio/forsaken/2026-05-03/20260515T031522Z-a1b2c3d4/audio"
|
|
||||||
m.S3Bucket = "my-dnd-archive"
|
m.S3Bucket = "my-dnd-archive"
|
||||||
m.S3SessionPrefix = "dnd/campaigns/forsaken/sessions/2026-05-03/"
|
m.S3SessionPrefix = "dnd/campaigns/forsaken/sessions/2026-05-03/"
|
||||||
m.S3RunPrefix = "dnd/campaigns/forsaken/sessions/2026-05-03/runs/20260515T031522Z-a1b2c3d4/"
|
m.S3RunPrefix = "dnd/campaigns/forsaken/sessions/2026-05-03/runs/20260515T031522Z-a1b2c3d4/"
|
||||||
|
|||||||
@@ -2,13 +2,10 @@ package stage
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
|
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
|
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -20,10 +17,8 @@ const (
|
|||||||
type cleanupStage struct{}
|
type cleanupStage struct{}
|
||||||
|
|
||||||
type cleanupSemanticConfig struct {
|
type cleanupSemanticConfig struct {
|
||||||
DeleteSpoolAudio bool `json:"delete_spool_audio"`
|
DeleteWorkspace bool `json:"delete_workspace"`
|
||||||
SpoolRoot string `json:"spool_root"`
|
WorkspaceRoot string `json:"workspace_root"`
|
||||||
DeleteWorkspace bool `json:"delete_workspace"`
|
|
||||||
WorkspaceRoot string `json:"workspace_root"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cleanupStage) Name() string { return "cleanup" }
|
func (cleanupStage) Name() string { return "cleanup" }
|
||||||
@@ -47,12 +42,7 @@ func (cleanupStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S
|
|||||||
if err := ctx.Err(); err != nil {
|
if err := ctx.Err(); err != nil {
|
||||||
return nil, fmt.Errorf("cleanup canceled before %s: %w", target.policy, err)
|
return nil, fmt.Errorf("cleanup canceled before %s: %w", target.policy, err)
|
||||||
}
|
}
|
||||||
var err error
|
_, err := cleanRunWithRetainedBundle(target.root, target.target, true)
|
||||||
if target.policy == cleanupWorkspacePolicy {
|
|
||||||
_, err = cleanRunWithRetainedBundle(target.root, target.target, true)
|
|
||||||
} else {
|
|
||||||
err = fileops.RemoveAllUnderRoot(target.root, target.target)
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("apply %s: %w", target.policy, err)
|
return nil, fmt.Errorf("apply %s: %w", target.policy, err)
|
||||||
}
|
}
|
||||||
@@ -72,10 +62,8 @@ func (cleanupStage) SemanticConfigFingerprint(env *Env) (manifest.SemanticConfig
|
|||||||
}
|
}
|
||||||
pipeline := env.Config.Pipeline
|
pipeline := env.Config.Pipeline
|
||||||
return FingerprintSemanticConfig(cleanupSemanticConfigVersion, cleanupSemanticConfig{
|
return FingerprintSemanticConfig(cleanupSemanticConfigVersion, cleanupSemanticConfig{
|
||||||
DeleteSpoolAudio: pipeline.Spool.DeleteAudioAfterPublish,
|
DeleteWorkspace: pipeline.Workspace.CleanupAfterPublish,
|
||||||
SpoolRoot: normalizedCleanupRoot(pipeline.Spool.Root),
|
WorkspaceRoot: normalizedCleanupRoot(pipeline.Workspace.Root),
|
||||||
DeleteWorkspace: pipeline.Workspace.CleanupAfterPublish,
|
|
||||||
WorkspaceRoot: normalizedCleanupRoot(pipeline.Workspace.Root),
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,20 +79,12 @@ func (cleanupStage) ValidateResume(ctx context.Context, env *Env, m *manifest.Ma
|
|||||||
if err := ctx.Err(); err != nil {
|
if err := ctx.Err(); err != nil {
|
||||||
return ResumeValidation{}, fmt.Errorf("validate cleanup resume for %s: %w", target.policy, err)
|
return ResumeValidation{}, fmt.Errorf("validate cleanup resume for %s: %w", target.policy, err)
|
||||||
}
|
}
|
||||||
if target.policy == cleanupWorkspacePolicy {
|
pending, err := cleanRunWithRetainedBundle(target.root, target.target, false)
|
||||||
pending, err := cleanRunWithRetainedBundle(target.root, target.target, false)
|
if err != nil {
|
||||||
if err != nil {
|
return ResumeValidation{}, err
|
||||||
return ResumeValidation{}, err
|
|
||||||
}
|
|
||||||
if pending {
|
|
||||||
return NonResumable(fmt.Sprintf("cleanup target for %s exists", target.policy)), nil
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
}
|
||||||
if _, err := os.Lstat(target.target); err == nil {
|
if pending {
|
||||||
return NonResumable(fmt.Sprintf("cleanup target for %s exists", target.policy)), nil
|
return NonResumable(fmt.Sprintf("cleanup target for %s exists", target.policy)), nil
|
||||||
} else if !errors.Is(err, os.ErrNotExist) {
|
|
||||||
return ResumeValidation{}, fmt.Errorf("inspect cleanup target for %s: %w", target.policy, err)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return Resumable(), nil
|
return Resumable(), nil
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
cleanupSpoolPolicy = "pipeline.spool.delete_audio_after_publish"
|
|
||||||
cleanupWorkspacePolicy = "pipeline.workspace.cleanup_after_publish"
|
cleanupWorkspacePolicy = "pipeline.workspace.cleanup_after_publish"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -31,9 +30,8 @@ func buildCleanupPlan(env *Env, m *manifest.Manifest) (cleanupPlan, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pipeline := env.Config.Pipeline
|
pipeline := env.Config.Pipeline
|
||||||
spoolRequested := pipeline.Spool.DeleteAudioAfterPublish
|
|
||||||
workspaceRequested := pipeline.Workspace.CleanupAfterPublish
|
workspaceRequested := pipeline.Workspace.CleanupAfterPublish
|
||||||
if !spoolRequested && !workspaceRequested {
|
if !workspaceRequested {
|
||||||
return cleanupPlan{}, nil
|
return cleanupPlan{}, nil
|
||||||
}
|
}
|
||||||
if m == nil {
|
if m == nil {
|
||||||
@@ -69,22 +67,6 @@ func buildCleanupPlan(env *Env, m *manifest.Manifest) (cleanupPlan, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
plan := cleanupPlan{enabled: true, publishedRunID: publishedRunID}
|
plan := cleanupPlan{enabled: true, publishedRunID: publishedRunID}
|
||||||
if spoolRequested {
|
|
||||||
root := strings.TrimSpace(pipeline.Spool.Root)
|
|
||||||
if root == "" {
|
|
||||||
return cleanupPlan{}, fmt.Errorf("pipeline.spool.root is required for cleanup")
|
|
||||||
}
|
|
||||||
plan.targets = append(plan.targets, cleanupPlanTarget{
|
|
||||||
root: root,
|
|
||||||
target: artifacts.SessionSpoolAudioDir(
|
|
||||||
root,
|
|
||||||
campaign,
|
|
||||||
sessionID,
|
|
||||||
publishedRunID,
|
|
||||||
),
|
|
||||||
policy: cleanupSpoolPolicy,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
if workspaceRequested {
|
if workspaceRequested {
|
||||||
root := strings.TrimSpace(pipeline.Workspace.Root)
|
root := strings.TrimSpace(pipeline.Workspace.Root)
|
||||||
if root == "" {
|
if root == "" {
|
||||||
|
|||||||
@@ -20,83 +20,16 @@ func TestBuildCleanupPlanDisabledNeedsNoPublishEvidence(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestBuildCleanupPlanSelectsCanonicalPublishedRunTargets(t *testing.T) {
|
func TestBuildCleanupPlanSelectsCanonicalPublishedRunTarget(t *testing.T) {
|
||||||
tests := []struct {
|
env, m, runID := cleanupPlanningFixture(t)
|
||||||
name string
|
env.Config.Pipeline.Workspace.CleanupAfterPublish = true
|
||||||
spool bool
|
plan, err := buildCleanupPlan(env, m)
|
||||||
workspace bool
|
if err != nil {
|
||||||
wantPolicies []string
|
t.Fatal(err)
|
||||||
wantTargetBuilder func(workspaceRoot, spoolRoot, campaign, sessionID, runID string) []string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "spool only",
|
|
||||||
spool: true,
|
|
||||||
wantPolicies: []string{cleanupSpoolPolicy},
|
|
||||||
wantTargetBuilder: func(_, spoolRoot, campaign, sessionID, runID string) []string {
|
|
||||||
return []string{artifacts.SessionSpoolAudioDir(spoolRoot, campaign, sessionID, runID)}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "workspace only",
|
|
||||||
workspace: true,
|
|
||||||
wantPolicies: []string{cleanupWorkspacePolicy},
|
|
||||||
wantTargetBuilder: func(workspaceRoot, _, campaign, sessionID, runID string) []string {
|
|
||||||
return []string{artifacts.SessionRunRootForCampaign(workspaceRoot, campaign, sessionID, runID)}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "spool precedes workspace",
|
|
||||||
spool: true,
|
|
||||||
workspace: true,
|
|
||||||
wantPolicies: []string{cleanupSpoolPolicy, cleanupWorkspacePolicy},
|
|
||||||
wantTargetBuilder: func(workspaceRoot, spoolRoot, campaign, sessionID, runID string) []string {
|
|
||||||
return []string{
|
|
||||||
artifacts.SessionSpoolAudioDir(spoolRoot, campaign, sessionID, runID),
|
|
||||||
artifacts.SessionRunRootForCampaign(workspaceRoot, campaign, sessionID, runID),
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
want := artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, m.Campaign, m.SessionID, runID)
|
||||||
for _, test := range tests {
|
if !plan.enabled || plan.publishedRunID != runID || len(plan.targets) != 1 || plan.targets[0].target != want || plan.targets[0].policy != cleanupWorkspacePolicy {
|
||||||
t.Run(test.name, func(t *testing.T) {
|
t.Fatalf("cleanup plan = %#v", plan)
|
||||||
env, m, publishedRunID := cleanupPlanningFixture(t)
|
|
||||||
env.Config.Pipeline.Spool.DeleteAudioAfterPublish = test.spool
|
|
||||||
env.Config.Pipeline.Workspace.CleanupAfterPublish = test.workspace
|
|
||||||
|
|
||||||
plan, err := buildCleanupPlan(env, m)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("buildCleanupPlan() error = %v", err)
|
|
||||||
}
|
|
||||||
if !plan.enabled || plan.publishedRunID != publishedRunID {
|
|
||||||
t.Fatalf("cleanup plan identity = %#v", plan)
|
|
||||||
}
|
|
||||||
wantTargets := test.wantTargetBuilder(
|
|
||||||
env.Config.Pipeline.Workspace.Root,
|
|
||||||
env.Config.Pipeline.Spool.Root,
|
|
||||||
m.Campaign,
|
|
||||||
m.SessionID,
|
|
||||||
publishedRunID,
|
|
||||||
)
|
|
||||||
if len(plan.targets) != len(wantTargets) {
|
|
||||||
t.Fatalf("cleanup targets = %#v, want %d", plan.targets, len(wantTargets))
|
|
||||||
}
|
|
||||||
for index, target := range plan.targets {
|
|
||||||
if target.policy != test.wantPolicies[index] || target.target != wantTargets[index] {
|
|
||||||
t.Fatalf("cleanup target %d = %#v, want policy %q path %q", index, target, test.wantPolicies[index], wantTargets[index])
|
|
||||||
}
|
|
||||||
wantRoot := env.Config.Pipeline.Workspace.Root
|
|
||||||
if target.policy == cleanupSpoolPolicy {
|
|
||||||
wantRoot = env.Config.Pipeline.Spool.Root
|
|
||||||
}
|
|
||||||
if target.root != wantRoot {
|
|
||||||
t.Fatalf("cleanup target %d root = %q, want %q", index, target.root, wantRoot)
|
|
||||||
}
|
|
||||||
if target.target == m.LocalWorkDir || target.target == m.LocalSpoolDir || filepath.Base(target.target) == m.RunID {
|
|
||||||
t.Fatalf("cleanup target used current-invocation state: %#v", target)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,7 +64,6 @@ func TestBuildCleanupPlanRejectsInvalidPublishEvidenceWithoutExecutablePlan(t *t
|
|||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
t.Run(test.name, func(t *testing.T) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
env, m, _ := cleanupPlanningFixture(t)
|
env, m, _ := cleanupPlanningFixture(t)
|
||||||
env.Config.Pipeline.Spool.DeleteAudioAfterPublish = true
|
|
||||||
env.Config.Pipeline.Workspace.CleanupAfterPublish = true
|
env.Config.Pipeline.Workspace.CleanupAfterPublish = true
|
||||||
test.mutate(env, m)
|
test.mutate(env, m)
|
||||||
|
|
||||||
@@ -157,8 +89,6 @@ func cleanupPlanningFixture(t *testing.T) (*Env, *manifest.Manifest, string) {
|
|||||||
env := &Env{Config: &config.Config{
|
env := &Env{Config: &config.Config{
|
||||||
Pipeline: &config.PipelineConfig{
|
Pipeline: &config.PipelineConfig{
|
||||||
Workspace: config.WorkspaceConfig{Root: filepath.Join(root, "workspace")},
|
Workspace: config.WorkspaceConfig{Root: filepath.Join(root, "workspace")},
|
||||||
Spool: config.SpoolConfig{Root: filepath.Join(root, "spool")},
|
|
||||||
Cache: config.CacheConfig{Root: filepath.Join(root, "cache")},
|
|
||||||
},
|
},
|
||||||
Session: &config.SessionConfig{Campaign: campaign, SessionID: sessionID},
|
Session: &config.SessionConfig{Campaign: campaign, SessionID: sessionID},
|
||||||
}}
|
}}
|
||||||
@@ -167,7 +97,6 @@ func cleanupPlanningFixture(t *testing.T) (*Env, *manifest.Manifest, string) {
|
|||||||
SessionID: sessionID,
|
SessionID: sessionID,
|
||||||
RunID: "current-invocation-run",
|
RunID: "current-invocation-run",
|
||||||
LocalWorkDir: filepath.Join(root, "untrusted-workdir"),
|
LocalWorkDir: filepath.Join(root, "untrusted-workdir"),
|
||||||
LocalSpoolDir: filepath.Join(root, "untrusted-spool"),
|
|
||||||
S3SessionPrefix: sessionPrefix,
|
S3SessionPrefix: sessionPrefix,
|
||||||
Stages: map[string]*manifest.StageRecord{
|
Stages: map[string]*manifest.StageRecord{
|
||||||
"publish": {
|
"publish": {
|
||||||
|
|||||||
@@ -26,86 +26,30 @@ func TestCleanupStageDisabledSelfSkips(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCleanupStageRemovesOnlySelectedPublishedRunTargets(t *testing.T) {
|
func TestCleanupStageRemovesOnlySelectedPublishedRunTarget(t *testing.T) {
|
||||||
tests := []struct {
|
env, m, publishedRunID := cleanupPlanningFixture(t)
|
||||||
name string
|
env.Config.Pipeline.Workspace.CleanupAfterPublish = true
|
||||||
spool bool
|
target := artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, m.Campaign, m.SessionID, publishedRunID)
|
||||||
workspace bool
|
session := artifacts.NewLocalStore(env.Config.Pipeline.Workspace.Root).SessionPathsFor(m.Campaign, m.SessionID)
|
||||||
}{
|
audio := filepath.Join(session.AudioDir, "alice.flac")
|
||||||
{name: "spool only", spool: true},
|
other := artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, m.Campaign, m.SessionID, "other-run")
|
||||||
{name: "workspace only", workspace: true},
|
writeStageTestFile(t, filepath.Join(target, "result.txt"), "result")
|
||||||
{name: "both", spool: true, workspace: true},
|
writeStageTestFile(t, filepath.Join(other, "result.txt"), "other")
|
||||||
|
writeStageTestFile(t, audio, "audio")
|
||||||
|
result, err := (cleanupStage{}).Run(context.Background(), env, m)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
if _, err := os.Lstat(target); !errors.Is(err, os.ErrNotExist) {
|
||||||
for _, test := range tests {
|
t.Fatalf("target still exists: %v", err)
|
||||||
t.Run(test.name, func(t *testing.T) {
|
}
|
||||||
env, m, publishedRunID := cleanupPlanningFixture(t)
|
for _, path := range []string{audio, filepath.Join(other, "result.txt")} {
|
||||||
env.Config.Pipeline.Spool.DeleteAudioAfterPublish = test.spool
|
if _, err := os.Stat(path); err != nil {
|
||||||
env.Config.Pipeline.Workspace.CleanupAfterPublish = test.workspace
|
t.Fatalf("preserved %q: %v", path, err)
|
||||||
plan, err := buildCleanupPlan(env, m)
|
}
|
||||||
if err != nil {
|
}
|
||||||
t.Fatal(err)
|
if !reflect.DeepEqual(result.Metadata["completed_policies"], []string{cleanupWorkspacePolicy}) {
|
||||||
}
|
t.Fatalf("metadata = %#v", result.Metadata)
|
||||||
publishedSpool := artifacts.SessionSpoolAudioDir(
|
|
||||||
env.Config.Pipeline.Spool.Root, m.Campaign, m.SessionID, publishedRunID,
|
|
||||||
)
|
|
||||||
publishedWorkspace := artifacts.SessionRunRootForCampaign(
|
|
||||||
env.Config.Pipeline.Workspace.Root, m.Campaign, m.SessionID, publishedRunID,
|
|
||||||
)
|
|
||||||
writeStageTestFile(t, filepath.Join(publishedSpool, "nested", "audio.wav"), "audio")
|
|
||||||
writeStageTestFile(t, filepath.Join(publishedWorkspace, "nested", "result.txt"), "result")
|
|
||||||
|
|
||||||
otherSpool := filepath.Join(env.Config.Pipeline.Spool.Root, m.Campaign, m.SessionID, "other-run", "audio")
|
|
||||||
otherWorkspace := filepath.Join(env.Config.Pipeline.Workspace.Root, "work", m.Campaign, m.SessionID, "runs", "other-run")
|
|
||||||
cacheFile := filepath.Join(env.Config.Pipeline.Cache.Root, "s3", "audio.cache")
|
|
||||||
sessionPaths := artifacts.NewLocalStore(env.Config.Pipeline.Workspace.Root).SessionPathsFor(m.Campaign, m.SessionID)
|
|
||||||
referenceCacheFile := filepath.Join(artifacts.SessionNotariusReferenceCacheDir(sessionPaths), strings.Repeat("a", 64), "party.yml")
|
|
||||||
writeStageTestFile(t, filepath.Join(otherSpool, "audio.wav"), "other spool")
|
|
||||||
writeStageTestFile(t, filepath.Join(otherWorkspace, "result.txt"), "other workspace")
|
|
||||||
writeStageTestFile(t, cacheFile, "cache")
|
|
||||||
writeStageTestFile(t, referenceCacheFile, "reference cache")
|
|
||||||
|
|
||||||
result, err := (cleanupStage{}).Run(context.Background(), env, m)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Run() error = %v", err)
|
|
||||||
}
|
|
||||||
for _, target := range plan.targets {
|
|
||||||
if _, err := os.Lstat(target.target); !errors.Is(err, os.ErrNotExist) {
|
|
||||||
t.Fatalf("cleanup target %q still exists: %v", target.target, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !test.spool {
|
|
||||||
if _, err := os.Stat(publishedSpool); err != nil {
|
|
||||||
t.Fatalf("unselected spool target changed: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !test.workspace {
|
|
||||||
if _, err := os.Stat(publishedWorkspace); err != nil {
|
|
||||||
t.Fatalf("unselected workspace target changed: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, preserved := range []string{otherSpool, otherWorkspace, cacheFile, referenceCacheFile} {
|
|
||||||
if _, err := os.Stat(preserved); err != nil {
|
|
||||||
t.Fatalf("preserved path %q: %v", preserved, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(result.Outputs) != 0 || len(result.Logs) != 0 || len(result.GeneratedConfigs) != 0 {
|
|
||||||
t.Fatalf("cleanup returned canonical or diagnostic outputs: %#v", result)
|
|
||||||
}
|
|
||||||
if len(result.Metadata) != 3 || result.Metadata["stage"] != "cleanup" || result.Metadata["published_run_id"] != publishedRunID {
|
|
||||||
t.Fatalf("cleanup metadata = %#v", result.Metadata)
|
|
||||||
}
|
|
||||||
wantPolicies := make([]string, 0, 2)
|
|
||||||
if test.spool {
|
|
||||||
wantPolicies = append(wantPolicies, cleanupSpoolPolicy)
|
|
||||||
}
|
|
||||||
if test.workspace {
|
|
||||||
wantPolicies = append(wantPolicies, cleanupWorkspacePolicy)
|
|
||||||
}
|
|
||||||
if got := result.Metadata["completed_policies"]; !reflect.DeepEqual(got, wantPolicies) {
|
|
||||||
t.Fatalf("completed policies = %#v, want %#v", got, wantPolicies)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,9 +64,9 @@ func TestCleanupStageAcceptsAlreadyAbsentRootAndTarget(t *testing.T) {
|
|||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
t.Run(test.name, func(t *testing.T) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
env, m, _ := cleanupPlanningFixture(t)
|
env, m, _ := cleanupPlanningFixture(t)
|
||||||
env.Config.Pipeline.Spool.DeleteAudioAfterPublish = true
|
env.Config.Pipeline.Workspace.CleanupAfterPublish = true
|
||||||
if test.createRoot {
|
if test.createRoot {
|
||||||
if err := os.MkdirAll(env.Config.Pipeline.Spool.Root, 0o755); err != nil {
|
if err := os.MkdirAll(env.Config.Pipeline.Workspace.Root, 0o755); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -135,7 +79,7 @@ func TestCleanupStageAcceptsAlreadyAbsentRootAndTarget(t *testing.T) {
|
|||||||
|
|
||||||
func TestCleanupStageHonorsCancellationBeforeDeletion(t *testing.T) {
|
func TestCleanupStageHonorsCancellationBeforeDeletion(t *testing.T) {
|
||||||
env, m, _ := cleanupPlanningFixture(t)
|
env, m, _ := cleanupPlanningFixture(t)
|
||||||
env.Config.Pipeline.Spool.DeleteAudioAfterPublish = true
|
env.Config.Pipeline.Workspace.CleanupAfterPublish = true
|
||||||
plan, err := buildCleanupPlan(env, m)
|
plan, err := buildCleanupPlan(env, m)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -154,8 +98,8 @@ func TestCleanupStageHonorsCancellationBeforeDeletion(t *testing.T) {
|
|||||||
|
|
||||||
func TestCleanupStageRejectsUnsafeIdentityBeforeDeletion(t *testing.T) {
|
func TestCleanupStageRejectsUnsafeIdentityBeforeDeletion(t *testing.T) {
|
||||||
env, m, _ := cleanupPlanningFixture(t)
|
env, m, _ := cleanupPlanningFixture(t)
|
||||||
env.Config.Pipeline.Spool.DeleteAudioAfterPublish = true
|
env.Config.Pipeline.Workspace.CleanupAfterPublish = true
|
||||||
sentinel := filepath.Join(env.Config.Pipeline.Spool.Root, "sentinel.txt")
|
sentinel := filepath.Join(env.Config.Pipeline.Workspace.Root, "sentinel.txt")
|
||||||
writeStageTestFile(t, sentinel, "keep")
|
writeStageTestFile(t, sentinel, "keep")
|
||||||
m.Campaign = ".."
|
m.Campaign = ".."
|
||||||
env.Config.Session.Campaign = ".."
|
env.Config.Session.Campaign = ".."
|
||||||
@@ -168,43 +112,6 @@ func TestCleanupStageRejectsUnsafeIdentityBeforeDeletion(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCleanupStageRetriesAfterPartialDeletion(t *testing.T) {
|
|
||||||
env, m, _ := cleanupPlanningFixture(t)
|
|
||||||
env.Config.Pipeline.Spool.DeleteAudioAfterPublish = true
|
|
||||||
env.Config.Pipeline.Workspace.CleanupAfterPublish = true
|
|
||||||
plan, err := buildCleanupPlan(env, m)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
spoolTarget := plan.targets[0].target
|
|
||||||
workspaceTarget := plan.targets[1].target
|
|
||||||
writeStageTestFile(t, filepath.Join(spoolTarget, "audio.wav"), "audio")
|
|
||||||
if err := os.MkdirAll(filepath.Dir(env.Config.Pipeline.Workspace.Root), 0o755); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := os.WriteFile(env.Config.Pipeline.Workspace.Root, []byte("not a directory"), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := (cleanupStage{}).Run(context.Background(), env, m); err == nil {
|
|
||||||
t.Fatal("Run() error = nil with invalid workspace root")
|
|
||||||
}
|
|
||||||
if _, err := os.Lstat(spoolTarget); !errors.Is(err, os.ErrNotExist) {
|
|
||||||
t.Fatalf("first target remains after partial cleanup: %v", err)
|
|
||||||
}
|
|
||||||
if err := os.Remove(env.Config.Pipeline.Workspace.Root); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
writeStageTestFile(t, filepath.Join(workspaceTarget, "result.txt"), "result")
|
|
||||||
|
|
||||||
if _, err := (cleanupStage{}).Run(context.Background(), env, m); err != nil {
|
|
||||||
t.Fatalf("retry Run() error = %v", err)
|
|
||||||
}
|
|
||||||
if _, err := os.Lstat(workspaceTarget); !errors.Is(err, os.ErrNotExist) {
|
|
||||||
t.Fatalf("second target remains after retry: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCleanupSemanticConfigFingerprintTracksPoliciesAndNormalizedRoots(t *testing.T) {
|
func TestCleanupSemanticConfigFingerprintTracksPoliciesAndNormalizedRoots(t *testing.T) {
|
||||||
env, _, _ := cleanupPlanningFixture(t)
|
env, _, _ := cleanupPlanningFixture(t)
|
||||||
base, err := (cleanupStage{}).SemanticConfigFingerprint(env)
|
base, err := (cleanupStage{}).SemanticConfigFingerprint(env)
|
||||||
@@ -217,23 +124,11 @@ func TestCleanupSemanticConfigFingerprintTracksPoliciesAndNormalizedRoots(t *tes
|
|||||||
mutate func()
|
mutate func()
|
||||||
restore func()
|
restore func()
|
||||||
}{
|
}{
|
||||||
{
|
|
||||||
name: "spool policy",
|
|
||||||
mutate: func() { env.Config.Pipeline.Spool.DeleteAudioAfterPublish = true },
|
|
||||||
restore: func() { env.Config.Pipeline.Spool.DeleteAudioAfterPublish = false },
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
name: "workspace policy",
|
name: "workspace policy",
|
||||||
mutate: func() { env.Config.Pipeline.Workspace.CleanupAfterPublish = true },
|
mutate: func() { env.Config.Pipeline.Workspace.CleanupAfterPublish = true },
|
||||||
restore: func() { env.Config.Pipeline.Workspace.CleanupAfterPublish = false },
|
restore: func() { env.Config.Pipeline.Workspace.CleanupAfterPublish = false },
|
||||||
},
|
},
|
||||||
{
|
|
||||||
name: "spool root",
|
|
||||||
mutate: func() { env.Config.Pipeline.Spool.Root += "-changed" },
|
|
||||||
restore: func() {
|
|
||||||
env.Config.Pipeline.Spool.Root = strings.TrimSuffix(env.Config.Pipeline.Spool.Root, "-changed")
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
name: "workspace root",
|
name: "workspace root",
|
||||||
mutate: func() { env.Config.Pipeline.Workspace.Root += "-changed" },
|
mutate: func() { env.Config.Pipeline.Workspace.Root += "-changed" },
|
||||||
|
|||||||
@@ -197,13 +197,13 @@ func (prepareStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S
|
|||||||
}
|
}
|
||||||
inputs = append(inputs, partyInputs...)
|
inputs = append(inputs, partyInputs...)
|
||||||
|
|
||||||
var audioCacheStats s3AudioMaterializationStats
|
var audioStats s3AudioMaterializationStats
|
||||||
if useS3Audio {
|
if useS3Audio {
|
||||||
stats, err := materializeS3AudioInputs(ctx, env, m, sessionID, &inputs)
|
stats, err := materializeS3AudioInputs(ctx, env, m, sessionID, &inputs)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("prepare: materialize s3 audio: %w", err)
|
return nil, fmt.Errorf("prepare: materialize s3 audio: %w", err)
|
||||||
}
|
}
|
||||||
audioCacheStats = stats
|
audioStats = stats
|
||||||
} else {
|
} else {
|
||||||
if err := materializeLocalAudioInputs(env, paths, resolvedLocalAudio, registerInput); err != nil {
|
if err := materializeLocalAudioInputs(env, paths, resolvedLocalAudio, registerInput); err != nil {
|
||||||
return nil, fmt.Errorf("prepare: %w", err)
|
return nil, fmt.Errorf("prepare: %w", err)
|
||||||
@@ -242,9 +242,8 @@ func (prepareStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S
|
|||||||
"audio_files_resolved": countAudioInputs(inputs),
|
"audio_files_resolved": countAudioInputs(inputs),
|
||||||
}
|
}
|
||||||
if useS3Audio {
|
if useS3Audio {
|
||||||
metadata["audio_cache_hits"] = audioCacheStats.CacheHits
|
metadata["audio_reused"] = audioStats.Reused
|
||||||
metadata["audio_cache_misses"] = audioCacheStats.CacheMisses
|
metadata["audio_s3_downloads"] = audioStats.Downloads
|
||||||
metadata["audio_s3_downloads"] = audioCacheStats.Downloads
|
|
||||||
}
|
}
|
||||||
if len(previousRequirements) > 0 {
|
if len(previousRequirements) > 0 {
|
||||||
metadata["previous_requirements_count"] = len(previousRequirements)
|
metadata["previous_requirements_count"] = len(previousRequirements)
|
||||||
@@ -403,9 +402,8 @@ func localAudioDestinations(audioPaths []string) map[string]string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type s3AudioMaterializationStats struct {
|
type s3AudioMaterializationStats struct {
|
||||||
CacheHits int
|
Reused int
|
||||||
CacheMisses int
|
Downloads int
|
||||||
Downloads int
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func materializeS3AudioInputs(ctx context.Context, env *Env, m *manifest.Manifest, sessionID string, inputs *[]manifest.InputRecord) (s3AudioMaterializationStats, error) {
|
func materializeS3AudioInputs(ctx context.Context, env *Env, m *manifest.Manifest, sessionID string, inputs *[]manifest.InputRecord) (s3AudioMaterializationStats, error) {
|
||||||
@@ -430,58 +428,37 @@ func materializeS3AudioInputs(ctx context.Context, env *Env, m *manifest.Manifes
|
|||||||
return s3AudioMaterializationStats{}, err
|
return s3AudioMaterializationStats{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
spoolAudioDir := strings.TrimSpace(m.LocalSpoolDir)
|
workAudioDir := sessionPathsForEnv(env, sessionID).AudioDir
|
||||||
if spoolAudioDir == "" {
|
|
||||||
spoolAudioDir = artifacts.SessionSpoolAudioDir(env.Config.Pipeline.Spool.Root, campaign, sessionID, runID)
|
|
||||||
}
|
|
||||||
workAudioDir := filepath.Join(pathsWorkDirForManifest(env, m, sessionID), "audio")
|
|
||||||
|
|
||||||
if err := fileops.EnsureWorkspaceDirectory(spoolAudioDir); err != nil {
|
|
||||||
return s3AudioMaterializationStats{}, fmt.Errorf("create spool audio directory %q: %w", spoolAudioDir, err)
|
|
||||||
}
|
|
||||||
if err := fileops.EnsureWorkspaceDirectory(workAudioDir); err != nil {
|
if err := fileops.EnsureWorkspaceDirectory(workAudioDir); err != nil {
|
||||||
return s3AudioMaterializationStats{}, fmt.Errorf("create work audio directory %q: %w", workAudioDir, err)
|
return s3AudioMaterializationStats{}, fmt.Errorf("create work audio directory %q: %w", workAudioDir, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
stats := s3AudioMaterializationStats{}
|
stats := s3AudioMaterializationStats{}
|
||||||
cacheEnabled := env.Config.Pipeline.Cache.S3Audio == nil || *env.Config.Pipeline.Cache.S3Audio
|
|
||||||
for _, obj := range audioObjects {
|
for _, obj := range audioObjects {
|
||||||
base := path.Base(obj.Key)
|
workPath := filepath.Join(workAudioDir, path.Base(obj.Key))
|
||||||
spoolPath := filepath.Join(spoolAudioDir, base)
|
var prior *manifest.InputRecord
|
||||||
workPath := filepath.Join(workAudioDir, base)
|
for i := range m.Inputs {
|
||||||
|
if m.Inputs[i].Kind == "audio" && filepath.Clean(m.Inputs[i].Path) == filepath.Clean(workPath) {
|
||||||
|
prior = &m.Inputs[i]
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
result, err := audio.MaterializeS3Audio(ctx, audio.S3MaterializeRequest{
|
result, err := audio.MaterializeS3Audio(ctx, audio.S3MaterializeRequest{
|
||||||
Reporter: env.Reporter,
|
Reporter: env.Reporter, Store: env.ObjectStore, Object: obj,
|
||||||
Store: env.ObjectStore,
|
Bucket: strings.TrimSpace(env.Config.Pipeline.Storage.S3.Bucket), DestPath: workPath, Prior: prior,
|
||||||
Object: obj,
|
|
||||||
Bucket: strings.TrimSpace(env.Config.Pipeline.Storage.S3.Bucket),
|
|
||||||
CacheRoot: strings.TrimSpace(env.Config.Pipeline.Cache.Root),
|
|
||||||
CacheEnabled: cacheEnabled,
|
|
||||||
SpoolPath: spoolPath,
|
|
||||||
DestPath: workPath,
|
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return s3AudioMaterializationStats{}, err
|
return s3AudioMaterializationStats{}, err
|
||||||
}
|
}
|
||||||
if result.CacheHit {
|
if result.Reused {
|
||||||
stats.CacheHits++
|
stats.Reused++
|
||||||
} else {
|
|
||||||
stats.CacheMisses++
|
|
||||||
}
|
}
|
||||||
if result.Downloaded {
|
if result.Downloaded {
|
||||||
stats.Downloads++
|
stats.Downloads++
|
||||||
}
|
}
|
||||||
|
|
||||||
*inputs = append(*inputs, manifest.InputRecord{
|
*inputs = append(*inputs, manifest.InputRecord{
|
||||||
Kind: "audio",
|
Kind: "audio", Path: workPath, Checksum: result.Checksum, Source: "s3",
|
||||||
Path: workPath,
|
S3Bucket: strings.TrimSpace(env.Config.Pipeline.Storage.S3.Bucket), S3Key: obj.Key,
|
||||||
Checksum: result.Checksum,
|
S3Size: obj.Size, S3ETag: obj.ETag,
|
||||||
Source: "s3",
|
|
||||||
S3Bucket: strings.TrimSpace(env.Config.Pipeline.Storage.S3.Bucket),
|
|
||||||
S3Key: obj.Key,
|
|
||||||
S3Size: obj.Size,
|
|
||||||
S3ETag: obj.ETag,
|
|
||||||
SpoolPath: result.SpoolPath,
|
|
||||||
CachePath: result.CachePath,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -573,27 +550,6 @@ func clearManagedPreviousState(paths artifacts.SessionPaths) error {
|
|||||||
return fileops.EnsureWorkspaceDirectory(previousDir)
|
return fileops.EnsureWorkspaceDirectory(previousDir)
|
||||||
}
|
}
|
||||||
|
|
||||||
func pathsWorkDirForManifest(env *Env, m *manifest.Manifest, sessionID string) string {
|
|
||||||
if env == nil || env.Config == nil || env.Config.Pipeline == nil || env.Config.Session == nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
campaign := strings.TrimSpace(env.Config.Session.Campaign)
|
|
||||||
if campaign == "" {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
if m != nil && strings.TrimSpace(m.LocalWorkDir) != "" {
|
|
||||||
return strings.TrimSpace(m.LocalWorkDir)
|
|
||||||
}
|
|
||||||
runID := ""
|
|
||||||
if m != nil {
|
|
||||||
runID = strings.TrimSpace(m.RunID)
|
|
||||||
}
|
|
||||||
if runID != "" {
|
|
||||||
return artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, campaign, sessionID, runID)
|
|
||||||
}
|
|
||||||
return artifacts.SessionWorkDirForCampaign(env.Config.Pipeline.Workspace.Root, campaign, sessionID)
|
|
||||||
}
|
|
||||||
|
|
||||||
func resolvePath(baseDir, p string) (string, error) {
|
func resolvePath(baseDir, p string) (string, error) {
|
||||||
trimmed := strings.TrimSpace(p)
|
trimmed := strings.TrimSpace(p)
|
||||||
if trimmed == "" {
|
if trimmed == "" {
|
||||||
|
|||||||
@@ -318,11 +318,9 @@ func TestPrepareResumeValidatesCurrentS3ObjectIdentity(t *testing.T) {
|
|||||||
env.Config.Session.Campaign = "forsaken"
|
env.Config.Session.Campaign = "forsaken"
|
||||||
env.Config.Session.Inputs.AudioDir = ""
|
env.Config.Session.Inputs.AudioDir = ""
|
||||||
env.Config.Session.Inputs.AudioS3 = &config.SessionAudioS3Input{Prefix: "audio/"}
|
env.Config.Session.Inputs.AudioS3 = &config.SessionAudioS3Input{Prefix: "audio/"}
|
||||||
env.Config.Pipeline.Spool = config.SpoolConfig{Root: filepath.Join(t.TempDir(), "spool")}
|
|
||||||
env.Config.Pipeline.Storage.S3 = &config.StorageS3Config{Bucket: "archive", RootPrefix: "dnd"}
|
env.Config.Pipeline.Storage.S3 = &config.StorageS3Config{Bucket: "archive", RootPrefix: "dnd"}
|
||||||
m.RunID = "20260515T031522Z-a1b2c3d4"
|
m.RunID = "20260515T031522Z-a1b2c3d4"
|
||||||
m.LocalWorkDir = artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, "forsaken", m.SessionID, m.RunID)
|
m.LocalWorkDir = artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, "forsaken", m.SessionID, m.RunID)
|
||||||
m.LocalSpoolDir = artifacts.SessionSpoolAudioDir(env.Config.Pipeline.Spool.Root, "forsaken", m.SessionID, m.RunID)
|
|
||||||
key := "dnd/campaigns/forsaken/sessions/2026-05-03/audio/alice.flac"
|
key := "dnd/campaigns/forsaken/sessions/2026-05-03/audio/alice.flac"
|
||||||
fake := &storage.FakeBackend{}
|
fake := &storage.FakeBackend{}
|
||||||
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("alice")})
|
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("alice")})
|
||||||
|
|||||||
@@ -242,7 +242,7 @@ func TestPrepareStageRecordsLocalSessionProvenance(t *testing.T) {
|
|||||||
if sessionInput.Source != "session_config" {
|
if sessionInput.Source != "session_config" {
|
||||||
t.Fatalf("session source = %q, want session_config", sessionInput.Source)
|
t.Fatalf("session source = %q, want session_config", sessionInput.Source)
|
||||||
}
|
}
|
||||||
if sessionInput.S3Bucket != "" || sessionInput.S3Key != "" || sessionInput.SpoolPath != "" {
|
if sessionInput.S3Bucket != "" || sessionInput.S3Key != "" {
|
||||||
t.Fatalf("local session input has unexpected remote provenance: %#v", sessionInput)
|
t.Fatalf("local session input has unexpected remote provenance: %#v", sessionInput)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -262,11 +262,9 @@ func TestPrepareStageRecordsRemoteSessionProvenance(t *testing.T) {
|
|||||||
S3Size: 58,
|
S3Size: 58,
|
||||||
S3ETag: "session-etag",
|
S3ETag: "session-etag",
|
||||||
}
|
}
|
||||||
env.Config.Pipeline.Spool = config.SpoolConfig{Root: filepath.Join(t.TempDir(), "spool")}
|
|
||||||
env.Config.Pipeline.Storage.S3 = &config.StorageS3Config{Bucket: "my-dnd-archive", RootPrefix: "dnd"}
|
env.Config.Pipeline.Storage.S3 = &config.StorageS3Config{Bucket: "my-dnd-archive", RootPrefix: "dnd"}
|
||||||
m.RunID = "20260515T031522Z-a1b2c3d4"
|
m.RunID = "20260515T031522Z-a1b2c3d4"
|
||||||
m.LocalWorkDir = artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, "sample-campaign", m.SessionID, m.RunID)
|
m.LocalWorkDir = artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, "sample-campaign", m.SessionID, m.RunID)
|
||||||
m.LocalSpoolDir = artifacts.SessionSpoolAudioDir(env.Config.Pipeline.Spool.Root, "sample-campaign", m.SessionID, m.RunID)
|
|
||||||
fake := &storage.FakeBackend{}
|
fake := &storage.FakeBackend{}
|
||||||
fake.SeedObject(storage.FakeObject{Key: "dnd/campaigns/sample-campaign/sessions/2026-05-03/audio/alice.flac", Data: []byte("alice")})
|
fake.SeedObject(storage.FakeObject{Key: "dnd/campaigns/sample-campaign/sessions/2026-05-03/audio/alice.flac", Data: []byte("alice")})
|
||||||
env.ObjectStore = fake
|
env.ObjectStore = fake
|
||||||
@@ -281,7 +279,7 @@ func TestPrepareStageRecordsRemoteSessionProvenance(t *testing.T) {
|
|||||||
if sessionInput.S3Bucket != "my-dnd-archive" || sessionInput.S3Key != "dnd/campaigns/sample-campaign/sessions/2026-05-03/session.yml" {
|
if sessionInput.S3Bucket != "my-dnd-archive" || sessionInput.S3Key != "dnd/campaigns/sample-campaign/sessions/2026-05-03/session.yml" {
|
||||||
t.Fatalf("remote session input missing bucket/key: %#v", sessionInput)
|
t.Fatalf("remote session input missing bucket/key: %#v", sessionInput)
|
||||||
}
|
}
|
||||||
if sessionInput.S3Size != 58 || sessionInput.S3ETag != "session-etag" || sessionInput.SpoolPath != "" {
|
if sessionInput.S3Size != 58 || sessionInput.S3ETag != "session-etag" {
|
||||||
t.Fatalf("remote session input missing metadata: %#v", sessionInput)
|
t.Fatalf("remote session input missing metadata: %#v", sessionInput)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -292,11 +290,9 @@ func TestPrepareStageS3AudioDownloadAndMaterialization(t *testing.T) {
|
|||||||
env.Config.Session.Inputs.AudioDir = ""
|
env.Config.Session.Inputs.AudioDir = ""
|
||||||
env.Config.Session.Inputs.AudioFiles = nil
|
env.Config.Session.Inputs.AudioFiles = nil
|
||||||
env.Config.Session.Inputs.AudioS3 = &config.SessionAudioS3Input{Prefix: "audio/"}
|
env.Config.Session.Inputs.AudioS3 = &config.SessionAudioS3Input{Prefix: "audio/"}
|
||||||
env.Config.Pipeline.Spool = config.SpoolConfig{Root: filepath.Join(t.TempDir(), "spool")}
|
|
||||||
env.Config.Pipeline.Storage.S3 = &config.StorageS3Config{Bucket: "my-dnd-archive", RootPrefix: "dnd"}
|
env.Config.Pipeline.Storage.S3 = &config.StorageS3Config{Bucket: "my-dnd-archive", RootPrefix: "dnd"}
|
||||||
m.RunID = "20260515T031522Z-a1b2c3d4"
|
m.RunID = "20260515T031522Z-a1b2c3d4"
|
||||||
m.LocalWorkDir = artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, "forsaken", m.SessionID, m.RunID)
|
m.LocalWorkDir = artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, "forsaken", m.SessionID, m.RunID)
|
||||||
m.LocalSpoolDir = artifacts.SessionSpoolAudioDir(env.Config.Pipeline.Spool.Root, "forsaken", m.SessionID, m.RunID)
|
|
||||||
|
|
||||||
fake := &storage.FakeBackend{}
|
fake := &storage.FakeBackend{}
|
||||||
fake.SeedObject(storage.FakeObject{Key: "dnd/campaigns/forsaken/sessions/2026-05-03/audio/alice.flac", Data: []byte("alice")})
|
fake.SeedObject(storage.FakeObject{Key: "dnd/campaigns/forsaken/sessions/2026-05-03/audio/alice.flac", Data: []byte("alice")})
|
||||||
@@ -312,20 +308,15 @@ func TestPrepareStageS3AudioDownloadAndMaterialization(t *testing.T) {
|
|||||||
t.Fatalf("result metadata = %#v, want audio_files_resolved=2", result)
|
t.Fatalf("result metadata = %#v, want audio_files_resolved=2", result)
|
||||||
}
|
}
|
||||||
|
|
||||||
aliceWork := filepath.Join(m.LocalWorkDir, "audio", "alice.flac")
|
aliceWork := filepath.Join(sessionPathsForEnv(env, m.SessionID).AudioDir, "alice.flac")
|
||||||
bobWork := filepath.Join(m.LocalWorkDir, "audio", "bob.FLAC")
|
bobWork := filepath.Join(sessionPathsForEnv(env, m.SessionID).AudioDir, "bob.FLAC")
|
||||||
aliceSpool := filepath.Join(m.LocalSpoolDir, "alice.flac")
|
for _, p := range []string{aliceWork, bobWork} {
|
||||||
bobSpool := filepath.Join(m.LocalSpoolDir, "bob.FLAC")
|
|
||||||
for _, p := range []string{aliceWork, bobWork, aliceSpool, bobSpool} {
|
|
||||||
if _, err := os.Stat(p); err != nil {
|
if _, err := os.Stat(p); err != nil {
|
||||||
t.Fatalf("expected file %q: %v", p, err)
|
t.Fatalf("expected file %q: %v", p, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if got := result.Metadata["audio_cache_hits"]; got != 0 {
|
if got := result.Metadata["audio_reused"]; got != 0 {
|
||||||
t.Fatalf("audio_cache_hits = %#v, want 0", got)
|
t.Fatalf("audio_reused = %#v, want 0", got)
|
||||||
}
|
|
||||||
if got := result.Metadata["audio_cache_misses"]; got != 2 {
|
|
||||||
t.Fatalf("audio_cache_misses = %#v, want 2", got)
|
|
||||||
}
|
}
|
||||||
if got := result.Metadata["audio_s3_downloads"]; got != 2 {
|
if got := result.Metadata["audio_s3_downloads"]; got != 2 {
|
||||||
t.Fatalf("audio_s3_downloads = %#v, want 2", got)
|
t.Fatalf("audio_s3_downloads = %#v, want 2", got)
|
||||||
@@ -343,73 +334,47 @@ func TestPrepareStageS3AudioDownloadAndMaterialization(t *testing.T) {
|
|||||||
if in.S3Bucket != "my-dnd-archive" {
|
if in.S3Bucket != "my-dnd-archive" {
|
||||||
t.Fatalf("audio input bucket = %q", in.S3Bucket)
|
t.Fatalf("audio input bucket = %q", in.S3Bucket)
|
||||||
}
|
}
|
||||||
if in.S3Key == "" || in.SpoolPath == "" || in.CachePath == "" || in.Checksum == "" {
|
if in.S3Key == "" || in.Checksum == "" {
|
||||||
t.Fatalf("audio input missing provenance: %#v", in)
|
t.Fatalf("audio input missing provenance: %#v", in)
|
||||||
}
|
}
|
||||||
if _, err := os.Stat(in.CachePath); err != nil {
|
|
||||||
t.Fatalf("expected cache path %q: %v", in.CachePath, err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if audioInputs != 2 {
|
if audioInputs != 2 {
|
||||||
t.Fatalf("audio input count = %d, want 2", audioInputs)
|
t.Fatalf("audio input count = %d, want 2", audioInputs)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestPrepareStageS3AudioUsesCacheOnRerun(t *testing.T) {
|
func TestPrepareStageS3AudioReusesPreparedCopy(t *testing.T) {
|
||||||
env, m := setupPrepareEnv(t)
|
env, m := setupPrepareEnv(t)
|
||||||
env.Config.Session.Campaign = "forsaken"
|
env.Config.Session.Campaign = "forsaken"
|
||||||
env.Config.Session.Inputs.AudioDir = ""
|
env.Config.Session.Inputs.AudioDir = ""
|
||||||
env.Config.Session.Inputs.AudioFiles = nil
|
env.Config.Session.Inputs.AudioFiles = nil
|
||||||
env.Config.Session.Inputs.AudioS3 = &config.SessionAudioS3Input{Prefix: "audio/"}
|
env.Config.Session.Inputs.AudioS3 = &config.SessionAudioS3Input{Prefix: "audio/"}
|
||||||
env.Config.Pipeline.Spool = config.SpoolConfig{Root: filepath.Join(t.TempDir(), "spool")}
|
|
||||||
env.Config.Pipeline.Storage.S3 = &config.StorageS3Config{Bucket: "my-dnd-archive", RootPrefix: "dnd"}
|
env.Config.Pipeline.Storage.S3 = &config.StorageS3Config{Bucket: "my-dnd-archive", RootPrefix: "dnd"}
|
||||||
m.RunID = "20260515T031522Z-a1b2c3d4"
|
m.RunID = "20260515T031522Z-a1b2c3d4"
|
||||||
m.LocalWorkDir = artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, "forsaken", m.SessionID, m.RunID)
|
|
||||||
m.LocalSpoolDir = artifacts.SessionSpoolAudioDir(env.Config.Pipeline.Spool.Root, "forsaken", m.SessionID, m.RunID)
|
|
||||||
|
|
||||||
fake := &storage.FakeBackend{}
|
fake := &storage.FakeBackend{}
|
||||||
fake.SeedObject(storage.FakeObject{Key: "dnd/campaigns/forsaken/sessions/2026-05-03/audio/alice.flac", Data: []byte("alice")})
|
fake.SeedObject(storage.FakeObject{Key: "dnd/campaigns/forsaken/sessions/2026-05-03/audio/alice.flac", Data: []byte("alice"), ETag: "generation"})
|
||||||
env.ObjectStore = fake
|
env.ObjectStore = fake
|
||||||
if _, err := (prepareStage{}).Run(context.Background(), env, m); err != nil {
|
if _, err := (prepareStage{}).Run(context.Background(), env, m); err != nil {
|
||||||
t.Fatalf("first prepare.Run() error = %v", err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if len(fake.Downloads) != 1 {
|
m.RunID = "20260515T041522Z-a1b2c3d4"
|
||||||
t.Fatalf("downloads = %d, want 1", len(fake.Downloads))
|
result, err := (prepareStage{}).Run(context.Background(), env, m)
|
||||||
}
|
|
||||||
|
|
||||||
if err := os.RemoveAll(filepath.Join(m.LocalWorkDir, "audio")); err != nil {
|
|
||||||
t.Fatalf("remove work audio: %v", err)
|
|
||||||
}
|
|
||||||
if err := os.RemoveAll(m.LocalSpoolDir); err != nil {
|
|
||||||
t.Fatalf("remove spool audio: %v", err)
|
|
||||||
}
|
|
||||||
fake.DownloadErr = os.ErrPermission
|
|
||||||
|
|
||||||
m2 := manifest.New("2026-05-03", time.Now().UTC())
|
|
||||||
m2.RunID = "20260515T041522Z-a1b2c3d4"
|
|
||||||
m2.LocalWorkDir = artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, "forsaken", m2.SessionID, m2.RunID)
|
|
||||||
m2.LocalSpoolDir = artifacts.SessionSpoolAudioDir(env.Config.Pipeline.Spool.Root, "forsaken", m2.SessionID, m2.RunID)
|
|
||||||
result, err := (prepareStage{}).Run(context.Background(), env, m2)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("cached prepare.Run() error = %v", err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if len(fake.Downloads) != 1 {
|
if result.Metadata["audio_reused"] != 1 || len(fake.Downloads) != 1 {
|
||||||
t.Fatalf("downloads = %d, want cached rerun to avoid new download", len(fake.Downloads))
|
t.Fatalf("result=%#v downloads=%d", result.Metadata, len(fake.Downloads))
|
||||||
}
|
}
|
||||||
if got := result.Metadata["audio_cache_hits"]; got != 1 {
|
dest := filepath.Join(sessionPathsForEnv(env, m.SessionID).AudioDir, "alice.flac")
|
||||||
t.Fatalf("audio_cache_hits = %#v, want 1", got)
|
mustReadFileEquals(t, dest, "alice")
|
||||||
|
if err := os.Remove(dest); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if got := result.Metadata["audio_s3_downloads"]; got != 0 {
|
result, err = (prepareStage{}).Run(context.Background(), env, m)
|
||||||
t.Fatalf("audio_s3_downloads = %#v, want 0", got)
|
if err != nil || result.Metadata["audio_s3_downloads"] != 1 || len(fake.Downloads) != 2 {
|
||||||
|
t.Fatalf("result=%#v downloads=%d error=%v", result, len(fake.Downloads), err)
|
||||||
}
|
}
|
||||||
audioInput := findManifestInput(t, m2.Inputs, "audio")
|
|
||||||
if audioInput.CachePath == "" {
|
|
||||||
t.Fatalf("audio input missing cache path: %#v", audioInput)
|
|
||||||
}
|
|
||||||
if audioInput.SpoolPath != "" {
|
|
||||||
t.Fatalf("audio input spool path = %q, want empty on cache hit", audioInput.SpoolPath)
|
|
||||||
}
|
|
||||||
mustReadFileEquals(t, filepath.Join(m2.LocalWorkDir, "audio", "alice.flac"), "alice")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestPrepareStageS3AudioFailures(t *testing.T) {
|
func TestPrepareStageS3AudioFailures(t *testing.T) {
|
||||||
@@ -457,11 +422,9 @@ func TestPrepareStageS3AudioFailures(t *testing.T) {
|
|||||||
env.Config.Session.Inputs.AudioDir = ""
|
env.Config.Session.Inputs.AudioDir = ""
|
||||||
env.Config.Session.Inputs.AudioFiles = nil
|
env.Config.Session.Inputs.AudioFiles = nil
|
||||||
env.Config.Session.Inputs.AudioS3 = &config.SessionAudioS3Input{Prefix: "audio/"}
|
env.Config.Session.Inputs.AudioS3 = &config.SessionAudioS3Input{Prefix: "audio/"}
|
||||||
env.Config.Pipeline.Spool = config.SpoolConfig{Root: filepath.Join(t.TempDir(), "spool")}
|
|
||||||
env.Config.Pipeline.Storage.S3 = &config.StorageS3Config{Bucket: "my-dnd-archive", RootPrefix: "dnd"}
|
env.Config.Pipeline.Storage.S3 = &config.StorageS3Config{Bucket: "my-dnd-archive", RootPrefix: "dnd"}
|
||||||
m.RunID = "20260515T031522Z-a1b2c3d4"
|
m.RunID = "20260515T031522Z-a1b2c3d4"
|
||||||
m.LocalWorkDir = artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, "forsaken", m.SessionID, m.RunID)
|
m.LocalWorkDir = artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, "forsaken", m.SessionID, m.RunID)
|
||||||
m.LocalSpoolDir = artifacts.SessionSpoolAudioDir(env.Config.Pipeline.Spool.Root, "forsaken", m.SessionID, m.RunID)
|
|
||||||
|
|
||||||
fake := &storage.FakeBackend{}
|
fake := &storage.FakeBackend{}
|
||||||
tt.setup(env, m, fake)
|
tt.setup(env, m, fake)
|
||||||
@@ -725,7 +688,6 @@ inputs:
|
|||||||
cfg := &config.Config{
|
cfg := &config.Config{
|
||||||
Pipeline: &config.PipelineConfig{
|
Pipeline: &config.PipelineConfig{
|
||||||
Workspace: config.WorkspaceConfig{Root: workspace},
|
Workspace: config.WorkspaceConfig{Root: workspace},
|
||||||
Cache: config.CacheConfig{Root: filepath.Join(t.TempDir(), "cache"), S3Audio: boolPtr(true)},
|
|
||||||
},
|
},
|
||||||
Campaign: &config.CampaignConfig{CampaignID: "sample-campaign", Inputs: config.CampaignInputsConfig{SpeakersFile: "./speakers.yml", PartyFile: "./party.yml"}},
|
Campaign: &config.CampaignConfig{CampaignID: "sample-campaign", Inputs: config.CampaignInputsConfig{SpeakersFile: "./speakers.yml", PartyFile: "./party.yml"}},
|
||||||
SessionPath: sessionPath,
|
SessionPath: sessionPath,
|
||||||
|
|||||||
@@ -29,10 +29,8 @@ func TestPrepareSemanticConfigSensitivity(t *testing.T) {
|
|||||||
name string
|
name string
|
||||||
mutate func(*Env)
|
mutate func(*Env)
|
||||||
}{
|
}{
|
||||||
{name: "workspace and spool", mutate: func(env *Env) {
|
{name: "workspace", mutate: func(env *Env) {
|
||||||
env.Config.Pipeline.Workspace.Root = "/different/work"
|
env.Config.Pipeline.Workspace.Root = "/different/work"
|
||||||
env.Config.Pipeline.Spool.Root = "/different/spool"
|
|
||||||
env.Config.Pipeline.Cache.Root = "/different/cache"
|
|
||||||
}},
|
}},
|
||||||
{name: "stable input owner", mutate: func(env *Env) {
|
{name: "stable input owner", mutate: func(env *Env) {
|
||||||
env.Config.StableInputs.PartyFile.Source = "party_file"
|
env.Config.StableInputs.PartyFile.Source = "party_file"
|
||||||
@@ -105,8 +103,6 @@ func initialSemanticEnv() *Env {
|
|||||||
return &Env{Config: &config.Config{
|
return &Env{Config: &config.Config{
|
||||||
Pipeline: &config.PipelineConfig{
|
Pipeline: &config.PipelineConfig{
|
||||||
Workspace: config.WorkspaceConfig{Root: "/work"},
|
Workspace: config.WorkspaceConfig{Root: "/work"},
|
||||||
Spool: config.SpoolConfig{Root: "/spool"},
|
|
||||||
Cache: config.CacheConfig{Root: "/cache"},
|
|
||||||
WhisperX: config.WhisperXConfig{
|
WhisperX: config.WhisperXConfig{
|
||||||
TranscribeURL: "https://whisper.example/transcribe", Language: "en",
|
TranscribeURL: "https://whisper.example/transcribe", Language: "en",
|
||||||
Timeout: "10m", Retries: intPointer(3), RetryDelay: "1s", Concurrency: intPointer(2),
|
Timeout: "10m", Retries: intPointer(3), RetryDelay: "1s", Concurrency: intPointer(2),
|
||||||
|
|||||||
Reference in New Issue
Block a user