225 lines
11 KiB
Go
225 lines
11 KiB
Go
package releasekit
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/url"
|
|
"strings"
|
|
"time"
|
|
|
|
"go.maximumdirect.net/releasekit/internal/forge"
|
|
"go.maximumdirect.net/releasekit/internal/rehearsal"
|
|
"go.maximumdirect.net/releasekit/internal/woodpecker"
|
|
)
|
|
|
|
// RehearsalTimeout is a duration expressed in nanoseconds, like time.Duration.
|
|
type RehearsalTimeout time.Duration
|
|
|
|
// RehearsalRequest supplies captured-source selection and explicit credentials.
|
|
// ProfilePath names a file in Ref, or in HEAD when Ref is empty. Product,
|
|
// Source, Build, and the CI credential declaration must correspond to that
|
|
// profile; the CLI verifies this binding before calling the facade.
|
|
type RehearsalRequest struct {
|
|
// RepositoryDir may name any directory in the checkout. Ref defaults to HEAD.
|
|
RepositoryDir string
|
|
Ref string
|
|
// ProfilePath must identify a file in Ref within the repository.
|
|
ProfilePath string
|
|
ModuleDir string
|
|
Source *SourceSpec
|
|
Product string
|
|
Selector string
|
|
Remote string
|
|
ExpectedPushURL string
|
|
Build *BuildSpec
|
|
RequiredFiles []string
|
|
Destination DeliveryDestination
|
|
Woodpecker WoodpeckerObservation
|
|
// CIConfigured asserts that the supplied selection declares CI delivery credentials.
|
|
// Rehearse also checks the committed profile for that declaration.
|
|
CIConfigured bool
|
|
// RecordDir overrides the Git-common-directory private record location.
|
|
RecordDir string
|
|
// ObservationTimeout zero observes until the context is canceled.
|
|
ObservationTimeout RehearsalTimeout
|
|
// CleanupTimeout is reserved for the independent cleanup operation; zero uses its default.
|
|
CleanupTimeout RehearsalTimeout
|
|
Output io.Writer
|
|
}
|
|
|
|
// RehearsalJob identifies an observed CI workflow and delivery step.
|
|
type RehearsalJob struct {
|
|
PipelineID, PipelineNumber, WorkflowID, StepID int64
|
|
PipelineStatus, WorkflowState, StepState string
|
|
}
|
|
|
|
// RehearsalWorkflow reports a workflow observed in a matching pipeline.
|
|
type RehearsalWorkflow struct {
|
|
PipelineID, PipelineNumber, ID int64
|
|
Name, State string
|
|
}
|
|
|
|
// RehearsalArtifact describes content verified by the delivery job.
|
|
type RehearsalArtifact struct {
|
|
Name string
|
|
Size int64
|
|
SHA256 string
|
|
}
|
|
|
|
// RehearsalResult retains partial outcomes and the explicit recovery record.
|
|
// Workflow, Build, Verification, and Cleanup describe independent observations;
|
|
// an error can accompany a partially or completely successful outcome.
|
|
type RehearsalResult struct {
|
|
AttemptID, Tag, Commit, ProfilePath, ProfileSHA256 string
|
|
Selector, SourceDir, DiagnosticVersion, Scope string
|
|
RecordPath, TagObject string
|
|
PageURL string
|
|
Workflow, Build, Verification, Cleanup string
|
|
PageID int64
|
|
PipelineIDs, PipelineNumbers []int64
|
|
PipelineURLs []string
|
|
Jobs []RehearsalJob
|
|
Workflows []RehearsalWorkflow
|
|
Artifacts []RehearsalArtifact
|
|
Remaining []string
|
|
Diagnostics []string
|
|
}
|
|
|
|
// RehearsalError preserves the underlying failure or cancellation with Unwrap.
|
|
type RehearsalError struct{ Err error }
|
|
|
|
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, 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}
|
|
}
|
|
var build = internalBuildSpec(request.Build)
|
|
if request.Woodpecker.CredentialError != nil {
|
|
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; no record
|
|
// is selected automatically. Zero observation timeout waits for cancellation,
|
|
// and zero cleanup timeout selects the bounded default.
|
|
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}
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func publicRehearsalOutcome(outcome rehearsal.Outcome) RehearsalResult {
|
|
attempt := outcome.Attempt
|
|
manifest := attempt.Manifest
|
|
result := RehearsalResult{AttemptID: manifest.AttemptID, Tag: manifest.Tag, Commit: manifest.Commit, ProfilePath: manifest.ProfilePath, ProfileSHA256: manifest.ProfileSHA256, Selector: manifest.Selector, SourceDir: manifest.SourceDir, DiagnosticVersion: manifest.DiagnosticVersion, RecordPath: outcome.RecordPath, TagObject: attempt.TagObject, Workflow: outcome.Workflow, Build: outcome.Build, Verification: outcome.Verification, Cleanup: outcome.Cleanup, PageID: attempt.PageID, PipelineIDs: append([]int64(nil), attempt.PipelineIDs...), PipelineNumbers: append([]int64(nil), attempt.PipelineNumbers...), Diagnostics: append([]string(nil), outcome.Diagnostics...)}
|
|
if outcome.RecordPath != "" {
|
|
result.Scope = "page"
|
|
if len(attempt.PlannedAssets) > 0 {
|
|
result.Scope = "page-and-assets"
|
|
}
|
|
}
|
|
if attempt.PageID > 0 && attempt.ForgeBaseURL != "" {
|
|
result.PageURL = strings.TrimRight(attempt.ForgeBaseURL, "/") + "/" + url.PathEscape(attempt.ForgeOwner) + "/" + url.PathEscape(attempt.ForgeRepository) + "/releases/tag/" + url.PathEscape(manifest.Tag)
|
|
}
|
|
for _, job := range attempt.Jobs {
|
|
result.Jobs = append(result.Jobs, RehearsalJob{PipelineID: job.PipelineID, PipelineNumber: job.PipelineNumber, WorkflowID: job.WorkflowID, StepID: job.StepID, PipelineStatus: job.PipelineStatus, WorkflowState: job.WorkflowState, StepState: job.StepState})
|
|
}
|
|
for _, workflow := range attempt.Workflows {
|
|
result.Workflows = append(result.Workflows, RehearsalWorkflow{PipelineID: workflow.PipelineID, PipelineNumber: workflow.PipelineNumber, ID: workflow.ID, Name: workflow.Name, State: workflow.State})
|
|
}
|
|
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["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" {
|
|
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 {
|
|
result.Scope = attempt.JobEvidence.Scope
|
|
for _, a := range attempt.JobEvidence.Artifacts {
|
|
result.Artifacts = append(result.Artifacts, RehearsalArtifact{Name: a.Name, Size: a.Size, SHA256: a.SHA256})
|
|
}
|
|
}
|
|
return result
|
|
}
|