Documentation
¶
Overview ¶
Package trigger contains the provider-neutral, authenticated trigger dispatch core. HTTP and provider adapters are intentionally outside this package; P0 exposes only an in-process invocation seam for tests and server orchestration.
Index ¶
- Constants
- Variables
- func ExternalEventID(tc config.TriggerConfig, req TriggerRequest) (string, error)
- func FeishuEncrypt(encryptKey string, plain, iv []byte) string
- func Sign(secret, timestamp string, body []byte) string
- func SignDingTalk(secret, timestamp string) string
- func SignFeishu(encryptKey, timestamp, nonce string, body []byte) string
- func SignGitHub(secret string, body []byte) string
- func VerifyHMAC(tc config.TriggerConfig, body []byte, headers map[string]string, now time.Time) error
- type Admission
- type AuditFunc
- type AuthView
- type ConditionView
- type Decision
- type DedupView
- type DeliveryView
- type Endpoint
- type Engine
- func (e *Engine) Deliveries(name string, limit int) (rows []DeliveryView, known bool, err error)
- func (e *Engine) Endpoint(name string) (Endpoint, bool)
- func (e *Engine) Invoke(ctx context.Context, req TriggerRequest) (Result, error)
- func (e *Engine) List() []View
- func (e *Engine) Maintain(ctx context.Context) (settled, pruned int, err error)
- func (e *Engine) PruneReceipts() (int, error)
- func (e *Engine) Reconcile(_ context.Context) (int, error)
- func (e *Engine) Run(interval time.Duration, stop <-chan struct{}, onErr func(error))
- func (e *Engine) SetAudit(a AuditFunc)
- func (e *Engine) SetClaimTimeout(d time.Duration)
- func (e *Engine) SetClock(now func() time.Time)
- func (e *Engine) SetConfigFunc(f func() *config.Config)
- func (e *Engine) SetLimiter(l *Limiter)
- func (e *Engine) SetPreflight(f PreflightFunc)
- func (e *Engine) Show(name string) (View, bool)
- type Envelope
- type GitHubView
- type IMView
- type IssueView
- type JobGate
- type Limit
- type Limiter
- type LimitsView
- type PermissionFunc
- type PreflightFunc
- type RateLimitedError
- type RateView
- type Result
- type SubmitFunc
- type TriggerRequest
- type View
Constants ¶
const ( DingTalkTimestampHeader = "timestamp" DingTalkSignHeader = "sign" )
DingTalk robot callback headers the adapter reads.
const ( FeishuTimestampHeader = "X-Lark-Request-Timestamp" FeishuNonceHeader = "X-Lark-Request-Nonce" FeishuSignatureHeader = "X-Lark-Signature" )
Feishu event subscription headers the adapter reads.
const ( GitHubSignatureHeader = "X-Hub-Signature-256" GitHubDeliveryHeader = "X-GitHub-Delivery" GitHubEventHeader = "X-GitHub-Event" )
GitHub request headers the adapter reads.
const ( IgnoredPing = "ping" IgnoredEventNotListed = "event_not_listed" IgnoredConditionUnmet = "condition_not_met" )
Why a github delivery was acknowledged but not dispatched (the "reason" of the 200).
const ( IgnoredHandshake = "url_verification" IgnoredUnsupported = "unsupported_event" IgnoredNotText = "not_text" IgnoredFromBot = "from_bot" IgnoredNotAllowed = "not_allowed" IgnoredPrefixMismatch = "prefix_not_matched" IgnoredEmptyText = "empty_text" )
Why an IM delivery was acknowledged but not dispatched (the "reason" of the 200).
const ( ProviderGeneric = config.TriggerProviderGeneric ProviderGitHub = config.TriggerProviderGitHub // The IM inbound adapters (im.go): they verify the platform signature and normalize the // message into an Envelope. ProviderDingTalk = config.TriggerProviderDingTalk ProviderFeishu = config.TriggerProviderFeishu )
ProviderGeneric and ProviderGitHub are the adapter names (server.triggers[].provider).
const DefaultClaimTimeout = 5 * time.Minute
DefaultClaimTimeout is how long a claimed receipt may stay unfinished before a redelivery may take it over and the reconciler settles it.
const MaxHeaderValueBytes = 4096
MaxHeaderValueBytes bounds every request header the trigger reads (signature, timestamp, idempotency key and the headers input.vars / dedup.key refer to).
Variables ¶
var ( ErrUnknownTrigger = errors.New("unknown or disabled trigger") ErrUnauthenticated = errors.New("trigger authentication failed") ErrReplay = errors.New("trigger timestamp outside replay window") ErrBodyTooLarge = errors.New("trigger body exceeds limit") ErrEventIDTooLong = errors.New("trigger external event id is too long") // ErrEventInFlight: the same event is being handled by another request right now. The // sender should retry later; no job id exists yet. ErrEventInFlight = errors.New("trigger event is already being processed") // ErrBodyNotJSON: the body is not a JSON object. ErrBodyNotJSON = errors.New("trigger body must be a JSON object") // ErrInvalidInput: a declared input variable is missing or too large. The error text // names the variable, never its value. ErrInvalidInput = errors.New("trigger input is invalid") // ErrHeaderTooLarge: a header the trigger reads is longer than MaxHeaderValueBytes. ErrHeaderTooLarge = errors.New("trigger header exceeds limit") )
var ErrOwnerDenied = errors.New("trigger owner is not permitted to submit jobs")
ErrOwnerDenied is the permanent refusal of a trigger whose owner caller may not submit jobs right now (undeclared, root, or without job.submit). HTTP maps it to 403.
var ErrRateLimited = &RateLimitedError{}
ErrRateLimited matches any *RateLimitedError through errors.Is.
Functions ¶
func ExternalEventID ¶ added in v0.205.0
func ExternalEventID(tc config.TriggerConfig, req TriggerRequest) (string, error)
ExternalEventID resolves the external event id of a request: the adapter's, else the configured dedup.key reference, else the Idempotency-Key header. An empty result means "no stable event id": the request is delivered at least once and not deduplicated (design 7a); it is not an error.
func FeishuEncrypt ¶ added in v0.207.0
FeishuEncrypt is the platform's encryption, used by tests to build encrypted fixtures.
func Sign ¶ added in v0.207.0
Sign returns the signature header value of the generic scheme: "sha256=" followed by the hex HMAC-SHA256 of timestamp + "\n" + body, with timestamp the exact header text. It is the one place the algorithm is written, shared by VerifyHMAC, the CLI self-test and tests.
func SignDingTalk ¶ added in v0.207.0
SignDingTalk returns the "sign" header value for a timestamp (milliseconds, as sent).
func SignFeishu ¶ added in v0.207.0
SignFeishu returns the X-Lark-Signature value; shared by the adapter and tests.
func SignGitHub ¶ added in v0.207.0
SignGitHub returns the X-Hub-Signature-256 value of body; shared by the adapter and tests.
func VerifyHMAC ¶
Types ¶
type Admission ¶ added in v0.205.0
type Admission struct {
// contains filtered or unexported fields
}
Admission is the owner-admission seam of design 3.2: the trigger's fixed request is judged against the OWNER's current effective permission and ceiling before the job layer takes it. The decision is made on every call from the live configuration and grants, never from a snapshot taken at load, so revoking job.submit (or tightening the ceiling) stops the next invocation.
func NewAdmission ¶ added in v0.205.0
func NewAdmission(cfg func() *config.Config, jobs JobGate, can PermissionFunc) *Admission
NewAdmission builds the admission over the live config, the job layer and the permission model.
func (*Admission) CheckOwner ¶ added in v0.205.0
CheckOwner refuses an owner that is not a declared, non-root caller holding job.submit.
type AuditFunc ¶
type AuditFunc func(jobstore.TriggerAuditEvent) error
type AuthView ¶ added in v0.207.0
type AuthView struct {
Kind string `json:"kind"`
SecretEnv string `json:"secret_env"`
SecretConfigured bool `json:"secret_configured"`
TimestampHeader string `json:"timestamp_header"`
SignatureHeader string `json:"signature_header"`
ReplayWindowSec int `json:"replay_window_sec"`
// VerificationTokenEnv / VerificationTokenConfigured: feishu only (the token value never appears).
VerificationTokenEnv string `json:"verification_token_env,omitempty"`
VerificationTokenConfigured bool `json:"verification_token_configured,omitempty"`
}
AuthView shows how a request is authenticated, never the secret.
type ConditionView ¶ added in v0.207.0
type Decision ¶ added in v0.205.0
type Decision struct {
OK bool
// RetryAfter is how long until the refused request could pass (token refill time, or
// a short fixed hint when the in-flight cap is what refused it). It is what a Retry-After
// header is made of; zero when OK.
RetryAfter time.Duration
}
Decision is the verdict of Limiter.Acquire.
type DeliveryView ¶ added in v0.207.0
type DeliveryView struct {
EventHash string `json:"event_hash"`
Status string `json:"status"`
JobID string `json:"job_id,omitempty"`
RequestID string `json:"request_id,omitempty"`
ReceivedAt int64 `json:"received_at"`
// Error is the (truncated) failure text of a failed or rejected delivery.
Error string `json:"error,omitempty"`
}
DeliveryView is one receipt as the read routes show it: the event id only as a truncated hash, the status, the job and the time; the payload is not stored and never shown.
type Endpoint ¶ added in v0.207.0
type Endpoint struct {
MaxBodyBytes int
// Headers are the request headers the engine reads for this trigger (canonical or not;
// matching is case-insensitive).
Headers []string
}
Endpoint is what an HTTP entry needs to know about a trigger BEFORE it reads the request body: how much it may read and which headers matter. It exists for enabled triggers only; a disabled or unknown name has no endpoint, which is how both answer the same 404.
func (Endpoint) CollectHeaders ¶ added in v0.207.0
CollectHeaders reads the headers of the endpoint through get (a case-insensitive header lookup) and keeps only those: nothing else of the request reaches the engine. A value longer than MaxHeaderValueBytes is ErrHeaderTooLarge.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
func NewServerEngine ¶ added in v0.205.0
NewServerEngine is the production assembly: the live config, the job layer behind the owner admission, and the durable receipts of the job store.
func (*Engine) Deliveries ¶ added in v0.207.0
Deliveries lists the newest receipts of a configured trigger. known is false for a name the configuration does not declare.
func (*Engine) List ¶ added in v0.207.0
List describes every configured trigger (enabled or not) in configuration order.
func (*Engine) Maintain ¶ added in v0.205.0
Maintain runs one pass of the periodic work: settle interrupted claims, then prune expired receipts.
func (*Engine) PruneReceipts ¶ added in v0.205.0
PruneReceipts deletes receipts whose dedup window has passed.
func (*Engine) Reconcile ¶ added in v0.205.0
Reconcile settles receipts that stayed claimed longer than the claim timeout (the process died between the claim and the end of the submit; design 3.5). The receipt does not keep the payload, so the reconciler cannot rebuild the request; it can only find out what happened:
- the job layer holds a job under the receipt's request id: the submit did succeed, the receipt becomes submitted with that job id;
- otherwise nothing was created: the receipt becomes failed, and the sender's redelivery takes it over (Engine.claim) and submits under the same request id.
The updates are compare-and-set on status=claimed, so a request that finishes meanwhile is never overwritten. It returns how many receipts were settled.
func (*Engine) Run ¶ added in v0.205.0
Run calls Maintain once at start (the startup reconciler) and then every interval until stop closes.
func (*Engine) SetClaimTimeout ¶ added in v0.205.0
SetClaimTimeout overrides DefaultClaimTimeout.
func (*Engine) SetConfigFunc ¶ added in v0.205.0
SetConfigFunc makes the engine read the configuration per call, so a reload applies.
func (*Engine) SetLimiter ¶
func (*Engine) SetPreflight ¶ added in v0.205.0
func (e *Engine) SetPreflight(f PreflightFunc)
type Envelope ¶ added in v0.207.0
type Envelope struct {
// Provider is the adapter name (dingtalk / feishu).
Provider string
// EventID is the platform's message / event id: the durable dedup key.
EventID string
// Timestamp is the platform's creation time of the message (zero when absent).
Timestamp time.Time
// SenderID / SenderName identify the human sender (the name may be empty).
SenderID, SenderName string
// ConversationID is the group / chat the message was sent in.
ConversationID string
// Text is the plain text with the bot mention and the command prefix removed.
Text string
// BodyHash is the hex SHA-256 of the raw request body, for correlation without storing it.
BodyHash string
}
Envelope is the provider-neutral inbound IM message (design P2.1). An IM adapter only verifies the platform signature and fills it; it never dispatches. Everything a template variable can see comes from here (config.IMVarFields), never from the raw payload.
type GitHubView ¶ added in v0.207.0
type GitHubView struct {
Events []string `json:"events"`
Conditions []ConditionView `json:"conditions,omitempty"`
MaxAgeSec int `json:"max_age_sec,omitempty"`
}
GitHubView summarizes the github provider's event filter.
type IMView ¶ added in v0.207.0
type IMView struct {
CommandPrefix string `json:"command_prefix,omitempty"`
AllowedConversations int `json:"allowed_conversations"`
AllowedSenders int `json:"allowed_senders"`
}
IMView summarizes the IM provider's message filter: the prefix and how many allowlist entries exist (the ids themselves are not shown).
type IssueView ¶ added in v0.207.0
IssueView is one reason an enabled trigger is unavailable (config.TriggerIssue).
type JobGate ¶ added in v0.205.0
type JobGate interface {
PreflightFixedRequest(job.JobRequest) error
Submit(job.JobRequest) (job.JobResult, error)
}
JobGate is what admission needs from the job layer.
type Limit ¶ added in v0.205.0
Limit is ONE bucket a request must pass: a token bucket (RatePerSec refills, Burst capacity) plus an in-flight cap. A zero RatePerSec means "no rate gating" and a zero MaxInflight "no in-flight cap". Key names the bucket, so two limits with the same key share state (the owner caller's limit is shared by all its triggers).
func EffectiveLimits ¶ added in v0.205.0
func EffectiveLimits(tc config.TriggerConfig, sc *config.ServerConfig) []Limit
EffectiveLimits is the set of limits a request to tc must pass: the trigger's own (per_minute with burst, max_inflight) and the owner caller's (rate_limit / rate_burst and max_concurrent_jobs, with the governance defaults), each in its own bucket. Acquire admits only when every one admits, which is the "stricter of the two" rule of design 3.5-4: a trigger can lower its own rate below the owner's, never raise it above.
The owner's bucket is shared by all of its triggers.
type Limiter ¶
type Limiter struct {
// contains filtered or unexported fields
}
Limiter is an in-process token-bucket limiter with an injected clock. The state is deliberately not persisted (design 7a: memory limiter + durable idempotency).
func NewLimiter ¶
NewLimiter builds a limiter that reads time from now (time.Now when nil).
func (*Limiter) Acquire ¶ added in v0.205.0
Acquire passes a request through every limit atomically: it is admitted only if ALL limits admit it, and then consumes one token and one in-flight slot from each; a refusal consumes nothing. The returned release must be called when the request is done (it is idempotent and a no-op for a refused request).
When several limits refuse, RetryAfter is the longest wait, since the request needs every one of them to open.
type LimitsView ¶ added in v0.207.0
type PermissionFunc ¶ added in v0.205.0
PermissionFunc answers whether a user-class caller currently holds a permission, with the live effective-permission model (config-derived plus database grants). It is injected by the process assembly, so this package depends on neither httpapi nor the grant store.
type PreflightFunc ¶ added in v0.205.0
type PreflightFunc func(context.Context, job.JobRequest) error
PreflightFunc judges a fixed request without submitting it (see Admission.Preflight).
type RateLimitedError ¶ added in v0.205.0
RateLimitedError is the 429 case. RetryAfter is what a Retry-After header is made of.
func (*RateLimitedError) Error ¶ added in v0.205.0
func (e *RateLimitedError) Error() string
func (*RateLimitedError) Is ¶ added in v0.205.0
func (e *RateLimitedError) Is(target error) bool
Is makes errors.Is(err, ErrRateLimited) true for every rate-limit refusal.
type Result ¶
type Result struct {
RequestID, JobID string
Duplicate bool
// Status is the receipt status for a duplicate (submitted / rejected).
Status string
// Ignored is true when an authenticated delivery was acknowledged without dispatching
// (an event the trigger does not subscribe to, a failed condition, a ping); Reason says
// why (Ignored* constants). No receipt exists for it and no job was created.
Ignored bool
Reason string
// Challenge is the answer of a platform endpoint-verification handshake (Feishu); the
// HTTP entry returns it instead of the usual body.
Challenge string
}
type SubmitFunc ¶
type TriggerRequest ¶
type TriggerRequest struct {
TriggerName string
RequestID string
// ExternalEventID, when set by a provider adapter, wins over dedup.key / Idempotency-Key.
ExternalEventID string
ReceivedAt time.Time
RawBody []byte
Headers map[string]string
Payload map[string]any
Source string
// Provider names the adapter ("" = generic). RemoteAddr is hashed before it reaches the
// audit trail; it stays empty until an HTTP entry exists.
Provider string
RemoteAddr string
}
type View ¶ added in v0.207.0
type View struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
Owner string `json:"owner_caller"`
Project string `json:"project"`
Template string `json:"template"`
Provider string `json:"provider"`
// GitHub is the event filter summary of a github trigger (no secret, no payload).
GitHub *GitHubView `json:"github,omitempty"`
// IM is the message filter summary of an IM trigger (no ids, no secret).
IM *IMView `json:"im,omitempty"`
Auth AuthView `json:"auth"`
Dedup DedupView `json:"dedup"`
Rate RateView `json:"rate"`
Limits LimitsView `json:"limits"`
// Inputs are the declared template variables and the payload field each is read from.
Inputs map[string]string `json:"inputs,omitempty"`
// Available is false while an enabled trigger cannot work on this server (see Issues).
Available bool `json:"available"`
Issues []IssueView `json:"issues,omitempty"`
// Last is the newest delivery, nil when none is on record.
Last *DeliveryView `json:"last_delivery,omitempty"`
}
View is the redacted, operator-facing description of a trigger. It is what GET /v1/triggers, `gofer tool trigger` and the MCP tools show: the fixed resources, the policies, and whether the secret is configured. The secret value, the signature and any payload never appear.