execution

package
v1.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 31, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package execution 提供跨业务模块的公共执行记录、安全确认和取消约定。 Package execution provides shared execution records, safety confirmation, and cancellation contracts across modules.

Index

Constants

View Source
const (
	ErrorCodeNotFound             = "execution_not_found"
	ErrorCodePermissionDenied     = "permission_denied"
	ErrorCodeInvalidTransition    = "invalid_transition"
	ErrorCodeConcurrentUpdate     = "concurrent_update"
	ErrorCodeIdempotencyConflict  = "idempotency_conflict"
	ErrorCodeIdempotencyRequired  = "idempotency_key_required"
	ErrorCodeConfirmationRequired = "confirmation_required"
	ErrorCodeConfirmationInvalid  = "confirmation_invalid"
	ErrorCodeAdminRequired        = "admin_required"
	ErrorCodeNotCancellable       = "not_cancellable"
)
View Source
const (
	HeaderIdempotencyKey = "Idempotency-Key"
	HeaderConfirm        = "X-STX-Confirm"
	HeaderConfirmationID = "X-STX-Confirmation-ID"
	HeaderRequestID      = "X-Request-ID"
)
View Source
const (
	TriggerSourceRequest       = "request"
	TriggerSourceReconciler    = "reconciler"
	TriggerSourceScheduler     = "scheduler"
	TriggerSourceDolphinWorker = "dolphin_worker"
	TriggerSourceAgentCallback = "agent_callback"
)

TriggerSource 取值:谁写入了这次状态迁移。 TriggerSource values identify who wrote the state transition.

Variables

View Source
var (
	ErrExecutionNotFound     = errors.New("execution not found")
	ErrPermissionDenied      = errors.New("permission denied")
	ErrInvalidTransition     = errors.New("invalid execution status transition")
	ErrConcurrentUpdate      = errors.New("execution status changed concurrently")
	ErrIdempotencyConflict   = errors.New("idempotency key was already used with a different request")
	ErrIdempotencyKeyMissing = errors.New("idempotency key is required")
	ErrConfirmationRequired  = errors.New("operation confirmation is required")
	ErrConfirmationInvalid   = errors.New("operation confirmation is invalid or expired")
	ErrExplicitConfirmNeeded = errors.New("explicit confirmation is required")
	ErrAdminRequired         = errors.New("administrator permission is required")
	ErrNotCancellable        = errors.New("execution is not cancellable")
	ErrProviderNotRegistered = errors.New("execution cancellation provider is not registered")
	ErrInvalidExecution      = errors.New("invalid execution")
)

Functions

func CanTransition

func CanTransition(from, to Status) bool

CanTransition 判断公共执行状态是否允许迁移到目标状态。 CanTransition reports whether a public execution status may move to the target status.

func HashRequest

func HashRequest(value any) (string, error)

HashRequest 对规范 JSON 编码后的请求计算摘要,不应传入秘密原文以外的持久化用途。 HashRequest hashes the canonical JSON encoding of a request and must not be used to persist the original secret-bearing body.

func HashString

func HashString(value string) string

HashString 返回字符串的 SHA-256 十六进制摘要。 HashString returns the hexadecimal SHA-256 digest of a string.

func IsTerminal

func IsTerminal(status Status) bool

IsTerminal 判断状态是否已经结束。 IsTerminal reports whether a status is terminal.

func TriggerSourceFromContext added in v1.2.0

func TriggerSourceFromContext(ctx context.Context) string

TriggerSourceFromContext 读取 Transition 写入来源。 TriggerSourceFromContext reads the Transition writer source.

func WithTriggerSource added in v1.2.0

func WithTriggerSource(ctx context.Context, source string) context.Context

WithTriggerSource 标记本次 Transition 的写入来源。 WithTriggerSource marks the writer for this Transition.

func WriteError added in v1.0.0

func WriteError(c *gin.Context, err error)

WriteError 将公共执行错误写成统一的 HTTP 响应,供业务写接口复用。 WriteError writes a shared-execution error as a common HTTP response for business write endpoints.

Types

type Actor

type Actor struct {
	UserID  uint64
	IsAdmin bool
}

Actor 保存本次调用者的用户身份和管理员标记。 Actor stores the current user's identity and administrator flag.

type ActorType

type ActorType string

ActorType 表示执行由用户还是系统发起。 ActorType identifies whether an execution was started by a user or by the system.

const (
	ActorTypeUser   ActorType = "user"
	ActorTypeSystem ActorType = "system"
)

type AuthorizationInput

type AuthorizationInput struct {
	OperationID    string
	RiskLevel      RiskLevel
	Impact         string
	IdempotencyKey string
	RequestHash    string
	Confirmed      bool
	ConfirmationID string
}

AuthorizationInput 保存风险确认校验参数。 AuthorizationInput stores risk-confirmation validation parameters.

type CancelResult

type CancelResult struct {
	Status            Status
	Cancellable       bool
	CancellableReason string
}

CancelResult 描述业务模块实际接收取消请求后的状态。 CancelResult describes the state confirmed by a business module after receiving a cancellation request.

type CancellationProvider

type CancellationProvider interface {
	RequestCancel(ctx context.Context, execution *Execution, actor Actor) (CancelResult, error)
}

CancellationProvider 由业务模块实现,用于执行真实停止或确认安全取消点。 CancellationProvider is implemented by a business module to perform a real stop or confirm a safe cancellation point.

type Confirmation

type Confirmation struct {
	ID                 uint64     `json:"-" gorm:"primaryKey;autoIncrement"`
	ConfirmationHash   string     `json:"-" gorm:"size:64;uniqueIndex;not null"`
	OwnerUserID        uint64     `json:"owner_user_id" gorm:"not null;index"`
	OperationID        string     `json:"operation_id" gorm:"size:160;not null;index"`
	IdempotencyKeyHash string     `json:"-" gorm:"size:64;not null"`
	RequestHash        string     `json:"-" gorm:"size:64;not null"`
	RiskLevel          RiskLevel  `json:"risk_level" gorm:"size:4;not null"`
	Impact             string     `json:"impact" gorm:"type:text"`
	ExpiresAt          time.Time  `json:"expires_at" gorm:"not null;index"`
	ConsumedAt         *time.Time `json:"consumed_at,omitempty"`
	CreatedAt          time.Time  `json:"created_at" gorm:"autoCreateTime"`
}

Confirmation 保存一次性确认编号的哈希和绑定条件,不保存确认编号原文。 Confirmation stores a one-time confirmation hash and its binding conditions without the raw token.

func (Confirmation) TableName

func (Confirmation) TableName() string

TableName 返回一次性确认记录的固定表名。 TableName returns the fixed table name for one-time confirmation records.

type ConfirmationData

type ConfirmationData struct {
	ConfirmationRequired bool      `json:"confirmation_required"`
	ConfirmationID       string    `json:"confirmation_id"`
	RiskLevel            RiskLevel `json:"risk_level"`
	Impact               string    `json:"impact"`
	ExpiresAt            time.Time `json:"expires_at"`
}

ConfirmationData 返回危险操作的影响说明和一次性确认编号。 ConfirmationData returns impact information and a one-time confirmation ID for a risky operation.

type ConfirmationRequiredError

type ConfirmationRequiredError struct {
	ConfirmationID string
	RiskLevel      RiskLevel
	Impact         string
	ExpiresAt      time.Time
}

ConfirmationRequiredError 返回一次性确认编号和影响说明。 ConfirmationRequiredError returns a one-time confirmation ID and impact description.

func (*ConfirmationRequiredError) Error

func (e *ConfirmationRequiredError) Error() string

func (*ConfirmationRequiredError) Unwrap

func (e *ConfirmationRequiredError) Unwrap() error

type CreateInput

type CreateInput struct {
	OperationID       string
	OwnerUserID       uint64
	ActorType         ActorType
	Module            string
	ModuleRef         string
	RequestID         string
	IdempotencyKey    string
	RequestHash       string
	RiskLevel         RiskLevel
	Status            Status
	Cancellable       bool
	CancellableReason string
	ClientType        string
	ActorTokenID      *uint64
	TokenPrefix       string
	TokenName         string
	ClientIP          string
	UserAgent         string
	TriggerSource     string
}

CreateInput 保存创建公共执行记录所需的非敏感字段。 CreateInput stores the non-sensitive fields needed to create a shared execution record.

type Execution

type Execution struct {
	ID          uint64    `json:"-" gorm:"primaryKey;autoIncrement"`
	ExecutionID string    `json:"execution_id" gorm:"size:36;uniqueIndex;not null"`
	OperationID string    `json:"operation_id" gorm:"size:160;not null;index;uniqueIndex:idx_execution_idempotency"`
	OwnerUserID uint64    `json:"owner_user_id" gorm:"not null;index;uniqueIndex:idx_execution_idempotency"`
	ActorType   ActorType `json:"actor_type" gorm:"size:16;not null"`
	Module      string    `json:"module" gorm:"size:64;not null;index"`
	ModuleRef   string    `json:"module_ref" gorm:"size:160;index"`
	RequestID   string    `json:"request_id" gorm:"size:64;index"`
	// ClientType 记录发起端(cli/web/api/system),后续 start/result 审计沿用,避免被改写成 system。
	// ClientType records the originating client so later start/result audits keep it instead of rewriting system.
	ClientType string `json:"client_type,omitempty" gorm:"size:20"`
	// ActorTokenID / TokenPrefix / TokenName 保存创建时的 CLI 令牌,供异步 start/result 审计复用。
	// ActorTokenID / TokenPrefix / TokenName keep the creating CLI token for async start/result audits.
	ActorTokenID *uint64 `json:"actor_token_id,omitempty" gorm:"index"`
	TokenPrefix  string  `json:"token_prefix,omitempty" gorm:"size:16"`
	TokenName    string  `json:"token_name,omitempty" gorm:"size:100"`
	// ClientIP / UserAgent 保存创建时的请求归因,供异步审计复用。
	// ClientIP / UserAgent keep create-time request attribution for async audits.
	ClientIP  string `json:"client_ip,omitempty" gorm:"size:45"`
	UserAgent string `json:"user_agent,omitempty" gorm:"size:500"`
	// TriggerSource 区分写入方:request / reconciler / scheduler / dolphin_worker / agent_callback。
	// TriggerSource identifies the writer: request / reconciler / scheduler / dolphin_worker / agent_callback.
	TriggerSource      string     `json:"trigger_source,omitempty" gorm:"size:32"`
	IdempotencyKeyHash *string    `json:"-" gorm:"size:64;uniqueIndex:idx_execution_idempotency"`
	RequestHash        string     `json:"-" gorm:"size:64"`
	RiskLevel          RiskLevel  `json:"risk_level" gorm:"size:4;not null"`
	Status             Status     `json:"status" gorm:"size:32;not null;index"`
	Cancellable        bool       `json:"cancellable" gorm:"not null;default:false"`
	CancellableReason  string     `json:"cancellable_reason,omitempty" gorm:"size:160"`
	Progress           int        `json:"progress" gorm:"not null;default:0"`
	ResultRef          string     `json:"result_ref,omitempty" gorm:"size:500"`
	ErrorCode          string     `json:"error_code,omitempty" gorm:"size:80"`
	ErrorMessage       string     `json:"error_message,omitempty" gorm:"type:text"`
	StartedAt          *time.Time `json:"started_at,omitempty"`
	FinishedAt         *time.Time `json:"finished_at,omitempty"`
	CreatedAt          time.Time  `json:"created_at" gorm:"autoCreateTime;index"`
	UpdatedAt          time.Time  `json:"updated_at" gorm:"autoUpdateTime"`
}

Execution 保存统一执行协议所需的最小信息,不保存任务正文或敏感配置。 Execution stores the minimum shared execution contract without request bodies or sensitive configuration.

func (Execution) TableName

func (Execution) TableName() string

TableName 返回公共执行记录的固定表名。 TableName returns the fixed table name for shared execution records.

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler 提供公共执行查询、等待和取消接口。 Handler exposes shared execution get, wait, and cancel endpoints.

func NewHandler

func NewHandler(service *Service) *Handler

NewHandler 创建公共执行 HTTP 处理器。 NewHandler creates the shared execution HTTP handler.

func (*Handler) Cancel

func (h *Handler) Cancel(c *gin.Context)

Cancel 请求取消执行;接口只在业务模块确认停止后返回 cancelled。 Cancel requests cancellation and returns cancelled only after the business module confirms the stop. @Tags execution @Produce json @Param id path string true "公共执行编号" @Param Idempotency-Key header string true "幂等键" @Param X-STX-Confirm header bool true "确认取消影响" @Success 200 {object} Response @Router /api/v1/executions/{id}/cancel [post]

func (*Handler) Get

func (h *Handler) Get(c *gin.Context)

Get 读取当前用户有权查看的执行记录。 Get reads an execution visible to the current user. @Tags execution @Produce json @Param id path string true "公共执行编号" @Success 200 {object} Response @Router /api/v1/executions/{id} [get]

func (*Handler) Wait

func (h *Handler) Wait(c *gin.Context)

Wait 等待执行结束,最长等待三十秒。 Wait waits for completion for at most thirty seconds. @Tags execution @Produce json @Param id path string true "公共执行编号" @Param timeout_seconds query int false "服务端单次等待秒数,范围为 1 到 30" @Success 200 {object} Response @Router /api/v1/executions/{id}/wait [get]

type ProviderRegistry

type ProviderRegistry struct {
	// contains filtered or unexported fields
}

ProviderRegistry 按模块保存取消实现。 ProviderRegistry stores cancellation implementations by module.

func NewProviderRegistry

func NewProviderRegistry() *ProviderRegistry

NewProviderRegistry 创建空的业务取消实现登记表。 NewProviderRegistry creates an empty business cancellation provider registry.

func (*ProviderRegistry) Get

Get 返回模块对应的取消实现。 Get returns the cancellation provider registered for a module.

func (*ProviderRegistry) Register

func (r *ProviderRegistry) Register(module string, provider CancellationProvider)

Register 注册或替换一个模块的取消实现。 Register registers or replaces the cancellation provider for a module.

type Repository

type Repository struct {
	// contains filtered or unexported fields
}

Repository 负责公共执行记录和一次性确认记录的持久化。 Repository persists shared execution records and one-time confirmations.

func NewRepository

func NewRepository(db *gorm.DB) *Repository

NewRepository 创建公共执行仓储。 NewRepository creates a shared execution repository.

func (*Repository) BindModuleRef

func (r *Repository) BindModuleRef(ctx context.Context, executionID, moduleRef string) error

BindModuleRef 将公共执行记录绑定到业务模块任务,且不覆盖已经存在的绑定。 BindModuleRef binds a shared execution to its business task without replacing an existing binding.

func (*Repository) ConsumeConfirmation

func (r *Repository) ConsumeConfirmation(ctx context.Context, confirmationHash string, ownerUserID uint64, operationID, idempotencyKeyHash, requestHash string, now time.Time) error

ConsumeConfirmation 原子消费仍有效且尚未使用的确认记录。 ConsumeConfirmation atomically consumes a confirmation that is valid and unused.

func (*Repository) CreateConfirmation

func (r *Repository) CreateConfirmation(ctx context.Context, item *Confirmation) error

CreateConfirmation 保存一次性确认记录。 CreateConfirmation stores a one-time confirmation record.

func (*Repository) CreateOrGet

func (r *Repository) CreateOrGet(ctx context.Context, item *Execution) (*Execution, bool, error)

CreateOrGet 按幂等约定创建执行记录,或返回同一请求已创建的记录。 CreateOrGet creates an execution under the idempotency contract or returns the record created by the same request.

func (*Repository) GetByExecutionID

func (r *Repository) GetByExecutionID(ctx context.Context, executionID string) (*Execution, error)

GetByExecutionID 按对外执行编号读取记录。 GetByExecutionID loads a record by its public execution ID.

func (*Repository) UpdateStatus

func (r *Repository) UpdateStatus(ctx context.Context, executionID string, expected []Status, updates map[string]any) error

UpdateStatus 使用旧状态条件更新记录,防止迟到回调覆盖终态。 UpdateStatus updates a record with an expected-state condition so late callbacks cannot overwrite terminal states.

type RequestMetadata

type RequestMetadata struct {
	RequestID      string
	IdempotencyKey string
	Confirmed      bool
	ConfirmationID string
	ClientType     string
}

RequestMetadata 保存写操作所需的请求头信息。 RequestMetadata stores request header values required by write operations.

func MetadataFromGin

func MetadataFromGin(c *gin.Context) RequestMetadata

MetadataFromGin 从请求头读取安全执行元数据,并为缺失的请求编号生成 UUID。 MetadataFromGin reads safe-execution metadata from headers and creates a UUID when the request ID is absent.

type Response

type Response struct {
	ErrorCode string `json:"error_code,omitempty"`
	ErrorMsg  string `json:"error_msg,omitempty"`
	Data      any    `json:"data,omitempty"`
}

Response 是公共执行接口的统一响应。 Response is the common response envelope for execution endpoints.

type RiskLevel

type RiskLevel string

RiskLevel 表示操作对服务器或集群的影响等级。 RiskLevel represents the impact level of an operation on a server or cluster.

const (
	RiskLevelR0 RiskLevel = "R0"
	RiskLevelR1 RiskLevel = "R1"
	RiskLevelR2 RiskLevel = "R2"
	RiskLevelR3 RiskLevel = "R3"
)

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service 实现公共状态、权限、幂等、确认和取消规则。 Service implements shared state, access, idempotency, confirmation, and cancellation rules.

func NewService

func NewService(repo *Repository, providers *ProviderRegistry) *Service

NewService 创建公共执行服务。 NewService creates a shared execution service.

func (*Service) Authorize

func (s *Service) Authorize(ctx context.Context, actor Actor, input AuthorizationInput) error

Authorize 校验 R0 至 R3 的幂等键、显式确认、一次性确认和管理员要求。 Authorize validates idempotency, explicit confirmation, one-time confirmation, and administrator requirements for R0 through R3.

func (*Service) BeginSynchronous added in v1.0.0

func (s *Service) BeginSynchronous(ctx context.Context, actor Actor, input SynchronousInput) (*Execution, bool, error)

BeginSynchronous 校验确认与幂等约定,并创建同步写操作的运行记录。 BeginSynchronous validates confirmation and idempotency contracts and creates a running record for a synchronous write.

func (*Service) BindModuleRef

func (s *Service) BindModuleRef(ctx context.Context, executionID, moduleRef string) error

BindModuleRef 将公共执行记录绑定到业务模块任务编号。 BindModuleRef binds a shared execution to a business-module task identifier.

func (*Service) Cancel

func (s *Service) Cancel(ctx context.Context, actor Actor, executionID string) (*Execution, error)

Cancel 请求业务模块真实停止执行,重复请求返回同一取消进度。 Cancel asks the business module to stop the execution and returns the same cancellation progress for repeated requests.

func (*Service) Create

func (s *Service) Create(ctx context.Context, input CreateInput) (*Execution, bool, error)

Create 创建执行记录,风险操作应在调用前先通过 Authorize 校验。 Create creates an execution record; risky operations should call Authorize first.

func (*Service) EnrichAuditDetails added in v1.0.0

func (s *Service) EnrichAuditDetails(ctx context.Context, executionID string, extraDetails map[string]any) error

EnrichAuditDetails updates audit logs associated with an execution with extra details (e.g. engine URL).

func (*Service) FindIdempotent

func (s *Service) FindIdempotent(ctx context.Context, actor Actor, operationID, idempotencyKey, requestHash string) (*Execution, bool, error)

FindIdempotent 查找同一用户和操作下已存在的幂等执行记录。 FindIdempotent finds an existing idempotent execution for the same owner and operation.

func (*Service) FinishSynchronous added in v1.0.0

func (s *Service) FinishSynchronous(ctx context.Context, item *Execution, resultRef string, runErr error) error

FinishSynchronous 将同步写操作记录为成功或失败,只保存安全结果引用。 FinishSynchronous marks a synchronous write as succeeded or failed and stores only a safe result reference.

func (*Service) Get

func (s *Service) Get(ctx context.Context, actor Actor, executionID string) (*Execution, error)

Get 返回调用者有权查看的执行记录。 Get returns an execution visible to the current actor.

func (*Service) SetAuditRepository

func (s *Service) SetAuditRepository(repo *audit.Repository)

SetAuditRepository 设置公共执行服务使用的审计仓库。 SetAuditRepository sets the audit repository used by the shared execution service.

func (*Service) Transition

func (s *Service) Transition(ctx context.Context, executionID string, from, to Status, updates map[string]any) error

Transition 按当前状态条件执行公共状态迁移。 Transition performs a shared state transition guarded by the current status.

func (*Service) Wait

func (s *Service) Wait(ctx context.Context, actor Actor, executionID string, timeout time.Duration) (*Execution, bool, error)

Wait 等待执行进入终态;超时只结束本次等待,不修改任务状态。 Wait waits for a terminal state; a timeout ends only this wait and does not mutate the execution.

type Status

type Status string

Status 表示对外统一的执行状态。 Status represents the public execution status shared by all modules.

const (
	StatusPending         Status = "pending"
	StatusRunning         Status = "running"
	StatusCancelRequested Status = "cancel_requested"
	StatusCancelling      Status = "cancelling"
	StatusCancelled       Status = "cancelled"
	StatusSucceeded       Status = "succeeded"
	StatusFailed          Status = "failed"
	StatusTimedOut        Status = "timed_out"
)

type SynchronousInput added in v1.0.0

type SynchronousInput struct {
	OperationID    string
	Module         string
	ModuleRef      string
	RequestID      string
	IdempotencyKey string
	RequestHash    string
	RiskLevel      RiskLevel
	Impact         string
	Confirmed      bool
	ConfirmationID string
	ClientType     string
}

SynchronousInput 保存同步写操作开始执行所需的安全字段。 SynchronousInput stores the safe fields required to begin a synchronous write operation.

type WaitData

type WaitData struct {
	Execution *Execution `json:"execution"`
	TimedOut  bool       `json:"wait_timed_out"`
}

WaitData 返回最新执行记录和本次等待是否超时。 WaitData returns the latest execution record and whether this wait timed out.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL