runtime

package
v0.141.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Overview

Package runtime is the machine layer of go-git-platform: the user-facing and automation-facing helpers that drive the contract seam instead of declaring it — platform detection (DetectPlatform), idempotent Ensure machines (EnsureWebhook, EnsureBranchProtection, EnsureDeployKey, EnsureIssueState, EnsureIssueLabels), commit-status polling (WaitForCommitStatus), webhook signature validation (ValidateWebhookWithRegistry and the WebhookValidator family), the bounded-concurrency batch engine (GetFileContents/GetCRs/ SetCommitStatuses), the page-walking iterators (Each/Collect), the token cache and its background janitor (Manager), due_on time parsing, and the shared name/event helpers (SplitFullName/BuildEventRepo/ResolveMRSHAs).

Layering

runtime sits directly above the contract seam: it may import provider (interfaces, options, errors) and model (entities), plus standard library and the whitelisted oekit modules — and nothing else from this repository. It must not import adapter, contracttest, transport or gitbackend, and no layer below it may import runtime back (spec §4.1 edge table: provider only looks down at model; provider → runtime is a forbidden edge). Signatures here take provider's manager interfaces and return model entities, so callers wire an adapter-built provider.Provider into a machine without either layer knowing the other's package path.

Only this file carries the package comment; per-file package comments would concatenate in godoc.

Index

Constants

View Source
const (
	// EnsureCreated: the resource did not exist and was created.
	EnsureCreated = OutcomeCreated
	// EnsureUpdated: the resource existed with different content and was
	// updated (for webhooks and deploy keys: replaced, see below).
	EnsureUpdated = OutcomeUpdated
	// EnsureUnchanged: the resource already matched the desired state.
	EnsureUnchanged = OutcomeUnchanged
)

Ensure* outcomes (aliases of the Outcome* names, kept for source compatibility).

View Source
const (
	DefaultWaitInterval = 5 * time.Second
	DefaultWaitTimeout  = 10 * time.Minute
)

Default polling parameters for WaitForCommitStatus.

View Source
const (
	// CR (change request / pull request / merge request) actions.
	CRActionOpened   = "opened"
	CRActionClosed   = "closed"
	CRActionMerged   = "merged"
	CRActionReopened = "reopened"
	CRActionUpdated  = "updated"

	// Event type prefixes.
	EventTypeCR      = "cr."
	EventTypePush    = "push"
	EventTypeTag     = "tag."
	EventTypeBranch  = "branch."
	EventTypeIssue   = "issue."
	EventTypeComment = "comment."

	// Comment actions. GitHub delivers created/edited/deleted; the other
	// platforms only notify on creation today.
	CommentActionCreated = "created"
	CommentActionEdited  = "edited"
	CommentActionDeleted = "deleted"
)
View Source
const DefaultBatchConcurrency = 4

DefaultBatchConcurrency is the number of in-flight operations used by the batch helpers when BatchOptions.Concurrency is unset.

View Source
const DefaultGiteeSignMaxAge = 10 * time.Minute

DefaultGiteeSignMaxAge bounds the accepted X-Gitee-Timestamp drift in sign mode when GiteeWebhookValidator.MaxAge is zero.

View Source
const DefaultIterMaxPages = 100

DefaultIterMaxPages is the page budget applied by Each/Collect when no explicit bound is given. At the default page size (20) this caps a walk at 2000 items; with PerPage=100 it caps at 10000 — far beyond any real list. The budget is a safety net against genuinely endless list walks; platforms that ignore the page parameter (observed in the field: Forgejo 15.0.1 on issue-comment lists) are cut short earlier by EachBounded's no-progress page detection.

View Source
const MaxBatchConcurrency = 16

MaxBatchConcurrency caps the caller-configurable concurrency so a misconfigured batch cannot hammer a platform into rate limiting.

View Source
const SkipValidationSecret = "\x00skip-signature-validation"

SkipValidationSecret is the sentinel secret that makes WebhookEnvelope.Read skip the platform's signature validator.

It exists for hosts that verify the webhook signature themselves and then reuse the SDK purely as a payload parser. Two situations need it:

  • The platform's header convention differs from the SDK's model (e.g. a GitLab-family payload delivered by a platform that brands its own token header).
  • The host validates the signature before dispatch, so the SDK's validation would be a redundant second check on an already-trusted request.

The sentinel is intentionally unusable as a real secret: it contains a NUL byte, which no HTTP header value or config file can carry. It is honoured only inside WebhookEnvelope.Read; ValidateWebhookWithRegistry and provider.Provider.ValidateWebhookSignature always run the real validator, so passing the sentinel there does NOT bypass signature checking.

View Source
const WebhookDeletionSHA = "0000000000000000000000000000000000000000"

WebhookDeletionSHA 是 push/tag_push 类投递的「删除标记」:平台在删除 tag/分支时把 after 置成全零 SHA(issue #47)。GitLab 家族(GitLab/Gitee/ GitCode/TencentCode)没有独立的 delete 事件,删除只能靠这个标记识别。

Variables

View Source
var ErrPageBudgetExceeded = oekiterrors.New("page budget exceeded before an empty page")

ErrPageBudgetExceeded is returned when the walk hits its MaxPages bound before the platform returns an empty page: the list is genuinely longer than the budget (服务器不推进分页的伪翻页形态由 EachBounded 的无进展检测 在预算内收手,不走本错误). Retry with a higher bound via EachBounded/CollectBounded if the former.

View Source
var ErrStopIteration = oekiterrors.New("iteration stopped")

ErrStopIteration is the sentinel a Each callback returns to stop the walk early without reporting an error. Everything fetched so far stands.

View Source
var ErrWaitTimedOut = oekiterrors.New("commit status did not reach a terminal state before the timeout")

ErrWaitTimedOut is returned by WaitForCommitStatus when the commit stays non-terminal past WaitOptions.Timeout.

Functions

func BuildEventRepo

func BuildEventRepo(fullName string) *model.EventRepo

BuildEventRepo creates an EventRepo from a full name string.

func Collect

func Collect[T any](ctx context.Context, fetch PageFetch[T]) ([]T, error)

Collect walks every page of a paginated list call and returns all items as one slice. It is the convenient counterpart of Each for callers that want the whole list in memory.

func CollectBounded

func CollectBounded[T any](ctx context.Context, fetch PageFetch[T], maxPages int) ([]T, error)

CollectBounded is Collect with an explicit page budget (maxPages <= 0 falls back to DefaultIterMaxPages).

func Each

func Each[T any](ctx context.Context, fetch PageFetch[T], fn func(T) error) error

Each walks every page of a paginated list call, invoking fn once per item, until the platform returns an empty page or stops advancing pagination. Pages are fetched lazily: fn sees items page by page, so a walk over a long list does not buffer it in memory. Use Collect instead when the full slice is wanted.

fn returning ErrStopIteration ends the walk with a nil error; any other error aborts immediately and is returned as-is. ctx cancellation between items and between page fetches is honored.

func EachBounded

func EachBounded[T any](ctx context.Context, fetch PageFetch[T], maxPages int, fn func(T) error) error

EachBounded is Each with an explicit page budget. maxPages <= 0 falls back to DefaultIterMaxPages. Exceeding the budget fails the walk with an error wrapping ErrPageBudgetExceeded (a public walk must not truncate silently).

伪翻页无进展检测(v0.99.10):与上一页**逐值相同**的页视为服务器未推进 分页(实测 Forgejo 15.0.1 的 issue 评论列表忽略 page 参数、每页返回同一批 全量数据),按"已到列表末尾"收手并返回已收集数据——继续翻页只会把同一页 重复到预算耗尽再报错丢弃全部数据。该形态下首页即全量(这正是服务器无法 分页的原因),截断风险仅出现在"忽略 page 但遵守 limit"的另一种服务器形态, 此时返回首页数据也优于整体报错。

快照语义(issue #143):上一页取 slices.Clone 快照再比较。旧实现 `prev = batch` 存的是切片头别名——fetch 复用同一底层数组(避免每页分配的 常规写法)时,batch 与 prev 永远逐值相同,第 2 页就被判成无进展而静默 收手:列表被截成第 1 页且 err 为 nil,违反"a public walk must not truncate silently"的自身契约。

func ExtractOwnerFromFullName

func ExtractOwnerFromFullName(fullName string) string

ExtractOwnerFromFullName returns just the owner portion of "owner/repo".

func HashToken

func HashToken(token string) string

HashToken returns the first 16 hex characters of SHA-256(token). It is the default token hasher used by Manager and is exported so callers can compute cache keys for diagnostics or external caches.

An empty token hashes to an empty string (no anonymous cache entries).

func IsWebhookDeletionSHA

func IsWebhookDeletionSHA(after string) bool

IsWebhookDeletionSHA 报告 after 值是否为平台的删除标记。

func LatestCommitStatuses

func LatestCommitStatuses(statuses []model.CommitStatus) []model.CommitStatus

LatestCommitStatuses collapses a commit's status history to one status per context, keeping the FIRST occurrence of each context. All platform list endpoints return statuses newest-first (GitHub documents reverse chronological order; Gitea/GitLab/Gitee/GitCode/Forgejo/Tencent Code sort descending by creation), so first-seen is the most recent report of that context — the same entry GitHub's combined status would use. CI re-runs append history instead of replacing it, so folding the raw list would let a stale failure (or pending) outvote the latest result.

func NormalizeBranchAction

func NormalizeBranchAction(action string) string

NormalizeBranchAction maps platform-specific branch event actions.

func NormalizeCRAction

func NormalizeCRAction(action string, merged bool) string

NormalizeCRAction maps platform-specific PR/MR action strings to the canonical vocabulary. Each backend should call this instead of ad-hoc string mapping.

Mappings:

GitHub:   "opened" → opened, "closed" (+merged) → merged/closed,
          "reopened" → reopened, "synchronize"/"edited" → updated
GitLab:   "open" → opened, "close" → closed, "merge" → merged,
          "reopen" → reopened, "update" → updated
Gitee:    "open" → opened, "close" (+merged check) → merged/closed
GitCode:  "opened" → opened, "closed" (+merged check) → merged/closed
Gitea:    "opened" → opened, "closed" (+merged check) → merged/closed

func NormalizeIssueAction

func NormalizeIssueAction(action string) string

NormalizeIssueAction maps platform-specific issue event actions.

func NormalizeTagAction

func NormalizeTagAction(action string) string

NormalizeTagAction maps platform-specific tag event actions to the canonical vocabulary. The canonical full event type is "tag.created": GitLab/Gitea/Tencent signal a tag with a tag_push hook (a tag being pushed is the tag coming into existence), and GitHub's create/delete events carry ref_type "tag".

func ParseTimestamp

func ParseTimestamp(field, value string) (time.Time, error)

ParseTimestamp resolves one RFC3339 timestamp option (issue #52). The option fields carrying timestamps (ListCommitsOptions.Since/Until, ListNotificationsOptions.Since, MarkNotificationsOptions.LastReadAt) document the RFC3339 layout; an unparsable value must NOT silently widen the result set: a date-only string in an incremental sync used to drop the filter and return the full history with err == nil — the failure looked like "the sync was slow", never like "the filter was ignored".

An empty value resolves to the zero time ("no filter requested"). Every backend resolves its timestamp options through this one parser, so the same input is accepted or rejected identically on every platform — including the backends that forward the raw string to the platform (Gitee/GitCode/TencentCode): they validate here first, then forward.

func ReadAndRestoreBody

func ReadAndRestoreBody(r *http.Request) ([]byte, error)

ReadAndRestoreBody reads the full body of r and replaces it with a fresh NopCloser so that downstream readers (signature verification, JSON decoding) can still consume it. Use it at the entry point of webhook handlers that need to inspect the raw bytes.

func RegisterHostAlias

func RegisterHostAlias(host string, platform model.Platform, baseURL string)

RegisterHostAlias teaches DetectPlatform that host (and its subdomains) identifies platform with the given base API URL — the registry extension matching Register: adding a self-hosted alias no longer requires editing the provider core. Panics on an empty host, an empty platform, or a duplicate host (same fail-fast convention as Register).

func ResolveMRSHAs

func ResolveMRSHAs(diffRefsHead, diffRefsBase, diffRefsStart, mergeCommitSHA, lastCommitID string) (head, base, start string)

ResolveMRSHAs derives the (head, base, start) SHAs for a GitLab-style merge request from the raw webhook fields. This encodes the shared priority used by the GitLab, TencentCode (and future GitCode) backends:

  • head: diff_refs.head_sha when present, otherwise last_commit.id
  • base: merge_commit_sha when present, otherwise diff_refs.base_sha
  • start: diff_refs.start_sha (may be empty)

Keeping this in one place guarantees identical fallback semantics across the GitLab-family backends and avoids behavioural drift.

func SplitFullName

func SplitFullName(fullName string) (owner, name string)

SplitFullName splits "owner/repo" into (owner, repo). If the input doesn't contain "/", owner is empty.

func ValidateWebhookWithRegistry

func ValidateWebhookWithRegistry(p model.Platform, r *http.Request, secret string) error

ValidateWebhookWithRegistry validates req's webhook signature with the default registry entry for platform — the single implementation per signature scheme (STRATEGY dispatch). The body is read and restored so callers can keep parsing the payload afterwards. Platforms without a registered validator yield provider.ErrNotImplemented; an empty secret is rejected (an empty HMAC key is trivially forgeable on predictable payloads).

Backend provider.WebhookManager implementations delegate here instead of keeping an inline copy of their platform's crypto, which had already drifted from the registry (empty-secret semantics) before v0.77.0.

func WaitForCommitStatus

func WaitForCommitStatus(ctx context.Context, p provider.Provider, owner, repo, sha string, opts WaitOptions) (model.CommitStatusState, error)

WaitForCommitStatus polls ListCommitStatuses until the commit's combined state is terminal (success/failure/error/canceled) and returns it. It is the CI-gate primitive for automation and agent flows: create your status (or push a commit), wait, then decide.

The provider must implement provider.CommitStatusManager; otherwise the error wraps provider.ErrNotImplemented. Context cancellation is honored between and during polls. A combined state of pending/running past the timeout fails with ErrWaitTimedOut (so a red build is never confused with "gave up waiting"): distinguish them via errors.Is.

States are combined with CombineCommitStatusStates semantics — any error beats failure beats canceled; any pending/running keeps waiting; an all-success set succeeds. With WaitOptions.Contexts set, only the named contexts are folded; contexts that have not reported yet are simply absent, so the wait continues until each named context lands a terminal state.

Types

type BatchOptions

type BatchOptions struct {
	// Concurrency is the maximum number of in-flight operations;
	// defaults to DefaultBatchConcurrency, capped at
	// MaxBatchConcurrency.
	Concurrency int
}

BatchOptions tunes the batch helpers' concurrency. Zero fields take the defaults.

type BatchResult

type BatchResult[T any] struct {
	// Key is the input selector: the file path, CR number, or the
	// status context.
	Key string
	// Value carries the operation result when Err is nil.
	Value T
	// Err is the per-item failure, already wrapped as a provider error
	// by the underlying call.
	Err error
}

BatchResult pairs one batch item's outcome with its input key so callers can attribute per-item failures without re-deriving order. A per-item Err never aborts the whole batch.

func GetCRs

func GetCRs(ctx context.Context, p provider.Provider, owner, repo string, numbers []string, batchOpts ...BatchOptions) []BatchResult[*model.ChangeRequest]

GetCRs fetches many change requests from one repository with bounded concurrency, in input order. A lookup failure for one number fails only that item.

func GetFileContents

func GetFileContents(ctx context.Context, p provider.Provider, owner, repo, ref string, paths []string, batchOpts ...BatchOptions) []BatchResult[string]

GetFileContents reads many files from one repository with bounded concurrency. ref may be empty to use the repository's default branch (a single ref applies to the whole batch; per-path refs are expressible by calling the helper once per ref).

It is the context-economy read primitive for agent flows: fetch the handful of files that matter in one call, then trim each payload with projection if needed.

func SetCommitStatuses

func SetCommitStatuses(ctx context.Context, p provider.Provider, owner, repo, sha string, statuses []provider.CommitStatusOptions, batchOpts ...BatchOptions) []BatchResult[struct{}]

SetCommitStatuses reports many statuses on one commit with bounded concurrency (the usual "CI publishes lint+test+build at once" shape). The provider must implement provider.CommitStatusManager; a provider without it yields every item failed with provider.ErrNotImplemented.

type CombinedCommitStatus

type CombinedCommitStatus struct {
	State model.CommitStatusState `json:"state"`
	// Contexts maps each contributing context to its latest state.
	Contexts map[string]model.CommitStatusState `json:"contexts,omitempty"`
}

CombinedCommitStatus is the fold of a commit's statuses with a snapshot of the per-context states it was derived from.

func (CombinedCommitStatus) String

func (c CombinedCommitStatus) String() string

type DetectResult

type DetectResult struct {
	Platform model.Platform
	Owner    string
	Repo     string
	BaseURL  string
}

DetectResult holds the platform, owner, repo, and base API URL extracted from a git remote URL by DetectPlatform.

Owner/Repo are split as "first path segment = Owner, remainder = Repo". For GitLab repositories nested in subgroups the full subgroup path stays part of Repo: "https://gitlab.com/group/sub/repo" yields Owner="group" and Repo="sub/repo". Callers must therefore treat Repo as a path (it may contain "/"), not a bare repository name.

func DetectPlatform

func DetectPlatform(remoteURL string) (*DetectResult, error)

DetectPlatform parses a git remote URL (HTTPS, SSH, or ssh://) and returns the detected platform, owner, repo name, and base API URL. Returns provider.ErrPlatformNotSupported for unrecognized hosts; use provider.NewProvider with explicit provider.Config for self-hosted instances not in the known-host list.

type EnsureAction

type EnsureAction = MutationOutcome

EnsureAction 是 MutationOutcome 的既有名——类型别名,源码完全兼容; 既有 EnsureCreated/EnsureUpdated/EnsureUnchanged 常量保留(新代码 优先用 Outcome* 名)。

func EnsureBranchProtection

EnsureBranchProtection converges the branch protection rule for opts.BranchName onto opts, creating, updating, or leaving it untouched as required, and returns the resulting rule plus the action taken. It targets the provider.BranchProtectionManager directly so it works with any provider.Provider (type-assert it at the call site) or test double. 契约防御:Get 违约返回 (nil, nil)(iface 契约禁止)时视为缺席走 Create 而非 Update——见 iface_branch_protection.go Get 的契约注释。

func EnsureDeployKey

EnsureDeployKey converges the repository's deploy key titled opts.Title onto opts, creating, replacing, or leaving it untouched as required, and returns the resulting key plus the action taken.

Existing keys are matched by title; a title collision with different key material or read-only flag replaces the key (the manager interface has no update: delete + re-add), which changes its platform ID.

func EnsureWebhook

EnsureWebhook makes the repository carry exactly one webhook for opts.URL with opts.Events, creating or replacing as needed, and returns the resulting webhook plus the action taken. It is the idempotent building block automation wants: "make this hook exist, whatever it takes", safe to re-run.

Semantics:

  • No webhook with that URL → created.
  • Same URL, same event set → unchanged. Secrets are write-only on every platform (list responses never return them), so an existing hook's secret is not comparable; re-running with a different secret reports unchanged and keeps the old secret. Set provider.CreateWebhookOptions.EnsureSecretMode to provider.EnsureSecretAlwaysUpdate to rewrite the secret in that case instead (rotation convergence).
  • Same URL, different event set → updated. The provider.WebhookManager interface has no update method, so the hook is deleted and recreated; its platform ID changes as a result.
  • Empty opts.Events defaults to {push, pull_request}, matching CreateWebhook's platform-side default.

Multiple existing hooks with the same URL are all replaced by one.

type ForgejoWebhookValidator

type ForgejoWebhookValidator struct{}

ForgejoWebhookValidator verifies Forgejo webhooks. Current Forgejo sends X-Forgejo-Signature; releases forked from older Gitea send X-Gitea-Signature, so both are accepted — whichever header is present is used (the signature format itself is identical raw-hex HMAC-SHA256).

func (ForgejoWebhookValidator) Name

Name implements WebhookValidator.

func (ForgejoWebhookValidator) Validate

func (ForgejoWebhookValidator) Validate(r *http.Request, body []byte, secret string) error

Validate implements WebhookValidator. 双 header 回退由 oekit 构造器内置 (WithFallbackHeaders),缺席/错签的错误分类经 wrapValidation 保持哨兵链。

type GitCodeWebhookValidator

type GitCodeWebhookValidator struct{}

GitCodeWebhookValidator accepts GitCode's two webhook verification modes: an HMAC-SHA256 body signature (X-GitCode-Signature, falling back to the gitea-inherited X-Gitea-Signature) or the documented static password in X-GitCode-Token. Whichever header is present is used.

func (GitCodeWebhookValidator) Name

Name implements WebhookValidator.

func (GitCodeWebhookValidator) Validate

func (GitCodeWebhookValidator) Validate(r *http.Request, body []byte, secret string) error

Validate implements WebhookValidator. 三模消歧(签名 → gitea 形 → 静态令牌)由 oekit 构造器内置的 Fallback 组合子裁决:签名 header 在场 即裁决、错签硬失败不降级(防同 secret 交叉认证),仅 header 缺席让位 下一候选。

type GiteeWebhookValidator

type GiteeWebhookValidator struct {
	// AllowPasswordMode opts in to the password mode. It is disabled by
	// default: the password only proves "knowledge of the secret" and does
	// not bind request integrity, so sign mode is always preferred when its
	// headers are present.
	AllowPasswordMode bool
	// MaxAge bounds the accepted timestamp drift. Zero selects
	// DefaultGiteeSignMaxAge; a negative value disables the freshness
	// check entirely.
	MaxAge time.Duration
}

GiteeWebhookValidator verifies Gitee webhooks. Gitee offers two security modes and both ride the X-Gitee-Token header:

  • 签名密钥 (sign) mode: X-Gitee-Timestamp carries the send time in unix millis and X-Gitee-Token carries Base64(HMAC-SHA256(key=secret, msg=timestamp+"\n"+secret)).
  • 密码 (password) mode: the plain password in X-Gitee-Token.

验签核心委托 oekit/webhook 的 TimestampHMACValidator(时间戳防重放: 秒/毫秒自动识别、容忍窗、官方 message 形态)+ StaticTokenValidator (密码常量时间比对)。

func (GiteeWebhookValidator) Name

Name implements WebhookValidator.

func (GiteeWebhookValidator) Validate

func (v GiteeWebhookValidator) Validate(r *http.Request, body []byte, secret string) error

Validate implements WebhookValidator.

type HMACSHA256Validator

type HMACSHA256Validator struct {
	Header string
}

HMACSHA256Validator verifies a "Header: sha256=<hex>" style signature using HMAC-SHA256 over the request body. The expected header is configurable so it works for GitHub (X-Hub-Signature-256), Gitea (X-Gitea-Signature), Gitee (X-Gitee-Token) and others.

验签核心委托 oekit/webhook(pkg#270 收编):HMAC 计算/hex 解码/常量时间 比较全部下沉,本类型保留平台 header 约定与 secret 逐调用的多租户形态 (适配层按调用构造验证器——单个结构体的开销远小于 HMAC 计算本身)。

func (HMACSHA256Validator) Name

func (HMACSHA256Validator) Name() string

Name implements WebhookValidator.

func (HMACSHA256Validator) Validate

func (h HMACSHA256Validator) Validate(r *http.Request, body []byte, secret string) error

Validate implements WebhookValidator. The signature must be exactly "sha256=<hex>" or just "<hex>". Comparison is done in constant time.

type HmacValidator

type HmacValidator struct {
	Header    string
	Algorithm string // "sha1", "sha256", "sha512"
	Prefix    string // expected signature prefix ("sha256=")
}

HmacValidator is a lower-level helper that supports arbitrary hash algorithms. It is intended for use by platform implementations that need something other than SHA-256.

func (*HmacValidator) Name

func (h *HmacValidator) Name() string

Name implements WebhookValidator.

func (*HmacValidator) Validate

func (h *HmacValidator) Validate(r *http.Request, body []byte, secret string) error

Validate implements WebhookValidator. 算法白名单映射到 oekit 构造器 (未知算法保持旧缺省 sha256);前缀剥离由 oekit 的 WithSignaturePrefix 处理(错前缀不剥离交裸解码拒绝)。

type Manager

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

Manager caches provider.Provider instances keyed by configuration so repeated constructions of the same (platform, baseURL, token, and every other wire-affecting config field) reuse the underlying HTTP client pools instead of leaking a fresh one per call.

It automatically detects the platform from clone URLs and reuses existing provider.Provider instances within the TTL window. The cache key is derived from the full provider.Config: platform + baseURL + a SHA-256 hash of the token, plus SkipTLS, TokenStyle, ConditionalRequests, the provider.RetryConfig fingerprint and the identity of TokenSource/Hooks/Logger — so differently configured callers never share a provider (issue #66) and the token itself never leaks into logs or memory dumps.

The type is deliberately thin: the cache mechanics (TTL, LRU capacity eviction, counters) live in ttlCache and the background-cleanup lifecycle in janitor, leaving Manager exactly key derivation + factory call.

func NewManager

func NewManager(ttl time.Duration, opts ...ManagerOption) *Manager

NewManager creates a new provider.Provider Manager with the given TTL. A TTL of 0 means providers never expire (until the process exits).

func (*Manager) Cleanup

func (m *Manager) Cleanup()

Cleanup removes expired entries from the cache. Safe to call manually; also invoked periodically by StartJanitor.

func (*Manager) Get

func (m *Manager) Get(cfg provider.Config) (provider.Provider, error)

Get returns a cached or newly created provider.Provider for the given config. The cache key is platform + baseURL + hash(token), so the same (platform, baseURL) with a different token gets a distinct entry.

func (*Manager) GetByURL

func (m *Manager) GetByURL(cloneURL, token string) (provider.Provider, error)

GetByURL detects the platform from the clone URL and returns a cached or newly created provider.Provider.

func (*Manager) Len

func (m *Manager) Len() int

Len returns the number of cached Providers.

func (*Manager) Purge

func (m *Manager) Purge()

Purge removes all cached Providers.

func (*Manager) Remove

func (m *Manager) Remove(cfg provider.Config)

Remove removes a cached provider.Provider by config.

func (*Manager) ResetStats

func (m *Manager) ResetStats()

ResetStats zeroes the hit/miss/eviction counters. Cache entries are not affected.

func (*Manager) StartJanitor

func (m *Manager) StartJanitor(ctx context.Context, interval time.Duration)

StartJanitor launches a background goroutine that calls Cleanup every interval until ctx is cancelled or Stop is called. Calling StartJanitor more than once without an intervening Stop (or without the previous goroutine having exited) is a no-op. When the goroutine exits on its own — e.g. because ctx was cancelled — it resets the janitor state, so a subsequent StartJanitor with a fresh ctx launches a new goroutine instead of being mistaken for "already running".

func (*Manager) Stats

func (m *Manager) Stats() Stats

Stats returns a snapshot of cache counters. The counters continue to accumulate across calls; reset them with ResetStats.

Evictions 口径与本仓历史实现一致:容量淘汰与 TTL 过期回收**都计入** (上游 LocalCache 把两者分列为 Evictions / Expirations,此处按历史口径合并)。

func (*Manager) Stop

func (m *Manager) Stop()

Stop halts the background janitor and blocks until it has exited.

type ManagerOption

type ManagerOption func(*Manager)

ManagerOption configures a Manager at construction time.

func WithHasher

func WithHasher(h func(token string) string) ManagerOption

WithHasher overrides the default SHA-256 token hasher. Useful for tests that want deterministic, human-readable keys.

func WithMaxSize

func WithMaxSize(n int) ManagerOption

WithMaxSize caps the cache at n entries. When the cap is reached, the least recently used entry is evicted before a new one is inserted.

type MutationOutcome

type MutationOutcome string

MutationOutcome 是统一变更结果(2B spec 2026-11-14-phase2b):自动化按 outcome 分支,不必解析错误文本或比对返回对象。

const (
	OutcomeCreated   MutationOutcome = "created"   // 资源原本不存在,已创建
	OutcomeUpdated   MutationOutcome = "updated"   // 存在且发生了写入
	OutcomeUnchanged MutationOutcome = "unchanged" // 已达期望态,零写入
	// OutcomeConflict 是唯一同时携带 outcome 与非 nil error 的分支
	// (并发冲突 409,err 经 provider.IsConflict 可判);其余 outcome 错误一律
	// ("", nil, err)。实体是写前快照(pre-write snapshot),冲突浮出时
	// 可能已被并发改动/删除——以 err 为准。
	OutcomeConflict MutationOutcome = "conflict"
)

func EnsureIssueLabels

func EnsureIssueLabels(ctx context.Context, p provider.Provider, owner, repo, number string, want []string) (MutationOutcome, []string, error)

EnsureIssueLabels 收敛 issue 标签(2B spec):GET 现状 labels,集合相等 (map 归一,顺序与重复无关)零写入返 Unchanged(返 current 原样);否则 按差集写入——toAdd = want∖current(保序去重)批量 AddIssueLabels、 toRemove = current∖want 批量 RemoveIssueLabels(各非空才调一次, #163 循环收口 SDK 单点)——返 Updated。写撞 409 返 (OutcomeConflict, 写前快照, err),其余写错与 GET 错误一律 ("", nil, err)。

全集替换语义:want 即目标全集,current 中多余标签一律删除,want 缺失者 补齐。返回值为本地计算的收敛目标(want 去重保序),非再读回——并发窗口 内平台侧可能已再变动,以 err / 下次 GET 为准。

形态与既有 Ensure* 不同(取 provider.Provider 而非 provider.IssueManager):provider.IssueManager 不在 provider.Provider 组成里,内部断言让调用方免二次断言,缺能力统一 provider.ErrNotImplemented。

func EnsureIssueState

func EnsureIssueState(ctx context.Context, p provider.Provider, owner, repo, number string, want model.IssueState) (MutationOutcome, *model.Issue, error)

EnsureIssueState 收敛 issue 状态(2B spec):GET 现状,已达 want 零写入 返 Unchanged;否则 Close/Reopen 恰一次返 Updated。写撞 409 返 (OutcomeConflict, 写前快照, err),其余写错与 GET 错误一律 ("", nil, err)。

形态与既有 Ensure* 不同(取 provider.Provider 而非 provider.IssueManager):provider.IssueManager 不在 provider.Provider 组成里,内部断言让调用方免二次断言,缺能力统一 provider.ErrNotImplemented。

type PageFetch

type PageFetch[T any] func(ctx context.Context, page int) ([]T, error)

PageFetch fetches one page of a paginated list. page is the 1-based page number; the implementation must forward it into the platform call's page options (and should set an explicit PerPage so page sizes stay stable across the walk):

err := runtime.Each(ctx, func(ctx context.Context, page int) ([]model.PlatformRepo, error) {
    return p.ListRepos(ctx, provider.ListRepoOptions{Owner: "org", Page: page, PerPage: 100})
}, func(r model.PlatformRepo) error {
    fmt.Println(r.FullName)
    return nil
})

The iterator keeps a copy of the previous page for its no-progress detection, so a fetch backed by a reused buffer is safe (issue #143): returning a re-sliced buffer whose contents change per page does not trip the check, and the items handed to fn are consumed before the next fetch may overwrite the buffer.

type StaticTokenValidator

type StaticTokenValidator struct {
	Header string
}

StaticTokenValidator compares a static token header against the configured secret in constant time. Used for GitLab's X-Gitlab-Token.

func (StaticTokenValidator) Name

Name implements WebhookValidator.

func (StaticTokenValidator) Validate

func (s StaticTokenValidator) Validate(r *http.Request, body []byte, secret string) error

Validate implements WebhookValidator.

type Stats

type Stats struct {
	Hits      int64
	Misses    int64
	Evictions int64
	Size      int
}

Stats reports cache hit/miss counters and the current size. Counters are atomically incremented and safe to read concurrently.

type ValidatorFunc

type ValidatorFunc struct {
	N  string
	Fn func(r *http.Request, body []byte, secret string) error
}

ValidatorFunc adapts a plain function into a WebhookValidator.

func (ValidatorFunc) Name

func (v ValidatorFunc) Name() string

Name implements WebhookValidator.

func (ValidatorFunc) Validate

func (v ValidatorFunc) Validate(r *http.Request, body []byte, secret string) error

Validate implements WebhookValidator.

type WaitOptions

type WaitOptions struct {
	// Interval is the poll cadence; defaults to DefaultWaitInterval and
	// is clamped up to minWaitInterval.
	Interval time.Duration
	// Timeout bounds the whole wait. Zero uses DefaultWaitTimeout; a
	// negative value disables the budget entirely (rely on your own
	// context deadline). Expiry surfaces as ErrWaitTimedOut carrying the
	// last observed combined state.
	Timeout time.Duration
	// Contexts, when non-empty, restricts the combined state to the
	// named status contexts (e.g. []string{"ci/lint", "ci/test"}).
	// Empty means every context reported on the commit.
	Contexts []string
	// InitialDelay defers the first poll; useful right after
	// CreateCommitStatus, whose result may not be queryable for a
	// moment. Defaults to no delay.
	InitialDelay time.Duration
}

WaitOptions tunes the polling loop in WaitForCommitStatus.

type WebhookEnvelope

type WebhookEnvelope struct {
	// Platform selects the registered signature validator.
	Platform model.Platform
	// EventHeaders are checked in order for the event-type header; the first
	// non-empty value wins (multi-header dialects list fallbacks). Leave
	// empty when the platform dispatches on a payload field (e.g. GitLab's
	// object_kind) instead of a header.
	EventHeaders []string
	// IDPrefix prefixes generated event IDs ("<prefix>-<unixnano>-<key>").
	// Empty falls back to the platform name — the ID is **never empty**
	// (see NewEvent).
	IDPrefix string
	// IDHeaders are checked in order for the platform's **delivery ID**
	// (e.g. GitHub's "X-GitHub-Delivery"); the first non-empty value wins.
	//
	// The delivery ID is a true idempotency key: the platform repeats the
	// same value when it redelivers an event, so callers can deduplicate
	// properly. Without it the ID is synthesized locally and differs on
	// every delivery (no deduplication possible).
	IDHeaders []string
}

WebhookEnvelope carries one platform's webhook dialect for the shared envelope steps every ParseWebhookEvent must run before its payload switch (validate → read/restore body → event header → event skeleton). Payload decoding and the event-type switch stay per-platform: those are the dialect, not the envelope.

func (WebhookEnvelope) NewEvent

func (e WebhookEnvelope) NewEvent(idKey int64, body []byte) *model.NormalizedEvent

NewEvent builds the event skeleton: Source, Timestamp, RawPayload — plus ID "<prefix>-<unixnano>-<idKey>". idKey is the platform's payload identifier for the event (issue number, MR IID, ...). Actor/Repo remain the caller's: they come from the payload the mapper decodes.

The ID is **never empty**: without an explicit IDPrefix the platform name is used as the prefix. An empty event ID is not merely "missing data" — callers commonly key their dedup table and their unique index on it, and an empty key makes every later event collide with the first one (silently dropping all events after the first).

func (WebhookEnvelope) NewEventWithID

func (e WebhookEnvelope) NewEventWithID(r *http.Request, idKey int64, body []byte) *model.NormalizedEvent

NewEventWithID behaves like NewEvent but prefers the platform's delivery ID (X-GitHub-Delivery and friends) as the event ID.

The delivery ID is a real idempotency key: the platform repeats it when it redelivers the same event, so a caller keying dedup on the event ID can actually suppress the duplicate. Falls back to NewEvent's synthesized ID when the platform sends no such header.

func (WebhookEnvelope) Read

func (e WebhookEnvelope) Read(r *http.Request, secret string) (string, []byte, error)

Read validates the signature via the platform's registered validator, restores the body for downstream parsing, and returns the event-type header ("" when EventHeaders is empty or unmatched) plus the raw payload. Error ops mirror the historical hand-written sequence: body-read failures surface under ParseWebhookEvent, validation failures under ValidateWebhookSignature.

Passing secret == SkipValidationSecret skips the signature validation step: see that constant for the hosts that need parse-only access.

type WebhookValidator

type WebhookValidator interface {
	Name() string
	Validate(r *http.Request, body []byte, secret string) error
}

WebhookValidator verifies the authenticity of an incoming webhook request. Implementations are stateless and safe for concurrent use.

The signature scheme varies per platform:

  • GitHub: HMAC-SHA256 of the body, sent in X-Hub-Signature-256.
  • GitLab: static token compared in constant time against X-Gitlab-Token.
  • Gitea / Forgejo: HMAC-SHA256 of the body, sent in X-Gitea-Signature.
  • GitCode: static password compared in constant time against X-GitCode-Token (an HMAC sign mode exists on the platform; its message format is not yet mirrored here).
  • Tencent: static token compared in constant time against X-Token.
  • Gitee: sign mode — Base64(HMAC-SHA256(secret, timestamp+"\n"+ secret)) in X-Gitee-Token with X-Gitee-Timestamp; or password mode — the plain password in X-Gitee-Token.

type WebhookValidatorRegistry

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

WebhookValidatorRegistry indexes WebhookValidator implementations by platform. It is safe for concurrent use; registrations happen during package init and reads happen on the request path. Storage delegates to oekit container.SafeMap.

func DefaultWebhookRegistry

func DefaultWebhookRegistry() *WebhookValidatorRegistry

DefaultWebhookRegistry returns the process-wide registry.

func NewWebhookValidatorRegistry

func NewWebhookValidatorRegistry() *WebhookValidatorRegistry

NewWebhookValidatorRegistry builds an empty registry.

func (*WebhookValidatorRegistry) Get

Get returns the validator for the given platform, or nil if none is registered.

func (*WebhookValidatorRegistry) Register

Register associates a validator with a platform.

func (*WebhookValidatorRegistry) Validate

func (r *WebhookValidatorRegistry) Validate(p model.Platform, req *http.Request, body []byte, secret string) error

Validate looks up the validator for the given platform and runs it. A nil validator or missing platform produces provider.ErrNotImplemented.

Jump to

Keyboard shortcuts

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