Help us shape the future of Go! Take the 2026 Go Developer Survey

service

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2026 License: MIT Imports: 35 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrRepoNotFound is returned when a repository is not found.
	ErrRepoNotFound = errors.New("repo not found")

	// ErrTaskNotFound is returned when a sync task is not found.
	ErrTaskNotFound = errors.New("task not found")

	// ErrTaskDisabled is returned when attempting to run a disabled task.
	ErrTaskDisabled = errors.New("task is disabled")

	// ErrTaskRunning is returned when a task is already executing (concurrent run skipped).
	ErrTaskRunning = errors.New("task is already running")

	// ErrTooManyConcurrent is returned when the global concurrency limit is reached.
	ErrTooManyConcurrent = errors.New("too many concurrent sync tasks")

	// ErrRuleNotFound is returned when a webhook rule is not found.
	ErrRuleNotFound = errors.New("rule not found")

	// ErrEventNotFound is returned when a webhook event is not found.
	ErrEventNotFound = errors.New("event not found")

	// ErrPlatformNotFound 平台记录缺失:查询"任意错误或空记录"统一归一化为此哨兵,
	// 文案是对外契约(壳层 404 回传),不可改动。
	ErrPlatformNotFound = errors.New("platform not found")

	// ErrTargetPlatformNotFound 元数据回灌目标平台缺失(target_platform 查无记录)。
	ErrTargetPlatformNotFound = errors.New("target platform not found")

	// ErrTemplateNotFound 策略模板缺失(壳层回 404,文案是对外契约)。
	ErrTemplateNotFound = errors.New("template not found")

	// ErrTemplateCycle 模板继承链成环(壳层回 400,完整文案带链路)。
	ErrTemplateCycle = errors.New("template extends cycle")

	// ErrStarredUnsupported 平台不支持 starred 列举(壳层回 400,文案是对外契约)。
	ErrStarredUnsupported = errors.New("starred import currently supports github only")

	// ErrMetadataValidation 元数据请求/快照读取类错误的分类哨兵(壳层据此回 400)。
	// 具体文案由 metadataError.Error() 给出(如 "no snapshot for <key>"、
	// "sync.backup_dir not configured"),保持逐字契约。
	ErrMetadataValidation = errors.New("metadata validation")
)

Functions

func ClearGitHubAppTokenCache added in v0.6.0

func ClearGitHubAppTokenCache()

ClearGitHubAppTokenCache 清空缓存(测试用)。

func FetchGitHubInstallationToken added in v0.6.0

func FetchGitHubInstallationToken(ctxTimeout time.Duration, apiBase string, appID, installationID int64, privateKeyPEM string) (string, error)

FetchGitHubInstallationToken 用 JWT 换 installation access token。 平台实现带 ctx;这里沿用历史签名(ctxTimeout),包一层超时。

func IsPersonalOwner added in v0.7.0

func IsPersonalOwner(owner, targetUser string, orgOwners map[string]bool) bool

IsPersonalOwner 判定源 owner 是否个人命名空间。 orgOwners 为已知组织集合;owner 不在其中且等于 targetUser 时判为个人仓。

func MintGitHubAppJWT added in v0.6.0

func MintGitHubAppJWT(appID int64, privateKeyPEM string) (string, error)

MintGitHubAppJWT 用 App 私钥签发 JWT(RS256),iss=app_id,有效期最长 10 分钟。 这是 GitHub App 调 API 的第一层凭证,再换 installation access token。 签发逻辑在平台 githubapp.MintJWT,这里只保留导出名与错误风格。

func ResolvePlatformToken added in v0.6.0

func ResolvePlatformToken(p *model.Platform) (string, error)

ResolvePlatformToken 解析平台实际使用的访问令牌。 优先级:GitHub App installation token(若配置) > AccessToken。 App token 带缓存,过期前自动刷新。

func RewriteRepoURL added in v0.9.0

func RewriteRepoURL(raw, owner, repo string) string

RewriteRepoURL 把 clone URL 中的 owner/repo 换成目标(支持 https 与 ssh)。

func ValidForcePushPolicy added in v0.6.0

func ValidForcePushPolicy(p string) bool

ValidForcePushPolicy 校验策略字符串。

func ValidOrgMapStrategy added in v0.7.0

func ValidOrgMapStrategy(s string) bool

ValidOrgMapStrategy 校验策略。

Types

type AuditChainResult added in v0.6.0

type AuditChainResult struct {
	OK       bool   `json:"ok"`
	Checked  int    `json:"checked"`
	BrokenAt uint   `json:"broken_at,omitempty"`
	Message  string `json:"message"`
}

AuditChainResult 审计哈希链校验结果。

type AutoDiscoverOptions added in v0.6.0

type AutoDiscoverOptions struct {
	// ImportNew=true 时直接导入新仓库,否则只报告
	ImportNew bool
	Filter    *RepoImportFilter
}

AutoDiscoverOptions 自动发现参数。

type AutoRetryPolicy added in v0.9.0

type AutoRetryPolicy struct {
	// MaxAutoRetries 失败后的自动重跑次数;0=不自动重跑
	MaxAutoRetries int
	// Cooldown 两次自动重跑之间的冷却
	Cooldown time.Duration
}

AutoRetryPolicy 同一运行失败后的自动重跑策略。

type BackupManifest added in v0.6.0

type BackupManifest = executor.BackupManifest

BackupManifest = executor.BackupManifest

type BulkMirrorItem added in v0.9.0

type BulkMirrorItem struct {
	Source  string
	Target  string
	Action  string
	Message string
}

BulkMirrorItem 单仓映射结果。Action: planned|imported|task_created|skipped|failed

type BulkMirrorRequest added in v0.9.0

type BulkMirrorRequest struct {
	SourcePlatformKey string
	SourceOrg         string
	// TargetPlatform 已校验存在的目标平台(建仓用 ID / InstanceURL)。
	TargetPlatform *model.Platform
	Strategy       OrgMapStrategy
	TargetOrg      string
	TargetUser     string
	ImportNew      bool
	CreateTasks    bool
	DryRun         bool
}

BulkMirrorRequest 组织镜像请求(平台存在性校验由壳层完成并保留其文案)。

type BulkMirrorResult added in v0.9.0

type BulkMirrorResult struct {
	Planned      int
	Imported     int
	TasksCreated int
	Items        []*BulkMirrorItem
	Warnings     []string
}

BulkMirrorResult 组织镜像结果。

type BundleInfo added in v0.5.1

type BundleInfo = executor.BundleInfo

BundleInfo bundle 文件信息(executor 同构,便于壳层直接用)。

type Config

type Config = model.Config

type CreateMirrorChannelInput

type CreateMirrorChannelInput struct {
	Name    string              `json:"name"`
	Mode    string              `json:"mode"`
	RepoKey string              `json:"repoKey"`
	Targets []MirrorTargetInput `json:"targets"`
}

type Decision added in v0.9.0

type Decision struct {
	// Retry 是否应触发自动重跑
	Retry bool
	// Attempt 本次将要进行的第几次重跑(1 起)
	Attempt int
	// Reason 不重跑时的原因(可日志输出)
	Reason string
}

Decision 一次判定结果。

type DiscoveryReport added in v0.6.0

type DiscoveryReport struct {
	PlatformKey string    `json:"platform_key"`
	ScannedAt   time.Time `json:"scanned_at"`
	Found       int       `json:"found"`
	Existing    int       `json:"existing"`
	NewRepos    []string  `json:"new_repos"`
	Imported    int       `json:"imported"`
	Warnings    []string  `json:"warnings,omitempty"`
}

DiscoveryReport 自动发现结果。

type DriftItem added in v0.6.0

type DriftItem struct {
	TaskKey     string `json:"task_key"`
	RepoKey     string `json:"repo_key"`
	Branch      string `json:"branch"`
	LocalRef    string `json:"local_ref"`
	RemoteRef   string `json:"remote_ref,omitempty"`
	Drifted     bool   `json:"drifted"`
	LocalAhead  int    `json:"local_ahead"`
	RemoteAhead int    `json:"remote_ahead"`
	Message     string `json:"message"`
}

DriftItem 单个仓库的漂移检测结果。

type DriftReport added in v0.6.0

type DriftReport struct {
	Generated time.Time   `json:"generated"`
	Checked   int         `json:"checked"`
	Drifted   int         `json:"drifted"`
	Items     []DriftItem `json:"items"`
	Warnings  []string    `json:"warnings,omitempty"`
}

DriftReport 漂移检测汇总。

type DrillHistoryEntry added in v0.6.0

type DrillHistoryEntry = executor.DrillHistoryEntry

DrillHistoryEntry = executor.DrillHistoryEntry

type DrillReport added in v0.6.0

type DrillReport = executor.DrillReport

DrillReport = executor.DrillReport(壳层直接使用)

type ErrorClass added in v0.9.0

type ErrorClass string

ErrorClass 错误到传输层(HTTP)的分类契约:壳层据此选状态码, 不必逐个 errors.Is 哨兵。core 只给类别,不绑任何 Web 框架。

const (
	ErrorClassNotFound    ErrorClass = "not_found"
	ErrorClassConflict    ErrorClass = "conflict"
	ErrorClassValidation  ErrorClass = "validation"
	ErrorClassAuth        ErrorClass = "auth"
	ErrorClassRateLimited ErrorClass = "rate_limited"
	ErrorClassUnavailable ErrorClass = "unavailable"
	ErrorClassInternal    ErrorClass = "internal"
)

func Classify added in v0.9.0

func Classify(err error) ErrorClass

Classify 归类错误;err 为 nil 返回空串。 优先哨兵错误,其次 SDK provider 结构化错误,最后回落 internal。

type ExecuteMirrorRunInput

type ExecuteMirrorRunInput struct {
	TargetID       uint     `json:"targetId"`
	Tags           []string `json:"tags"`
	AllowOverwrite bool     `json:"allowOverwrite"`
	// Kind 省略时为 publish。
	Kind string `json:"kind"`
	// Module/Version 供 verify 类别使用。
	Version string `json:"-"`
}

type ForcePushApproval added in v0.9.0

type ForcePushApproval struct {
	ID         string     `json:"id"`
	TaskKey    string     `json:"task_key"`
	Branch     string     `json:"branch"`
	Reason     string     `json:"reason"`
	CreatedAt  time.Time  `json:"created_at"`
	Approved   bool       `json:"approved"`
	ApprovedBy string     `json:"approved_by,omitempty"`
	ApprovedAt *time.Time `json:"approved_at,omitempty"`
}

ForcePushApproval 一条审批记录。

type ForcePushPolicy added in v0.6.0

type ForcePushPolicy string

ForcePushPolicy 强制推送保护策略。

const (
	// ForcePushAllow 允许强制覆盖(原 keep_divergent=false 行为)
	ForcePushAllow ForcePushPolicy = "allow"
	// ForcePushBlock 遇分歧直接失败,不覆盖
	ForcePushBlock ForcePushPolicy = "block"
	// ForcePushBackupOnDemand 覆盖前自动打 bundle 快照(可回滚)
	ForcePushBackupOnDemand ForcePushPolicy = "backup_on_demand"
)

func ResolveForcePushPolicy added in v0.6.0

func ResolveForcePushPolicy(t *model.SyncTask) ForcePushPolicy

ResolveForcePushPolicy 从任务配置解析策略。 优先 task.ForcePushPolicy;否则按 keep_divergent 兼容映射。

type ForcePushStore added in v0.9.0

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

ForcePushStore 文件型审批存储,满足 executor.ForcePushApprover。

func NewForcePushStore added in v0.9.0

func NewForcePushStore(path string) *ForcePushStore

NewForcePushStore 打开审批存储(文件不存在=空列表)。

func (*ForcePushStore) Approve added in v0.9.0

func (st *ForcePushStore) Approve(id, actor string) (found bool, err error)

Approve 放行指定审批;未找到返回 found=false。

func (*ForcePushStore) IsForcePushApproved added in v0.9.0

func (st *ForcePushStore) IsForcePushApproved(taskKey, branch string) bool

IsForcePushApproved 查询任务+分支是否已放行(executor 分歧保护回调)。

func (*ForcePushStore) List added in v0.9.0

func (st *ForcePushStore) List() []ForcePushApproval

List 返回全部审批(文件不可读时返回空列表)。

func (*ForcePushStore) Path added in v0.9.0

func (st *ForcePushStore) Path() string

Path 审批文件路径。

func (*ForcePushStore) PendingCount added in v0.9.0

func (st *ForcePushStore) PendingCount() int

PendingCount 未放行条数。

func (*ForcePushStore) Request added in v0.9.0

func (st *ForcePushStore) Request(taskKey, branch, reason string) (ForcePushApproval, error)

Request 追加一条 pending 审批(HTTP 端点语义:不幂等,调用方校验入参)。

func (*ForcePushStore) RequestApproval added in v0.9.0

func (st *ForcePushStore) RequestApproval(taskKey, branch, reason string)

RequestApproval 满足 executor.ForcePushApprover:同 task+branch 已有 pending 则跳过, 写失败 best-effort(不影响同步主流程)。

type HealthScoreItem added in v0.9.0

type HealthScoreItem struct {
	Key    string   `json:"key"`
	Name   string   `json:"name"`
	Score  int      `json:"score"` // 0-100
	Level  string   `json:"level"` // gold/silver/bronze/basic
	Issues []string `json:"issues,omitempty"`
	// Dimensions 分项:reliability / freshness / schedule / safety / completeness
	Dimensions []health.Dimension `json:"dimensions,omitempty"`
	// Actions 建议动作(CLI 命令或人工步骤)
	Actions []string `json:"actions,omitempty"`
	// ActionItems 结构化动作(带可复制命令)
	ActionItems []health.Action `json:"action_items,omitempty"`
}

HealthScoreItem 单仓库/任务健康分(含 Scorecards 风格维度)。 JSON 标签与壳层历史响应逐字一致,前端/CLI 依赖。

type HealthSnapshot added in v0.9.0

type HealthSnapshot struct {
	Items   []HealthScoreItem
	Summary HealthSummary
}

HealthSnapshot 一次评分的完整结果。

type HealthSummary added in v0.9.0

type HealthSummary struct {
	Levels      map[string]int    `json:"levels"`
	BelowSilver int               `json:"below_silver"`
	TopActions  []string          `json:"top_actions"`
	Attention   []HealthScoreItem `json:"attention"`
}

HealthSummary 评分列表的聚合视图。

type InventoryItem added in v0.9.0

type InventoryItem struct {
	RepoKey       string   `json:"repo_key"`
	RepoName      string   `json:"repo_name"`
	Platform      string   `json:"platform,omitempty"`
	Status        string   `json:"status,omitempty"`
	HasTask       bool     `json:"has_task"`
	TaskKeys      []string `json:"task_keys,omitempty"`
	LastRunStatus string   `json:"last_run_status,omitempty"`
	LastRunAt     string   `json:"last_run_at,omitempty"`
	Coverage      string   `json:"coverage"` // covered | no_task | stale | failing
}

InventoryItem 仓库资产盘点项:有没有任务覆盖、最近执行。

type InventoryResult added in v0.9.0

type InventoryResult struct {
	Items   []InventoryItem
	Covered int
	Orphan  int
	Failing int
}

InventoryResult 资产盘点汇总。

type ManifestVerifyResult added in v0.6.0

type ManifestVerifyResult = executor.ManifestVerifyResult

ManifestVerifyResult = executor.ManifestVerifyResult

type MetadataBackupInfo added in v0.9.0

type MetadataBackupInfo = MetadataSnapshot

MetadataBackupInfo 列表条目(与快照清单同构)。

type MetadataBackupOptions added in v0.9.0

type MetadataBackupOptions struct {
	RepoKey         string
	MaxIssues       int
	MaxPRs          int
	MaxReleases     int
	MaxGists        int
	MaxAssets       int
	IncludeIssues   bool
	IncludePRs      bool
	IncludeReleases bool
	IncludeSource   bool // 源码归档(原 with_archives)
	IncludeAssets   bool // Release 附件(另受 Capabilities().ReleaseAssets 门控)
	IncludeGists    bool // Gists(另受 Capabilities().Gists 门控)
	Since           string
	DryRun          bool // 预留:当前备份无 dry-run 入参(壳层恒 false),不影响落盘行为
}

MetadataBackupOptions 元数据备份入参。 上限 ≤0 时按引擎缺省:issues/PRs/releases=500(>2000 截到 2000,与壳 max_items 口径一致)、gists=200、assets=100。 Include* 为解析后的布尔(壳层 optBoolDefault 缺省全开语义在壳侧完成)。 Since 为 RFC3339 增量:仅保留 updatedAt >= since 的 issue。

type MetadataBackupResult added in v0.9.0

type MetadataBackupResult struct {
	MetadataSnapshot
	Truncated bool
}

MetadataBackupResult 备份结果:嵌入快照字段(壳层整体转换为 ops.MetadataSnapshot)。 Truncated 为信息性标记(任一集合拉满上限即 true),不进 manifest/HTTP 响应。

type MetadataSnapshot added in v0.9.0

type MetadataSnapshot struct {
	RepoKey   string           `json:"repo_key"`
	Platform  string           `json:"platform"`
	Owner     string           `json:"owner"`
	Repo      string           `json:"repo"`
	CreatedAt string           `json:"created_at"`
	Dir       string           `json:"dir"`
	Counts    map[string]int32 `json:"counts"`
	Files     []string         `json:"files"`
	Archives  []string         `json:"archives"`
	Assets    []string         `json:"assets"`
	Warnings  []string         `json:"warnings"`
}

MetadataSnapshot 元数据快照清单(manifest.json 与 HTTP 响应共用结构)。 字段顺序与 JSON 标签对齐壳层 biz/model/ops.MetadataSnapshot(IDL 生成), 保证落盘文件与响应体逐字节兼容。

type MirrorService

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

MirrorService 镜像通道编排:通道 CRUD、源仓库本地克隆管理、 预检/执行/验证,底层调用 git-ferry-core/mirror。

func NewMirrorService

func NewMirrorService(svc *Service, db *gorm.DB) (*MirrorService, error)

func (*MirrorService) CreateMirrorChannel

func (m *MirrorService) CreateMirrorChannel(ctx context.Context, in CreateMirrorChannelInput) (*model.MirrorChannel, error)

CreateMirrorChannel 创建通道。publish 模式会先拉取源仓库并读取 go.mod, 提前暴露仓库不可达 / module 缺失 / 目标身份相同等问题。

func (*MirrorService) DeleteMirrorChannel

func (m *MirrorService) DeleteMirrorChannel(confirm string, id uint) error

func (*MirrorService) DeleteMirrorTarget

func (m *MirrorService) DeleteMirrorTarget(targetID uint) error

func (*MirrorService) ExecuteMirrorRun

func (m *MirrorService) ExecuteMirrorRun(ctx context.Context, channelID uint, in ExecuteMirrorRunInput) (*model.MirrorRun, error)

ExecuteMirrorRun 创建并异步执行一条镜像 run。同一通道同时只允许一个 进行中的执行(含预检外的写操作),避免克隆目录竞争。

func (*MirrorService) GetMirrorChannel

func (m *MirrorService) GetMirrorChannel(id uint) (*model.MirrorChannel, error)

func (*MirrorService) GetMirrorRun

func (m *MirrorService) GetMirrorRun(id uint) (*model.MirrorRun, error)

GetMirrorRun 单条执行记录详情。

func (*MirrorService) GetMirrorVersions

func (m *MirrorService) GetMirrorVersions(ctx context.Context, channelID uint) (*MirrorVersionsResult, error)

GetMirrorVersions 通道版本矩阵:tag × target 状态。

func (*MirrorService) ListMirrorChannels

func (m *MirrorService) ListMirrorChannels(page dao.Pagination) ([]*model.MirrorChannel, int64, error)

func (*MirrorService) ListMirrorRuns

func (m *MirrorService) ListMirrorRuns(channelID uint, page dao.Pagination) ([]*model.MirrorRun, int64, error)

ListMirrorRuns 分页列出通道执行记录。

func (*MirrorService) PreviewMirrorRun

func (m *MirrorService) PreviewMirrorRun(ctx context.Context, channelID, targetID uint, tag string) (*mirror.TagReport, error)

PreviewMirrorRun 对单个 tag 做预检(DryRun,不推送)。

func (*MirrorService) TestMirrorTarget

func (m *MirrorService) TestMirrorTarget(ctx context.Context, targetID uint) error

func (*MirrorService) UpdateMirrorTarget

func (m *MirrorService) UpdateMirrorTarget(ctx context.Context, targetID uint, in MirrorTargetInput) (*model.MirrorTarget, error)

UpdateMirrorTarget 更新目标(凭据为空串表示保持不变)。

func (*MirrorService) VerifyMirrorTargetVersion

func (m *MirrorService) VerifyMirrorTargetVersion(ctx context.Context, channelID, targetID uint, tag string) (*model.MirrorRun, error)

VerifyMirrorTargetVersion 验证目标 module@tag 可被 go 工具链消费。

type MirrorTargetInput

type MirrorTargetInput struct {
	Remote       string `json:"remote"`
	RepoURL      string `json:"repoUrl"`
	TargetModule string `json:"targetModule"`
	CredType     string `json:"credType"`
	// Credential 明文仅在创建/更新时提交,格式随 CredType:
	// token→token 值;ssh_key→私钥 PEM。存储前整体加密。
	Credential string `json:"credential"`
	Username   string `json:"username"`
}

type MirrorVersion

type MirrorVersion struct {
	Tag     string                `json:"tag"`
	Commit  string                `json:"commit,omitempty"`
	Targets []MirrorVersionTarget `json:"targets"`
}

type MirrorVersionTarget

type MirrorVersionTarget struct {
	TargetID   uint   `json:"targetId"`
	Target     string `json:"target"`
	State      string `json:"state"` // unpublished|published|divergent|failed
	ExecutedAt string `json:"executedAt,omitempty"`
	Commit     string `json:"commit,omitempty"`
	Tree       string `json:"tree,omitempty"`
	Verify     string `json:"verify"` // unverified|passed|failed
}

type MirrorVersionsResult

type MirrorVersionsResult struct {
	Mode     string          `json:"mode"`
	Module   string          `json:"module"`
	Versions []MirrorVersion `json:"versions"`
}

type OperationLogService

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

OperationLogService 处理审计日志相关操作。

func NewOperationLogService

func NewOperationLogService(opLogDAO *dao.OperationLogDAO) *OperationLogService

NewOperationLogService 创建新的 OperationLogService 实例。

func (*OperationLogService) List

func (s *OperationLogService) List(ctx context.Context, offset, limit int, filter *dao.OperationLogFilter) ([]*model.OperationLog, int64, error)

List 按过滤条件分页返回审计日志。

func (*OperationLogService) Record

func (s *OperationLogService) Record(ctx context.Context, entry *model.OperationLog) error

Record 记录一条审计日志(best-effort,由调用方决定如何处理错误)。 自动续接哈希链:EntryHash = SHA256(PrevHash || payload)。

func (*OperationLogService) Stats

func (s *OperationLogService) Stats(ctx context.Context) (today, week, total int64, err error)

Stats 返回今日、近 7 天(本周)、总操作数。单次 SQL 查询。

func (*OperationLogService) VerifyAuditChain added in v0.6.0

func (s *OperationLogService) VerifyAuditChain() (*AuditChainResult, error)

VerifyAuditChain 全量校验审计哈希链完整性。

type OpsTodoItem added in v0.9.0

type OpsTodoItem struct {
	ID       string          `json:"id"`
	Kind     string          `json:"kind"`     // health | orphan | rpo | drift
	Priority int             `json:"priority"` // 1=紧急
	TaskKey  string          `json:"task_key,omitempty"`
	RepoKey  string          `json:"repo_key,omitempty"`
	Title    string          `json:"title"`
	Reason   string          `json:"reason,omitempty"`
	Actions  []health.Action `json:"actions,omitempty"`
}

OpsTodoItem 统一待办项(Renovate Dependency Dashboard 模式)。

type OpsTrendsResult added in v0.9.0

type OpsTrendsResult struct {
	Days        int
	Items       []*TrendPoint
	Total       int
	Success     int
	Failed      int
	SuccessRate float64
}

OpsTrendsResult 趋势序列 + 汇总。

type Option added in v0.9.0

type Option func(*serviceOptions)

Option 装配期依赖注入。全部在 NewService 之前生效, 取代此前"先 SetProviderHooks 再 NewService"的时序约定。

func WithDB added in v0.9.0

func WithDB(db *gorm.DB) Option

WithDB 注入外部 *gorm.DB(调用方持有连接生命周期,core 不再自行 initDB/Close)。

func WithForcePushApprover added in v0.9.0

func WithForcePushApprover(a executor.ForcePushApprover) Option

WithForcePushApprover 注入分歧保护的审批实现(壳层 HTTP 审批流)。

func WithProviderHooks added in v0.9.0

func WithProviderHooks(h *sdkprov.Hooks) Option

WithProviderHooks 注入 provider 请求/响应生命周期钩子(壳层限流指标等)。 每次 provider 构造都会带上,无需再在 NewService 之前调用全局 SetProviderHooks。

type OrgMapOptions added in v0.9.0

type OrgMapOptions struct {
	// Strategy 策略;空视为 preserve。
	Strategy OrgMapStrategy
	// TargetOrg single 落点;MixedOrgToTarget 时作 mixed 组织仓落点。
	TargetOrg string
	// TargetUser flat 与 mixed 个人仓落点。
	TargetUser string
	// SourceIsPersonal 源为个人命名空间(mixed 个人仓判定)。
	// 组织镜像侧可用 IsPersonalOwner(owner, TargetUser, nil) 得到「owner 已等于目标用户」的等价判定。
	SourceIsPersonal bool
	// PreserveRedirect=true 时 preserve 分支按落点重定向:
	// 组织仓→TargetOrg、个人仓→TargetUser;false 保持源 owner。
	PreserveRedirect bool
	// MixedOrgToTarget=true 时 mixed 组织仓落 TargetOrg;false 保持源 owner。
	MixedOrgToTarget bool
	// RequireTarget=true 时 single/flat/mixed 个人仓缺落点返回错误;false 回落源 owner。
	RequireTarget bool
	// SourceKey owner/repo 为空时从此解析,支持 "platform/owner/repo" 或 "owner/repo"。
	SourceKey string
	// TargetPlatform 非空时拼 Result.Key。
	TargetPlatform string
}

OrgMapOptions 目标 owner/repo 落点选项。

各调用方语义不同,用显式开关表达,core 不做隐式改写:

导入(org_import):RequireTarget=true, MixedOrgToTarget=false, PreserveRedirect=false
组织镜像(org_mirror):MixedOrgToTarget=true, PreserveRedirect=false
落点缺失时 RequireTarget=true 报错,false 静默回落源 owner。

type OrgMapResult added in v0.9.0

type OrgMapResult struct {
	Owner string
	Repo  string
	// Key 形如 <platform>/<owner>/<repo>,仅 TargetPlatform 非空时填充。
	Key string
}

OrgMapResult 映射结果。

func ResolveOrgTarget added in v0.7.0

func ResolveOrgTarget(sourceOwner, sourceRepo string, o OrgMapOptions) (OrgMapResult, error)

ResolveOrgTarget 计算目标 owner/repo。策略语义见 OrgMapOptions 注释。

type OrgMapStrategy added in v0.7.0

type OrgMapStrategy string

OrgMapStrategy 批量镜像时目标仓落点策略(对标 gitea-mirror)。

const (
	// OrgMapPreserve 保持源 owner/repo 结构。
	OrgMapPreserve OrgMapStrategy = "preserve"
	// OrgMapSingle 全部落到同一 org,仓库名不变。
	OrgMapSingle OrgMapStrategy = "single"
	// OrgMapFlat 全部落到目标 user,仓库名不变。
	OrgMapFlat OrgMapStrategy = "flat"
	// OrgMapMixed 个人仓→flat;组织仓→见 OrgMapOptions.MixedOrgToTarget。
	OrgMapMixed OrgMapStrategy = "mixed"
)

func ParseStrategy added in v0.9.0

func ParseStrategy(s string) (OrgMapStrategy, error)

ParseStrategy 解析策略名;空串视为 preserve。

type OrgRepoItem added in v0.9.0

type OrgRepoItem struct {
	FullName string
	CloneURL string
	Fork     bool
	Archived bool
	Stars    int
}

OrgRepoItem 公开组织仓预览项。

type PlatformService

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

PlatformService 平台服务

func NewPlatformService

func NewPlatformService(platformDAO *dao.PlatformDAO, repoDAO *dao.RepoDAO, providerMgr *sdkprov.Manager) *PlatformService

NewPlatformService 创建 PlatformService

func (*PlatformService) CountReposByPlatform

func (s *PlatformService) CountReposByPlatform(ctx context.Context, platformKey string) (int64, error)

CountReposByPlatform 统计平台下的仓库数量(不加载数据)

func (*PlatformService) CreatePlatform

func (s *PlatformService) CreatePlatform(ctx context.Context, platform *model.Platform) error

CreatePlatform 创建平台

func (*PlatformService) DeletePlatform

func (s *PlatformService) DeletePlatform(ctx context.Context, key string) error

DeletePlatform 删除平台

func (*PlatformService) GetPlatform

func (s *PlatformService) GetPlatform(ctx context.Context, key string) (*model.Platform, error)

GetPlatform 获取平台

func (*PlatformService) GetPlatformByID

func (s *PlatformService) GetPlatformByID(ctx context.Context, id uint) (*model.Platform, error)

GetPlatformByID 根据 ID 获取平台

func (*PlatformService) ListPlatformRepos

func (s *PlatformService) ListPlatformRepos(ctx context.Context, key, page, perPage string) ([]*sdkprov.PlatformRepo, error)

ListPlatformRepos 列出平台上的仓库

func (*PlatformService) ListPlatforms

func (s *PlatformService) ListPlatforms(ctx context.Context) ([]*model.Platform, error)

ListPlatforms 列出所有平台

func (*PlatformService) ListReposByPlatform

func (s *PlatformService) ListReposByPlatform(ctx context.Context, platformKey string) ([]*model.Repo, error)

ListReposByPlatform 列出平台下的仓库

func (*PlatformService) SetDefaultPlatform

func (s *PlatformService) SetDefaultPlatform(ctx context.Context, key string) error

SetDefaultPlatform 设置默认平台

func (*PlatformService) SyncPlatformRepos

func (s *PlatformService) SyncPlatformRepos(ctx context.Context, key string) (int, error)

SyncPlatformRepos 同步平台仓库到本地 SyncPlatformRepos 同步平台仓库(不过滤)。

func (*PlatformService) SyncPlatformReposFiltered added in v0.5.0

func (s *PlatformService) SyncPlatformReposFiltered(ctx context.Context, key string, filter *RepoImportFilter) (int, error)

SyncPlatformReposFiltered 按过滤器同步平台仓库(排除 archived/fork 等)。

func (*PlatformService) TestPlatformConnection

func (s *PlatformService) TestPlatformConnection(ctx context.Context, key string) (*sdkprov.TestConnectionResult, error)

TestPlatformConnection 测试平台连接

func (*PlatformService) UpdatePlatform

func (s *PlatformService) UpdatePlatform(ctx context.Context, platform *model.Platform) error

UpdatePlatform 更新平台

func (*PlatformService) UpdatePlatformStatus

func (s *PlatformService) UpdatePlatformStatus(ctx context.Context, key, status, testResult string) error

UpdatePlatformStatus 更新平台状态

type PublicOrgImportRequest added in v0.9.0

type PublicOrgImportRequest struct {
	PlatformKey    string
	Org            string
	CreateTasks    bool
	TargetPlatform string
	TargetOrg      string
	Filter         *RepoImportFilter
	DryRun         bool
	Max            int
}

PublicOrgImportRequest 公开组织仓导入请求(入参已由壳层校验/归一化)。

type PublicOrgImportResult added in v0.9.0

type PublicOrgImportResult struct {
	Items        []OrgRepoItem
	Warnings     []string
	Imported     int
	CreatedTasks int
}

PublicOrgImportResult 导入结果。

type RPOMetric added in v0.6.0

type RPOMetric struct {
	TaskKey      string    `json:"task_key"`
	RepoKey      string    `json:"repo_key,omitempty"`
	LatestBundle string    `json:"latest_bundle"`
	LastBackupAt time.Time `json:"last_backup_at"`
	BundleCount  int       `json:"bundle_count"`
	TotalSize    int64     `json:"total_size"`
	RPOSeconds   int64     `json:"rpo_seconds"`
	RPOHuman     string    `json:"rpo_human"`
	RPOViolated  bool      `json:"rpo_violated"`
	EstRTO       string    `json:"est_rto"`
}

RPOMetric 单任务/仓库的恢复点观测。

type RPOReport added in v0.6.0

type RPOReport struct {
	Generated       time.Time   `json:"generated"`
	BackupDir       string      `json:"backup_dir"`
	RPOMaxSeconds   int64       `json:"rpo_max_seconds"`
	OverallRPOSec   int64       `json:"overall_rpo_seconds"`
	OverallRPOHuman string      `json:"overall_rpo_human"`
	WorstTask       string      `json:"worst_task"`
	Violations      int         `json:"violations"`
	Metrics         []RPOMetric `json:"metrics"`
}

RPOReport 全量 RPO/RTO 观测。

type RepoImportFilter added in v0.5.0

type RepoImportFilter struct {
	ExcludeArchived bool
	ExcludeForks    bool
	MinStars        int
	// IncludeLanguage 只导入该语言(空=不过滤)
	IncludeLanguage string
	// IncludeGlobs / ExcludeGlobs 按 FullName 匹配
	IncludeGlobs []string
	ExcludeGlobs []string
}

RepoImportFilter 平台仓库导入过滤(借鉴 gickup filter.*)。

func (*RepoImportFilter) Allow added in v0.5.0

Allow 判断仓库是否应导入。

type RepoService

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

RepoService handles repository-related operations.

func NewRepoService

func NewRepoService(repoDAO *dao.RepoDAO, platformDAO *dao.PlatformDAO, providerMgr *sdkprov.Manager) *RepoService

NewRepoService creates a new RepoService instance.

func (*RepoService) CountRepos

func (rs *RepoService) CountRepos() (int64, error)

CountRepos returns the total repo count via COUNT aggregate.

func (*RepoService) CreateRepo

func (rs *RepoService) CreateRepo(ctx context.Context, req *model.CreateRepoRequest) (*model.Repo, error)

CreateRepo creates a new repository.

func (*RepoService) DeleteRepo

func (rs *RepoService) DeleteRepo(ctx context.Context, key string) error

DeleteRepo deletes a repository by key.

func (*RepoService) GetRepo

func (rs *RepoService) GetRepo(ctx context.Context, key string) (*model.Repo, error)

GetRepo returns a repository by key.

func (*RepoService) GetRepoByKey

func (rs *RepoService) GetRepoByKey(key string) (*model.Repo, error)

GetRepoByKey returns a repository by key.

func (*RepoService) GetRepoWithProvider

func (rs *RepoService) GetRepoWithProvider(repoKey string) (*model.Repo, sdkprov.Provider, error)

GetRepoWithProvider 一次调用完成 repo 查找 + provider 解析, 消除调用方重复的 "GetRepoByKey → nil check → resolveRepoProvider" 样板。

func (*RepoService) ListBranches

func (rs *RepoService) ListBranches(ctx context.Context, repoKey string) ([]string, error)

ListBranches returns a list of branches for a repository.

func (*RepoService) ListRepos

func (rs *RepoService) ListRepos(ctx context.Context, offset, limit int) ([]*model.Repo, int64, error)

ListRepos returns a paginated list of repositories.

func (*RepoService) ListReposWithFilter

func (rs *RepoService) ListReposWithFilter(ctx context.Context, offset, limit int, filter *dao.RepoFilter) ([]*model.Repo, int64, error)

ListReposWithFilter returns a filtered, sorted, paginated list of repositories.

func (*RepoService) SetWebhookSecret

func (rs *RepoService) SetWebhookSecret(repoKey, secret string) error

SetWebhookSecret 设置仓库的 Webhook 密钥(经 repo_dao 加密落库),供入站验签使用。

func (*RepoService) TestConnection

func (rs *RepoService) TestConnection(ctx context.Context, repoKey string) (*model.TestConnectionResult, error)

TestConnection tests the connection to a repository.

func (*RepoService) UpdateRepo

func (rs *RepoService) UpdateRepo(ctx context.Context, req *model.UpdateRepoRequest) (*model.Repo, error)

UpdateRepo updates an existing repository.

type RestoreItem added in v0.9.0

type RestoreItem struct {
	Kind   string `json:"kind"`
	Name   string `json:"name"`
	Action string `json:"action"` // created | skipped | failed(dry-run 下 created 表示"将会创建")
	Error  string `json:"error,omitempty"`
}

RestoreItem 回灌逐条明细。

type RestoreKindStat added in v0.9.0

type RestoreKindStat struct {
	Planned int `json:"planned"`
	Created int `json:"created"`
	Skipped int `json:"skipped"`
	Failed  int `json:"failed"`
}

RestoreKindStat 单类回灌统计(JSON 标签与壳 ops.RestoreKindStat 一致)。

type RestoreRequest added in v0.9.0

type RestoreRequest struct {
	RepoKey        string
	SnapshotDir    string
	Kinds          []string
	DryRun         bool
	Overwrite      bool
	TargetPlatform string // 平台 key,空 = repo 关联平台
	TargetOwner    string // 空 = repo.PlatformOwner
	TargetRepo     string // 空 = repo.PlatformRepo
}

RestoreRequest 元数据回灌入参。Kinds 空时按快照内存在的分片推导 (labels|milestones|issues|prs|releases)。

type RestoreResult added in v0.9.0

type RestoreResult struct {
	SnapshotDir string                      `json:"snapshot_dir"`
	Target      string                      `json:"target"`
	Stats       map[string]*RestoreKindStat `json:"stats"`
	Warnings    []string                    `json:"warnings"`
	DryRun      bool                        `json:"dry_run"`
	StartedAt   string                      `json:"started_at"`
	FinishedAt  string                      `json:"finished_at"`
	Applied     int                         `json:"applied"`
	Skipped     int                         `json:"skipped"`
	Failed      int                         `json:"failed"`
	Details     []RestoreItem               `json:"details"`
}

RestoreResult 回灌结果。SnapshotDir/Target/Stats/Warnings/DryRun/StartedAt/ FinishedAt 与壳 ops.MetadataRestoreResult 同构(历史落盘走 restoreHistoryRecord, 文件格式不含扩展字段);Applied/Skipped/Failed 是 Stats 的聚合视图, Details 为逐条明细。

type RetryTracker added in v0.9.0

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

RetryTracker 自动重跑计数器(进程内;多实例部署时各实例只认自己触发的重跑, 与 runwatch 历史行为一致)。

func NewRetryTracker added in v0.9.0

func NewRetryTracker(maxKeep int) *RetryTracker

NewRetryTracker 创建计数器;maxKeep<=0 时用默认 1000。

func (*RetryTracker) ShouldRetry added in v0.9.0

func (t *RetryTracker) ShouldRetry(run *model.SyncRun, p AutoRetryPolicy) Decision

ShouldRetry 判定该失败运行是否应自动重跑,并在放行时记账。 只对 Status=failed 的运行放行;成功运行直接跳过。

type RunEvent added in v0.9.0

type RunEvent struct {
	TaskKey string
	// Run 完成态快照(CreateRun 失败时为 nil)。
	Run     *model.SyncRun
	Trigger string
	// Err Execute 返回的错误(结果本身以 Run.Status 为准)。
	Err error
	At  time.Time
}

RunEvent 一次运行结束的事件。

type Service

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

func NewService

func NewService(cfg *Config, opts ...Option) (*Service, error)

func (*Service) ApplyTemplate added in v0.9.0

func (s *Service) ApplyTemplate(ctx context.Context, templateID string, dryRun bool) (*TemplateApplyResult, error)

ApplyTemplate 批量套用策略模板:沿 Extends 链合并 Spec(子覆盖父), 只更新已存在任务的 cron/启用位;不隐式创建任务,避免误建。

func (*Service) AutoDiscover added in v0.6.0

func (s *Service) AutoDiscover(ctx context.Context, platformKey string, opts AutoDiscoverOptions) (*DiscoveryReport, error)

AutoDiscover 扫描平台仓库,找出本地尚未登记的(可选自动导入)。 借鉴 gitea-mirror 的 auto-discovery:新仓库自动入册,无需人工点选。

func (*Service) AutoRetry added in v0.9.0

func (s *Service) AutoRetry() *RetryTracker

AutoRetry 返回失败自动补偿的策略计数器(NewService 建好)。

func (*Service) BackupDir added in v0.5.1

func (s *Service) BackupDir() string

BackupDir 返回配置的冷备目录。

func (*Service) BackupGists added in v0.9.0

func (s *Service) BackupGists(ctx context.Context, prov sdkprov.Provider, destDir string, maxGists int) (count int, warnings []string, err error)

BackupGists 拉取 token 用户可见的 gists(分页到 maxGists 为止)并逐个写 JSON 文件。 返回成功落盘条数与逐条 warning;平台不声明 Gists 能力时报错。

func (*Service) BackupMetadata added in v0.9.0

BackupMetadata 抓取 issues/PR/labels/milestones/releases 元数据快照, 可选下载 source archive / GitHub Release 附件 / Gists。 provider 经 ProviderForPlatform 获取(Manager 缓存 + GitHub App token 感知)。 校验顺序与历史壳层一致:repo → platform → provider → backup_dir → 落盘。

func (*Service) BatchDRDrill added in v0.6.0

func (s *Service) BatchDRDrill(ctx context.Context, names []string, max int) ([]*DrillReport, map[string]any, error)

BatchDRDrill 演练多个 bundle(空=目录下全部,最多 max 个)。

func (*Service) BuildBackupManifest added in v0.6.0

func (s *Service) BuildBackupManifest() (*executor.BackupManifest, error)

BuildBackupManifest 生成并保存冷备完整性清单。

func (*Service) BulkMirrorOrg added in v0.9.0

func (s *Service) BulkMirrorOrg(ctx context.Context, req BulkMirrorRequest) (*BulkMirrorResult, error)

BulkMirrorOrg 按策略把源组织仓库映射到目标命名空间,并可选建同步任务。 顺序:(可选)同步源平台仓库 → 过滤源组织 → 映射 → 建仓 → 建任务。

func (*Service) CleanupExpiredBackups added in v0.6.0

func (s *Service) CleanupExpiredBackups() (removed int, err error)

CleanupExpiredBackups 按 retention 天数清理过期冷备(legal_hold 时拒绝执行)。 返回删除数量。与 BackupKeep 轮转互补:keep 管数量,retention 管时效。

func (*Service) CleanupOldData

func (s *Service) CleanupOldData(ctx context.Context, maxAge time.Duration) (events, runs, steps int64, err error)

func (*Service) CompleteRun

func (s *Service) CompleteRun(run *model.SyncRun) error

CompleteRun updates a sync run with final status and details. Satisfies executor.RunManager.

func (*Service) CompleteRunWithTaskUpdate

func (s *Service) CompleteRunWithTaskUpdate(run *model.SyncRun, task *model.SyncTask) error

CompleteRunWithTaskUpdate 在同一事务中完成 run + task 更新. Satisfies executor.RunManager.

func (*Service) CountRepos

func (s *Service) CountRepos() (int64, error)

CountRepos returns the total repo count via COUNT aggregate (no row loading).

func (*Service) CountReposByPlatform

func (s *Service) CountReposByPlatform(ctx context.Context, platformKey string) (int64, error)

CountReposByPlatform 统计平台下的仓库数量

func (*Service) CountTasksByStatus

func (s *Service) CountTasksByStatus() (map[string]int64, error)

CountTasksByStatus returns task counts grouped by last_status (key "total" = overall).

func (*Service) CreatePlatform

func (s *Service) CreatePlatform(ctx context.Context, platform *model.Platform) error

CreatePlatform 创建平台

func (*Service) CreateRepo

func (s *Service) CreateRepo(ctx context.Context, req *model.CreateRepoRequest) (*model.Repo, error)

CreateRepo creates a new repository.

func (*Service) CreateRule

func (s *Service) CreateRule(ctx context.Context, req *model.CreateRuleRequest) (*model.WebhookRule, error)

CreateRule creates a new webhook rule.

func (*Service) CreateRun

func (s *Service) CreateRun(task *model.SyncTask, trigger string, webhookEventID *uint) (*model.SyncRun, error)

CreateRun creates a new sync run record. Satisfies executor.RunManager.

func (*Service) CreateRunStep

func (s *Service) CreateRunStep(step *model.SyncRunStep) error

CreateRunStep creates a new sync run step record. Satisfies executor.RunManager.

func (*Service) CreateTask

func (s *Service) CreateTask(ctx context.Context, req *model.CreateTaskRequest) (*model.SyncTask, error)

func (*Service) DeleteHistory

func (s *Service) DeleteHistory(ctx context.Context, id uint) error

DeleteHistory deletes a sync run by ID.

func (*Service) DeletePlatform

func (s *Service) DeletePlatform(ctx context.Context, key string) error

DeletePlatform 删除平台

func (*Service) DeletePlatformWebhook

func (s *Service) DeletePlatformWebhook(ctx context.Context, repoKey string, webhookID int64) error

DeletePlatformWebhook 删除平台侧的 Webhook。

func (*Service) DeleteRepo

func (s *Service) DeleteRepo(ctx context.Context, key string) error

DeleteRepo deletes a repository by key.

func (*Service) DeleteRule

func (s *Service) DeleteRule(ctx context.Context, id uint) error

DeleteRule deletes a webhook rule by ID.

func (*Service) DeleteTask

func (s *Service) DeleteTask(ctx context.Context, key string) error

func (*Service) DetectDrift added in v0.6.0

func (s *Service) DetectDrift(ctx context.Context, taskKeys []string) (*DriftReport, error)

DetectDrift 检测本地 workdir 与目标远端的分支漂移。 用于发现「镜像声称同步成功但 refs 实际不一致」的静默故障。 taskKeys 为空时扫描全部启用任务。

func (*Service) DownloadReleaseAssets added in v0.9.0

func (s *Service) DownloadReleaseAssets(ctx context.Context, prov sdkprov.Provider, owner, repo string,
	releases []*sdkprov.ReleaseInfo, destDir string, maxAssets int) (saved, warnings []string, err error)

DownloadReleaseAssets 下载 release 附件到 destDir(流式写盘)。 releases 非空时直接复用(带 Assets 元数据,不重复请求);否则现拉 ListReleases。 文件名 tag__name(均经路径清洗),上限 maxAssets,warning 文案逐附件。 平台不声明 ReleaseAssets 能力时报错。

func (*Service) DrillHistory added in v0.6.0

func (s *Service) DrillHistory(limit int) ([]executor.DrillHistoryEntry, error)

DrillHistory 读取演练历史。

func (*Service) ExportDrillHistory added in v0.6.1

func (s *Service) ExportDrillHistory(format string, limit int) (contentType string, data []byte, err error)

ExportDrillHistory 导出演练历史为 JSON 或 CSV(供审计/上报)。

func (*Service) ForcePushApprovals added in v0.9.0

func (s *Service) ForcePushApprovals() *ForcePushStore

ForcePushApprovals 返回 force-push 审批存储(NewService 按 backup_dir 定位文件)。

func (*Service) GetConfig

func (s *Service) GetConfig() *model.Config

func (*Service) GetPlatform

func (s *Service) GetPlatform(ctx context.Context, key string) (*model.Platform, error)

GetPlatform 获取平台

func (*Service) GetPlatformByID

func (s *Service) GetPlatformByID(ctx context.Context, id uint) (*model.Platform, error)

GetPlatformByID returns a platform by ID. Satisfies executor.PlatformProvider.

func (*Service) GetRepo

func (s *Service) GetRepo(ctx context.Context, key string) (*model.Repo, error)

GetRepo returns a repository by key.

func (*Service) GetRepoByKey

func (s *Service) GetRepoByKey(key string) (*model.Repo, error)

GetRepoByKey returns a repository by key. Satisfies executor.RepoProvider.

func (*Service) GetRule

func (s *Service) GetRule(ctx context.Context, id uint) (*model.WebhookRule, error)

GetRule returns a webhook rule by ID.

func (*Service) GetTask

func (s *Service) GetTask(ctx context.Context, key string) (*model.SyncTask, error)

GetTask returns a sync task by key.

func (*Service) GetTempDir

func (s *Service) GetTempDir(taskKey string) string

func (*Service) HealthCheck

func (s *Service) HealthCheck() map[string]string

HealthCheck checks the health of all dependencies. Returns a map of component name to "ok" or error message. 内部对每个组件设置 5s 超时:基础设施卡住时健康检查不会无限阻塞。

func (*Service) HealthSnapshot added in v0.9.0

func (s *Service) HealthSnapshot(ctx context.Context, limit int, driftByTask map[string]int) (*HealthSnapshot, error)

HealthSnapshot 按维度规则给任务打分(借鉴 OpenSSF Scorecards)。 维度:reliability(35) / freshness(20) / schedule(15) / safety(15) / completeness(15)

limit ≤0 → 50,>200 → 200;driftByTask 非空时折入 safety 维度 (with_drift 的网络开销由调用方决定是否触发 DetectDrift)。

func (*Service) ImportPublicOrg added in v0.9.0

func (s *Service) ImportPublicOrg(ctx context.Context, req PublicOrgImportRequest) (*PublicOrgImportResult, error)

ImportPublicOrg 列出组织公开仓并可选建同步任务(默认只导入仓库记录)。

顺序与历史壳层一致:列仓(仅 GitHub)→ 导入仓库记录 → 批量建任务; DryRun 时跳过后两步(由壳层追加 dry_run 警告)。

func (*Service) LegalHold added in v0.6.0

func (s *Service) LegalHold() bool

LegalHold 当前是否处于合规冻结。

func (*Service) ListBranches

func (s *Service) ListBranches(ctx context.Context, repoKey string) ([]string, error)

ListBranches returns a list of branches for a repository.

func (*Service) ListBundles added in v0.5.1

func (s *Service) ListBundles(taskKey string) ([]BundleInfo, error)

ListBundles 列出冷备 bundle。

func (*Service) ListEvents

func (s *Service) ListEvents(ctx context.Context, repoKey string, offset, limit int) ([]*model.WebhookEvent, int64, error)

ListEvents returns webhook events for a repository.

func (*Service) ListHistory

func (s *Service) ListHistory(ctx context.Context, taskKey string, offset, limit int) ([]*model.SyncRun, int64, error)

ListHistory returns a paginated list of sync run history.

func (*Service) ListMetadataBackups added in v0.9.0

func (s *Service) ListMetadataBackups(_ context.Context, repoKey string) ([]MetadataBackupInfo, error)

ListMetadataBackups 扫描 MetadataBackupDir 下的 manifest.json; 读取/解析失败的条目静默跳过(与历史行为一致)。repoKey 非空时按快照 repo_key 过滤。BackupDir 未配置时返回空列表。

func (*Service) ListOperations

func (s *Service) ListOperations(ctx context.Context, offset, limit int, filter *dao.OperationLogFilter) ([]*model.OperationLog, int64, error)

ListOperations 按过滤条件分页返回审计日志。

func (*Service) ListPlatformRepos

func (s *Service) ListPlatformRepos(ctx context.Context, key, page, perPage string) ([]*sdkprov.PlatformRepo, error)

ListPlatformRepos 列出平台上的仓库

func (*Service) ListPlatformWebhooks

func (s *Service) ListPlatformWebhooks(ctx context.Context, repoKey string) ([]*sdkprov.PlatformWebhook, error)

ListPlatformWebhooks 列出平台侧已注册的 Webhook。

func (*Service) ListPlatforms

func (s *Service) ListPlatforms(ctx context.Context) ([]*model.Platform, error)

ListPlatforms 列出所有平台

func (*Service) ListRepos

func (s *Service) ListRepos(ctx context.Context, offset, limit int) ([]*model.Repo, int64, error)

ListRepos returns a paginated list of repositories.

func (*Service) ListReposByPlatform

func (s *Service) ListReposByPlatform(ctx context.Context, platformKey string) ([]*model.Repo, error)

ListReposByPlatform 列出平台下的仓库

func (*Service) ListReposWithFilter

func (s *Service) ListReposWithFilter(ctx context.Context, offset, limit int, filter *dao.RepoFilter) ([]*model.Repo, int64, error)

ListReposWithFilter returns a filtered, sorted, paginated list of repositories.

func (*Service) ListRules

func (s *Service) ListRules(ctx context.Context, repoKey string) ([]*model.WebhookRule, error)

ListRules returns webhook rules for a repository.

func (*Service) ListStarredRepos added in v0.9.0

func (s *Service) ListStarredRepos(ctx context.Context, platformKey string, max int) ([]*sdkprov.PlatformRepo, error)

ListStarredRepos 拉取平台 starred 仓库(能力门控 + 分页拉到 max 条)。

func (*Service) ListTasks

func (s *Service) ListTasks(ctx context.Context, repoKey string, offset, limit int) ([]*model.SyncTask, int64, error)

ListTasks returns a paginated list of sync tasks.

func (*Service) MetadataBackupDir added in v0.9.0

func (s *Service) MetadataBackupDir() string

MetadataBackupDir 元数据快照根目录 = BackupDir()+"/metadata",目录布局唯一来源。

func (*Service) Mirror

func (s *Service) Mirror() *MirrorService

Mirror 返回镜像通道服务(开源发布/仓库备份)。

func (*Service) OperationStats

func (s *Service) OperationStats(ctx context.Context) (today, week, total int64, err error)

OperationStats 返回今日、本周、总操作数。

func (*Service) OpsTodo added in v0.9.0

func (s *Service) OpsTodo(ctx context.Context) []OpsTodoItem

OpsTodo 聚合健康 attention + 孤儿仓库 + RPO 超标,按优先级输出可执行队列。 排序:优先级 → kind → id。

func (*Service) OpsTrends added in v0.9.0

func (s *Service) OpsTrends(ctx context.Context, days int) (*OpsTrendsResult, error)

OpsTrends 同步成功率/耗时时间序列。

取全局最近 trendsHistoryLimit 条 run 按日聚合(id DESC → 新日期在前, 顺序沿用历史实现)。days ≤0 或 >365 由调用方归一化为 30。

func (*Service) PreviewSync

PreviewSync previews a sync operation.

func (*Service) PreviewTemplate added in v0.9.0

func (s *Service) PreviewTemplate(ctx context.Context, templateID string) (*tpl.Template, []TemplateMatch, error)

PreviewTemplate 套用前预览命中结果(Renovate dry-run 语义)。

func (*Service) ProviderForPlatform added in v0.8.0

func (s *Service) ProviderForPlatform(p *model.Platform, tokenOverride string) (sdkprov.Provider, error)

ProviderForPlatform 按平台取 provider,供壳层复用: tokenOverride 非空优先,否则 ResolvePlatformToken(GitHub App 感知)。

func (*Service) PushTaskBackup added in v0.8.0

func (s *Service) PushTaskBackup(ctx context.Context, task *model.SyncTask, workDir, remoteURL, refspec string, force bool) (string, error)

PushTaskBackup 把任务 mirror 工作区(workDir)推到任意备份远端(github/gitlab 任意 git remote)。与 executor/backup_remote.go 同套路:临时 remote + backend.Push, 推送带仓库凭证——裸 exec git push 无凭证,https 私有仓必败。

  • refspec 原样传入(壳层默认 "+refs/heads/*:refs/heads/*");空值补默认。
  • force 决定 PushOptions.Force(--force)。
  • 凭证按 task.SourceRepoKey 查仓库走 executor.BuildRepoAuth(repo token 优先、 平台 token 回退);取不到仓库时退 AuthNone(匿名)。

返回成功的 git 输出摘要(推上的 ref 列表,可为空串);失败时错误自带 stderr (gitbackend GitError)。临时 remote 推送后清理。

func (*Service) RPOReport added in v0.6.0

func (s *Service) RPOReport(rpoMaxSeconds int64) (*RPOReport, error)

RPOReport 按冷备目录聚合每个任务的备份新鲜度(RPO)与估算恢复时间(RTO)。 rpoMaxSeconds>0 时标记超标任务。

func (*Service) ReceiveWebhook

func (s *Service) ReceiveWebhook(ctx context.Context, repoKey string, payload *WebhookPayload) error

func (*Service) RecordOperation

func (s *Service) RecordOperation(ctx context.Context, entry *model.OperationLog) error

RecordOperation 记录一条审计日志。

func (*Service) RegisterPlatformWebhook

func (s *Service) RegisterPlatformWebhook(ctx context.Context, repoKey, callbackURL, secret string, events []string) (*sdkprov.PlatformWebhook, error)

RegisterPlatformWebhook 在平台侧为仓库注册 Webhook,回调指向本服务的接收端点 (/api/webhook/receive/:repoKey)。secret 非空时持久化到仓库记录(加密存储), 用于入站事件验签。events 为空时默认订阅 push。

func (*Service) RepoInventory added in v0.9.0

func (s *Service) RepoInventory(ctx context.Context) (*InventoryResult, error)

RepoInventory 消灭孤儿仓库:哪些仓库没同步任务、哪些一直失败、哪些很久没跑。

func (*Service) ResolvePlatformToken added in v0.6.0

func (s *Service) ResolvePlatformToken(p *model.Platform) (string, error)

ResolvePlatformToken Service 包装,便于壳层/业务调用。

func (*Service) RestoreBundle added in v0.5.1

func (s *Service) RestoreBundle(ctx context.Context, name, destDir string) error

RestoreBundle 从 bundle 恢复到 destDir。 支持 .bundle 与 .bundle.enc(需配置 backup_encrypt_key)。

func (*Service) RestoreMetadata added in v0.9.0

func (s *Service) RestoreMetadata(ctx context.Context, req RestoreRequest) (*RestoreResult, error)

RestoreMetadata 回灌快照到目标仓。校验顺序与历史壳层一致: backup_dir → 最新快照解析 → manifest 加载 → repo → 目标平台 → provider。 错误文案是对外契约:快照类经 ErrMetadataValidation 归 400, repo/平台缺失归 404,provider 类回落 500。

func (*Service) RetryEvent

func (s *Service) RetryEvent(ctx context.Context, eventID uint) error

func (*Service) RunDRDrill added in v0.6.0

func (s *Service) RunDRDrill(ctx context.Context, name string) (*DrillReport, error)

RunDRDrill 对指定 bundle 做灾备演练,并写入哈希链历史。

func (*Service) RunTask

func (s *Service) RunTask(ctx context.Context, taskKey string) error

func (*Service) RunTaskAsync

func (s *Service) RunTaskAsync(taskKey, trigger string, webhookEventID *uint) error

RunTaskAsync 异步触发一次同步:校验与并发快速失败在调用方 goroutine 内完成, 实际执行纳入 WaitGroup + bgCtx(优雅关停时被等待/取消),适合 HTTP 手动触发路径, 避免 handler 被分钟级同步任务挂住。返回 nil 仅代表"已受理",结果见执行历史。

func (*Service) RunTaskWithTrigger

func (s *Service) RunTaskWithTrigger(ctx context.Context, taskKey, trigger string, webhookEventID *uint) error

func (*Service) SampleMetadataVerify added in v0.9.0

func (s *Service) SampleMetadataVerify(_ context.Context, repoKey string, n int) (VerifyReport, error)

SampleMetadataVerify 抽样比对元数据快照:清单存在、分片可解析、数量一致。 最多检查 n 个快照(n ≤ 0 → 5);repoKey 非空时按快照目录布局过滤 (metadata/<sanitized repoKey>/ 下的才算)。BackupDir 未配置时返回 Reason="backup_dir not configured"(壳层据此回 {ok,reason})。

func (*Service) SetDefaultPlatform

func (s *Service) SetDefaultPlatform(ctx context.Context, key string) error

SetDefaultPlatform 设置默认平台

func (*Service) SetForcePushApprover added in v0.7.1

func (s *Service) SetForcePushApprover(a executor.ForcePushApprover)

SetForcePushApprover 注入 force-push 审批器(壳层 force-push-approvals)。 block 策略触发分歧时:已放行则继续,否则登记 pending 并拒绝。

func (*Service) SetTemplates added in v0.9.0

func (s *Service) SetTemplates(st *tpl.Store)

SetTemplates 覆盖模板库(测试隔离 / 运行时切换文件)。

func (*Service) Start

func (s *Service) Start() error

func (*Service) Stop

func (s *Service) Stop()

func (*Service) SubscribeRuns added in v0.9.0

func (s *Service) SubscribeRuns(fn func(RunEvent)) (cancel func())

SubscribeRuns 注册运行完成回调,返回取消函数(幂等)。 回调在独立 goroutine 中执行并 recover panic;调用方需自行保证非阻塞语义 (要串行处理就自己起 worker)。Stop/进程退出不等待订阅者。

func (*Service) SyncPlatformRepos

func (s *Service) SyncPlatformRepos(ctx context.Context, key string) (int, error)

SyncPlatformRepos 同步平台仓库到本地

func (*Service) SyncPlatformReposFiltered added in v0.5.0

func (s *Service) SyncPlatformReposFiltered(ctx context.Context, key string, filter *RepoImportFilter) (int, error)

SyncPlatformReposFiltered 按过滤条件导入平台仓库。

func (*Service) Templates added in v0.9.0

func (s *Service) Templates() *tpl.Store

Templates 返回同步策略模板库(NewService 时按 cfg.Templates.Path 打开)。

func (*Service) TestConnection

func (s *Service) TestConnection(ctx context.Context, repoKey string) (*model.TestConnectionResult, error)

TestConnection tests the connection to a repository.

func (*Service) TestPlatformConnection

func (s *Service) TestPlatformConnection(ctx context.Context, key string) (*sdkprov.TestConnectionResult, error)

TestPlatformConnection 测试平台连接

func (*Service) UpdatePlatform

func (s *Service) UpdatePlatform(ctx context.Context, platform *model.Platform) error

UpdatePlatform 更新平台

func (*Service) UpdatePlatformStatus

func (s *Service) UpdatePlatformStatus(ctx context.Context, key, status, testResult string) error

UpdatePlatformStatus 更新平台状态

func (*Service) UpdateRepo

func (s *Service) UpdateRepo(ctx context.Context, req *model.UpdateRepoRequest) (*model.Repo, error)

UpdateRepo updates an existing repository.

func (*Service) UpdateRule

func (s *Service) UpdateRule(ctx context.Context, req *model.UpdateRuleRequest) (*model.WebhookRule, error)

UpdateRule updates an existing webhook rule.

func (*Service) UpdateRunStep

func (s *Service) UpdateRunStep(step *model.SyncRunStep) error

UpdateRunStep updates an existing sync run step record. Satisfies executor.RunManager.

func (*Service) UpdateTask

func (s *Service) UpdateTask(ctx context.Context, req *model.UpdateTaskRequest) (*model.SyncTask, error)

func (*Service) UpdateTaskLastRun

func (s *Service) UpdateTaskLastRun(task *model.SyncTask, run *model.SyncRun) error

UpdateTaskLastRun updates the task's last run status. Satisfies executor.RunManager.

func (*Service) VerifyAuditChain added in v0.6.0

func (s *Service) VerifyAuditChain() (*AuditChainResult, error)

VerifyAuditChain 校验审计哈希链。

func (*Service) VerifyBackupManifest added in v0.6.0

func (s *Service) VerifyBackupManifest() (*executor.ManifestVerifyResult, error)

VerifyBackupManifest 现场重算并比对清单。

func (*Service) VerifyBundle added in v0.5.1

func (s *Service) VerifyBundle(ctx context.Context, name string) (*BundleInfo, error)

VerifyBundle 校验 bundle 完整性。 自动识别 .enc 加密冷备:先解密到临时目录再校验。

func (*Service) VerifyDrillChain added in v0.6.0

func (s *Service) VerifyDrillChain() (bool, int, string)

VerifyDrillChain 校验演练历史哈希链。

type TaskService

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

TaskService handles sync task-related operations.

func NewTaskService

func NewTaskService(taskDAO *dao.SyncTaskDAO, runDAO *dao.SyncRunDAO, runStepDAO *dao.SyncRunStepDAO, repoDAO *dao.RepoDAO) *TaskService

NewTaskService creates a new TaskService instance.

func (*TaskService) CleanupOldRunSteps

func (ts *TaskService) CleanupOldRunSteps(ctx context.Context, maxAge time.Duration) (int64, error)

CleanupOldRunSteps removes sync run steps older than the specified duration.

func (*TaskService) CleanupOldRuns

func (ts *TaskService) CleanupOldRuns(ctx context.Context, maxAge time.Duration) (int64, error)

CleanupOldRuns removes sync runs older than the specified duration.

func (*TaskService) CompleteRun

func (ts *TaskService) CompleteRun(run *model.SyncRun) error

CompleteRun updates a sync run with final status and details.

func (*TaskService) CompleteRunWithTaskUpdate

func (ts *TaskService) CompleteRunWithTaskUpdate(run *model.SyncRun, task *model.SyncTask) error

CompleteRunWithTaskUpdate 在同一事务中完成 run 更新 + task 状态更新,保证原子性。

func (*TaskService) CountTasksByStatus

func (ts *TaskService) CountTasksByStatus() (map[string]int64, error)

CountTasksByStatus returns task counts grouped by last_status (key "total" = overall).

func (*TaskService) CreateRun

func (ts *TaskService) CreateRun(task *model.SyncTask, trigger string, webhookEventID *uint) (*model.SyncRun, error)

CreateRun creates a new sync run record for a task.

func (*TaskService) CreateRunStep

func (ts *TaskService) CreateRunStep(step *model.SyncRunStep) error

CreateRunStep creates a new sync run step record.

func (*TaskService) CreateTask

func (ts *TaskService) CreateTask(ctx context.Context, req *model.CreateTaskRequest) (*model.SyncTask, error)

CreateTask creates a new sync task.

func (*TaskService) DeleteHistory

func (ts *TaskService) DeleteHistory(ctx context.Context, id uint) error

DeleteHistory deletes a sync run by ID.

func (*TaskService) DeleteTask

func (ts *TaskService) DeleteTask(ctx context.Context, key string) error

DeleteTask deletes a sync task by key.

func (*TaskService) FindAllEnabledTasks

func (ts *TaskService) FindAllEnabledTasks() ([]*model.SyncTask, error)

FindAllEnabledTasks returns all enabled sync tasks.

func (*TaskService) FindTaskByKey

func (ts *TaskService) FindTaskByKey(key string) (*model.SyncTask, error)

FindTaskByKey returns a sync task by key (internal use).

func (*TaskService) GetTask

func (ts *TaskService) GetTask(ctx context.Context, key string) (*model.SyncTask, error)

GetTask returns a sync task by key.

func (*TaskService) ListHistory

func (ts *TaskService) ListHistory(ctx context.Context, taskKey string, offset, limit int) ([]*model.SyncRun, int64, error)

ListHistory returns a paginated list of sync run history.

func (*TaskService) ListTasks

func (ts *TaskService) ListTasks(ctx context.Context, repoKey string, offset, limit int) ([]*model.SyncTask, int64, error)

ListTasks returns a paginated list of sync tasks.

func (*TaskService) PreviewSync

PreviewSync previews a sync operation.

func (*TaskService) RecentRuns added in v0.9.0

func (ts *TaskService) RecentRuns(offset, limit int) ([]*model.SyncRun, error)

RecentRuns 取全局最近的 run(不分任务),供趋势类聚合使用。

func (*TaskService) UpdateRunStep

func (ts *TaskService) UpdateRunStep(step *model.SyncRunStep) error

UpdateRunStep updates an existing sync run step record.

func (*TaskService) UpdateTask

func (ts *TaskService) UpdateTask(ctx context.Context, req *model.UpdateTaskRequest) (*model.SyncTask, error)

UpdateTask updates an existing sync task.

func (*TaskService) UpdateTaskLastRun

func (ts *TaskService) UpdateTaskLastRun(task *model.SyncTask, run *model.SyncRun) error

UpdateTaskLastRun updates the task's last run time and status.

type TemplateApplyResult added in v0.9.0

type TemplateApplyResult struct {
	Template     *tpl.Template
	Effective    tpl.Spec
	ExtendsChain []string
	Changed      []TemplateChange
	DryRun       bool
}

TemplateApplyResult 批量套用结果。

type TemplateChange added in v0.9.0

type TemplateChange struct {
	Key    string         `json:"key"`
	Name   string         `json:"name"`
	Before map[string]any `json:"before"`
	After  map[string]any `json:"after"`
}

TemplateChange 批量套用产生的单条变更(Before/After 为变更前后字段快照)。

type TemplateMatch added in v0.9.0

type TemplateMatch struct {
	Key  string `json:"key"`
	Name string `json:"name"`
}

TemplateMatch 命中的任务摘要。

type TrendPoint added in v0.9.0

type TrendPoint struct {
	Date    string  `json:"date"`
	Total   int     `json:"total"`
	Success int     `json:"success"`
	Failed  int     `json:"failed"`
	AvgMs   float64 `json:"avg_duration_ms"`
}

TrendPoint 单日同步成功率/耗时聚合(供前端小图)。 JSON 标签与壳层历史响应逐字一致。

type VerifyReport added in v0.9.0

type VerifyReport struct {
	Checked  int      `json:"checked"`
	OK       bool     `json:"ok"`
	Warnings []string `json:"warnings"`
	Reason   string   `json:"reason,omitempty"`
}

VerifyReport 元数据快照抽样校验报告。 Reason 非空表示 backup_dir 未配置:此时响应结构仅 {ok,reason}(与历史行为一致)。

type WebhookPayload

type WebhookPayload struct {
	Method     string
	Path       string
	Header     map[string][]string
	Body       []byte
	RemoteAddr string
}

WebhookPayload 是协议无关的入站 Webhook 载荷。 core 不提供 HTTP 服务端;壳层(hz/gin/…)负责收包后转成该结构再调用。 内部会拼一个临时 *http.Request 交给 git-platform-sdk 做验签/解析(SDK 契约如此), 库对外 API 不暴露 Web 服务器语义。

type WebhookService

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

WebhookService handles webhook-related operations.

func NewWebhookService

func NewWebhookService(ruleDAO *dao.WebhookRuleDAO, eventDAO *dao.WebhookEventDAO, repoDAO *dao.RepoDAO) *WebhookService

NewWebhookService creates a new WebhookService instance.

func (*WebhookService) ApplyRules

func (ws *WebhookService) ApplyRules(ctx context.Context, repoKey string, event *model.WebhookEvent, lastTriggerTime *sync.Map, runTaskFn func(ctx context.Context, taskKey, trigger string, webhookEventID *uint) error, webhookEventID *uint)

ApplyRules applies webhook rules to an event.

func (*WebhookService) CleanupOldEvents

func (ws *WebhookService) CleanupOldEvents(ctx context.Context, maxAge time.Duration) (int64, error)

CleanupOldEvents removes webhook events older than the specified duration.

func (*WebhookService) CreateRule

CreateRule creates a new webhook rule.

func (*WebhookService) CreateWebhookEvent

func (ws *WebhookService) CreateWebhookEvent(event *model.WebhookEvent) error

CreateWebhookEvent creates a new webhook event.

func (*WebhookService) DeleteRule

func (ws *WebhookService) DeleteRule(ctx context.Context, id uint) error

DeleteRule deletes a webhook rule by ID.

func (*WebhookService) FindEventByEventID

func (ws *WebhookService) FindEventByEventID(eventID string) (*model.WebhookEvent, error)

FindEventByEventID returns a webhook event by event ID (internal use).

func (*WebhookService) FindEventByID

func (ws *WebhookService) FindEventByID(id uint) (*model.WebhookEvent, error)

FindEventByID returns a webhook event by ID (internal use).

func (*WebhookService) GetRule

func (ws *WebhookService) GetRule(ctx context.Context, id uint) (*model.WebhookRule, error)

GetRule returns a webhook rule by ID.

func (*WebhookService) ListEvents

func (ws *WebhookService) ListEvents(ctx context.Context, repoKey string, offset, limit int) ([]*model.WebhookEvent, int64, error)

ListEvents returns webhook events for a repository.

func (*WebhookService) ListRules

func (ws *WebhookService) ListRules(ctx context.Context, repoKey string) ([]*model.WebhookRule, error)

ListRules returns webhook rules for a repository.

func (*WebhookService) MarkEventProcessed

func (ws *WebhookService) MarkEventProcessed(event *model.WebhookEvent) error

MarkEventProcessed 标记事件为 processed(处理完成后调用)。 用 targeted UPDATE 仅写 status+processed_at,避免全字段回写大 payload。

func (*WebhookService) MarkEventProcessing

func (ws *WebhookService) MarkEventProcessing(ctx context.Context, eventID uint) (*model.WebhookEvent, error)

MarkEventProcessing 查找事件并标记为 processing,返回该事件供后续处理。

func (*WebhookService) UpdateRule

UpdateRule updates an existing webhook rule.

Jump to

Keyboard shortcuts

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