DBOS Contexts
Background
DBOS automatically supplies a context to each registered function. A function can use its context to call other DBOS functions, interact with the runtime or the database, and access the logger. Each DBOS function has a specific context:
- Contexts used within DBOS functions inherit from
DBOSContext
. - Handlers use
HandlerContext
. - Workflows use
WorkflowContext
. - Transactions use
TransactionContext<T>
with a specific database client type. - Steps use
StepContext
. - Initialization functions use
InitContext
. - Middleware functions use
MiddlewareContext
. - Event receivers use
DBOSExecutorContext
.
DBOSContext
Many contexts inherit from DBOSContext
and share its properties and methods. (InitContext
and MiddlewareContext
are exceptions, as these are applied outside the context of DBOS functions.)
Properties
Methods
ctxt.request
readonly request: HTTPRequest
An object with information about the originating HTTP request that triggered this function (directly or indirectly).
interface HTTPRequest {
readonly headers?: IncomingHttpHeaders; // A node's http.IncomingHttpHeaders object.
readonly rawHeaders?: string[]; // Raw headers.
readonly params?: unknown; // Parsed path parameters from the URL.
readonly body?: unknown; // parsed HTTP body as an object.
readonly rawBody?: string; // Unparsed raw HTTP body string.
readonly query?: ParsedUrlQuery; // Parsed query string.
readonly querystring?: string; // Unparsed raw query string.
readonly url?: string; // Request URL.
readonly ip?: string; // Request remote address.
}
ctxt.workflowUUID
readonly workflowUUID: string
The current workflow's identity UUID, a string uniquely identifying a workflow execution. In a transaction or step, this field is set to the identity UUID of the calling workflow. In a handler, this field is empty.
ctxt.authenticatedUser
readonly authenticatedUser: string
The identity of the authenticated user who ran this function. Authenticated users are set by authentication middleware and inherited through the calling chain.
ctxt.authenticatedRoles
readonly authenticatedRoles: string[];
A list of roles the authenticated user has, if any. Authenticated roles are set by authentication middleware and inherited through the calling chain.
ctxt.assumedRole
readonly assumedRole: string;
The role used to run this function. Empty string if authorization is not required. DBOS's authorization sets the assumed role right before executing a function and this property is not inherited through the calling chain.
ctxt.logger
readonly logger: DBOSLogger
A reference to DBOS's logger. Please see our logging tutorial for more information.
ctxt.span
readonly span: Span
An OpenTelemetry Span associated with this context. You can assign custom trace attributes to this span. Please see the Span API for more information.
ctxt.getConfig
getConfig<T>(key: string): T | undefined;
getConfig<T>(key: string, defaultValue: T): T;
Retrieves an application property specified in the application section of the configuration. Optionally accepts a default value, returned when the key cannot be found in the configuration.
HandlerContext
Handlers use HandlerContext
to invoke other functions, interact with active workflows, and interact directly with HTTP requests and responses.
Properties
Methods
- invoke(target)
- invokeWorkflow(target, [workflowID])
- startWorkflow(target, [workflowID], [queue])
- retrieveWorkflow(workflowID)
- send(destinationUUID, message, [topic, idempotencyKey])
- getEvent(workflowID, key, [timeoutSeconds])
handlerCtxt.koaContext
koaContext: Koa.Context;
The Koa Context of the current request, giving handlers access to the raw HTTP request and response.
handlerCtxt.invoke
invoke<T>(target: T, workflowID?: string): InvokeFuncs<T>
Invoke a transaction or step on the target
class or configured instance.
To invoke workflows, use invokeWorkflow
or startWorkflow
instead.
The syntax for invoking function fn
in class Cls
with argument arg
is:
const output = await handlerCtxt.invoke(Cls).fn(arg);
You don't supply a context to the invoked function—the DBOS Transact runtime does this for you. You can optionally provide an idempotency key to the invoked function. For more information, see our idempotency tutorial.
handlerCtxt.invokeWorkflow
invokeWorkflow<T>(target: T, workflowID?: string): InvokeFuncs<T>
Invoke a workflow and wait for it to complete, returning its result.
To start a workflow without waiting for it to complete, use startWorkflow
.
The syntax for invoking workflow wf
in class Cls
with argument arg
is:
const output = await handlerCtxt.invokeWorkflow(Cls).wf(arg);
You don't supply a context to the invoked workflow—the DBOS Transact runtime does this for you.
handlerCtxt.startWorkflow
startWorkflow<T>(target: T, workflowID?: string, queue?: WorkflowQueue): InvokeFuncs<T>
Start or enqueue a workflow and return a handle to it.
This does not wait for the workflow to complete, though the resulting handle can be used to wait for the workflow result.
To start a workflow and wait for the result, see invokeWorkflow
.
The startWorkflow
method resolves after the handle is durably created; at this point the workflow is guaranteed to run to completion even if the handler is interrupted.
The syntax for starting workflow wf
in class Cls
with argument arg
is:
const workflowHandle = await handlerCtxt.startWorkflow(Cls).wf(arg);
If the workflowID
argument is provided, the workflow will execute exactly once per the specified ID.
If the queue
argument is provided, the workflow may not start immediately. Start of execution will be determined by the queue and its contents.
You don't supply a context to the newly started workflow—the DBOS Transact runtime does this for you.
handlerCtxt.retrieveWorkflow
retrieveWorkflow<R>(workflowID: string): WorkflowHandle<R>
Returns a workflow handle to the workflow with identity workflowID
.
R
is the return type of the target workflow.
handlerCtxt.send
send<T extends NonNullable<any>>(destinationUUID: string, message: T, topic?: string, idempotencyKey?: string): Promise<void>
Sends a message to workflow destinationUUID
.
Messages can optionally be associated with a topic.
You can provide an optional idempotency key to guarantee only a single message is sent even if send
is called more than once.
For more information, see our messages API tutorial.
handlerCtxt.getEvent
getEvent<T extends NonNullable<any>>(workflowID: string, key: string, timeoutSeconds?: number): Promise<T | null>
Retrieves an event published by workflowID
for a given key using the events API.
Awaiting on the promise returned by getEvent()
waits for the workflow to publish the key, returning null
if the wait times out.
handlerCtxt.getWorkflows
getWorkflows(input: GetWorkflowsInput): Promise<GetWorkflowsOutput>
This function allows querying workflow execution history. Its input is an object describing which workflows to retrieve (by default, retrieve all workflows):
export interface GetWorkflowsInput {
workflowName?: string; // The name of the workflow function
authenticatedUser?: string; // The user who ran the workflow.
startTime?: string; // Timestamp in RFC 3339 format
endTime?: string; // Timestamp in RFC 3339 format
status?: "PENDING" | "SUCCESS" | "ERROR" | "RETRIES_EXCEEDED" | "CANCELLED" ; // The status of the workflow.
applicationVersion?: string; // The application version that ran this workflow.
limit?: number; // Return up to this many workflows IDs. IDs are ordered by workflow creation time.
}
It returns as output an object containing a list of the UUIDs of all retrieved workflows, ordered by workflow creation time:
export interface GetWorkflowsOutput {
workflowUUIDs: string[];
}
To obtain further information about a particular workflow, call retrieveWorkflow
on its UUID to obtain its handle.
WorkflowContext
Workflows use WorkflowContext
to invoke other functions and interact with other workflows.
Methods
- invoke(target)
- invokeWorkflow(target)
- startWorkflow(target)
- send(destinationUUID, message, [topic])
- recv([topic, timeoutSeconds])
- setEvent(key, value)
- getEvent()
- retrieveWorkflow(workflowID)
- sleep(durationSec)
- sleepms(durationMS)
workflowCtxt.invoke
invoke<T>(target: T, workflowID?: string): InvokeFuncs<T>
Invoke transactions and steps.
To invoke other workflows, use invokeWorkflow
or startWorkflow
.
The syntax for invoking function fn
in class Cls
with argument arg
is:
const output = await workflowCtxt.invoke(Cls).fn(arg);
You don't supply a context to the invoked function—the DBOS Transact runtime does this for you.
workflowCtxt.invokeWorkflow
invokeWorkflow<T>(target: T)
Invoke a child workflow and wait for it to complete, returning its result.
To start a workflow without waiting it to complete, use startWorkflow
.
The syntax for invoking workflow wf
in class Cls
with argument arg
is:
const output = await ctxt.invokeWorkflow(Cls).wf(arg);
You don't supply a context to the invoked child workflow—the DBOS Transact runtime does this for you.
workflowCtxt.startWorkflow
startWorkflow<T>(target: T, workflowID?: string, queue?: WorkflowQueue).workflowFunction(args)
Start a child workflow and return a handle to it but do not wait for the workflow to complete.
This method resolves after the handle is durably created; at this point the workflow is guaranteed to run to completion.
The syntax for starting workflow wf
in class Cls
with argument arg
is:
const workflowHandle = await ctxt.startWorkflow(Cls).wf(arg);
If the workflowID
argument is provided, the workflow will execute exactly once per the specified ID.
If the queue
argument is provided, the workflow may not start immediately. Start of execution will be determined by the queue and its contents.
You don't supply a context to the newly started child workflow—the DBOS Transact runtime does this for you.
workflowCtxt.invokeChildWorkflow
Deprecated in favor of workflowCtxt.invokeWorkflow
, which is equivalent but syntactically simpler.
workflowCtxt.startChildWorkflow
Deprecated in favor of workflowCtxt.startWorkflow
, which is equivalent but syntactically simpler.
workflowCtxt.send
send<T extends NonNullable<any>>(destinationUUID: string, message: T, topic?: string): Promise<void>
Sends a message to destinationUUID
.
Messages can optionally be associated with a topic.
For more information, see our messages API tutorial.
workflowCtxt.recv
recv<T extends NonNullable<any>>(topic?: string, timeoutSeconds?: number): Promise<T | null>
Receive messages sent to the workflow, optionally for a particular topic.
Messages are dequeued first-in, first-out, from a queue associated with the topic.
Calls to recv()
wait for the next message in the queue, returning null
if the wait times out.
If no topic is specified, recv
can only access messages sent without a topic.
For more information, see our messages API tutorial.
workflowCtxt.setEvent
setEvent<T extends NonNullable<any>>(key: string, value: T): Promise<void>
Creates or updates an event named key
with value value
.
Workflows and HTTP handlers can read events by calling getEvent
with the workflow's UUID.
Events are mutable. Attempting to emit an event twice from a given workflow instance will update the value, but care should be taken to ensure that the value is calculated deterministically for consistency when workflows are recovered.
For more information, see our events API tutorial.
workflowCtxt.getEvent
getEvent<T extends NonNullable<any>>(workflowID: string, key: string, timeoutSeconds?: number): Promise<T | null>
Retrieves an event published by workflowID
for a given key using the events API.
Awaiting on the promise returned by getEvent()
waits for the workflow to set the key, returning null
if the wait times out.