Add native session initialization and remote lock commands
This commit is contained in:
@@ -18,8 +18,22 @@ func newApplication(deps commandDependencies, executor pipelineExecutor) (*comma
|
||||
commandkit.Identity{Name: "narratio", Version: buildinfo.Version},
|
||||
configurationCommand(deps),
|
||||
executionCommand("run", "Execute a session pipeline.", false, deps, executor),
|
||||
commandkit.Group("artifacts", "Inspect and regenerate configured artifacts.", artifactCatalogCommand(deps), executionCommand("regenerate", "Rebuild extraction and analysis artifacts.", true, deps, executor)),
|
||||
commandkit.Group("session", "Manage and inspect sessions.", sessionPlanCommand(deps), sessionValidationCommand(deps), sessionStateCommand("status", true, deps), sessionStateCommand("artifacts", false, deps)),
|
||||
commandkit.Group("artifacts", "Inspect and regenerate configured artifacts.",
|
||||
artifactCatalogCommand(deps),
|
||||
executionCommand("regenerate", "Rebuild extraction and analysis artifacts.", true, deps, executor),
|
||||
),
|
||||
commandkit.Group("session", "Manage and inspect sessions.",
|
||||
sessionPlanCommand(deps),
|
||||
sessionInitializationCommand(deps),
|
||||
sessionValidationCommand(deps),
|
||||
sessionStateCommand("status", true, deps),
|
||||
sessionStateCommand("artifacts", false, deps),
|
||||
commandkit.Group("locks", "Manage remote publication locks.",
|
||||
lockCommand("list", deps),
|
||||
lockCommand("add", deps),
|
||||
lockCommand("remove", deps),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
155
internal/app/lock_command.go
Normal file
155
internal/app/lock_command.go
Normal file
@@ -0,0 +1,155 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
||||
"go.maximumdirect.net/commandkit"
|
||||
)
|
||||
|
||||
type lockCommandInput struct {
|
||||
Selection configurationSelection
|
||||
PreviousSession commandkit.Supplied[string]
|
||||
Source commandkit.Supplied[string]
|
||||
Reason commandkit.Supplied[string]
|
||||
Force commandkit.Supplied[bool]
|
||||
}
|
||||
type lockCommandReport struct {
|
||||
Campaign string `json:"campaign"`
|
||||
SessionID string `json:"session_id"`
|
||||
Operation string `json:"operation"`
|
||||
Source string `json:"source,omitempty"`
|
||||
Result string `json:"result"`
|
||||
Complete bool `json:"complete"`
|
||||
Locks []lockListEntry `json:"locks"`
|
||||
}
|
||||
type lockListEntry struct {
|
||||
Source string `json:"source"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ConfiguredForPublish bool `json:"configured_for_publish"`
|
||||
}
|
||||
|
||||
func lockCommand(operation string, deps commandDependencies) commandkit.Command {
|
||||
common := newConfigurationFlags(func(input **lockCommandInput) *configurationSelection { return &(*input).Selection })
|
||||
flags := []commandkit.Flag[*lockCommandInput]{common.Config, common.Overlay, common.Campaign, common.CampaignFile, common.SessionFile, common.PartyFile, common.SecretsDir,
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "previous-session-id", Usage: "Assert the previous session identity."}, nil, stringValue, func(input **lockCommandInput, value commandkit.Supplied[string]) { (*input).PreviousSession = value }),
|
||||
}
|
||||
if operation == "add" {
|
||||
flags = append(flags,
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "reason", Usage: "Reason for the publish lock."}, nil, stringValue, func(input **lockCommandInput, value commandkit.Supplied[string]) { (*input).Reason = value }),
|
||||
commandkit.BoolFlag(commandkit.FlagMeta{Name: "force", Usage: "Replace an existing lock conditionally."}, false, func(input **lockCommandInput, value commandkit.Supplied[bool]) { (*input).Force = value }),
|
||||
)
|
||||
}
|
||||
arguments := []commandkit.Argument[*lockCommandInput]{commandkit.ValueArgument(commandkit.ArgumentMeta{Name: "SESSION", Usage: "Session identity."}, true, stringValue, func(input **lockCommandInput, value commandkit.Supplied[string]) { (*input).Selection.Session = value })}
|
||||
if operation != "list" {
|
||||
arguments = append(arguments, commandkit.ValueArgument(commandkit.ArgumentMeta{Name: "SOURCE", Usage: "Canonical publish source identity."}, true, stringValue, func(input **lockCommandInput, value commandkit.Supplied[string]) { (*input).Source = value }))
|
||||
}
|
||||
return commandkit.NewCommand(commandkit.CommandSpec[*lockCommandInput]{Name: operation, Summary: "Manage independent remote publication locks.", NewInput: func() *lockCommandInput { return &lockCommandInput{} }, Flags: flags, Arguments: arguments,
|
||||
CheckInput: func(input *lockCommandInput) error {
|
||||
if err := checkConfigurationSelection(input.Selection); err != nil {
|
||||
return err
|
||||
}
|
||||
if operation != "list" {
|
||||
_, err := artifacts.NewRemoteLock(input.Source.Value, strings.TrimSpace(input.Reason.Value), nowUTC())
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
},
|
||||
Run: func(invocation commandkit.Invocation, input *lockCommandInput) commandkit.Outcome {
|
||||
report, err := executeLockCommand(invocation.Context, input, operation, deps)
|
||||
if report != nil {
|
||||
err = errors.Join(err, invocation.Reporter().Report(commandkit.Report{Value: report}))
|
||||
}
|
||||
return operationOutcome(err)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func executeLockCommand(ctx context.Context, input *lockCommandInput, operation string, deps commandDependencies) (report *lockCommandReport, err error) {
|
||||
deps = normalizeCommandDependencies(deps)
|
||||
deps.secretsBootstrap = &secretsBootstrap{}
|
||||
acquired := newConfigurationAcquisition(input.Selection, deps)
|
||||
acquired.previousSessionID = input.PreviousSession.Value
|
||||
defer func() { err = errors.Join(err, acquired.Close()) }()
|
||||
report = &lockCommandReport{SessionID: input.Selection.Session.Value, Operation: operation, Source: input.Source.Value, Result: "not_applied"}
|
||||
cfg, err := acquired.Domain(ctx)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
report.Campaign = config.CampaignID(cfg.Campaign)
|
||||
if err := config.Validate(cfg); err != nil {
|
||||
return report, err
|
||||
}
|
||||
store, err := newCommandObjectStoreWithDependencies(ctx, cfg, nil, deps)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
prefix, err := artifacts.ResolvePublishSessionPrefix(cfg, nil)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
if operation == "list" {
|
||||
locks, err := artifacts.ListRemoteLocks(ctx, store, prefix)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
selected := map[string]bool{}
|
||||
for _, rule := range cfg.PublicationOutputs() {
|
||||
selected[rule.Source] = true
|
||||
}
|
||||
report.Locks = make([]lockListEntry, 0, len(locks))
|
||||
for _, lock := range locks {
|
||||
report.Locks = append(report.Locks, lockListEntry{Source: lock.Source, Reason: lock.Reason, CreatedAt: lock.CreatedAt, ConfiguredForPublish: selected[lock.Source]})
|
||||
}
|
||||
report.Complete = true
|
||||
report.Result = "listed"
|
||||
return report, nil
|
||||
}
|
||||
result, err := applyRemoteLockMutation(ctx, store, prefix, operation, input.Source.Value, input.Reason.Value, input.Force.Value)
|
||||
report.Result = result
|
||||
report.Complete = err == nil
|
||||
return report, err
|
||||
}
|
||||
|
||||
func applyRemoteLockMutation(ctx context.Context, store storage.ObjectStore, prefix, operation, source, reason string, force bool) (string, error) {
|
||||
if operation == "remove" {
|
||||
current, err := artifacts.LookupRemoteLock(ctx, store, prefix, source)
|
||||
if err != nil {
|
||||
return "not_applied", err
|
||||
}
|
||||
if err := artifacts.RemoveRemoteLock(ctx, store, prefix, source); err != nil {
|
||||
return "not_applied", err
|
||||
}
|
||||
if !current.Present {
|
||||
return "not_locked", nil
|
||||
}
|
||||
return "unlocked", nil
|
||||
}
|
||||
lock, err := artifacts.NewRemoteLock(source, strings.TrimSpace(reason), nowUTC())
|
||||
if err != nil {
|
||||
return "not_applied", err
|
||||
}
|
||||
if !force {
|
||||
current, err := artifacts.LookupRemoteLock(ctx, store, prefix, source)
|
||||
if err != nil {
|
||||
return "not_applied", err
|
||||
}
|
||||
if current.Present {
|
||||
return "already_locked", fmt.Errorf("remote lock for %q already exists; pass --force to update", source)
|
||||
}
|
||||
}
|
||||
if err := artifacts.AddRemoteLock(ctx, store, prefix, lock, force); err != nil {
|
||||
if errors.Is(err, storage.ErrConditionNotMet) {
|
||||
return "not_applied", fmt.Errorf("remote lock for %q changed concurrently; retry: %w", source, err)
|
||||
}
|
||||
return "not_applied", err
|
||||
}
|
||||
return "locked", nil
|
||||
}
|
||||
99
internal/app/lock_command_test.go
Normal file
99
internal/app/lock_command_test.go
Normal file
@@ -0,0 +1,99 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
||||
"go.maximumdirect.net/commandkit"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func TestLockCommandsPreserveConditionalMutationAndIdempotentRemoval(t *testing.T) {
|
||||
pipeline, campaign, session := writeValidConfigFiles(t, t.TempDir())
|
||||
fake := &storage.FakeBackend{}
|
||||
deps, _ := remoteSessionLoaderDependencies(fake)
|
||||
app, err := newApplication(deps, executePlan)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
invoke := func(operation string, options ...string) (lockCommandReport, commandkit.Outcome) {
|
||||
t.Helper()
|
||||
args := []string{"session", "locks", operation, "2026-05-03"}
|
||||
if operation != "list" {
|
||||
args = append(args, "narratio.transcript.final_trimmed")
|
||||
}
|
||||
args = append(args, "--config", pipeline, "--campaign-file", campaign, "--session-file", session, "--format", "json")
|
||||
args = append(args, options...)
|
||||
var out, diagnostic bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &diagnostic})
|
||||
var report lockCommandReport
|
||||
if err := json.Unmarshal(out.Bytes(), &report); err != nil {
|
||||
t.Fatalf("report error=%v output=%s diagnostics=%s", err, out.String(), diagnostic.String())
|
||||
}
|
||||
return report, outcome
|
||||
}
|
||||
report, outcome := invoke("add", "--reason", "synthetic original reason")
|
||||
if outcome.Status != 0 || !report.Complete || report.Result != "locked" {
|
||||
t.Fatalf("add=%#v outcome=%#v", report, outcome)
|
||||
}
|
||||
report, outcome = invoke("add")
|
||||
if outcome.Status != 1 || report.Complete || report.Result != "already_locked" {
|
||||
t.Fatalf("duplicate add=%#v outcome=%#v", report, outcome)
|
||||
}
|
||||
report, outcome = invoke("add", "--force", "--reason", "synthetic revised reason")
|
||||
if outcome.Status != 0 || report.Result != "locked" {
|
||||
t.Fatalf("forced add=%#v outcome=%#v", report, outcome)
|
||||
}
|
||||
report, outcome = invoke("list")
|
||||
if outcome.Status != 0 || len(report.Locks) != 1 || report.Locks[0].Reason != "synthetic revised reason" || !report.Locks[0].ConfiguredForPublish {
|
||||
t.Fatalf("list=%#v outcome=%#v", report, outcome)
|
||||
}
|
||||
fake.UploadHook = func(storage.FakeUploadCall) error { return storage.ErrConditionNotMet }
|
||||
report, outcome = invoke("add", "--force")
|
||||
if outcome.Status != 1 || report.Complete || !errors.Is(outcome.Cause, storage.ErrConditionNotMet) {
|
||||
t.Fatalf("conflict=%#v outcome=%#v", report, outcome)
|
||||
}
|
||||
fake.UploadHook = nil
|
||||
for _, want := range []string{"unlocked", "not_locked"} {
|
||||
report, outcome = invoke("remove")
|
||||
if outcome.Status != 0 || report.Result != want || !report.Complete {
|
||||
t.Fatalf("remove=%#v outcome=%#v", report, outcome)
|
||||
}
|
||||
}
|
||||
report, outcome = invoke("list")
|
||||
if outcome.Status != 0 || report.Locks == nil || len(report.Locks) != 0 {
|
||||
t.Fatalf("empty list=%#v outcome=%#v", report, outcome)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLockCommandsCheckOperandsBeforeAcquisitionAndKeepGroupLazy(t *testing.T) {
|
||||
app, err := newApplication(commandDependencies{
|
||||
loadSecretsDir: func(string) (*configkit.SecretsReport, error) {
|
||||
t.Fatal("help or invalid operands bootstrapped secrets")
|
||||
return nil, nil
|
||||
},
|
||||
loadPipelineConfig: func(string, config.PipelineLoadOptions) (*config.PipelineConfig, error) {
|
||||
t.Fatal("help or invalid operands loaded config")
|
||||
return nil, nil
|
||||
},
|
||||
}, executePlan)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, args := range [][]string{{"session", "locks"}, {"session", "locks", "--help"}, {"session", "locks", "add"}, {"session", "locks", "add", "session"}, {"session", "locks", "remove", "session"}, {"session", "locks", "list"}} {
|
||||
var out, diagnostic bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &diagnostic})
|
||||
if len(args) == 2 || args[2] == "--help" {
|
||||
if outcome.Status != 0 {
|
||||
t.Fatalf("help=%#v", outcome)
|
||||
}
|
||||
} else if outcome.Status != 2 {
|
||||
t.Fatalf("%v outcome=%#v diagnostics=%s", args, outcome, diagnostic.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -69,25 +68,10 @@ func locksAddWithDependencies(ctx context.Context, args []string, out io.Writer,
|
||||
return fmt.Errorf("locks add: %w", err)
|
||||
}
|
||||
defer cleanup()
|
||||
lock, err := artifacts.NewRemoteLock(source, strings.TrimSpace(reason), nowUTC())
|
||||
_, err = applyRemoteLockMutation(ctx, store, sessionPrefix, "add", source, reason, force)
|
||||
if err != nil {
|
||||
return fmt.Errorf("locks add: %w", err)
|
||||
}
|
||||
if !force {
|
||||
current, err := artifacts.LookupRemoteLock(ctx, store, sessionPrefix, source)
|
||||
if err != nil {
|
||||
return fmt.Errorf("locks add: %w", err)
|
||||
}
|
||||
if current.Present {
|
||||
return fmt.Errorf("locks add: remote lock for %q already exists; pass --force to update", source)
|
||||
}
|
||||
}
|
||||
if err := artifacts.AddRemoteLock(ctx, store, sessionPrefix, lock, force); err != nil {
|
||||
if errors.Is(err, storage.ErrConditionNotMet) {
|
||||
return fmt.Errorf("locks add: remote lock for %q changed concurrently; retry: %w", source, err)
|
||||
}
|
||||
return fmt.Errorf("locks add: %w", err)
|
||||
}
|
||||
_, err = fmt.Fprintf(out, "narratio session locks add: locked %s\n", source)
|
||||
return err
|
||||
}
|
||||
@@ -114,14 +98,11 @@ func locksRemoveWithDependencies(ctx context.Context, args []string, out io.Writ
|
||||
return fmt.Errorf("locks remove: %w", err)
|
||||
}
|
||||
defer cleanup()
|
||||
current, err := artifacts.LookupRemoteLock(ctx, store, sessionPrefix, source)
|
||||
result, err := applyRemoteLockMutation(ctx, store, sessionPrefix, "remove", source, "", false)
|
||||
if err != nil {
|
||||
return fmt.Errorf("locks remove: %w", err)
|
||||
}
|
||||
if err := artifacts.RemoveRemoteLock(ctx, store, sessionPrefix, source); err != nil {
|
||||
return fmt.Errorf("locks remove: %w", err)
|
||||
}
|
||||
if !current.Present {
|
||||
if result == "not_locked" {
|
||||
_, err = fmt.Fprintf(out, "narratio session locks remove: %s was not locked\n", source)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -11,9 +12,7 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
||||
"go.maximumdirect.net/commandkit"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
@@ -49,112 +48,16 @@ func sessionInitWithDependencies(ctx context.Context, args []string, out io.Writ
|
||||
if err := parseSessionAwareFlags("session init", fs, args, &sessionID); err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(sessionID) == "" {
|
||||
return fmt.Errorf("session init: session_id is required")
|
||||
}
|
||||
if (strings.TrimSpace(output) == "") == !remote {
|
||||
return fmt.Errorf("session init: specify exactly one target: --output <path> or --remote")
|
||||
}
|
||||
if strings.TrimSpace(audioDir) != "" && strings.TrimSpace(audioS3Prefix) != "" {
|
||||
return fmt.Errorf("session init: --audio-dir and --audio-s3-prefix are mutually exclusive")
|
||||
}
|
||||
if strings.TrimSpace(audioDir) != "" {
|
||||
var err error
|
||||
audioDir, err = filepath.Abs(audioDir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("session init: resolve --audio-dir: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
base, err := loadPipelineCampaignConfigWithDependencies(pipelinePath, campaignPath, campaignFilePath, config.PipelineLoadOptions{Overlay: overlay.pointer()}, secretsDir.pointer(), deps)
|
||||
if err != nil {
|
||||
return fmt.Errorf("session init: %w", err)
|
||||
}
|
||||
|
||||
input := sessionInitInput{
|
||||
Campaign: config.CampaignID(base.Campaign),
|
||||
CampaignPath: base.CampaignPath,
|
||||
TemplateFile: base.Campaign.SessionTemplateFile,
|
||||
SessionID: sessionID,
|
||||
PreviousSessionID: previousSessionID,
|
||||
Date: date,
|
||||
Title: title,
|
||||
AudioS3Prefix: audioS3Prefix,
|
||||
AudioDir: audioDir,
|
||||
}
|
||||
data, err := buildSessionInitYAML(input)
|
||||
if err != nil {
|
||||
return fmt.Errorf("session init: %w", err)
|
||||
}
|
||||
label := strings.TrimSpace(output)
|
||||
if label == "" {
|
||||
label = "remote session.yml"
|
||||
}
|
||||
// Generated defaults and CLI resources originate at the invocation. A
|
||||
// configured template supplies its own existing local authoring context.
|
||||
authoringPath := "session.yml"
|
||||
if input.TemplateFile != "" {
|
||||
authoringPath = resolveSessionInitTemplatePath(input.CampaignPath, input.TemplateFile)
|
||||
}
|
||||
sessionCfg, err := config.LoadSessionAuthoringBytes(authoringPath, data, config.SessionLoadOptions{
|
||||
Campaign: base.Campaign,
|
||||
CampaignPath: base.CampaignPath,
|
||||
SessionID: sessionID,
|
||||
PreviousSessionID: previousSessionID,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("session init: %w", err)
|
||||
}
|
||||
cfg, err := config.ResolveLoadedPipelineCampaign(*base, label, sessionCfg, config.SessionSource{Source: "session_config", LocalPath: label})
|
||||
if err != nil {
|
||||
return fmt.Errorf("session init: %w", err)
|
||||
}
|
||||
if err := config.Validate(cfg); err != nil {
|
||||
return fmt.Errorf("session init: %w", err)
|
||||
}
|
||||
data, err = config.RenderSessionDocument(cfg, sessionID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("session init: render effective session: %w", err)
|
||||
}
|
||||
|
||||
if !remote {
|
||||
if err := writeLocalFile(output, data, force); err != nil {
|
||||
return fmt.Errorf("session init: %w", err)
|
||||
}
|
||||
_, err := fmt.Fprintf(out, "narratio session init: wrote %s\n", filepath.Clean(output))
|
||||
request := &sessionInitializationInput{Selection: configurationSelection{
|
||||
Config: commandkit.Supplied[string]{Value: pipelinePath, Set: pipelinePath != ""}, Campaign: commandkit.Supplied[string]{Value: campaignPath, Set: campaignPath != ""}, CampaignFile: commandkit.Supplied[string]{Value: campaignFilePath, Set: campaignFilePath != ""}, Session: commandkit.Supplied[string]{Value: sessionID, Set: sessionID != ""}, Overlay: commandkit.Supplied[string]{Value: overlay.value, Set: overlay.set}, SecretsDir: commandkit.Supplied[string]{Value: secretsDir.value, Set: secretsDir.set},
|
||||
}, PreviousSessionID: previousSessionID, Date: date, Title: title, Output: output, AudioS3Prefix: audioS3Prefix, AudioDir: audioDir, Remote: remote, Force: force}
|
||||
if err := checkSessionInitializationInput(request); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
store, err := newCommandObjectStoreWithDependencies(ctx, cfg, nil, deps)
|
||||
if err != nil {
|
||||
return fmt.Errorf("session init: %w", err)
|
||||
report, err := initializeSession(ctx, request, deps)
|
||||
if report != nil {
|
||||
err = errors.Join(err, commandkit.RenderReport(out, commandkit.Report{Value: report}, ""))
|
||||
}
|
||||
sessionPrefix := artifacts.S3SessionPrefix(base.Pipeline.Storage.S3.RootPrefix, config.CampaignID(base.Campaign), sessionID)
|
||||
key := artifacts.S3SessionConfigKey(sessionPrefix)
|
||||
exists, err := store.Exists(ctx, key)
|
||||
if err != nil {
|
||||
return fmt.Errorf("session init: check remote session %q: %w", key, err)
|
||||
}
|
||||
if exists && !force {
|
||||
return fmt.Errorf("session init: remote session %q already exists; pass --force to overwrite", key)
|
||||
}
|
||||
tmp, err := os.CreateTemp("", "narratio-session-init-*.yml")
|
||||
if err != nil {
|
||||
return fmt.Errorf("session init: create temp file: %w", err)
|
||||
}
|
||||
tmpPath := tmp.Name()
|
||||
defer func() { _ = os.Remove(tmpPath) }()
|
||||
if _, err := tmp.Write(data); err != nil {
|
||||
_ = tmp.Close()
|
||||
return fmt.Errorf("session init: write temp file: %w", err)
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return fmt.Errorf("session init: close temp file: %w", err)
|
||||
}
|
||||
if _, err := store.Upload(ctx, tmpPath, key, storage.UploadOptions{ContentType: "application/x-yaml; charset=utf-8"}); err != nil {
|
||||
return fmt.Errorf("session init: upload remote session %q: %w", key, err)
|
||||
}
|
||||
_, err = fmt.Fprintf(out, "narratio session init: wrote s3://%s/%s\n", s3BucketName(base.Pipeline), key)
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
205
internal/app/session_init_command.go
Normal file
205
internal/app/session_init_command.go
Normal file
@@ -0,0 +1,205 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
||||
"go.maximumdirect.net/commandkit"
|
||||
)
|
||||
|
||||
type sessionInitializationInput struct {
|
||||
Selection configurationSelection
|
||||
PreviousSessionID, Date, Title, Output, AudioS3Prefix, AudioDir string
|
||||
Remote, Force bool
|
||||
}
|
||||
type sessionInitializationReport struct {
|
||||
Campaign string `json:"campaign"`
|
||||
SessionID string `json:"session_id"`
|
||||
Destination string `json:"destination"`
|
||||
Remote bool `json:"remote"`
|
||||
Written bool `json:"written"`
|
||||
}
|
||||
|
||||
func checkSessionInitializationInput(input *sessionInitializationInput) error {
|
||||
if err := checkConfigurationSelection(input.Selection); err != nil {
|
||||
return err
|
||||
}
|
||||
if input.Selection.Session.Value == "" {
|
||||
return fmt.Errorf("session identity is required")
|
||||
}
|
||||
if (strings.TrimSpace(input.Output) == "") == !input.Remote {
|
||||
return fmt.Errorf("specify exactly one target: --output or --remote")
|
||||
}
|
||||
if strings.TrimSpace(input.AudioDir) != "" && strings.TrimSpace(input.AudioS3Prefix) != "" {
|
||||
return fmt.Errorf("--audio-dir and --audio-s3-prefix are mutually exclusive")
|
||||
}
|
||||
if strings.TrimSpace(input.AudioDir) != "" {
|
||||
resolved, err := filepath.Abs(input.AudioDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
input.AudioDir = resolved
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sessionInitializationCommand(deps commandDependencies) commandkit.Command {
|
||||
common := newConfigurationFlags(func(input **sessionInitializationInput) *configurationSelection { return &(*input).Selection })
|
||||
return commandkit.NewCommand(commandkit.CommandSpec[*sessionInitializationInput]{Name: "init", Summary: "Create standalone local or remote session configuration.", NewInput: func() *sessionInitializationInput { return &sessionInitializationInput{} },
|
||||
Flags: []commandkit.Flag[*sessionInitializationInput]{common.Config, common.Overlay, common.Campaign, common.CampaignFile, common.SecretsDir,
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "previous-session-id", Usage: "Previous session identity."}, nil, stringValue, func(input **sessionInitializationInput, value commandkit.Supplied[string]) {
|
||||
(*input).PreviousSessionID = value.Value
|
||||
}),
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "date", Usage: "Session date."}, nil, stringValue, func(input **sessionInitializationInput, value commandkit.Supplied[string]) {
|
||||
(*input).Date = value.Value
|
||||
}),
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "title", Usage: "Session title."}, nil, stringValue, func(input **sessionInitializationInput, value commandkit.Supplied[string]) {
|
||||
(*input).Title = value.Value
|
||||
}),
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "output", Usage: "Local output YAML file."}, nil, stringValue, func(input **sessionInitializationInput, value commandkit.Supplied[string]) {
|
||||
(*input).Output = value.Value
|
||||
}),
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "audio-s3-prefix", Usage: "Session audio prefix in object storage."}, nil, stringValue, func(input **sessionInitializationInput, value commandkit.Supplied[string]) {
|
||||
(*input).AudioS3Prefix = value.Value
|
||||
}),
|
||||
commandkit.ValueFlag(commandkit.FlagMeta{Name: "audio-dir", Usage: "Local audio directory, relative to the invocation directory."}, nil, stringValue, func(input **sessionInitializationInput, value commandkit.Supplied[string]) {
|
||||
(*input).AudioDir = value.Value
|
||||
}),
|
||||
commandkit.BoolFlag(commandkit.FlagMeta{Name: "remote", Usage: "Create session configuration in object storage."}, false, func(input **sessionInitializationInput, value commandkit.Supplied[bool]) {
|
||||
(*input).Remote = value.Value
|
||||
}),
|
||||
commandkit.BoolFlag(commandkit.FlagMeta{Name: "force", Usage: "Overwrite an existing target."}, false, func(input **sessionInitializationInput, value commandkit.Supplied[bool]) {
|
||||
(*input).Force = value.Value
|
||||
}),
|
||||
},
|
||||
Arguments: []commandkit.Argument[*sessionInitializationInput]{commandkit.ValueArgument(commandkit.ArgumentMeta{Name: "SESSION", Usage: "New session identity."}, true, stringValue, func(input **sessionInitializationInput, value commandkit.Supplied[string]) {
|
||||
(*input).Selection.Session = value
|
||||
})},
|
||||
CheckInput: checkSessionInitializationInput,
|
||||
Run: func(invocation commandkit.Invocation, input *sessionInitializationInput) commandkit.Outcome {
|
||||
report, err := initializeSession(invocation.Context, input, deps)
|
||||
if report != nil {
|
||||
err = errors.Join(err, invocation.Reporter().Report(commandkit.Report{Value: report}))
|
||||
}
|
||||
return operationOutcome(err)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func initializeSession(ctx context.Context, request *sessionInitializationInput, deps commandDependencies) (report *sessionInitializationReport, err error) {
|
||||
deps = normalizeCommandDependencies(deps)
|
||||
deps.secretsBootstrap = &secretsBootstrap{}
|
||||
sessionID, previousSessionID, date, title, output, audioS3Prefix, audioDir := request.Selection.Session.Value, request.PreviousSessionID, request.Date, request.Title, request.Output, request.AudioS3Prefix, request.AudioDir
|
||||
remote, force := request.Remote, request.Force
|
||||
acquired := newConfigurationAcquisition(request.Selection, deps)
|
||||
defer func() { err = errors.Join(err, acquired.Close()) }()
|
||||
pipeline, err := acquired.Pipeline(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
campaign, err := acquired.Campaign(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
party, err := acquired.Party(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
catalog, err := acquired.Catalog(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
base := &config.LoadedPipelineCampaign{Pipeline: pipeline, PipelinePath: acquired.pipelinePath, Campaign: campaign, CampaignPath: acquired.campaignPath, Party: *party, ArtifactCatalog: catalog}
|
||||
|
||||
input := sessionInitInput{
|
||||
Campaign: config.CampaignID(base.Campaign),
|
||||
CampaignPath: base.CampaignPath,
|
||||
TemplateFile: base.Campaign.SessionTemplateFile,
|
||||
SessionID: sessionID,
|
||||
PreviousSessionID: previousSessionID,
|
||||
Date: date,
|
||||
Title: title,
|
||||
AudioS3Prefix: audioS3Prefix,
|
||||
AudioDir: audioDir,
|
||||
}
|
||||
data, err := buildSessionInitYAML(input)
|
||||
if err != nil {
|
||||
return report, fmt.Errorf("session init: %w", err)
|
||||
}
|
||||
label := strings.TrimSpace(output)
|
||||
if label == "" {
|
||||
label = "remote session.yml"
|
||||
}
|
||||
// Generated defaults and CLI resources originate at the invocation. A
|
||||
// configured template supplies its own existing local authoring context.
|
||||
authoringPath := "session.yml"
|
||||
if input.TemplateFile != "" {
|
||||
authoringPath = resolveSessionInitTemplatePath(input.CampaignPath, input.TemplateFile)
|
||||
}
|
||||
sessionCfg, err := config.LoadSessionAuthoringBytes(authoringPath, data, config.SessionLoadOptions{
|
||||
Campaign: base.Campaign,
|
||||
CampaignPath: base.CampaignPath,
|
||||
SessionID: sessionID,
|
||||
PreviousSessionID: previousSessionID,
|
||||
})
|
||||
if err != nil {
|
||||
return report, fmt.Errorf("session init: %w", err)
|
||||
}
|
||||
cfg, err := config.ResolveLoadedPipelineCampaign(*base, label, sessionCfg, config.SessionSource{Source: "session_config", LocalPath: label})
|
||||
if err != nil {
|
||||
return report, fmt.Errorf("session init: %w", err)
|
||||
}
|
||||
if err := config.Validate(cfg); err != nil {
|
||||
return report, fmt.Errorf("session init: %w", err)
|
||||
}
|
||||
data, err = config.RenderSessionDocument(cfg, sessionID)
|
||||
if err != nil {
|
||||
return report, fmt.Errorf("session init: render effective session: %w", err)
|
||||
}
|
||||
|
||||
if !remote {
|
||||
if err := writeLocalFile(output, data, force); err != nil {
|
||||
return report, fmt.Errorf("session init: %w", err)
|
||||
}
|
||||
report = &sessionInitializationReport{Campaign: config.CampaignID(base.Campaign), SessionID: sessionID, Destination: filepath.Clean(output), Written: true}
|
||||
return report, nil
|
||||
}
|
||||
|
||||
store, err := newCommandObjectStoreWithDependencies(ctx, cfg, nil, deps)
|
||||
if err != nil {
|
||||
return report, fmt.Errorf("session init: %w", err)
|
||||
}
|
||||
sessionPrefix := artifacts.S3SessionPrefix(base.Pipeline.Storage.S3.RootPrefix, config.CampaignID(base.Campaign), sessionID)
|
||||
key := artifacts.S3SessionConfigKey(sessionPrefix)
|
||||
exists, err := store.Exists(ctx, key)
|
||||
if err != nil {
|
||||
return report, fmt.Errorf("session init: check remote session %q: %w", key, err)
|
||||
}
|
||||
if exists && !force {
|
||||
return report, fmt.Errorf("session init: remote session %q already exists; pass --force to overwrite", key)
|
||||
}
|
||||
tmp, err := os.CreateTemp("", "narratio-session-init-*.yml")
|
||||
if err != nil {
|
||||
return report, fmt.Errorf("session init: create temp file: %w", err)
|
||||
}
|
||||
tmpPath := tmp.Name()
|
||||
defer func() { err = errors.Join(err, os.Remove(tmpPath)) }()
|
||||
if _, err := tmp.Write(data); err != nil {
|
||||
return report, fmt.Errorf("session init: write temp file: %w", errors.Join(err, tmp.Close()))
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return report, fmt.Errorf("session init: close temp file: %w", err)
|
||||
}
|
||||
if _, err := store.Upload(ctx, tmpPath, key, storage.UploadOptions{ContentType: "application/x-yaml; charset=utf-8"}); err != nil {
|
||||
return report, fmt.Errorf("session init: upload remote session %q: %w", key, err)
|
||||
}
|
||||
report = &sessionInitializationReport{Campaign: config.CampaignID(base.Campaign), SessionID: sessionID, Destination: "s3://" + s3BucketName(base.Pipeline) + "/" + key, Remote: true, Written: true}
|
||||
return report, nil
|
||||
}
|
||||
108
internal/app/session_init_command_test.go
Normal file
108
internal/app/session_init_command_test.go
Normal file
@@ -0,0 +1,108 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
||||
"go.maximumdirect.net/commandkit"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func TestSessionInitializationCommandKeepsYAMLIndependentOfReportFormat(t *testing.T) {
|
||||
pipeline, campaign, _ := writeValidConfigFiles(t, t.TempDir())
|
||||
invocation := t.TempDir()
|
||||
t.Chdir(invocation)
|
||||
output := filepath.Join(t.TempDir(), "created.yml")
|
||||
var out, diagnostic bytes.Buffer
|
||||
outcome := Execute(context.Background(), []string{"session", "init", "2026-05-04", "--config", pipeline, "--campaign-file", campaign, "--output", output, "--audio-dir", "audio", "--title", "Synthetic session", "--format", "json"}, commandkit.Streams{Out: &out, Err: &diagnostic})
|
||||
if outcome.Status != 0 {
|
||||
t.Fatalf("status=%d diagnostics=%s", outcome.Status, diagnostic.String())
|
||||
}
|
||||
var report sessionInitializationReport
|
||||
if err := json.Unmarshal(out.Bytes(), &report); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !report.Written || report.Remote || report.Destination != output {
|
||||
t.Fatalf("report=%#v", report)
|
||||
}
|
||||
cfg, err := config.LoadSession(output)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.SessionID != "2026-05-04" || cfg.Title != "Synthetic session" || cfg.Inputs.AudioDir != filepath.Join(invocation, "audio") {
|
||||
t.Fatalf("created session=%#v", cfg)
|
||||
}
|
||||
data, err := os.ReadFile(output)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if json.Valid(data) {
|
||||
t.Fatal("report format changed the generated YAML file format")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionInitializationCommandRemoteRoundTrips(t *testing.T) {
|
||||
pipeline, campaign, _ := writeValidConfigFiles(t, t.TempDir())
|
||||
fake := &storage.FakeBackend{}
|
||||
deps, _ := remoteSessionLoaderDependencies(fake)
|
||||
app, err := newApplication(deps, executePlan)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out, diagnostic bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), []string{"session", "init", "2026-05-04", "--config", pipeline, "--campaign-file", campaign, "--remote", "--audio-s3-prefix", "recordings/", "--format", "json"}, commandkit.Streams{Out: &out, Err: &diagnostic})
|
||||
if outcome.Status != 0 {
|
||||
t.Fatalf("status=%d diagnostics=%s", outcome.Status, diagnostic.String())
|
||||
}
|
||||
var report sessionInitializationReport
|
||||
if err := json.Unmarshal(out.Bytes(), &report); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !report.Remote || !report.Written || len(fake.Uploads) != 1 {
|
||||
t.Fatalf("report=%#v uploads=%v", report, fake.Uploads)
|
||||
}
|
||||
key := artifacts.S3SessionConfigKey(artifacts.S3SessionPrefix("dnd", "sample-campaign", "2026-05-04"))
|
||||
data := fake.Objects[key].Data
|
||||
session, err := config.LoadSessionBytesWithOptions("remote-created", data, config.SessionLoadOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if session.SessionID != "2026-05-04" || session.Inputs.AudioS3 == nil || session.Inputs.AudioS3.Prefix != "recordings/" {
|
||||
t.Fatalf("created session=%#v", session)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionInitializationCommandChecksTargetsBeforeAcquisition(t *testing.T) {
|
||||
app, err := newApplication(commandDependencies{
|
||||
loadSecretsDir: func(string) (*configkit.SecretsReport, error) {
|
||||
t.Fatal("invalid initialization bootstrapped secrets")
|
||||
return nil, nil
|
||||
},
|
||||
loadPipelineConfig: func(string, config.PipelineLoadOptions) (*config.PipelineConfig, error) {
|
||||
t.Fatal("invalid initialization loaded config")
|
||||
return nil, nil
|
||||
},
|
||||
}, executePlan)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
{"session", "init"}, {"session", "init", "session"},
|
||||
{"session", "init", "session", "--output", "created.yml", "--remote"},
|
||||
{"session", "init", "session", "--output", "created.yml", "--audio-dir", "audio", "--audio-s3-prefix", "audio/"},
|
||||
{"session", "init", "session", "--output", "created.yml", "--session-file", "existing.yml"},
|
||||
} {
|
||||
var out, diagnostic bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &diagnostic})
|
||||
if outcome.Status != 2 {
|
||||
t.Fatalf("%v status=%d diagnostics=%s", args, outcome.Status, diagnostic.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user