Resume and safely clean recorded rehearsals
This commit is contained in:
45
cmd/releasekit/internal/cli/rehearsal_recovery.go
Normal file
45
cmd/releasekit/internal/cli/rehearsal_recovery.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ResolveRehearsalRecoveryCredentials selects local credentials from the
|
||||
// captured profile, or explicit file overrides without loading that profile.
|
||||
func ResolveRehearsalRecoveryCredentials(ctx context.Context, repository, commit, profilePath, profileSHA256, deliveryOverride, woodpeckerOverride string) (string, string, error) {
|
||||
var delivery *DeliveryCredentials
|
||||
var woodpecker *WoodpeckerSettings
|
||||
if strings.TrimSpace(deliveryOverride) == "" || strings.TrimSpace(woodpeckerOverride) == "" {
|
||||
captured, err := CaptureCommittedProfile(ctx, repository, commit, profilePath)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("load recorded rehearsal profile: %w", err)
|
||||
}
|
||||
if captured.Commit != commit || captured.Path != profilePath || captured.SHA256 != profileSHA256 {
|
||||
return "", "", errors.New("recorded rehearsal profile identity does not match")
|
||||
}
|
||||
if captured.Settings.Delivery != nil {
|
||||
delivery = captured.Settings.Delivery.Credentials
|
||||
}
|
||||
if captured.Settings.Rehearsal != nil {
|
||||
woodpecker = captured.Settings.Rehearsal.Woodpecker
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(deliveryOverride) != "" {
|
||||
delivery = &DeliveryCredentials{Local: &LocalCredential{TokenFile: deliveryOverride}}
|
||||
}
|
||||
if strings.TrimSpace(woodpeckerOverride) != "" {
|
||||
woodpecker = &WoodpeckerSettings{TokenFile: woodpeckerOverride}
|
||||
}
|
||||
deliveryToken, _, err := ResolveDeliveryCredential(repository, delivery, LocalCredentials)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
woodpeckerToken, _, err := ResolveWoodpeckerCredential(repository, woodpecker)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return deliveryToken, woodpeckerToken, nil
|
||||
}
|
||||
56
cmd/releasekit/internal/cli/rehearsal_recovery_test.go
Normal file
56
cmd/releasekit/internal/cli/rehearsal_recovery_test.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRecoveryCredentialsUseCapturedProfileOrExplicitOverrides(t *testing.T) {
|
||||
repo := t.TempDir()
|
||||
run := func(args ...string) {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir = repo
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("git %v: %v: %s", args, err, out)
|
||||
}
|
||||
}
|
||||
run("init", "--initial-branch=main")
|
||||
run("config", "user.name", "ReleaseKit Test")
|
||||
run("config", "user.email", "releasekit@example.test")
|
||||
profile := `{"product":"Example","source":{},"delivery":{"credentials":{"local":{"token_file":"forge-token"}}},"rehearsal":{"woodpecker":{"token_file":"ci-token"}}}`
|
||||
if err := os.WriteFile(filepath.Join(repo, "releasekit.json"), []byte(profile), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run("add", "releasekit.json")
|
||||
run("commit", "-m", "captured profile")
|
||||
captured, err := CaptureCommittedProfile(t.Context(), repo, "HEAD", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(repo, "releasekit.json"), []byte(`{"product":"Different"}`), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(repo, "forge-token"), []byte(" forge-secret \n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(repo, "ci-token"), []byte(" ci-secret \n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
forge, wood, err := ResolveRehearsalRecoveryCredentials(t.Context(), repo, captured.Commit, captured.Path, captured.SHA256, "", "")
|
||||
if err != nil || forge != "forge-secret" || wood != "ci-secret" {
|
||||
t.Fatalf("credentials selected=%t/%t error=%v", forge == "forge-secret", wood == "ci-secret", err)
|
||||
}
|
||||
if _, _, err := ResolveRehearsalRecoveryCredentials(t.Context(), repo, captured.Commit, captured.Path, strings.Repeat("0", 64), "", ""); err == nil {
|
||||
t.Fatal("accepted a different captured profile digest")
|
||||
}
|
||||
forgePath := filepath.Join(repo, "forge-token")
|
||||
woodPath := filepath.Join(repo, "ci-token")
|
||||
forge, wood, err = ResolveRehearsalRecoveryCredentials(t.Context(), filepath.Join(t.TempDir(), "missing"), captured.Commit, captured.Path, captured.SHA256, forgePath, woodPath)
|
||||
if err != nil || forge != "forge-secret" || wood != "ci-secret" {
|
||||
t.Fatalf("override selection=%t/%t error=%v", forge == "forge-secret", wood == "ci-secret", err)
|
||||
}
|
||||
}
|
||||
@@ -49,3 +49,20 @@ keeps matching pipeline numbers, workflow and step observations, the job result,
|
||||
and partial outcomes in the selected attempt record. A timeout or cancellation
|
||||
leaves those observations available for explicit recovery; it does not cancel
|
||||
the independent CI job or establish that cleanup is safe.
|
||||
|
||||
## Cleanup and recovery
|
||||
|
||||
Recovery selects one explicit record and uses its captured destinations with
|
||||
current explicitly supplied credentials. A started or uncertain dispatch is
|
||||
eligible for cleanup only after every matching observed pipeline and relevant
|
||||
job is terminal and the CI search is checked again. Missing, active, or
|
||||
unavailable CI evidence leaves cleanup pending. Cleanup verifies the recorded
|
||||
tag object and page identity, then removes the page and its assets, the remote
|
||||
tag, and the matching local tag. It records intent before each deletion and
|
||||
reobserves ambiguous outcomes. A canceled observation does not cancel CI;
|
||||
cleanup uses an independent bounded context.
|
||||
|
||||
A completed result describes the recorded resources and the CI runs observed
|
||||
at cleanup time. Later operator-initiated reruns, CI history, notifications, and
|
||||
webhook effects are outside that result. Records remain available for operator
|
||||
retention.
|
||||
|
||||
@@ -656,6 +656,16 @@ cancellation. Use controlled clocks/waits at the external boundary where useful.
|
||||
|
||||
## Stage 13: Implement cleanup, resume, and uncertain-state recovery
|
||||
|
||||
**Completed:** Explicit resume and cleanup use recorded destinations and
|
||||
credentials supplied by the caller. Cleanup rechecks matching CI runs, verifies
|
||||
the diagnostic marker, page and tag identities, records each deletion intent,
|
||||
and reconciles ambiguous acknowledgments. It uses a bounded context independent
|
||||
of canceled observation and preserves conflicts and incomplete attempts.
|
||||
Credential recovery reads the captured profile or explicit file overrides.
|
||||
Local Git/HTTP tests cover active and missing pipelines, foreign resources,
|
||||
lost deletes, interruption, and repeated cleanup. The offline `go test ./...`
|
||||
suite, focused race tests, and API/dependency check pass.
|
||||
|
||||
**Work:** complete rehearsal lifecycle coordination and public recovery calls.
|
||||
|
||||
1. Expose `ResumeRehearsal` and `CleanupRehearsal`, each accepting an explicit
|
||||
|
||||
@@ -4,9 +4,34 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// QueryLocalDiagnosticTag distinguishes an absent local ref from an unreadable
|
||||
// or non-annotated ref; an error never establishes absence.
|
||||
func QueryLocalDiagnosticTag(ctx context.Context, repo, tag string) (RefState, AnnotatedTag, error) {
|
||||
if !strings.HasPrefix(tag, "releasekit-test/") {
|
||||
return RefUnreadable, AnnotatedTag{}, errors.New("diagnostic tag is required")
|
||||
}
|
||||
if err := CheckTagRef(ctx, repo, tag); err != nil {
|
||||
return RefUnreadable, AnnotatedTag{}, err
|
||||
}
|
||||
_, err := run(ctx, repo, nil, "show-ref", "--verify", "--quiet", "refs/tags/"+tag)
|
||||
if err != nil {
|
||||
var exit *exec.ExitError
|
||||
if errors.As(err, &exit) && exit.ExitCode() == 1 && ctx.Err() == nil {
|
||||
return RefAbsent, AnnotatedTag{}, nil
|
||||
}
|
||||
return RefUnreadable, AnnotatedTag{}, err
|
||||
}
|
||||
observed, err := ReadAnnotatedTag(ctx, repo, tag)
|
||||
if err != nil {
|
||||
return RefUnreadable, AnnotatedTag{}, err
|
||||
}
|
||||
return RefPresent, observed, nil
|
||||
}
|
||||
|
||||
func checkDiagnosticTag(ctx context.Context, repo, tag, object, commit string) error {
|
||||
if !strings.HasPrefix(tag, "releasekit-test/") || !ValidObjectID(object) || !ValidObjectID(commit) {
|
||||
return errors.New("a diagnostic tag and exact tag object and commit are required")
|
||||
|
||||
@@ -30,6 +30,18 @@ func ReadAnnotatedTag(ctx context.Context, repositoryDir, tag string) (Annotated
|
||||
if !validObjectID(object) {
|
||||
return AnnotatedTag{}, errors.New("invalid annotated tag object")
|
||||
}
|
||||
return ReadAnnotatedTagObject(ctx, repositoryDir, tag, object)
|
||||
}
|
||||
|
||||
// ReadAnnotatedTagObject verifies an explicitly recorded tag object even if
|
||||
// its local ref has already been removed.
|
||||
func ReadAnnotatedTagObject(ctx context.Context, repositoryDir, tag, object string) (AnnotatedTag, error) {
|
||||
if err := CheckTagRef(ctx, repositoryDir, tag); err != nil {
|
||||
return AnnotatedTag{}, err
|
||||
}
|
||||
if !validObjectID(object) {
|
||||
return AnnotatedTag{}, errors.New("invalid annotated tag object")
|
||||
}
|
||||
tagType, err := run(ctx, repositoryDir, nil, "cat-file", "-t", object)
|
||||
if err != nil {
|
||||
return AnnotatedTag{}, fmt.Errorf("inspect annotated tag: %w", err)
|
||||
|
||||
444
internal/rehearsal/cleanup.go
Normal file
444
internal/rehearsal/cleanup.go
Normal file
@@ -0,0 +1,444 @@
|
||||
package rehearsal
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"reflect"
|
||||
"time"
|
||||
|
||||
"go.maximumdirect.net/releasekit/internal/forge"
|
||||
"go.maximumdirect.net/releasekit/internal/git"
|
||||
"go.maximumdirect.net/releasekit/internal/woodpecker"
|
||||
)
|
||||
|
||||
const defaultCleanupTimeout = 2 * time.Minute
|
||||
|
||||
// ErrResourceConflict means an observed resource differs from recorded identity.
|
||||
var ErrResourceConflict = errors.New("diagnostic resource conflict")
|
||||
|
||||
func cleanupFailure(attempt *Attempt, result *Outcome, err error) {
|
||||
state := "unknown"
|
||||
if errors.Is(err, ErrResourceConflict) {
|
||||
state = "conflict"
|
||||
}
|
||||
attempt.Outcomes["cleanup"], result.Cleanup = state, state
|
||||
}
|
||||
|
||||
type RecoveryRequest struct {
|
||||
RecordPath string
|
||||
Backend forge.DiagnosticBackend
|
||||
Woodpecker woodpecker.Client
|
||||
ObservationTimeout, CleanupTimeout time.Duration
|
||||
Output io.Writer
|
||||
}
|
||||
|
||||
// Cleanup inspects only the explicitly recorded resources. Unobserved or
|
||||
// active CI prevents remote deletion; missing evidence is never quiescence.
|
||||
func Cleanup(ctx context.Context, request RecoveryRequest) (Outcome, error) {
|
||||
if request.CleanupTimeout < 0 {
|
||||
return Outcome{}, errors.New("cleanup timeout cannot be negative")
|
||||
}
|
||||
store, attempt, err := OpenStore(request.RecordPath)
|
||||
if err != nil {
|
||||
return Outcome{}, err
|
||||
}
|
||||
result := outcomeFromAttempt(store.Path, attempt)
|
||||
return cleanup(ctx, request, store, attempt, result)
|
||||
}
|
||||
|
||||
func cleanup(ctx context.Context, request RecoveryRequest, store *Store, attempt Attempt, result Outcome) (outcome Outcome, resultErr error) {
|
||||
defer func() { outcome.Attempt = attempt }()
|
||||
save := func() error { result.Attempt = attempt; return store.Save(attempt) }
|
||||
if attempt.Outcomes == nil {
|
||||
attempt.Outcomes = map[string]string{}
|
||||
}
|
||||
if attempt.Outcomes["cleanup"] == "complete" {
|
||||
result.Cleanup = "complete"
|
||||
return result, nil
|
||||
}
|
||||
timeout := request.CleanupTimeout
|
||||
if timeout == 0 {
|
||||
timeout = defaultCleanupTimeout
|
||||
}
|
||||
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), timeout)
|
||||
defer cancel()
|
||||
result.Cleanup = "pending"
|
||||
push := attempt.Outcomes["push"]
|
||||
if push != "not_attempted" && push != "dispatched" && push != "unknown" && push != "attempting" {
|
||||
return result, errors.New("record does not establish diagnostic dispatch state")
|
||||
}
|
||||
remoteComplete := attempt.Outcomes["cleanup-page"] == "complete" && attempt.Outcomes["cleanup-remote-tag"] == "complete"
|
||||
if push != "not_attempted" && !remoteComplete {
|
||||
if request.Backend == nil {
|
||||
return result, errors.New("diagnostic forge access is required")
|
||||
}
|
||||
preflight, ok := request.Backend.(interface{ Preflight(context.Context) error })
|
||||
if !ok {
|
||||
return result, errors.New("diagnostic forge preflight is unavailable")
|
||||
}
|
||||
if err := preflight.Preflight(cleanupCtx); err != nil {
|
||||
attempt.Outcomes["cleanup"] = "unknown"
|
||||
result.Cleanup = "unknown"
|
||||
return result, errors.Join(err, save())
|
||||
}
|
||||
if err := quiescent(cleanupCtx, request.Woodpecker, &attempt); err != nil {
|
||||
attempt.Outcomes["cleanup"] = "pending"
|
||||
return result, errors.Join(err, save())
|
||||
}
|
||||
if err := verifyRecordedTagObject(cleanupCtx, attempt); err != nil {
|
||||
cleanupFailure(&attempt, &result, err)
|
||||
return result, errors.Join(err, save())
|
||||
}
|
||||
endpoint, err := git.ObserveEndpoint(cleanupCtx, attempt.RepositoryDir, attempt.Endpoint, attempt.Remote)
|
||||
if err != nil {
|
||||
attempt.Outcomes["cleanup"] = "unknown"
|
||||
result.Cleanup = "unknown"
|
||||
return result, errors.Join(err, save())
|
||||
}
|
||||
remoteTag, err := endpoint.QueryTag(cleanupCtx, attempt.RepositoryDir, attempt.Manifest.Tag)
|
||||
if err != nil {
|
||||
attempt.Outcomes["cleanup"] = "unknown"
|
||||
result.Cleanup = "unknown"
|
||||
return result, errors.Join(err, save())
|
||||
}
|
||||
if remoteTag.State != git.RefAbsent && (remoteTag.State != git.RefPresent || !git.EqualObjectID(remoteTag.Object, attempt.TagObject) || !git.EqualObjectID(remoteTag.Peeled, attempt.Manifest.Commit)) {
|
||||
conflict := fmt.Errorf("remote tag differs from recorded identity: %w", ErrResourceConflict)
|
||||
cleanupFailure(&attempt, &result, conflict)
|
||||
return result, errors.Join(conflict, save())
|
||||
}
|
||||
// Recheck all matching runs immediately before the first destructive effect.
|
||||
if err := quiescent(cleanupCtx, request.Woodpecker, &attempt); err != nil {
|
||||
attempt.Outcomes["cleanup"] = "pending"
|
||||
return result, errors.Join(err, save())
|
||||
}
|
||||
if err := save(); err != nil {
|
||||
return result, fmt.Errorf("record CI cleanup observations: %w", err)
|
||||
}
|
||||
if err := deleteRecordedPage(cleanupCtx, request.Backend, &attempt, save); err != nil {
|
||||
cleanupFailure(&attempt, &result, err)
|
||||
return result, errors.Join(err, save())
|
||||
}
|
||||
if err := deleteRecordedRemoteTag(cleanupCtx, endpoint, &attempt, save); err != nil {
|
||||
cleanupFailure(&attempt, &result, err)
|
||||
return result, errors.Join(err, save())
|
||||
}
|
||||
}
|
||||
if push == "not_attempted" && attempt.Outcomes["tag"] == "planned" {
|
||||
attempt.Outcomes["cleanup-local-tag"] = "complete"
|
||||
if err := save(); err != nil {
|
||||
return result, err
|
||||
}
|
||||
} else if err := deleteRecordedLocalTag(cleanupCtx, &attempt, save); err != nil {
|
||||
cleanupFailure(&attempt, &result, err)
|
||||
return result, errors.Join(err, save())
|
||||
}
|
||||
attempt.Outcomes["cleanup"] = "complete"
|
||||
result.Cleanup = "complete"
|
||||
if err := save(); err != nil {
|
||||
return result, err
|
||||
}
|
||||
if request.Output != nil {
|
||||
if _, err := fmt.Fprintf(request.Output, "diagnostic cleanup complete for %s\n", attempt.Manifest.AttemptID); err != nil {
|
||||
return result, err
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func outcomeFromAttempt(path string, attempt Attempt) Outcome {
|
||||
out := Outcome{Attempt: attempt, RecordPath: path, Workflow: attempt.Outcomes["workflow"], Build: attempt.Outcomes["build"], Verification: attempt.Outcomes["verification"], Cleanup: attempt.Outcomes["cleanup"]}
|
||||
if out.Workflow == "" {
|
||||
out.Workflow = "not_started"
|
||||
}
|
||||
if out.Build == "" {
|
||||
out.Build = "not_started"
|
||||
}
|
||||
if out.Verification == "" {
|
||||
out.Verification = "not_started"
|
||||
}
|
||||
if out.Cleanup == "" {
|
||||
out.Cleanup = "pending"
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func verifyRecordedTagObject(ctx context.Context, attempt Attempt) error {
|
||||
if !git.ValidObjectID(attempt.TagObject) {
|
||||
return errors.New("recorded diagnostic tag object is unavailable")
|
||||
}
|
||||
tagged, err := git.ReadAnnotatedTagObject(ctx, attempt.RepositoryDir, attempt.Manifest.Tag, attempt.TagObject)
|
||||
if err != nil {
|
||||
return fmt.Errorf("inspect recorded diagnostic tag: %w", err)
|
||||
}
|
||||
if !git.EqualObjectID(tagged.Commit, attempt.Manifest.Commit) {
|
||||
return fmt.Errorf("recorded tag targets a different commit: %w", ErrResourceConflict)
|
||||
}
|
||||
manifest, err := DecodeManifest(tagged.Message)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !reflect.DeepEqual(manifest, attempt.Manifest) {
|
||||
return fmt.Errorf("recorded marker does not match the attempt: %w", ErrResourceConflict)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func quiescent(ctx context.Context, client woodpecker.Client, attempt *Attempt) error {
|
||||
matches, err := client.MatchingPipelines(ctx, attempt.Manifest.Tag, attempt.Manifest.Commit)
|
||||
if err != nil {
|
||||
return fmt.Errorf("observe CI before cleanup: %w", err)
|
||||
}
|
||||
if len(matches) == 0 {
|
||||
return errors.New("cleanup pending: no matching CI pipeline has reached completion")
|
||||
}
|
||||
if len(attempt.PipelineIDs) != len(attempt.PipelineNumbers) {
|
||||
return errors.New("cleanup pending: recorded CI identities are incomplete")
|
||||
}
|
||||
listedNumbers := make(map[int64]int64, len(matches))
|
||||
for _, listed := range matches {
|
||||
listedNumbers[listed.ID] = listed.Number
|
||||
}
|
||||
for index, id := range attempt.PipelineIDs {
|
||||
if listedNumbers[id] != attempt.PipelineNumbers[index] {
|
||||
return errors.New("cleanup pending: a previously observed CI pipeline is unavailable")
|
||||
}
|
||||
}
|
||||
var workflows []WorkflowObservation
|
||||
var jobs []JobObservation
|
||||
for _, listed := range matches {
|
||||
if !containsID(attempt.PipelineIDs, listed.ID) {
|
||||
attempt.PipelineIDs = append(attempt.PipelineIDs, listed.ID)
|
||||
attempt.PipelineNumbers = append(attempt.PipelineNumbers, listed.Number)
|
||||
}
|
||||
detail, err := client.DiagnosticPipeline(ctx, listed.Number, attempt.Manifest.Tag, attempt.Manifest.Commit)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, workflow := range detail.Workflows {
|
||||
workflows = append(workflows, WorkflowObservation{PipelineID: detail.ID, PipelineNumber: detail.Number, ID: workflow.ID, Name: workflow.Name, State: workflow.State})
|
||||
if workflow.Name == attempt.Workflow {
|
||||
for _, step := range workflow.Steps {
|
||||
if step.Name == attempt.Step {
|
||||
jobs = append(jobs, JobObservation{PipelineID: detail.ID, PipelineNumber: detail.Number, WorkflowID: workflow.ID, StepID: step.ID, PipelineStatus: detail.Status, WorkflowState: workflow.State, StepState: step.State})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
attempt.Workflows, attempt.Jobs = workflows, jobs
|
||||
if detail.ID != listed.ID || woodpecker.StateClass(detail.Status) != "terminal" {
|
||||
return errors.New("cleanup pending: a matching CI pipeline is active or unknown")
|
||||
}
|
||||
for _, workflow := range detail.Workflows {
|
||||
if woodpecker.StateClass(workflow.State) != "terminal" {
|
||||
return errors.New("cleanup pending: a matching CI workflow is active or unknown")
|
||||
}
|
||||
for _, step := range workflow.Steps {
|
||||
if woodpecker.StateClass(step.State) != "terminal" {
|
||||
return errors.New("cleanup pending: a matching CI step is active or unknown")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func forgeNotFound(err error) bool {
|
||||
var failure *forge.Failure
|
||||
return errors.As(err, &failure) && failure.Kind == forge.FailureNotFound
|
||||
}
|
||||
|
||||
func deleteRecordedPage(ctx context.Context, backend forge.DiagnosticBackend, attempt *Attempt, save func() error) error {
|
||||
if attempt.Outcomes["cleanup-page"] == "complete" {
|
||||
return nil
|
||||
}
|
||||
page, err := backend.FindDiagnosticRelease(ctx, attempt.Manifest.Tag)
|
||||
if forgeNotFound(err) {
|
||||
if attempt.PageID != 0 {
|
||||
observed, byIDErr := backend.ObserveDiagnosticRelease(ctx, attempt.PageID)
|
||||
if byIDErr == nil {
|
||||
return fmt.Errorf("recorded release %d still exists under tag %q: %w", observed.ID, observed.Release.Tag, ErrResourceConflict)
|
||||
}
|
||||
if !forgeNotFound(byIDErr) {
|
||||
return byIDErr
|
||||
}
|
||||
}
|
||||
attempt.Outcomes["cleanup-page"] = "complete"
|
||||
return save()
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
digest := sha256.Sum256([]byte(page.Release.Body))
|
||||
if page.ID <= 0 || (attempt.PageID != 0 && page.ID != attempt.PageID) || page.Release.Tag != attempt.Manifest.Tag || page.Release.Title != attempt.ExpectedPageTitle || hex.EncodeToString(digest[:]) != attempt.ExpectedBodySHA256 || page.Release.Draft || page.Release.Prerelease {
|
||||
return fmt.Errorf("hosted page differs from recorded identity: %w", ErrResourceConflict)
|
||||
}
|
||||
// Confirm the tag's commit before adopting or deleting a page.
|
||||
tagged, ok := backend.(interface {
|
||||
TagCommit(context.Context, string) (string, error)
|
||||
})
|
||||
if !ok {
|
||||
return errors.New("hosted tag observation is unavailable")
|
||||
}
|
||||
commit, err := tagged.TagCommit(ctx, attempt.Manifest.Tag)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !git.EqualObjectID(commit, attempt.Manifest.Commit) {
|
||||
return fmt.Errorf("hosted tag targets a different commit: %w", ErrResourceConflict)
|
||||
}
|
||||
if attempt.PageID == 0 {
|
||||
attempt.PageID = page.ID
|
||||
if err := save(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
attempt.Outcomes["cleanup-page"] = "deleting"
|
||||
if err := save(); err != nil {
|
||||
return err
|
||||
}
|
||||
_, deleteErr := backend.DeleteDiagnosticRelease(ctx, page.ID, attempt.Manifest.Tag)
|
||||
if deleteErr != nil {
|
||||
_, observeErr := backend.ObserveDiagnosticRelease(ctx, page.ID)
|
||||
if !forgeNotFound(observeErr) {
|
||||
return errors.Join(deleteErr, observeErr)
|
||||
}
|
||||
}
|
||||
// Confirm there is no replacement page at this tag.
|
||||
_, lookupErr := backend.FindDiagnosticRelease(ctx, attempt.Manifest.Tag)
|
||||
if !forgeNotFound(lookupErr) {
|
||||
if lookupErr == nil {
|
||||
return fmt.Errorf("a release still exists at the diagnostic tag: %w", ErrResourceConflict)
|
||||
}
|
||||
return lookupErr
|
||||
}
|
||||
attempt.Outcomes["cleanup-page"] = "complete"
|
||||
return save()
|
||||
}
|
||||
|
||||
func deleteRecordedRemoteTag(ctx context.Context, endpoint git.Endpoint, attempt *Attempt, save func() error) error {
|
||||
if attempt.Outcomes["cleanup-remote-tag"] == "complete" {
|
||||
return nil
|
||||
}
|
||||
observed, err := endpoint.QueryTag(ctx, attempt.RepositoryDir, attempt.Manifest.Tag)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if observed.State == git.RefAbsent {
|
||||
attempt.Outcomes["cleanup-remote-tag"] = "complete"
|
||||
return save()
|
||||
}
|
||||
if observed.State != git.RefPresent || !git.EqualObjectID(observed.Object, attempt.TagObject) || !git.EqualObjectID(observed.Peeled, attempt.Manifest.Commit) {
|
||||
return fmt.Errorf("remote tag differs from recorded identity: %w", ErrResourceConflict)
|
||||
}
|
||||
attempt.Outcomes["cleanup-remote-tag"] = "deleting"
|
||||
if err := save(); err != nil {
|
||||
return err
|
||||
}
|
||||
deleteErr := endpoint.DeleteDiagnosticTag(ctx, attempt.RepositoryDir, attempt.Manifest.Tag, attempt.TagObject, attempt.Manifest.Commit)
|
||||
observed, observeErr := endpoint.QueryTag(ctx, attempt.RepositoryDir, attempt.Manifest.Tag)
|
||||
if observeErr != nil {
|
||||
return errors.Join(deleteErr, observeErr)
|
||||
}
|
||||
if observed.State != git.RefAbsent {
|
||||
return errors.Join(deleteErr, errors.New("remote diagnostic tag remains or changed after deletion"))
|
||||
}
|
||||
attempt.Outcomes["cleanup-remote-tag"] = "complete"
|
||||
return save()
|
||||
}
|
||||
|
||||
func deleteRecordedLocalTag(ctx context.Context, attempt *Attempt, save func() error) error {
|
||||
if attempt.Outcomes["cleanup-local-tag"] == "complete" {
|
||||
return nil
|
||||
}
|
||||
state, tagged, err := git.QueryLocalDiagnosticTag(ctx, attempt.RepositoryDir, attempt.Manifest.Tag)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if state == git.RefAbsent {
|
||||
attempt.Outcomes["cleanup-local-tag"] = "complete"
|
||||
return save()
|
||||
}
|
||||
manifest, err := DecodeManifest(tagged.Message)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !reflect.DeepEqual(manifest, attempt.Manifest) || !git.EqualObjectID(tagged.Commit, attempt.Manifest.Commit) || (attempt.TagObject != "" && !git.EqualObjectID(tagged.Object, attempt.TagObject)) {
|
||||
return fmt.Errorf("local tag differs from recorded identity: %w", ErrResourceConflict)
|
||||
}
|
||||
if attempt.TagObject == "" {
|
||||
attempt.TagObject = tagged.Object
|
||||
if err := save(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
attempt.Outcomes["cleanup-local-tag"] = "deleting"
|
||||
if err := save(); err != nil {
|
||||
return err
|
||||
}
|
||||
deleteErr := git.DeleteLocalDiagnosticTag(ctx, attempt.RepositoryDir, attempt.Manifest.Tag, attempt.TagObject, attempt.Manifest.Commit)
|
||||
state, _, observeErr := git.QueryLocalDiagnosticTag(ctx, attempt.RepositoryDir, attempt.Manifest.Tag)
|
||||
if observeErr != nil {
|
||||
return errors.Join(deleteErr, observeErr)
|
||||
}
|
||||
if state != git.RefAbsent {
|
||||
return errors.Join(deleteErr, errors.New("local diagnostic tag remains or changed after deletion"))
|
||||
}
|
||||
attempt.Outcomes["cleanup-local-tag"] = "complete"
|
||||
return save()
|
||||
}
|
||||
|
||||
// Resume observes an existing dispatched attempt without pushing another tag,
|
||||
// then attempts cleanup using an independent bounded context.
|
||||
func Resume(ctx context.Context, request RecoveryRequest) (Outcome, error) {
|
||||
if request.ObservationTimeout < 0 || request.CleanupTimeout < 0 {
|
||||
return Outcome{}, errors.New("recovery timeouts cannot be negative")
|
||||
}
|
||||
store, attempt, err := OpenStore(request.RecordPath)
|
||||
if err != nil {
|
||||
return Outcome{}, err
|
||||
}
|
||||
result := outcomeFromAttempt(store.Path, attempt)
|
||||
if attempt.Outcomes["cleanup"] == "complete" {
|
||||
if !hasVerifiedEvidence(attempt) {
|
||||
return result, errors.New("recorded rehearsal verification did not complete")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
push := attempt.Outcomes["push"]
|
||||
if push != "not_attempted" && push != "dispatched" && push != "unknown" && push != "attempting" {
|
||||
return result, errors.New("record does not establish diagnostic dispatch state")
|
||||
}
|
||||
var observationErr error
|
||||
if push != "not_attempted" && !hasVerifiedEvidence(attempt) {
|
||||
observationCtx := ctx
|
||||
cancel := func() {}
|
||||
if request.ObservationTimeout > 0 {
|
||||
observationCtx, cancel = context.WithTimeout(ctx, request.ObservationTimeout)
|
||||
}
|
||||
result, observationErr = observe(observationCtx, request.Woodpecker, attempt.Workflow, attempt.Step, store, attempt, result)
|
||||
cancel()
|
||||
attempt = result.Attempt
|
||||
}
|
||||
result, cleanupErr := cleanup(ctx, request, store, attempt, result)
|
||||
if observationErr == nil && result.Verification != "complete" {
|
||||
observationErr = errors.New("recorded rehearsal verification did not complete")
|
||||
}
|
||||
return result, errors.Join(observationErr, cleanupErr)
|
||||
}
|
||||
|
||||
func hasVerifiedEvidence(attempt Attempt) bool {
|
||||
if attempt.Outcomes["verification"] != "complete" || attempt.JobEvidence == nil {
|
||||
return false
|
||||
}
|
||||
frame, err := EncodeResult(*attempt.JobEvidence)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
result, err := ReadResult(bytes.NewReader(frame), attempt.Manifest)
|
||||
return err == nil && result.Verification == "complete" && matchesPlannedAssets(attempt.PlannedAssets, result.Artifacts)
|
||||
}
|
||||
331
internal/rehearsal/cleanup_test.go
Normal file
331
internal/rehearsal/cleanup_test.go
Normal file
@@ -0,0 +1,331 @@
|
||||
package rehearsal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"go.maximumdirect.net/releasekit/internal/forge"
|
||||
"go.maximumdirect.net/releasekit/internal/git"
|
||||
"go.maximumdirect.net/releasekit/internal/releaseidentity"
|
||||
"go.maximumdirect.net/releasekit/internal/woodpecker"
|
||||
)
|
||||
|
||||
type diagnosticForge struct {
|
||||
mu sync.Mutex
|
||||
page forge.DiagnosticRelease
|
||||
commit string
|
||||
exists, uncertain bool
|
||||
deletes int
|
||||
}
|
||||
|
||||
func (b *diagnosticForge) Preflight(context.Context) error { return nil }
|
||||
|
||||
func (b *diagnosticForge) FindDiagnosticRelease(_ context.Context, tag string) (forge.DiagnosticRelease, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if !b.exists || b.page.Release.Tag != tag {
|
||||
return forge.DiagnosticRelease{}, &forge.Failure{Kind: forge.FailureNotFound}
|
||||
}
|
||||
return b.page, nil
|
||||
}
|
||||
func (b *diagnosticForge) ObserveDiagnosticRelease(_ context.Context, id int64) (forge.DiagnosticRelease, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if !b.exists || b.page.ID != id {
|
||||
return forge.DiagnosticRelease{}, &forge.Failure{Kind: forge.FailureNotFound}
|
||||
}
|
||||
return b.page, nil
|
||||
}
|
||||
func (b *diagnosticForge) DeleteDiagnosticRelease(_ context.Context, id int64, tag string) (forge.WriteEvidence, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if !b.exists || b.page.ID != id || b.page.Release.Tag != tag {
|
||||
return forge.WriteEvidence{Disposition: forge.WriteNotAttempted}, errors.New("wrong page")
|
||||
}
|
||||
b.exists = false
|
||||
b.deletes++
|
||||
if b.uncertain {
|
||||
return forge.WriteEvidence{Attempted: true, Disposition: forge.WriteUncertain}, errors.New("acknowledgment lost")
|
||||
}
|
||||
return forge.WriteEvidence{Attempted: true, Disposition: forge.WriteAccepted}, nil
|
||||
}
|
||||
func (b *diagnosticForge) TagCommit(context.Context, string) (string, error) { return b.commit, nil }
|
||||
|
||||
func cleanupFixture(t *testing.T) (string, string, Attempt, *Store, *diagnosticForge, *atomic.Bool, *httptest.Server) {
|
||||
t.Helper()
|
||||
repo, bare, commit := coordinatorFixture(t)
|
||||
profile, err := git.ReadCommitFile(t.Context(), repo, commit, "releasekit.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source, err := releaseidentity.LoadCommittedSource(t.Context(), repo, "", commit, &releaseidentity.SourceSpec{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
identity, id, err := releaseidentity.NewDiagnostic(t.Context(), source, "root", commit)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifest := NewManifest(identity, id, "root", "releasekit.json", profile)
|
||||
object, err := CreateDiagnosticTag(t.Context(), repo, manifest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
endpoint, err := git.Resolve(t.Context(), repo, "origin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := endpoint.PushDiagnosticTag(t.Context(), repo, identity.Tag, object, commit); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
note := DiagnosticNote("Example", manifest)
|
||||
sum := sha256.Sum256([]byte(note))
|
||||
title := strings.TrimPrefix(strings.SplitN(note, "\n", 2)[0], "# ")
|
||||
attempt := Attempt{Manifest: manifest, RepositoryDir: repo, Endpoint: bare, Remote: "origin", TagObject: object, ExpectedPageTitle: title, ExpectedBodySHA256: hex.EncodeToString(sum[:]), Workflow: "release", Step: "deliver", JobEvidence: &JobResult{Manifest: manifest, Scope: "page", Build: "not_requested", Delivery: "complete", Verification: "complete", PageID: 17, Artifacts: []ArtifactEvidence{}}, Outcomes: map[string]string{"tag": "created", "push": "dispatched", "workflow": "complete", "verification": "complete", "cleanup": "pending"}}
|
||||
store, err := CreateAttempt(t.Context(), repo, "", attempt)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
backend := &diagnosticForge{page: forge.DiagnosticRelease{ID: 17, Release: forge.Release{Tag: identity.Tag, Title: title, Body: note}}, commit: commit, exists: true}
|
||||
active := &atomic.Bool{}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
state := "success"
|
||||
if active.Load() {
|
||||
state = "running"
|
||||
}
|
||||
switch r.URL.Path {
|
||||
case "/api/repos/42/pipelines":
|
||||
if r.URL.Query().Get("page") != "1" {
|
||||
fmt.Fprint(w, `[]`)
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(w, `[{"id":3,"number":4,"event":"tag","ref":%q,"commit":%q,"status":%q}]`, "refs/tags/"+identity.Tag, commit, state)
|
||||
case "/api/repos/42/pipelines/4":
|
||||
fmt.Fprintf(w, `{"id":3,"number":4,"event":"tag","ref":%q,"commit":%q,"status":%q,"workflows":[{"id":5,"name":"release","state":%q,"children":[{"id":6,"name":"deliver","state":%q}]}]}`, "refs/tags/"+identity.Tag, commit, state, state, state)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
return repo, bare, attempt, store, backend, active, server
|
||||
}
|
||||
func cleanupRequest(store *Store, backend *diagnosticForge, server *httptest.Server) RecoveryRequest {
|
||||
return RecoveryRequest{RecordPath: store.Path, Backend: backend, Woodpecker: woodpecker.Client{BaseURL: server.URL, RepositoryID: 42, Token: "token"}}
|
||||
}
|
||||
func TestCleanupWaitsForRerunsAndReconcilesLostDelete(t *testing.T) {
|
||||
repo, bare, attempt, store, backend, active, server := cleanupFixture(t)
|
||||
defer server.Close()
|
||||
cmd := exec.Command("git", "tag", "v1.0.0", attempt.Manifest.Commit)
|
||||
cmd.Dir = repo
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("tag: %v %s", err, out)
|
||||
}
|
||||
cmd = exec.Command("git", "push", "origin", "refs/tags/v1.0.0")
|
||||
cmd.Dir = repo
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("push: %v %s", err, out)
|
||||
}
|
||||
active.Store(true)
|
||||
result, err := Cleanup(t.Context(), cleanupRequest(store, backend, server))
|
||||
if err == nil || result.Cleanup != "pending" || backend.deletes != 0 {
|
||||
t.Fatalf("active result=%+v error=%v deletes=%d", result, err, backend.deletes)
|
||||
}
|
||||
active.Store(false)
|
||||
backend.uncertain = true
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
result, err = Cleanup(ctx, cleanupRequest(store, backend, server))
|
||||
if err != nil || result.Cleanup != "complete" || backend.deletes != 1 {
|
||||
t.Fatalf("cleanup=%+v error=%v deletes=%d", result, err, backend.deletes)
|
||||
}
|
||||
local, _, err := git.QueryLocalDiagnosticTag(t.Context(), repo, attempt.Manifest.Tag)
|
||||
if err != nil || local != git.RefAbsent {
|
||||
t.Fatalf("local=%v error=%v", local, err)
|
||||
}
|
||||
ep, err := git.ObserveEndpoint(t.Context(), repo, bare, "origin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remote, err := ep.QueryTag(t.Context(), repo, attempt.Manifest.Tag)
|
||||
if err != nil || remote.State != git.RefAbsent {
|
||||
t.Fatalf("remote=%+v error=%v", remote, err)
|
||||
}
|
||||
production, err := ep.QueryTag(t.Context(), repo, "v1.0.0")
|
||||
if err != nil || production.State != git.RefPresent {
|
||||
t.Fatalf("production=%+v error=%v", production, err)
|
||||
}
|
||||
saved, err := LoadAttempt(store.Path)
|
||||
if err != nil || saved.Outcomes["cleanup"] != "complete" || saved.PageID != 17 {
|
||||
t.Fatalf("saved=%+v error=%v", saved, err)
|
||||
}
|
||||
if _, err := Cleanup(t.Context(), cleanupRequest(store, backend, server)); err != nil || backend.deletes != 1 {
|
||||
t.Fatalf("repeated cleanup error=%v deletes=%d", err, backend.deletes)
|
||||
}
|
||||
server.Close()
|
||||
resumed, err := Resume(t.Context(), RecoveryRequest{RecordPath: store.Path})
|
||||
if err != nil || resumed.Cleanup != "complete" || resumed.Verification != "complete" {
|
||||
t.Fatalf("resume completed record = %+v error=%v", resumed, err)
|
||||
}
|
||||
}
|
||||
func TestCleanupPreservesForeignPageAndChangedTag(t *testing.T) {
|
||||
for _, mode := range []string{"page", "tag"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
repo, _, attempt, store, backend, _, server := cleanupFixture(t)
|
||||
defer server.Close()
|
||||
if mode == "page" {
|
||||
backend.page.Release.Body = "different content"
|
||||
} else {
|
||||
cmd := exec.Command("git", "tag", "-f", "-a", attempt.Manifest.Tag, "-m", "foreign annotation", attempt.Manifest.Commit)
|
||||
cmd.Dir = repo
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("replace: %v %s", err, out)
|
||||
}
|
||||
cmd = exec.Command("git", "push", "--force", "origin", "refs/tags/"+attempt.Manifest.Tag)
|
||||
cmd.Dir = repo
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("push replacement: %v %s", err, out)
|
||||
}
|
||||
}
|
||||
result, err := Cleanup(t.Context(), cleanupRequest(store, backend, server))
|
||||
if !errors.Is(err, ErrResourceConflict) || result.Cleanup != "conflict" || backend.deletes != 0 {
|
||||
t.Fatalf("result=%+v error=%v deletes=%d", result, err, backend.deletes)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestCleanupBeforeDispatchRemovesOnlyOwnedLocalTag(t *testing.T) {
|
||||
repo, _, attempt, store, _, _, server := cleanupFixture(t)
|
||||
server.Close()
|
||||
// Use a new recorded identity whose tag was never pushed.
|
||||
source, err := releaseidentity.LoadCommittedSource(t.Context(), repo, "", attempt.Manifest.Commit, &releaseidentity.SourceSpec{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
identity, id, err := releaseidentity.NewDiagnostic(t.Context(), source, "root", attempt.Manifest.Commit)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
profile, err := git.ReadCommitFile(t.Context(), repo, identity.Commit, "releasekit.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifest := NewManifest(identity, id, "root", "releasekit.json", profile)
|
||||
object, err := CreateDiagnosticTag(t.Context(), repo, manifest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
local := Attempt{Manifest: manifest, RepositoryDir: repo, TagObject: object, Outcomes: map[string]string{"tag": "created", "push": "not_attempted", "cleanup": "pending"}}
|
||||
localStore, err := CreateAttempt(t.Context(), repo, "", local)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := Cleanup(t.Context(), RecoveryRequest{RecordPath: localStore.Path})
|
||||
if err != nil || result.Cleanup != "complete" {
|
||||
t.Fatalf("result=%+v err=%v", result, err)
|
||||
}
|
||||
state, _, err := git.QueryLocalDiagnosticTag(t.Context(), repo, manifest.Tag)
|
||||
if err != nil || state != git.RefAbsent {
|
||||
t.Fatalf("state=%v err=%v", state, err)
|
||||
}
|
||||
resumed, resumeErr := Resume(t.Context(), RecoveryRequest{RecordPath: localStore.Path})
|
||||
if resumeErr == nil || resumed.Cleanup != "complete" || resumed.Verification == "complete" {
|
||||
t.Fatalf("resume incomplete result=%+v error=%v", resumed, resumeErr)
|
||||
}
|
||||
if _, err := LoadAttempt(store.Path); err != nil {
|
||||
t.Fatalf("other attempt changed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupReconcilesLostGitDeleteAcknowledgment(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("POSIX shell Git wrapper")
|
||||
}
|
||||
_, _, _, store, backend, _, server := cleanupFixture(t)
|
||||
defer server.Close()
|
||||
realGit, err := exec.LookPath("git")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bin := t.TempDir()
|
||||
script := `#!/bin/sh
|
||||
lost=no
|
||||
for arg in "$@"; do case "$arg" in :refs/tags/releasekit-test/*) lost=yes ;; esac; done
|
||||
"$REHEARSAL_TEST_GIT" "$@"
|
||||
status=$?
|
||||
if [ "$lost" = yes ] && [ "$status" -eq 0 ]; then exit 77; fi
|
||||
exit "$status"
|
||||
`
|
||||
if err := os.WriteFile(filepath.Join(bin, "git"), []byte(script), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("REHEARSAL_TEST_GIT", realGit)
|
||||
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
result, err := Cleanup(t.Context(), cleanupRequest(store, backend, server))
|
||||
if err != nil || result.Cleanup != "complete" {
|
||||
t.Fatalf("result=%+v error=%v", result, err)
|
||||
}
|
||||
}
|
||||
func TestCleanupDoesNotInferQuiescenceFromMissingPipeline(t *testing.T) {
|
||||
_, _, _, store, backend, _, server := cleanupFixture(t)
|
||||
server.Close()
|
||||
empty := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `[]`) }))
|
||||
defer empty.Close()
|
||||
result, err := Cleanup(t.Context(), cleanupRequest(store, backend, empty))
|
||||
if err == nil || result.Cleanup != "pending" || backend.deletes != 0 {
|
||||
t.Fatalf("result=%+v error=%v deletes=%d", result, err, backend.deletes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupCompletesLocalWorkAfterRemoteCleanupWasRecorded(t *testing.T) {
|
||||
repo, bare, attempt, store, backend, _, server := cleanupFixture(t)
|
||||
server.Close()
|
||||
endpoint, err := git.ObserveEndpoint(t.Context(), repo, bare, "origin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := endpoint.DeleteDiagnosticTag(t.Context(), repo, attempt.Manifest.Tag, attempt.TagObject, attempt.Manifest.Commit); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
backend.exists = false
|
||||
attempt.Outcomes["cleanup-page"] = "complete"
|
||||
attempt.Outcomes["cleanup-remote-tag"] = "complete"
|
||||
if err := store.Save(attempt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := Cleanup(t.Context(), RecoveryRequest{RecordPath: store.Path})
|
||||
if err != nil || result.Cleanup != "complete" {
|
||||
t.Fatalf("result=%+v error=%v", result, err)
|
||||
}
|
||||
state, _, err := git.QueryLocalDiagnosticTag(t.Context(), repo, attempt.Manifest.Tag)
|
||||
if err != nil || state != git.RefAbsent {
|
||||
t.Fatalf("local=%v error=%v", state, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumeCancellationStillRunsBoundedCleanupWhenQuiescent(t *testing.T) {
|
||||
_, _, attempt, store, backend, _, server := cleanupFixture(t)
|
||||
defer server.Close()
|
||||
attempt.JobEvidence = nil
|
||||
attempt.Outcomes["verification"] = "incomplete"
|
||||
if err := store.Save(attempt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
result, err := Resume(ctx, cleanupRequest(store, backend, server))
|
||||
if !errors.Is(err, context.Canceled) || result.Cleanup != "complete" || result.Workflow != "unknown" || backend.deletes != 1 {
|
||||
t.Fatalf("result=%+v error=%v deletes=%d", result, err, backend.deletes)
|
||||
}
|
||||
}
|
||||
80
rehearsal.go
80
rehearsal.go
@@ -2,11 +2,13 @@ package releasekit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.maximumdirect.net/releasekit/internal/forge"
|
||||
"go.maximumdirect.net/releasekit/internal/rehearsal"
|
||||
"go.maximumdirect.net/releasekit/internal/woodpecker"
|
||||
)
|
||||
@@ -82,8 +84,12 @@ func (err *RehearsalError) Error() string { return "rehearsal: " + err.Err.Error
|
||||
func (err *RehearsalError) Unwrap() error { return err.Err }
|
||||
|
||||
// Rehearse validates captured inputs, records and pushes a temporary diagnostic
|
||||
// tag, and observes the selected CI job. It never loads ambient credentials.
|
||||
// tag, observes the selected CI job, and attempts bounded cleanup when safe.
|
||||
// It never loads ambient credentials or cancels the independent CI job.
|
||||
func Rehearse(ctx context.Context, request RehearsalRequest) (RehearsalResult, error) {
|
||||
if request.CleanupTimeout < 0 {
|
||||
return RehearsalResult{}, &RehearsalError{Err: errors.New("cleanup timeout cannot be negative")}
|
||||
}
|
||||
backend, err := deliveryBackend(request.Destination)
|
||||
if err != nil {
|
||||
return RehearsalResult{}, &RehearsalError{Err: err}
|
||||
@@ -93,6 +99,69 @@ func Rehearse(ctx context.Context, request RehearsalRequest) (RehearsalResult, e
|
||||
return RehearsalResult{}, &RehearsalError{Err: request.Woodpecker.CredentialError}
|
||||
}
|
||||
outcome, err := rehearsal.Start(ctx, rehearsal.StartRequest{RepositoryDir: request.RepositoryDir, Ref: request.Ref, ProfilePath: request.ProfilePath, ModuleDir: request.ModuleDir, Source: internalSourceSpec(request.Source), Product: request.Product, Selector: request.Selector, Remote: request.Remote, ExpectedPushURL: request.ExpectedPushURL, Build: build, RequiredFiles: request.RequiredFiles, ForgeBaseURL: request.Destination.BaseURL, ForgeOwner: request.Destination.Owner, ForgeRepository: request.Destination.Repository, Backend: backend, Woodpecker: woodpecker.Client{BaseURL: request.Woodpecker.BaseURL, RepositoryID: request.Woodpecker.RepositoryID, Token: request.Woodpecker.Token}, Workflow: request.Woodpecker.Workflow, Step: request.Woodpecker.Step, CIConfigured: request.CIConfigured, RecordDir: request.RecordDir, ObservationTimeout: time.Duration(request.ObservationTimeout), Output: request.Output})
|
||||
if outcome.RecordPath != "" {
|
||||
diagnostic, ok := backend.(forge.DiagnosticBackend)
|
||||
if !ok {
|
||||
err = errors.Join(err, errors.New("diagnostic forge cleanup is unavailable"))
|
||||
} else {
|
||||
cleaned, cleanupErr := rehearsal.Cleanup(ctx, rehearsal.RecoveryRequest{RecordPath: outcome.RecordPath, Backend: diagnostic, Woodpecker: woodpecker.Client{BaseURL: request.Woodpecker.BaseURL, RepositoryID: request.Woodpecker.RepositoryID, Token: request.Woodpecker.Token}, CleanupTimeout: time.Duration(request.CleanupTimeout), Output: request.Output})
|
||||
if cleaned.RecordPath != "" {
|
||||
outcome = cleaned
|
||||
}
|
||||
err = errors.Join(err, cleanupErr)
|
||||
}
|
||||
}
|
||||
result := publicRehearsalOutcome(outcome)
|
||||
if err != nil {
|
||||
return result, &RehearsalError{Err: err}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// RehearsalRecoveryRequest selects one saved attempt and supplies current
|
||||
// credentials explicitly. Destinations come from the saved attempt.
|
||||
type RehearsalRecoveryRequest struct {
|
||||
RecordPath string
|
||||
DeliveryToken string
|
||||
WoodpeckerToken string
|
||||
ObservationTimeout RehearsalTimeout
|
||||
CleanupTimeout RehearsalTimeout
|
||||
Output io.Writer
|
||||
}
|
||||
|
||||
// ResumeRehearsal resumes observation and then attempts bounded cleanup.
|
||||
func ResumeRehearsal(ctx context.Context, request RehearsalRecoveryRequest) (RehearsalResult, error) {
|
||||
return recoverRehearsal(ctx, request, true)
|
||||
}
|
||||
|
||||
// CleanupRehearsal checks quiescence and cleans only recorded resources.
|
||||
func CleanupRehearsal(ctx context.Context, request RehearsalRecoveryRequest) (RehearsalResult, error) {
|
||||
return recoverRehearsal(ctx, request, false)
|
||||
}
|
||||
|
||||
func recoverRehearsal(ctx context.Context, request RehearsalRecoveryRequest, resume bool) (RehearsalResult, error) {
|
||||
if request.ObservationTimeout < 0 || request.CleanupTimeout < 0 {
|
||||
return RehearsalResult{}, &RehearsalError{Err: errors.New("recovery timeouts cannot be negative")}
|
||||
}
|
||||
attempt, err := rehearsal.LoadAttempt(request.RecordPath)
|
||||
if err != nil {
|
||||
return RehearsalResult{RecordPath: request.RecordPath}, &RehearsalError{Err: err}
|
||||
}
|
||||
backend, err := deliveryBackend(DeliveryDestination{Forge: ForgeGitea, BaseURL: attempt.ForgeBaseURL, Owner: attempt.ForgeOwner, Repository: attempt.ForgeRepository, Token: request.DeliveryToken})
|
||||
if err != nil {
|
||||
return RehearsalResult{RecordPath: request.RecordPath}, &RehearsalError{Err: err}
|
||||
}
|
||||
diagnostic, ok := backend.(forge.DiagnosticBackend)
|
||||
if !ok {
|
||||
return RehearsalResult{RecordPath: request.RecordPath}, &RehearsalError{Err: errors.New("diagnostic forge cleanup is unavailable")}
|
||||
}
|
||||
internal := rehearsal.RecoveryRequest{RecordPath: request.RecordPath, Backend: diagnostic, Woodpecker: woodpecker.Client{BaseURL: attempt.WoodpeckerBaseURL, RepositoryID: attempt.WoodpeckerRepositoryID, Token: request.WoodpeckerToken}, ObservationTimeout: time.Duration(request.ObservationTimeout), CleanupTimeout: time.Duration(request.CleanupTimeout), Output: request.Output}
|
||||
var outcome rehearsal.Outcome
|
||||
if resume {
|
||||
outcome, err = rehearsal.Resume(ctx, internal)
|
||||
} else {
|
||||
outcome, err = rehearsal.Cleanup(ctx, internal)
|
||||
}
|
||||
result := publicRehearsalOutcome(outcome)
|
||||
if err != nil {
|
||||
return result, &RehearsalError{Err: err}
|
||||
@@ -113,11 +182,16 @@ func publicRehearsalOutcome(outcome rehearsal.Outcome) RehearsalResult {
|
||||
for _, number := range attempt.PipelineNumbers {
|
||||
result.PipelineURLs = append(result.PipelineURLs, fmt.Sprintf("%s/repos/%d/pipeline/%d", strings.TrimRight(attempt.WoodpeckerBaseURL, "/"), attempt.WoodpeckerRepositoryID, number))
|
||||
}
|
||||
if attempt.Outcomes["tag"] == "created" || attempt.Outcomes["tag"] == "unknown" {
|
||||
if attempt.Outcomes["cleanup-local-tag"] != "complete" && (attempt.Outcomes["tag"] == "created" || attempt.Outcomes["tag"] == "creating" || attempt.Outcomes["tag"] == "unknown") {
|
||||
result.Remaining = append(result.Remaining, "local diagnostic tag")
|
||||
}
|
||||
if attempt.Outcomes["push"] == "dispatched" || attempt.Outcomes["push"] == "unknown" || attempt.Outcomes["push"] == "attempting" {
|
||||
result.Remaining = append(result.Remaining, "remote diagnostic tag and possible hosted release")
|
||||
if attempt.Outcomes["cleanup-remote-tag"] != "complete" {
|
||||
result.Remaining = append(result.Remaining, "remote diagnostic tag")
|
||||
}
|
||||
if attempt.Outcomes["cleanup-page"] != "complete" {
|
||||
result.Remaining = append(result.Remaining, "possible hosted release")
|
||||
}
|
||||
}
|
||||
if attempt.JobEvidence != nil {
|
||||
for _, a := range attempt.JobEvidence.Artifacts {
|
||||
|
||||
Reference in New Issue
Block a user