trigger

package
v0.205.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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.

Variables

View Source
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")
)
View Source
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.

View Source
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 VerifyHMAC

func VerifyHMAC(tc config.TriggerConfig, body []byte, headers map[string]string, now time.Time) error

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

func (a *Admission) CheckOwner(owner string) error

CheckOwner refuses an owner that is not a declared, non-root caller holding job.submit.

func (*Admission) Preflight added in v0.205.0

func (a *Admission) Preflight(_ context.Context, req job.JobRequest) error

Preflight judges the fixed request without submitting: owner permission, then the job layer's side-effect-free ceiling / template / project / agent / runner check.

func (*Admission) Submit added in v0.205.0

func (a *Admission) Submit(_ context.Context, req job.JobRequest) (string, error)

Submit re-checks the owner (it may have been revoked since Preflight) and submits. The job layer repeats the ceiling admission against req.OriginCaller.

type AuditFunc

type AuditFunc func(jobstore.TriggerAuditEvent) error

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 Engine

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

func NewEngine

func NewEngine(cfg *config.Config, store *jobstore.Store, submit SubmitFunc) *Engine

func NewServerEngine added in v0.205.0

func NewServerEngine(cfg func() *config.Config, jobs *job.Service, can PermissionFunc) *Engine

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) Invoke

func (e *Engine) Invoke(ctx context.Context, req TriggerRequest) (Result, error)

func (*Engine) Maintain added in v0.205.0

func (e *Engine) Maintain(ctx context.Context) (settled, pruned int, err error)

Maintain runs one pass of the periodic work: settle interrupted claims, then prune expired receipts.

func (*Engine) PruneReceipts added in v0.205.0

func (e *Engine) PruneReceipts() (int, error)

PruneReceipts deletes receipts whose dedup window has passed.

func (*Engine) Reconcile added in v0.205.0

func (e *Engine) Reconcile(_ context.Context) (int, error)

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

func (e *Engine) Run(interval time.Duration, stop <-chan struct{}, onErr func(error))

Run calls Maintain once at start (the startup reconciler) and then every interval until stop closes.

func (*Engine) SetAudit

func (e *Engine) SetAudit(a AuditFunc)

func (*Engine) SetClaimTimeout added in v0.205.0

func (e *Engine) SetClaimTimeout(d time.Duration)

SetClaimTimeout overrides DefaultClaimTimeout.

func (*Engine) SetClock

func (e *Engine) SetClock(now func() time.Time)

func (*Engine) SetConfigFunc added in v0.205.0

func (e *Engine) SetConfigFunc(f func() *config.Config)

SetConfigFunc makes the engine read the configuration per call, so a reload applies.

func (*Engine) SetLimiter

func (e *Engine) SetLimiter(l *Limiter)

func (*Engine) SetPreflight added in v0.205.0

func (e *Engine) SetPreflight(f PreflightFunc)

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

type Limit struct {
	Key         string
	RatePerSec  float64
	Burst       int
	MaxInflight int
}

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

func NewLimiter(now func() time.Time) *Limiter

NewLimiter builds a limiter that reads time from now (time.Now when nil).

func (*Limiter) Acquire added in v0.205.0

func (l *Limiter) Acquire(limits ...Limit) (release func(), d Decision)

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 PermissionFunc added in v0.205.0

type PermissionFunc func(callerID, permission string) bool

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

type RateLimitedError struct{ RetryAfter time.Duration }

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
}

type SubmitFunc

type SubmitFunc func(context.Context, job.JobRequest) (string, error)

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
}

Jump to

Keyboard shortcuts

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