Skip to main content

Contexts Reference

Context objects provide access to databases, authentication, environment variables, and dispatch capabilities within Forge handlers.

AuthContext

Authentication state for the current request. Available on all contexts via the auth field.

Fields

FieldTypeDescription
--Fields are private; use methods below

Methods

MethodSignatureDescription
is_authenticatedfn is_authenticated(&self) -> boolCheck if user is authenticated
user_idfn user_id(&self) -> Option<Uuid>Get user ID (if UUID-based auth)
require_user_idfn require_user_id(&self) -> Result<Uuid>Get user ID or return 401 error
subjectfn subject(&self) -> Option<&str>Get raw subject claim (any format)
require_subjectfn require_subject(&self) -> Result<&str>Get subject or return 401 error
has_rolefn has_role(&self, role: &str) -> boolCheck if user has role
require_rolefn require_role(&self, role: &str) -> Result<()>Require role or return 403 error
claimfn claim(&self, key: &str) -> Option<&Value>Get custom JWT claim
rolesfn roles(&self) -> &[String]Get all user roles

Constructors (Testing)

ConstructorSignatureDescription
unauthenticatedfn unauthenticated() -> SelfCreate unauthenticated context
authenticatedfn authenticated(user_id: Uuid, roles: Vec<String>, claims: HashMap<String, Value>) -> SelfCreate authenticated context with UUID
authenticated_without_uuidfn authenticated_without_uuid(roles: Vec<String>, claims: HashMap<String, Value>) -> SelfCreate authenticated context for non-UUID providers (Firebase, Clerk)

QueryContext

Read-only database access for query handlers.

Fields

FieldTypeDescription
authAuthContextAuthentication context
requestRequestMetadataRequest metadata (trace ID, client IP, timestamp)

Methods

MethodSignatureDescription
dbfn db(&self) -> &PgPoolGet database connection pool
require_user_idfn require_user_id(&self) -> Result<Uuid>Get user ID or return error
require_subjectfn require_subject(&self) -> Result<&str>Get subject or return error
envfn env(&self, key: &str) -> Option<String>Get environment variable
env_orfn env_or(&self, key: &str, default: &str) -> StringGet env var with default
env_requirefn env_require(&self, key: &str) -> Result<String>Get required env var
env_parsefn env_parse<T: FromStr>(&self, key: &str) -> Result<T>Parse env var to type
env_parse_orfn env_parse_or<T: FromStr>(&self, key: &str, default: T) -> Result<T>Parse env var with default
env_containsfn env_contains(&self, key: &str) -> boolCheck if env var is set

MutationContext

Transactional database access with HTTP client and job/workflow dispatch.

Fields

FieldTypeDescription
authAuthContextAuthentication context
requestRequestMetadataRequest metadata (trace ID, client IP, timestamp)

Methods

MethodSignatureDescription
dbfn db(&self) -> &PgPoolGet database connection pool
httpfn http(&self) -> &ClientGet HTTP client for external calls
require_user_idfn require_user_id(&self) -> Result<Uuid>Get user ID or return error
require_subjectfn require_subject(&self) -> Result<&str>Get subject or return error
dispatch_jobasync fn dispatch_job<T: Serialize>(&self, job_type: &str, args: T) -> Result<Uuid>Dispatch a background job
start_workflowasync fn start_workflow<T: Serialize>(&self, workflow_name: &str, input: T) -> Result<Uuid>Start a workflow
envfn env(&self, key: &str) -> Option<String>Get environment variable
env_orfn env_or(&self, key: &str, default: &str) -> StringGet env var with default
env_requirefn env_require(&self, key: &str) -> Result<String>Get required env var
env_parsefn env_parse<T: FromStr>(&self, key: &str) -> Result<T>Parse env var to type
env_parse_orfn env_parse_or<T: FromStr>(&self, key: &str, default: T) -> Result<T>Parse env var with default
env_containsfn env_contains(&self, key: &str) -> boolCheck if env var is set

JobContext

Background job execution context with progress reporting and heartbeats.

Fields

FieldTypeDescription
job_idUuidUnique job identifier
job_typeStringJob type name
attemptu32Current attempt number (1-based)
max_attemptsu32Maximum allowed attempts
authAuthContextAuthentication context

Methods

MethodSignatureDescription
dbfn db(&self) -> &PgPoolGet database connection pool
httpfn http(&self) -> &ClientGet HTTP client for external calls
progressfn progress(&self, percentage: u8, message: impl Into<String>) -> Result<()>Report progress (0-100, clamped)
heartbeatasync fn heartbeat(&self) -> Result<()>Send heartbeat to prevent stale reclaim
saveasync fn save(&self, key: &str, value: Value) -> Result<()>Save data for retries/compensation
savedasync fn saved(&self) -> ValueGet all saved job data
set_savedasync fn set_saved(&self, data: Value) -> Result<()>Replace all saved data
is_cancel_requestedasync fn is_cancel_requested(&self) -> Result<bool>Check if cancellation was requested
check_cancelledasync fn check_cancelled(&self) -> Result<()>Return error if cancellation requested
is_retryfn is_retry(&self) -> boolCheck if this is a retry attempt
is_last_attemptfn is_last_attempt(&self) -> boolCheck if this is the final attempt
envfn env(&self, key: &str) -> Option<String>Get environment variable
env_orfn env_or(&self, key: &str, default: &str) -> StringGet env var with default
env_requirefn env_require(&self, key: &str) -> Result<String>Get required env var
env_parsefn env_parse<T: FromStr>(&self, key: &str) -> Result<T>Parse env var to type
env_parse_orfn env_parse_or<T: FromStr>(&self, key: &str, default: T) -> Result<T>Parse env var with default
env_containsfn env_contains(&self, key: &str) -> boolCheck if env var is set

CronContext

Scheduled task execution context with timing information.

Fields

FieldTypeDescription
run_idUuidUnique run identifier
cron_nameStringCron job name
scheduled_timeDateTime<Utc>When the cron was supposed to run
execution_timeDateTime<Utc>Actual execution start time
timezoneStringConfigured timezone
is_catch_upboolWhether this is a catch-up run after downtime
authAuthContextAuthentication context
logCronLogStructured logger

Methods

MethodSignatureDescription
dbfn db(&self) -> &PgPoolGet database connection pool
httpfn http(&self) -> &ClientGet HTTP client for external calls
delayfn delay(&self) -> DurationTime between scheduled and actual execution
is_latefn is_late(&self) -> boolCheck if delay exceeds 1 minute
envfn env(&self, key: &str) -> Option<String>Get environment variable
env_orfn env_or(&self, key: &str, default: &str) -> StringGet env var with default
env_requirefn env_require(&self, key: &str) -> Result<String>Get required env var
env_parsefn env_parse<T: FromStr>(&self, key: &str) -> Result<T>Parse env var to type
env_parse_orfn env_parse_or<T: FromStr>(&self, key: &str, default: T) -> Result<T>Parse env var with default
env_containsfn env_contains(&self, key: &str) -> boolCheck if env var is set

CronLog Methods

MethodSignatureDescription
infofn info(&self, message: &str, data: Value)Log info with structured data
warnfn warn(&self, message: &str, data: Value)Log warning with structured data
errorfn error(&self, message: &str, data: Value)Log error with structured data
debugfn debug(&self, message: &str, data: Value)Log debug with structured data

WorkflowContext

Durable workflow execution with step tracking, sleep, events, and compensation.

Fields

FieldTypeDescription
run_idUuidUnique workflow run identifier
workflow_nameStringWorkflow name
versionu32Workflow version
started_atDateTime<Utc>When the workflow started
authAuthContextAuthentication context

Methods

MethodSignatureDescription
dbfn db(&self) -> &PgPoolGet database connection pool
httpfn http(&self) -> &ClientGet HTTP client for external calls
workflow_timefn workflow_time(&self) -> DateTime<Utc>Deterministic time (consistent across replays)
elapsedfn elapsed(&self) -> DurationTime since workflow started
is_resumedfn is_resumed(&self) -> boolCheck if this is a resumed execution
tenant_idfn tenant_id(&self) -> Option<Uuid>Get tenant ID for multi-tenancy
envfn env(&self, key: &str) -> Option<String>Get environment variable
env_orfn env_or(&self, key: &str, default: &str) -> StringGet env var with default
env_requirefn env_require(&self, key: &str) -> Result<String>Get required env var
env_parsefn env_parse<T: FromStr>(&self, key: &str) -> Result<T>Parse env var to type
env_parse_orfn env_parse_or<T: FromStr>(&self, key: &str, default: T) -> Result<T>Parse env var with default
env_containsfn env_contains(&self, key: &str) -> boolCheck if env var is set

Step Execution

MethodSignatureDescription
stepfn step<T, F, Fut>(&self, name: impl Into<String>, f: F) -> StepRunner<T>Create a step with fluent API
parallelfn parallel(&self) -> ParallelBuilderCreate parallel step builder

Durable Operations

MethodSignatureDescription
sleepasync fn sleep(&self, duration: Duration) -> Result<()>Durable sleep (survives restarts)
sleep_untilasync fn sleep_until(&self, wake_at: DateTime<Utc>) -> Result<()>Sleep until specific time
wait_for_eventasync fn wait_for_event<T: DeserializeOwned>(&self, event_name: &str, timeout: Option<Duration>) -> Result<T>Wait for external event

Step State

MethodSignatureDescription
is_step_completedfn is_step_completed(&self, name: &str) -> boolCheck if step completed
is_step_startedfn is_step_started(&self, name: &str) -> boolCheck if step started (running, completed, or failed)
get_step_resultfn get_step_result<T: DeserializeOwned>(&self, name: &str) -> Option<T>Get completed step result
get_step_statefn get_step_state(&self, name: &str) -> Option<StepState>Get full step state
all_step_statesfn all_step_states(&self) -> HashMap<String, StepState>Get all step states
completed_steps_reversedfn completed_steps_reversed(&self) -> Vec<String>Get completed steps in reverse order

Compensation

MethodSignatureDescription
register_compensationfn register_compensation(&self, step_name: &str, handler: CompensationHandler)Register rollback handler
get_compensation_handlerfn get_compensation_handler(&self, step_name: &str) -> Option<CompensationHandler>Get compensation handler
has_compensationfn has_compensation(&self, step_name: &str) -> boolCheck if step has compensation
run_compensationasync fn run_compensation(&self) -> Vec<(String, bool)>Run all compensations in reverse

StepRunner (Fluent API)

Created via ctx.step(name, || async { ... }).

MethodSignatureDescription
compensatefn compensate<F, Fut>(self, f: F) -> SelfSet rollback handler
timeoutfn timeout(self, duration: Duration) -> SelfSet step timeout
optionalfn optional(self) -> SelfMark step as optional (failure continues workflow)
runasync fn run(self) -> Result<T>Execute the step

ParallelBuilder

Created via ctx.parallel().

MethodSignatureDescription
stepfn step<T, F, Fut>(self, name: &str, handler: F) -> SelfAdd parallel step
step_with_compensatefn step_with_compensate<T, F, Fut, C, CFut>(self, name: &str, handler: F, compensate: C) -> SelfAdd parallel step with compensation
runasync fn run(self) -> Result<ParallelResults>Execute all steps in parallel

ParallelResults

Returned by ParallelBuilder::run().

MethodSignatureDescription
getfn get<T: DeserializeOwned>(&self, step_name: &str) -> Result<T>Get typed result by step name
containsfn contains(&self, step_name: &str) -> boolCheck if result exists
lenfn len(&self) -> usizeNumber of results
is_emptyfn is_empty(&self) -> boolCheck if empty
iterfn iter(&self) -> impl Iterator<Item = (&String, &Value)>Iterate over results

DaemonContext

Long-running service context with shutdown signaling and heartbeats.

Fields

FieldTypeDescription
daemon_nameStringDaemon name
instance_idUuidUnique instance identifier

Methods

MethodSignatureDescription
dbfn db(&self) -> &PgPoolGet database connection pool
httpfn http(&self) -> &ClientGet HTTP client for external calls
is_shutdown_requestedfn is_shutdown_requested(&self) -> boolCheck if shutdown was requested
shutdown_signalasync fn shutdown_signal(&self)Wait for shutdown signal
heartbeatasync fn heartbeat(&self) -> Result<()>Send heartbeat to indicate daemon is alive
envfn env(&self, key: &str) -> Option<String>Get environment variable
env_orfn env_or(&self, key: &str, default: &str) -> StringGet env var with default
env_requirefn env_require(&self, key: &str) -> Result<String>Get required env var
env_parsefn env_parse<T: FromStr>(&self, key: &str) -> Result<T>Parse env var to type
env_parse_orfn env_parse_or<T: FromStr>(&self, key: &str, default: T) -> Result<T>Parse env var with default
env_containsfn env_contains(&self, key: &str) -> boolCheck if env var is set

Graceful Shutdown Pattern

loop {
tokio::select! {
_ = do_work() => {}
_ = ctx.shutdown_signal() => break,
}
}

WebhookContext

Incoming webhook handler context with headers, job dispatch, and idempotency.

Fields

FieldTypeDescription
webhook_nameStringWebhook handler name
request_idStringUnique request identifier
idempotency_keyOption<String>Extracted idempotency key (if configured)

Methods

MethodSignatureDescription
dbfn db(&self) -> &PgPoolGet database connection pool
httpfn http(&self) -> &ClientGet HTTP client for external calls
headerfn header(&self, name: &str) -> Option<&str>Get request header (case-insensitive)
headersfn headers(&self) -> &HashMap<String, String>Get all headers
dispatch_jobasync fn dispatch_job<T: Serialize>(&self, job_type: &str, args: T) -> Result<Uuid>Dispatch background job for async processing
envfn env(&self, key: &str) -> Option<String>Get environment variable
env_orfn env_or(&self, key: &str, default: &str) -> StringGet env var with default
env_requirefn env_require(&self, key: &str) -> Result<String>Get required env var
env_parsefn env_parse<T: FromStr>(&self, key: &str) -> Result<T>Parse env var to type
env_parse_orfn env_parse_or<T: FromStr>(&self, key: &str, default: T) -> Result<T>Parse env var with default
env_containsfn env_contains(&self, key: &str) -> boolCheck if env var is set

RequestMetadata

Metadata about the incoming request. Available on QueryContext and MutationContext.

Fields

FieldTypeDescription
request_idUuidUnique request identifier
trace_idStringDistributed tracing ID
client_ipOption<String>Client IP address
user_agentOption<String>User agent string
timestampDateTime<Utc>Request timestamp

Environment Variables

All contexts implement EnvAccess for type-safe environment variable access.

MethodSignatureDescription
envfn env(&self, key: &str) -> Option<String>Get env var, returns None if unset
env_orfn env_or(&self, key: &str, default: &str) -> StringGet env var with default value
env_requirefn env_require(&self, key: &str) -> Result<String>Get env var, returns error if unset
env_parsefn env_parse<T: FromStr>(&self, key: &str) -> Result<T>Parse env var to type
env_parse_orfn env_parse_or<T: FromStr>(&self, key: &str, default: T) -> Result<T>Parse env var with default
env_containsfn env_contains(&self, key: &str) -> boolCheck if env var is set
// Get optional env var
let timeout = ctx.env("API_TIMEOUT");

// Get with default
let timeout = ctx.env_or("API_TIMEOUT", "30");

// Get required (returns error if missing)
let api_key = ctx.env_require("API_KEY")?;

// Parse to type
let port: u16 = ctx.env_parse("PORT")?;

// Parse with default
let max_retries: u32 = ctx.env_parse_or("MAX_RETRIES", 3)?;

StepState

Workflow step state (returned by get_step_state).

Fields

FieldTypeDescription
nameStringStep name
statusStepStatusCurrent status
resultOption<Value>Serialized result (if completed)
errorOption<String>Error message (if failed)
started_atOption<DateTime<Utc>>When step started
completed_atOption<DateTime<Utc>>When step completed

StepStatus

VariantDescription
PendingStep not yet started
RunningStep currently executing
CompletedStep finished successfully
FailedStep failed with error
CompensatedStep rolled back via compensation