Documentation
¶
Overview ¶
Package execution 提供跨业务模块的公共执行记录、安全确认和取消约定。 Package execution provides shared execution records, safety confirmation, and cancellation contracts across modules.
Index ¶
- Constants
- Variables
- func CanTransition(from, to Status) bool
- func HashRequest(value any) (string, error)
- func HashString(value string) string
- func IsTerminal(status Status) bool
- type Actor
- type ActorType
- type AuthorizationInput
- type CancelResult
- type CancellationProvider
- type Confirmation
- type ConfirmationData
- type ConfirmationRequiredError
- type CreateInput
- type Execution
- type Handler
- type ProviderRegistry
- type Repository
- func (r *Repository) BindModuleRef(ctx context.Context, executionID, moduleRef string) error
- func (r *Repository) ConsumeConfirmation(ctx context.Context, confirmationHash string, ownerUserID uint64, ...) error
- func (r *Repository) CreateConfirmation(ctx context.Context, item *Confirmation) error
- func (r *Repository) CreateOrGet(ctx context.Context, item *Execution) (*Execution, bool, error)
- func (r *Repository) GetByExecutionID(ctx context.Context, executionID string) (*Execution, error)
- func (r *Repository) UpdateStatus(ctx context.Context, executionID string, expected []Status, ...) error
- type RequestMetadata
- type Response
- type RiskLevel
- type Service
- func (s *Service) Authorize(ctx context.Context, actor Actor, input AuthorizationInput) error
- func (s *Service) BindModuleRef(ctx context.Context, executionID, moduleRef string) error
- func (s *Service) Cancel(ctx context.Context, actor Actor, executionID string) (*Execution, error)
- func (s *Service) Create(ctx context.Context, input CreateInput) (*Execution, bool, error)
- func (s *Service) FindIdempotent(ctx context.Context, actor Actor, ...) (*Execution, bool, error)
- func (s *Service) Get(ctx context.Context, actor Actor, executionID string) (*Execution, error)
- func (s *Service) SetAuditRepository(repo *audit.Repository)
- func (s *Service) Transition(ctx context.Context, executionID string, from, to Status, ...) error
- func (s *Service) Wait(ctx context.Context, actor Actor, executionID string, timeout time.Duration) (*Execution, bool, error)
- type Status
- type WaitData
Constants ¶
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" )
const ( HeaderIdempotencyKey = "Idempotency-Key" HeaderConfirm = "X-STX-Confirm" HeaderConfirmationID = "X-STX-Confirmation-ID" HeaderRequestID = "X-Request-ID" )
Variables ¶
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 ¶
CanTransition 判断公共执行状态是否允许迁移到目标状态。 CanTransition reports whether a public execution status may move to the target status.
func HashRequest ¶
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 ¶
HashString 返回字符串的 SHA-256 十六进制摘要。 HashString returns the hexadecimal SHA-256 digest of a string.
func IsTerminal ¶
IsTerminal 判断状态是否已经结束。 IsTerminal reports whether a status is terminal.
Types ¶
type Actor ¶
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.
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 ¶
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
}
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"`
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.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler 提供公共执行查询、等待和取消接口。 Handler exposes shared execution get, wait, and cancel endpoints.
func NewHandler ¶
NewHandler 创建公共执行 HTTP 处理器。 NewHandler creates the shared execution HTTP handler.
func (*Handler) Cancel ¶
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 ¶
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]
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 ¶
func (r *ProviderRegistry) Get(module string) (CancellationProvider, bool)
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 ¶
CreateOrGet 按幂等约定创建执行记录,或返回同一请求已创建的记录。 CreateOrGet creates an execution under the idempotency contract or returns the record created by the same request.
func (*Repository) GetByExecutionID ¶
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.
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 ¶
Authorize 校验 R0 至 R3 的幂等键、显式确认、一次性确认和管理员要求。 Authorize validates idempotency, explicit confirmation, one-time confirmation, and administrator requirements for R0 through R3.
func (*Service) BindModuleRef ¶
BindModuleRef 将公共执行记录绑定到业务模块任务编号。 BindModuleRef binds a shared execution to a business-module task identifier.
func (*Service) Cancel ¶
Cancel 请求业务模块真实停止执行,重复请求返回同一取消进度。 Cancel asks the business module to stop the execution and returns the same cancellation progress for repeated requests.
func (*Service) Create ¶
Create 创建执行记录,风险操作应在调用前先通过 Authorize 校验。 Create creates an execution record; risky operations should call Authorize first.
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) SetAuditRepository ¶
func (s *Service) SetAuditRepository(repo *audit.Repository)
SetAuditRepository 设置公共执行服务使用的审计仓库。 SetAuditRepository sets the audit repository used by the shared execution service.
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" )