Files
narratio/internal/app/restore_command.go

199 lines
9.0 KiB
Go
Raw Normal View History

package app
import (
"context"
"errors"
"fmt"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config"
"go.maximumdirect.net/commandkit"
)
type restoreCommandInput struct {
Selection configurationSelection
PreviousSession string
DryRun, Force, IncludeAudio bool
}
type restoreCommandReport struct {
Campaign string `json:"campaign"`
SessionID string `json:"session_id"`
RunID string `json:"run_id"`
DryRun bool `json:"dry_run"`
Complete bool `json:"complete"`
Status string `json:"status"`
Downloaded int `json:"downloaded"`
Conflicts int `json:"conflicts"`
Actions []restoreCommandAction `json:"actions"`
}
type restoreCommandAction struct {
Kind string `json:"kind"`
LocalPath string `json:"local_path"`
RemoteKey string `json:"remote_key"`
Status string `json:"status"`
Reason string `json:"reason,omitempty"`
Error string `json:"error,omitempty"`
}
func restoreSession(ctx context.Context, cfg *config.Config, opts RestorePlanOptions, deps commandDependencies) (public *restoreCommandReport, resultErr error) {
diagnostic, resultErr := restoreSessionState(ctx, cfg, opts, normalizeCommandDependencies(deps))
if diagnostic == nil {
return nil, resultErr
}
public = &restoreCommandReport{Campaign: diagnostic.Campaign, SessionID: diagnostic.SessionID, RunID: diagnostic.RunID, DryRun: opts.DryRun, Complete: !opts.DryRun && resultErr == nil && diagnostic.Status == "succeeded", Status: diagnostic.Status, Downloaded: diagnostic.Execution.Downloaded, Conflicts: diagnostic.Plan.Conflicts, Actions: []restoreCommandAction{}}
for _, action := range diagnostic.Actions {
public.Actions = append(public.Actions, restoreCommandAction{Kind: action.Kind, LocalPath: action.LocalRelativePath, RemoteKey: action.RemoteKey, Status: action.Status, Reason: action.Reason, Error: action.Error})
}
return public, resultErr
}
func restoreSessionState(ctx context.Context, cfg *config.Config, opts RestorePlanOptions, deps commandDependencies) (diagnostic *RestoreReport, resultErr error) {
if err := config.Validate(cfg); err != nil {
return diagnostic, fmt.Errorf("restore: %w", err)
}
objectStore, err := newCommandObjectStoreWithDependencies(ctx, cfg, nil, deps)
if err != nil {
return diagnostic, fmt.Errorf("restore: %w", err)
}
current, err := deps.discoverRemoteCurrentState(ctx, cfg, objectStore)
if err != nil {
return diagnostic, fmt.Errorf("restore: %w", err)
}
if opts.DryRun {
plan, err := deps.buildRestorePlan(ctx, cfg, current, objectStore, RestorePlanOptions{
IncludeAudio: opts.IncludeAudio,
Force: opts.Force,
DryRun: true,
})
if err != nil {
return diagnostic, fmt.Errorf("restore: %w", err)
}
report, err := newRestoreReport(current, plan, RestorePlanOptions{
IncludeAudio: opts.IncludeAudio,
Force: opts.Force,
DryRun: true,
})
if err != nil {
return diagnostic, fmt.Errorf("restore: %w", err)
}
diagnostic = report
return diagnostic, nil
}
artifactStore := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root)
if _, err := artifactStore.EnsureLayoutFor(cfg.Session.Campaign, cfg.Session.SessionID); err != nil {
return diagnostic, fmt.Errorf("restore: prepare workdir: %w", err)
}
lock, err := artifactStore.AcquireSessionLockForContext(ctx, cfg.Session.Campaign, cfg.Session.SessionID)
if err != nil {
return diagnostic, fmt.Errorf("restore: acquire session lock: %w", err)
}
defer func() {
if releaseErr := artifactStore.ReleaseSessionLock(lock); releaseErr != nil {
if resultErr == nil {
resultErr = fmt.Errorf("restore: release session lock: %w", releaseErr)
} else {
resultErr = errors.Join(resultErr, fmt.Errorf("restore: release session lock: %w", releaseErr))
}
}
}()
// Classification and installation share the same transition lock as a
// runner. This prevents a runner from making reuse decisions against state
// that restore is about to replace.
plan, err := deps.buildRestorePlan(ctx, cfg, current, objectStore, RestorePlanOptions{
IncludeAudio: opts.IncludeAudio,
Force: opts.Force,
})
if err != nil {
return diagnostic, fmt.Errorf("restore: %w", err)
}
report, err := newRestoreReport(current, plan, RestorePlanOptions{
IncludeAudio: opts.IncludeAudio,
Force: opts.Force,
})
if err != nil {
return diagnostic, fmt.Errorf("restore: %w", err)
}
diagnostic = report
if plan.ConflictCount > 0 {
conflictErr := fmt.Errorf("restore conflict: %d conflicting path(s); --force can replace eligible regular files but not unresolved conflicts (download=%d skip_same=%d conflicts=%d)", plan.ConflictCount, plan.DownloadCount, plan.SkipSameCount, plan.ConflictCount)
report.setFailed(conflictErr)
_, reportErr := persistRestoreReport(artifactStore, cfg, report)
return diagnostic, errors.Join(conflictErr, reportErr)
}
if err := writeRestoreMarker(artifactStore.SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)); err != nil {
return diagnostic, fmt.Errorf("restore: mark incomplete restore: %w", err)
}
result, err := deps.executeRestorePlan(ctx, cfg, current, plan, report, objectStore)
err = errors.Join(err, ctx.Err())
if err != nil {
report.setFailed(err)
if _, reportErr := persistRestoreReport(artifactStore, cfg, report); reportErr != nil {
return diagnostic, fmt.Errorf("restore: execute plan and persist report: %w", errors.Join(err, reportErr))
}
return diagnostic, fmt.Errorf("restore: execute plan: %w", err)
}
if result == nil {
return diagnostic, fmt.Errorf("restore execution returned no result")
}
report.Execution.Downloaded = result.DownloadedCount
report.setSucceeded()
if err := clearRestoreMarker(artifactStore.SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)); err != nil {
return diagnostic, fmt.Errorf("restore: clear incomplete restore marker: %w", err)
}
if _, err := persistRestoreReport(artifactStore, cfg, report); err != nil {
return diagnostic, fmt.Errorf("restore: write report: %w", err)
}
return diagnostic, nil
}
func restoreCommand(deps commandDependencies) commandkit.Command {
common := newConfigurationFlags(func(input **restoreCommandInput) *configurationSelection { return &(*input).Selection })
return commandkit.NewCommand(commandkit.CommandSpec[*restoreCommandInput]{Name: "restore", Summary: "Restore the committed remote session snapshot.", NewInput: func() *restoreCommandInput { return &restoreCommandInput{} },
Flags: []commandkit.Flag[*restoreCommandInput]{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 **restoreCommandInput, value commandkit.Supplied[string]) {
(*input).PreviousSession = value.Value
}),
commandkit.BoolFlag(commandkit.FlagMeta{Name: "dry-run", Usage: "Preview restore actions without writing local files."}, false, func(input **restoreCommandInput, value commandkit.Supplied[bool]) { (*input).DryRun = value.Value }),
commandkit.BoolFlag(commandkit.FlagMeta{Name: "force", Usage: "Replace eligible conflicting regular files."}, false, func(input **restoreCommandInput, value commandkit.Supplied[bool]) { (*input).Force = value.Value }),
commandkit.BoolFlag(commandkit.FlagMeta{Name: "include-audio", Usage: "Include session audio objects."}, false, func(input **restoreCommandInput, value commandkit.Supplied[bool]) {
(*input).IncludeAudio = value.Value
}),
},
Arguments: []commandkit.Argument[*restoreCommandInput]{commandkit.ValueArgument(commandkit.ArgumentMeta{Name: "SESSION", Usage: "Session identity."}, true, stringValue, func(input **restoreCommandInput, value commandkit.Supplied[string]) {
(*input).Selection.Session = value
})},
CheckInput: func(input *restoreCommandInput) error { return checkConfigurationSelection(input.Selection) },
Run: func(invocation commandkit.Invocation, input *restoreCommandInput) commandkit.Outcome {
report, err := restoreSelectedSession(invocation.Context, input, deps)
if report != nil {
err = errors.Join(err, invocation.Reporter().Report(commandkit.Report{Value: report}))
}
return operationOutcome(err)
},
})
}
func restoreSelectedSession(ctx context.Context, input *restoreCommandInput, deps commandDependencies) (report *restoreCommandReport, err error) {
deps = normalizeCommandDependencies(deps)
deps.secretsBootstrap = &secretsBootstrap{}
acquired := newConfigurationAcquisition(input.Selection, deps)
acquired.previousSessionID = input.PreviousSession
defer func() {
err = errors.Join(err, acquired.Close())
if report != nil && err != nil {
report.Complete = false
}
}()
cfg, err := acquired.Domain(ctx)
if err != nil {
return nil, err
}
return restoreSession(ctx, cfg, RestorePlanOptions{DryRun: input.DryRun, Force: input.Force, IncludeAudio: input.IncludeAudio}, deps)
}