@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 678 lines 26.3 KB
Raw
1 import * as Lambda from "@distilled.cloud/aws/lambda";
2 import type { PackageInstall } from "alchemy/Bundle/InstalledPackages";
3 import type { InputProps } from "alchemy/Input";
4 import * as Output from "alchemy/Output";
5 import type { PlatformServices } from "alchemy/Platform";
6 import { RuntimeContext } from "alchemy/RuntimeContext";
7 import { toSeconds, toWireDays } from "alchemy/Util/Duration";
8 import { effectClass, taggedFunction } from "alchemy/Util/effect";
9 import type { DistributiveOmit } from "alchemy/Util/types";
10 import type { ConfigError } from "effect/Config";
11 import * as Context from "effect/Context";
12 import type * as Duration from "effect/Duration";
13 import * as Effect from "effect/Effect";
14 import * as Effectable from "effect/Effectable";
15 import type * as Layer from "effect/Layer";
16 import * as Option from "effect/Option";
17 import type { Scope } from "effect/Scope";
18 import type { DurableExecutionContext, DurableStep } from "./Durable.ts";
19 import { DURABLE_SDK_MODULE, encodeDurableEnvelope, makeDurableListener } from "./DurableBridge.ts";
20 import { Function, type FunctionProps, type FunctionServices } from "./Function.ts";
21 import type { HandlerContext } from "./InvocationDeadline.ts";
22 import { qualifierOf } from "./QualifiedArn.ts";
23
24 type TypeId = "AWS.Lambda.DurableFunction";
25 const TypeId = "AWS.Lambda.DurableFunction" as const;
26
27 /**
28 * The services available inside a durable function's run body.
29 *
30 * The bridge provides all of them per durable invocation: `DurableStep`
31 * powers `Durable.step`/`Durable.sleep`/`Durable.waitForCallback`,
32 * `DurableExecutionContext` carries the execution ARN, `HandlerContext` is
33 * the raw `lambda.Context`, and a fresh `Scope` scopes per-invocation
34 * resources.
35 *
36 * Deliberately narrow: cloud clients (`Credentials`/`Region`-requiring
37 * effects) are NOT provided to the body directly — resolve typed binding
38 * clients in the init phase and call them inside `Durable.step`, which is
39 * exactly the determinism law the replay model requires.
40 */
41 export type DurableRunServices =
42 | DurableStep
43 | DurableExecutionContext
44 | HandlerContext
45 | Scope
46 // Runtime-only binding clients (`Alchemy.RuntimeContext`); provided per
47 // invocation from the function's own runtime context.
48 | RuntimeContext;
49
50 /**
51 * A durable function implementation: a function from a typed `Input` payload
52 * to an Effect producing the execution's `Result`. Code outside
53 * `Durable.step` re-runs on every replay and must be deterministic.
54 */
55 export type DurableFunctionImpl<Input = unknown, Result = unknown> = (
56 input: Input,
57 ) => Effect.Effect<Result, never, DurableRunServices>;
58
59 /**
60 * Services satisfied by the DurableFunction's own machinery (or the engine)
61 * and therefore excluded from the caller-facing requirements of the returned
62 * Effect/Layer.
63 */
64 export type DurableFunctionInitServices =
65 | FunctionServices
66 | PlatformServices
67 | Function
68 | DurableRunServices;
69
70 /**
71 * Properties of an {@link DurableFunction | AWS.Lambda.DurableFunction}.
72 *
73 * A DurableFunction accepts every {@link FunctionProps | Function prop}
74 * except `functionUrl` (every invocation of a durable function arrives as the
75 * durable-execution envelope — there is no HTTP surface), plus the
76 * `DurableConfig` tuning knobs below.
77 */
78 /** The DurableConfig tuning knobs a DurableFunction adds to Function props. */
79 export interface DurableFunctionTuning {
80 /**
81 * Maximum total duration of a durable execution, from start to terminal
82 * state (minimum 60 seconds, maximum 1 year). Rounded up to whole seconds.
83 * @default 24 hours (AWS default)
84 */
85 executionTimeout?: Duration.Input;
86 /**
87 * How long completed execution history is retained (e.g. `"7 days"`;
88 * 1–90 days). Rounded to whole days on the wire.
89 * @default "14 days" (AWS default)
90 */
91 retentionPeriod?: Duration.Input;
92 }
93
94 /**
95 * Props of a {@link DurableFunction}: any Function props that carry a
96 * `main` — the orchestrator body is an Effect that has to be bundled into
97 * an entrypoint — minus `functionUrl` (every invocation arrives as the
98 * durable envelope, so there is no HTTP surface), plus the DurableConfig
99 * knobs.
100 *
101 * Selected by SHAPE (`Extract<…, { main: string }>`), not by packaging, so
102 * any future main-bearing variant is durable-capable automatically; a
103 * prebuilt `image` function is excluded because it has no `main` for the
104 * `impl` Effect to live in.
105 *
106 * The Omit DISTRIBUTES over the union: a bare `Omit` computes the COMMON
107 * keys and merges the members, which would make `main` optional and let
108 * `image` through alongside it.
109 */
110 export type DurableFunctionProps = DistributiveOmit<
111 Extract<FunctionProps, { main: string }>,
112 "functionUrl" | "durableConfig"
113 > &
114 DurableFunctionTuning;
115
116 /**
117 * Options for starting a durable execution.
118 */
119 export interface DurableStartOptions<Input = unknown> {
120 /**
121 * Idempotent execution name (`DurableExecutionName`): starting again with
122 * the same name and payload reattaches to the existing execution; the same
123 * name with a different payload fails with
124 * `DurableExecutionAlreadyStartedException`.
125 */
126 name?: string;
127 /** The typed input payload delivered to the durable function body. */
128 params?: Input;
129 /**
130 * Function version or alias to pin the execution to. Durable executions
131 * replay against the version they started on. `$LATEST` is suitable for
132 * disposable development; production starts should target an immutable
133 * numbered {@link Version} or a stable {@link Alias}.
134 * @default the function's `alias` when set, otherwise `$LATEST`
135 */
136 qualifier?: string;
137 }
138
139 /**
140 * A started durable execution reference.
141 */
142 export interface DurableExecutionRef {
143 /** ARN of the durable execution (when returned by the Invoke response). */
144 executionArn: string | undefined;
145 statusCode: number | undefined;
146 }
147
148 /**
149 * The typed durable-execution handle: start, inspect, stop, and complete
150 * callbacks of durable executions of this function. Returned by
151 * `yield* MyDurableFunction` (as part of {@link DurableFunction}) and, inside
152 * the function's own init phase, by {@link DurableFunctionScope}.
153 */
154 export interface DurableFunctionHandle<Input = unknown, Result = unknown> {
155 Type: TypeId;
156 name: string;
157 /** @internal phantom */
158 Result?: Result;
159 /**
160 * Start a durable execution (async `Invoke` with the alchemy payload
161 * envelope). Returns immediately; the execution progresses through
162 * checkpointed re-invocations.
163 */
164 start(
165 options?: DurableStartOptions<Input>,
166 ): Effect.Effect<DurableExecutionRef, Lambda.InvokeError>;
167 /** Fetch the execution's status/result. */
168 get(
169 executionArn: string,
170 ): Effect.Effect<Lambda.GetDurableExecutionResponse, Lambda.GetDurableExecutionError>;
171 /** List executions of this function, optionally filtered by name/status. */
172 list(options?: {
173 name?: string;
174 statuses?: Lambda.ExecutionStatus[];
175 }): Effect.Effect<
176 Lambda.ListDurableExecutionsByFunctionResponse,
177 Lambda.ListDurableExecutionsByFunctionError
178 >;
179 /** Stop a running execution. */
180 stop(
181 executionArn: string,
182 error?: Lambda.ErrorObject,
183 ): Effect.Effect<Lambda.StopDurableExecutionResponse, Lambda.StopDurableExecutionError>;
184 /** Complete a `Durable.waitForCallback` from the outside. */
185 sendCallbackSuccess(
186 callbackId: string,
187 result?: unknown,
188 ): Effect.Effect<void, Lambda.SendDurableExecutionCallbackSuccessError>;
189 sendCallbackFailure(
190 callbackId: string,
191 error?: Lambda.ErrorObject,
192 ): Effect.Effect<void, Lambda.SendDurableExecutionCallbackFailureError>;
193 sendCallbackHeartbeat(
194 callbackId: string,
195 ): Effect.Effect<void, Lambda.SendDurableExecutionCallbackHeartbeatError>;
196 }
197
198 /**
199 * The value produced by `yield* MyDurableFunction`: the typed
200 * {@link DurableFunctionHandle} plus references to the underlying
201 * {@link Function} resource and its key attributes.
202 */
203 export interface DurableFunction<Input = unknown, Result = unknown> extends DurableFunctionHandle<
204 Input,
205 Result
206 > {
207 /** The underlying Lambda {@link Function} resource owned by this wrapper. */
208 function: Function;
209 /** Physical name of the underlying Lambda function. */
210 functionName: Function["functionName"];
211 /** ARN of the underlying Lambda function. */
212 functionArn: Function["functionArn"];
213 }
214
215 /**
216 * Inside a DurableFunction's init phase, resolves the function's own
217 * {@link DurableFunctionHandle} (e.g. for chained self-starts). Also what
218 * `yield* AWS.Lambda.DurableFunction` (the bare namespace value) resolves.
219 */
220 export class DurableFunctionScope extends Context.Service<
221 DurableFunctionScope,
222 DurableFunctionHandle
223 >()("AWS.Lambda.DurableFunctionScope") {}
224
225 export interface DurableFunctionClass {
226 <_Self>(): {
227 <Input = unknown, Result = unknown, PropsReq = never, InitReq = never>(
228 id: string,
229 props:
230 | InputProps<DurableFunctionProps>
231 | Effect.Effect<InputProps<DurableFunctionProps>, ConfigError, PropsReq>,
232 impl: Effect.Effect<DurableFunctionImpl<Input, Result>, ConfigError, InitReq>,
233 ): Effect.Effect<
234 DurableFunction<Input, Result>,
235 never,
236 Function["Providers"] | Exclude<PropsReq | InitReq, DurableFunctionInitServices>
237 > & {
238 new (_: never): DurableFunctionImpl<Input, Result>;
239 };
240 <const Id extends string>(
241 id: Id,
242 ): Effect.Effect<DurableFunction, never, Function["Providers"]> & {
243 make<Input = unknown, Result = unknown, PropsReq = never, InitReq = never>(
244 props:
245 | InputProps<DurableFunctionProps>
246 | Effect.Effect<InputProps<DurableFunctionProps>, ConfigError, PropsReq>,
247 impl: Effect.Effect<DurableFunctionImpl<Input, Result>, ConfigError, InitReq>,
248 ): Layer.Layer<
249 _Self,
250 never,
251 Function["Providers"] | Exclude<PropsReq | InitReq, DurableFunctionInitServices>
252 >;
253 new (_: never): {};
254 };
255 };
256 <Input = unknown, Result = unknown, PropsReq = never, InitReq = never>(
257 id: string,
258 props:
259 | InputProps<DurableFunctionProps>
260 | Effect.Effect<InputProps<DurableFunctionProps>, ConfigError, PropsReq>,
261 impl: Effect.Effect<DurableFunctionImpl<Input, Result>, ConfigError, InitReq>,
262 ): Effect.Effect<
263 DurableFunction<Input, Result>,
264 never,
265 Function["Providers"] | Exclude<PropsReq | InitReq, DurableFunctionInitServices>
266 >;
267 }
268
269 /**
270 * Where the composed init stashes the {@link DurableFunction} value on the
271 * owned Function instance so `yield*` of any authoring form can produce it.
272 * A symbol key passes through the Resource proxy untouched (string props
273 * fabricate `Output.PropExpr` accessors).
274 */
275 const DurableHandleKey = Symbol.for("alchemy/AWS.Lambda.DurableFunction");
276
277 /**
278 * Vendor the Durable Execution SDK into the artifact. `build.install` roots
279 * are excluded from the bundle and npm-installed into the zip targeting the
280 * function's architecture, so this single entry both externalizes the SDK
281 * (the bridge dynamic-imports it at runtime) and ships it. Respects an
282 * explicit user entry (e.g. a pinned version).
283 */
284 const withDurableSdkInstall = (install: PackageInstall | undefined): PackageInstall => {
285 if (install === undefined) {
286 return [DURABLE_SDK_MODULE];
287 }
288 if (Array.isArray(install)) {
289 return install.includes(DURABLE_SDK_MODULE) ? install : [...install, DURABLE_SDK_MODULE];
290 }
291 const record = install as Readonly<Record<string, string>>;
292 return DURABLE_SDK_MODULE in record ? record : { ...record, [DURABLE_SDK_MODULE]: "*" };
293 };
294
295 /**
296 * Lower DurableFunction props onto the base Function's props: split off the
297 * DurableConfig knobs into the internal wire-level `durableConfig` channel,
298 * disable the Function URL (durable invocations are the only surface), and
299 * vendor the Durable Execution SDK.
300 */
301 const mapDurableProps = (props: DurableFunctionProps): FunctionProps => {
302 const { executionTimeout, retentionPeriod, build, ...rest } =
303 props ?? ({} as DurableFunctionProps);
304 const executionTimeoutSeconds = toSeconds(executionTimeout);
305 const retentionPeriodDays = toWireDays(retentionPeriod);
306 return {
307 ...rest,
308 // Every invocation of a DurableConfig'd function arrives as the durable
309 // envelope — a Function URL could never be served.
310 functionUrl: false,
311 build: {
312 ...build,
313 install: withDurableSdkInstall(build?.install),
314 },
315 durableConfig: {
316 ...(executionTimeoutSeconds !== undefined
317 ? { ExecutionTimeout: executionTimeoutSeconds }
318 : {}),
319 ...(retentionPeriodDays !== undefined ? { RetentionPeriodInDays: retentionPeriodDays } : {}),
320 },
321 };
322 };
323
324 const mapDurablePropsInput = (props: unknown) =>
325 Effect.isEffect(props)
326 ? // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- props are untyped; Effect-valued props are resolved by the engine
327 Effect.map(props as Effect.Effect<DurableFunctionProps>, mapDurableProps)
328 : mapDurableProps(props as DurableFunctionProps);
329
330 const resolveDurableHandle = (id: string) => (instance: unknown) => {
331 const handle = (instance as Record<symbol, unknown> | undefined)?.[DurableHandleKey];
332 return handle !== undefined
333 ? Effect.succeed(handle as DurableFunction<any, any>)
334 : Effect.die(
335 new Error(
336 `AWS.Lambda.DurableFunction<${id}> has no durable handle — provide ` +
337 `its implementation (\`${id}.make(props, impl)\` or an inline ` +
338 `form) before yielding it.`,
339 ),
340 );
341 };
342
343 /**
344 * Compose the user's orchestrator init effect into the owned Function's init
345 * effect: resolve the durable management-plane clients, self-bind the
346 * checkpoint-protocol IAM onto the function's own execution role, register
347 * the durable listener on the owned entrypoint, and stash the typed handle
348 * for `yield* MyDurableFunction`.
349 */
350 const composeDurableImpl = (
351 name: string,
352 impl: Effect.Effect<DurableFunctionImpl<any, any>, any, any>,
353 ): Effect.Effect<void, any, any> =>
354 Effect.gen(function* () {
355 // Self: the Function resource this wrapper owns (the Platform machinery
356 // provides `Function.Self` during its own init).
357 const host = yield* Function;
358
359 // Resolve the distilled operations once at init — they close over the
360 // ambient Credentials/Region/HttpClient so the handle's runtime
361 // callables need no cloud services of their own.
362 const invoke = yield* Lambda.invoke;
363 const getDurableExecution = yield* Lambda.getDurableExecution;
364 const listDurableExecutionsByFunction = yield* Lambda.listDurableExecutionsByFunction;
365 const stopDurableExecution = yield* Lambda.stopDurableExecution;
366 const sendCallbackSuccess = yield* Lambda.sendDurableExecutionCallbackSuccess;
367 const sendCallbackFailure = yield* Lambda.sendDurableExecutionCallbackFailure;
368 const sendCallbackHeartbeat = yield* Lambda.sendDurableExecutionCallbackHeartbeat;
369
370 // Capture the function-name Output WITHOUT resolving it. This is a
371 // self-reference — `host` is the very Function this wrapper's init is
372 // building — and `functionName`'s Output source only registers during
373 // that function's own reconcile. Yielding it here (init/plan time) would
374 // block forever (the reconcile that produces it waits on this init to
375 // finish). Resolve it lazily inside the runtime callables instead, the
376 // same posture as `InvokeFunctionHttp`.
377 const FunctionName = host.functionName;
378 // Executions start on the alias when the function sets one.
379 // Typed like the iterator `FunctionName` resolves through, whose
380 // RuntimeContext the host always provides.
381 // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- the host provides RuntimeContext at runtime
382 const Qualifier = qualifierOf(host).bind(`${host.LogicalId}.qualifier`) as Effect.Effect<
383 Effect.Effect<string>
384 >;
385
386 if (!globalThis.__ALCHEMY_RUNTIME__) {
387 // Self-binding: the statements land on this function's own execution
388 // role through the standard bindings channel (precreate makes the stub,
389 // reconcile applies the collected bindings).
390 yield* host.bind`Allow(${host}, AWS.Lambda.DurableFunction(${name}))`({
391 policyStatements: [
392 // The checkpoint/replay protocol the Durable Execution SDK
393 // drives from inside the handler.
394 {
395 Effect: "Allow",
396 Action: ["lambda:CheckpointDurableExecution", "lambda:GetDurableExecutionState"],
397 Resource: [host.functionArn, Output.interpolate`${host.functionArn}:*`],
398 },
399 // Self-start (handle.start) and chained self-invokes.
400 {
401 Effect: "Allow",
402 Action: ["lambda:InvokeFunction"],
403 Resource: [host.functionArn, Output.interpolate`${host.functionArn}:*`],
404 },
405 // Management-plane handle methods. Durable execution ARNs are
406 // a distinct resource shape from the function ARN, so these
407 // stay account-wide for now.
408 {
409 Effect: "Allow",
410 Action: [
411 "lambda:GetDurableExecution",
412 "lambda:GetDurableExecutionHistory",
413 "lambda:ListDurableExecutionsByFunction",
414 "lambda:StopDurableExecution",
415 "lambda:SendDurableExecutionCallbackSuccess",
416 "lambda:SendDurableExecutionCallbackFailure",
417 "lambda:SendDurableExecutionCallbackHeartbeat",
418 ],
419 Resource: ["*"],
420 },
421 ],
422 });
423 }
424
425 const handle: DurableFunctionHandle<any, any> = {
426 Type: TypeId,
427 name,
428 start: (options) =>
429 Effect.gen(function* () {
430 // `FunctionName` is the host's own unresolved Output (captured raw at
431 // init to avoid the plan-time self-reference deadlock). Resolve both
432 // stages — Output → Accessor → string — lazily at runtime.
433 const functionName = yield* yield* FunctionName;
434 const response = yield* invoke({
435 FunctionName: functionName,
436 InvocationType: "Event",
437 DurableExecutionName: options?.name,
438 Qualifier: options?.qualifier ?? (yield* yield* Qualifier),
439 Payload: encodeDurableEnvelope(name, options?.params),
440 });
441 return {
442 executionArn: response.DurableExecutionArn,
443 statusCode: response.StatusCode,
444 };
445 }),
446 get: (executionArn) => getDurableExecution({ DurableExecutionArn: executionArn }),
447 list: (options) =>
448 Effect.gen(function* () {
449 const functionName = yield* yield* FunctionName;
450 return yield* listDurableExecutionsByFunction({
451 FunctionName: functionName,
452 DurableExecutionName: options?.name,
453 Statuses: options?.statuses,
454 });
455 }),
456 stop: (executionArn, error) =>
457 stopDurableExecution({
458 DurableExecutionArn: executionArn,
459 Error: error,
460 }),
461 sendCallbackSuccess: (callbackId, result) =>
462 sendCallbackSuccess({
463 CallbackId: callbackId,
464 Result: result === undefined ? undefined : JSON.stringify(result),
465 }).pipe(Effect.asVoid),
466 sendCallbackFailure: (callbackId, error) =>
467 sendCallbackFailure({
468 CallbackId: callbackId,
469 Error: error,
470 }).pipe(Effect.asVoid),
471 sendCallbackHeartbeat: (callbackId) =>
472 sendCallbackHeartbeat({ CallbackId: callbackId }).pipe(Effect.asVoid),
473 };
474
475 // Resolve the body function. Bindings resolved in the impl's init close
476 // over their services; the returned closure's only leftover requirements
477 // are DurableRunServices, provided per invocation by the bridge.
478 const fn = yield* (impl as Effect.Effect<DurableFunctionImpl<any, any>>).pipe(
479 Effect.provideService(DurableFunctionScope, handle),
480 );
481 const runtime = yield* RuntimeContext;
482
483 yield* host.listen(
484 makeDurableListener({
485 name,
486 run: (input) =>
487 // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- remaining run services are provided per invocation by the durable bridge
488 fn(input).pipe(Effect.provideService(RuntimeContext, runtime)) as Effect.Effect<unknown>,
489 }),
490 );
491
492 // Expose the full DurableFunction value (handle + resource refs) to
493 // `yield* MyDurableFunction` for every authoring form.
494 (host as unknown as Record<symbol, unknown>)[DurableHandleKey] = {
495 ...handle,
496 function: host,
497 functionName: host.functionName,
498 functionArn: host.functionArn,
499 } satisfies DurableFunction<any, any>;
500 });
501
502 /**
503 * An AWS Lambda Durable Function — a code-first, replay-based orchestrator
504 * that IS a durable Lambda Function. `AWS.Lambda.DurableFunction` is a
505 * wrapper of {@link Function}: it owns the underlying Lambda function,
506 * configures its `DurableConfig` at `CreateFunction` (durability is a
507 * create-time property — a DurableFunction is always durable), registers the
508 * durable-execution listener on the owned entrypoint, self-binds the
509 * checkpoint-protocol IAM (`lambda:CheckpointDurableExecution`,
510 * `lambda:GetDurableExecutionState`) onto the execution role, and vendors the
511 * open-source `@aws/durable-execution-sdk-js` into the artifact (install it
512 * in your project: `npm i @aws/durable-execution-sdk-js`).
513 *
514 * Executions progress by checkpoint + replay: a `Durable.sleep` or
515 * `Durable.waitForCallback` suspends the execution with zero compute billed
516 * until Lambda re-invokes the same function version to resume, and completed
517 * `Durable.step`s replay from the checkpoint log without re-executing.
518 *
519 * Every invocation of a durable function arrives as the durable-execution
520 * envelope, so a DurableFunction has no HTTP surface (`functionUrl` is disabled) —
521 * it does one thing: run durable orchestrations. Reusing a logical id
522 * between a plain `Function` and a `DurableFunction` replaces the physical
523 * function (DurableConfig cannot be flipped in place).
524 *
525 * ### Defining a Durable Function
526 * **Example:** Class form with steps and a durable sleep
527 * ```typescript
528 * export class OrderFlow extends AWS.Lambda.DurableFunction<OrderFlow>()(
529 * "OrderFlow",
530 * {
531 * main: import.meta.url,
532 * executionTimeout: "1 hour",
533 * retentionPeriod: "7 days",
534 * },
535 * Effect.gen(function* () {
536 * // init: resolve typed binding clients (IAM lands on this function's role)
537 * const putItem = yield* AWS.DynamoDB.PutItem(table);
538 *
539 * return Effect.fn(function* (input: { orderId: string }) {
540 * const reserved = yield* AWS.Lambda.Durable.step(
541 * "reserve",
542 * putItem({ Item: { pk: { S: input.orderId } } }).pipe(Effect.orDie),
543 * { retry: { limit: 3, delay: "5 seconds" } },
544 * );
545 * yield* AWS.Lambda.Durable.sleep("cooldown", "10 minutes");
546 * return { orderId: input.orderId, reserved };
547 * });
548 * }),
549 * ) {}
550 * ```
551 *
552 * **Example:** Tag + default export (entrypoint form)
553 * ```typescript
554 * // order-flow.ts — `main` points at this module
555 * export class OrderFlow extends AWS.Lambda.DurableFunction<OrderFlow>()(
556 * "OrderFlow",
557 * ) {}
558 *
559 * export default OrderFlow.make(
560 * { main: import.meta.url, executionTimeout: "1 hour" },
561 * Effect.gen(function* () {
562 * return Effect.fn(function* (input: { orderId: string }) {
563 * return yield* AWS.Lambda.Durable.step("work", doWork(input));
564 * });
565 * }),
566 * );
567 * ```
568 *
569 * **Example:** Inline effect form
570 * ```typescript
571 * const flow = yield* AWS.Lambda.DurableFunction(
572 * "OrderFlow",
573 * { main: "./src/order-flow.ts" },
574 * Effect.gen(function* () {
575 * return Effect.fn(function* (input: { orderId: string }) {
576 * return yield* AWS.Lambda.Durable.step("work", doWork(input));
577 * });
578 * }),
579 * );
580 * ```
581 *
582 * ### Starting and Monitoring Executions
583 * **Example:** Starting an execution
584 * ```typescript
585 * const orders = yield* OrderFlow;
586 * const ref = yield* orders.start({
587 * name: "order-123", // idempotent start
588 * params: { orderId: "123" },
589 * qualifier: "live",
590 * });
591 * ```
592 *
593 * **Example:** Publish and promote for production
594 * ```typescript
595 * const orders = yield* OrderFlow;
596 * const version = yield* AWS.Lambda.Version("OrderFlowVersion", {
597 * function: orders.function,
598 * });
599 * yield* AWS.Lambda.Alias("OrderFlowLive", {
600 * version,
601 * aliasName: "live",
602 * });
603 *
604 * const ref = yield* orders.start({
605 * name: "order-123",
606 * params: { orderId: "123" },
607 * qualifier: "live",
608 * });
609 * ```
610 *
611 * **Example:** Checking status
612 * ```typescript
613 * const execution = yield* orders.get(ref.executionArn!);
614 * // execution.Status: "RUNNING" | "SUCCEEDED" | "FAILED" | ...
615 * ```
616 *
617 * ### External Callbacks
618 * **Example:** Waiting for an approval
619 * ```typescript
620 * const approval = yield* AWS.Lambda.Durable.waitForCallback<{ ok: boolean }>(
621 * "approve",
622 * (callbackId) => storeCallbackId(callbackId),
623 * { timeout: "1 day" },
624 * );
625 * ```
626 *
627 * @resource
628 */
629 export const DurableFunction: DurableFunctionClass = taggedFunction(DurableFunctionScope, ((
630 ...args: [] | [id: string] | [id: string, props: unknown, impl: Effect.Effect<any, any, any>]
631 ) => {
632 if (args.length === 0) {
633 // `DurableFunction<Self>()` — the binder for the class/tag forms.
634 return DurableFunction;
635 }
636 const [id, props, impl] = args;
637 if (impl === undefined) {
638 // Tag form: `class OrderFlow extends DurableFunction<OrderFlow>()("OrderFlow") {}`
639 // + `export default OrderFlow.make(props, impl)`.
640 const fnTag = (Function as any)()(id);
641 return Object.assign(
642 function (props: unknown, impl: Effect.Effect<any, any, any>) {
643 return Effect.flatMap(
644 fnTag(mapDurablePropsInput(props), composeDurableImpl(id, impl)),
645 resolveDurableHandle(id),
646 );
647 },
648 fnTag,
649 {
650 make: (props: unknown, impl: Effect.Effect<any, any, any>) =>
651 fnTag.make(mapDurablePropsInput(props), composeDurableImpl(id, impl)),
652 },
653 Effectable.Prototype({
654 label: `${TypeId}<${id}>`,
655 evaluate: () =>
656 Effect.flatMap(
657 Effect.serviceOption(fnTag.Self),
658 Option.match({
659 onNone: () => resolveDurableHandle(id)(undefined),
660 onSome: resolveDurableHandle(id),
661 }),
662 ),
663 }),
664 );
665 }
666 // Inline forms (eager effect / inline class): delegate to the Function
667 // platform with lowered props and the composed durable init.
668 return effectClass(
669 Effect.flatMap(
670 (Function as any)(
671 id,
672 mapDurablePropsInput(props),
673 composeDurableImpl(id, impl),
674 ) as Effect.Effect<unknown>,
675 resolveDurableHandle(id),
676 ),
677 );
678 }) as any);