Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions .agents/rules/handlers.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,13 @@ Typed-error semantics inside the workflow context:

## Worker Setup

`createWorker` returns `AsyncResult<Worker, TechnicalError>` (org rule:
`Typed*.create()` factories model creation failures on the Err channel).
Same shape on the client: `TypedClient.create({ contract, client })` returns
`AsyncResult<TypedClient, TechnicalError>`. Deprecated throwing aliases
(`createWorkerOrThrow`, `TypedClient.createOrThrow`) exist for migration.
`createWorker` returns `AsyncResult<Worker, never>` — bundling / connection
failures are _technical_ infrastructure faults, so they ride the **defect**
channel (a `TechnicalError` instance as the cause), not the modeled Err
channel. Same shape on the client: `TypedClient.create({ contract, client })`
returns `AsyncResult<TypedClient, never>` (a `TechnicalError`-caused defect on
setup failure). Deprecated throwing aliases (`createWorkerOrThrow`,
`TypedClient.createOrThrow`) exist for migration.

```typescript
import { createWorker, workflowsPathFromURL } from "@temporal-contract/worker/worker";
Expand All @@ -114,8 +116,8 @@ const workerResult = await createWorker({
workflowsPath: workflowsPathFromURL(import.meta.url, "./workflows.js"),
activities,
});
if (workerResult.isErr()) {
// bundling / connection failure — modeled, not thrown
if (workerResult.isDefect()) {
// bundling / connection failure — a TechnicalError-caused defect, not thrown
process.exit(1);
}

Expand Down
12 changes: 12 additions & 0 deletions .changeset/bump-unthrown-beta-5.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
"@temporal-contract/contract": patch
"@temporal-contract/client": patch
"@temporal-contract/worker": patch
---

Bump `unthrown` to `5.0.0-beta.5`. This tracks two beta breaking changes:
`match`'s error handler key is renamed `err` → `errCases`, and the bare error
combinators gained the `*Cases` suffix (`flatMapErr` → `flatMapErrCases`,
`tapErr` → `tapErrCases`). `unthrown` also now declares `ts-pattern` as a peer
dependency, so `ts-pattern` (`^5`) is added alongside it. The peer range is
raised to `^5.0.0-beta.5`.
15 changes: 15 additions & 0 deletions .changeset/technical-errors-to-defect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
"@temporal-contract/client": patch
"@temporal-contract/contract": patch
"@temporal-contract/worker": patch
---

Route `TechnicalError` and `RuntimeClientError` to unthrown's defect channel instead of the modeled `Err` channel.

These two errors describe technical/infrastructure failures (connection/bundling faults, an unknown schedule ID, an unrecognized Temporal rejection) that are never branched on for domain logic. Per unthrown's Thesis #1, the `E` channel is only for anticipated domain failures, so they now surface as a `Defect` whose `cause` is a `TechnicalError` / `RuntimeClientError` instance — the classes stay exported so the descriptive message, `operation`, and `cause` survive for logging.

**Breaking.** Consumers who matched these on the error channel must move to the defect channel:

- `TypedClient.create` and `createWorker` now return `AsyncResult<_, never>` (was `AsyncResult<_, TechnicalError>`). Inspect setup faults via `result.isDefect()` / `match`'s `defect` handler / `recoverDefect`, not `isErr()`.
- Every modeled error union drops `RuntimeClientError` (`startWorkflow`, `signalWithStart`, `executeWorkflow`, `getHandle`, handle `queries`/`signals`/`updates`/`result`/`terminate`/`cancel`/`describe`/`fetchHistory`, the schedule handle methods, `ClientCallError`). Schedule handle methods now return `AsyncResult<_, never>`.
- Drop any `.with(tag("@temporal-contract/RuntimeClientError"), …)` / `.with(tag("@temporal-contract/TechnicalError"), …)` arm from exhaustive matchers; handle these in the `defect` arm (e.g. `recoverDefect` / `tapDefect`), matching on `cause instanceof RuntimeClientError` where needed.
2 changes: 1 addition & 1 deletion docs/examples/basic-order-processing.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ This example demonstrates the unthrown-based pattern:
- Activities return `AsyncResult<T, ApplicationFailure>` instead of throwing
- Child workflow calls return `Result<T, E>` for explicit error handling
- Errors are part of the type signature
- Enables railway-oriented programming via `.flatMap` / `.map` / `.mapErr`
- Enables railway-oriented programming via `.flatMap` / `.map` / `.mapErrCases`

### Worker Application

Expand Down
12 changes: 9 additions & 3 deletions docs/guide/activity-handlers.md
Original file line number Diff line number Diff line change
Expand Up @@ -341,9 +341,15 @@ import {
} from "@temporal-contract/worker/activity";

const logging: ActivityMiddleware = ({ activityName, workflowName }, next) =>
next().tapErr((error) => {
logger.warn({ activityName, workflowName, error }, "activity failed");
});
next().tapErrCases((matcher) =>
matcher.with(
P.instanceOf(ApplicationFailure),
tag("@temporal-contract/ContractError"),
(error) => {
logger.warn({ activityName, workflowName, error }, "activity failed");
},
),
);

const timing: ActivityMiddleware = async ({ activityName }, next) => {
const started = Date.now();
Expand Down
170 changes: 128 additions & 42 deletions docs/guide/client-usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,16 @@ const connection = await Connection.connect({

// Create Temporal client and typed client
const temporalClient = new Client({ connection });
// Creation returns AsyncResult<TypedClient, TechnicalError> — connection
// and capability failures land on the Err channel instead of throwing.
// Creation returns AsyncResult<TypedClient, never> — connection and capability
// failures are technical faults that ride the defect channel (a TechnicalError
// instance as the cause), not the modeled Err channel, and are never thrown.
const clientResult = await TypedClient.create({
contract: myContract,
client: temporalClient,
});
if (!clientResult.isOk()) {
// Err carries the modeled TechnicalError; a defect carries the raw cause.
throw clientResult.isErr() ? clientResult.error : clientResult.cause;
if (clientResult.isDefect()) {
// The defect's cause is a TechnicalError describing the setup failure.
throw clientResult.cause;
}
const client = clientResult.value;
```
Expand Down Expand Up @@ -63,9 +64,18 @@ result.match({
ok: (output) => {
console.log("Order processed:", output.status); // TypeScript knows the shape!
},
err: (error) => {
console.error("Workflow failed:", error);
},
errCases: (matcher) =>
matcher.with(
tag("@temporal-contract/ContractError"),
tag("@temporal-contract/WorkflowNotFoundError"),
tag("@temporal-contract/WorkflowValidationError"),
tag("@temporal-contract/WorkflowAlreadyStartedError"),
tag("@temporal-contract/WorkflowFailedError"),
tag("@temporal-contract/WorkflowExecutionNotFoundError"),
(error) => {
console.error("Workflow failed:", error);
},
),
defect: (cause) => {
console.error("Unexpected failure:", cause);
},
Expand Down Expand Up @@ -94,13 +104,26 @@ handleResult.match({
const result = await handle.result();
result.match({
ok: (output) => console.log("Completed:", output),
err: (error) => console.error("Failed:", error),
errCases: (matcher) =>
matcher.with(
tag("@temporal-contract/ContractError"),
tag("@temporal-contract/WorkflowValidationError"),
tag("@temporal-contract/WorkflowFailedError"),
tag("@temporal-contract/WorkflowExecutionNotFoundError"),
(error) => console.error("Failed:", error),
),
defect: (cause) => console.error("Unexpected failure:", cause),
});
},
err: (error) => {
console.error("Failed to start workflow:", error);
},
errCases: (matcher) =>
matcher.with(
tag("@temporal-contract/WorkflowNotFoundError"),
tag("@temporal-contract/WorkflowValidationError"),
tag("@temporal-contract/WorkflowAlreadyStartedError"),
(error) => {
console.error("Failed to start workflow:", error);
},
),
defect: (cause) => {
console.error("Unexpected failure:", cause);
},
Expand Down Expand Up @@ -142,7 +165,7 @@ await client.executeWorkflow("invalidWorkflow", {
The client uses `unthrown` for explicit error handling:

```typescript
import { Result } from "unthrown";
import { Result, tag } from "unthrown";

const result = await client.executeWorkflow("processOrder", {
workflowId: "order-123",
Expand All @@ -154,9 +177,18 @@ result.match({
ok: (value) => {
console.log("Order processed:", value.transactionId);
},
err: (error) => {
console.error("Order failed:", error);
},
errCases: (matcher) =>
matcher.with(
tag("@temporal-contract/ContractError"),
tag("@temporal-contract/WorkflowNotFoundError"),
tag("@temporal-contract/WorkflowValidationError"),
tag("@temporal-contract/WorkflowAlreadyStartedError"),
tag("@temporal-contract/WorkflowFailedError"),
tag("@temporal-contract/WorkflowExecutionNotFoundError"),
(error) => {
console.error("Order failed:", error);
},
),
defect: (cause) => {
console.error("Unexpected failure:", cause);
},
Expand Down Expand Up @@ -200,27 +232,47 @@ handleResult.match({
const statusResult = await handle.queries.getStatus({});
statusResult.match({
ok: (status) => console.log("Status:", status),
err: (error) => console.error("Query failed:", error),
errCases: (matcher) =>
matcher.with(
tag("@temporal-contract/QueryValidationError"),
tag("@temporal-contract/WorkflowExecutionNotFoundError"),
(error) => console.error("Query failed:", error),
),
defect: (cause) => console.error("Unexpected failure:", cause),
});

// Signal the workflow
const signalResult = await handle.signals.cancelOrder({ reason: "Customer request" });
signalResult.match({
ok: () => console.log("Signal sent"),
err: (error) => console.error("Signal failed:", error),
errCases: (matcher) =>
matcher.with(
tag("@temporal-contract/SignalValidationError"),
tag("@temporal-contract/WorkflowExecutionNotFoundError"),
(error) => console.error("Signal failed:", error),
),
defect: (cause) => console.error("Unexpected failure:", cause),
});

// Get the result
const result = await handle.result();
result.match({
ok: (output) => console.log("Result:", output),
err: (error) => console.error("Workflow failed:", error),
errCases: (matcher) =>
matcher.with(
tag("@temporal-contract/ContractError"),
tag("@temporal-contract/WorkflowValidationError"),
tag("@temporal-contract/WorkflowFailedError"),
tag("@temporal-contract/WorkflowExecutionNotFoundError"),
(error) => console.error("Workflow failed:", error),
),
defect: (cause) => console.error("Unexpected failure:", cause),
});
},
err: (error) => console.error("Failed to get handle:", error),
errCases: (matcher) =>
matcher.with(tag("@temporal-contract/WorkflowNotFoundError"), (error) =>
console.error("Failed to get handle:", error),
),
defect: (cause) => console.error("Unexpected failure:", cause),
});
```
Expand Down Expand Up @@ -253,7 +305,16 @@ const result = await client.executeWorkflow("processOrder", {

result.match({
ok: (value) => console.log("Success:", value),
err: (error) => console.error("Workflow returned error:", error),
errCases: (matcher) =>
matcher.with(
tag("@temporal-contract/ContractError"),
tag("@temporal-contract/WorkflowNotFoundError"),
tag("@temporal-contract/WorkflowValidationError"),
tag("@temporal-contract/WorkflowAlreadyStartedError"),
tag("@temporal-contract/WorkflowFailedError"),
tag("@temporal-contract/WorkflowExecutionNotFoundError"),
(error) => console.error("Workflow returned error:", error),
),
defect: (cause) => console.error("Unexpected failure:", cause),
});
```
Expand Down Expand Up @@ -320,21 +381,37 @@ import type { ClientInterceptor } from "@temporal-contract/client";

// Observe every operation
const logging: ClientInterceptor = (args, next) =>
next().tapErr((error) => {
logger.warn({ operation: args.operation, workflowId: args.workflowId, error });
});

// Retry a transient failure once
const retryOnce: ClientInterceptor = (args, next) =>
next().flatMapErr((error): ReturnType<typeof next> =>
error instanceof RuntimeClientError ? next() : Err(error).toAsync(),
next().tapErrCases((matcher) =>
matcher.with(
tag("@temporal-contract/WorkflowNotFoundError"),
tag("@temporal-contract/WorkflowValidationError"),
tag("@temporal-contract/WorkflowAlreadyStartedError"),
tag("@temporal-contract/WorkflowFailedError"),
tag("@temporal-contract/WorkflowExecutionNotFoundError"),
tag("@temporal-contract/SignalValidationError"),
tag("@temporal-contract/QueryValidationError"),
tag("@temporal-contract/UpdateValidationError"),
tag("@temporal-contract/ContractError"),
(error) => {
logger.warn({ operation: args.operation, workflowId: args.workflowId, error });
},
),
);

// Retry a transient failure once. Transient technical faults (an unrecognized
// Temporal rejection, a dropped connection) ride the defect channel now, so the
// retry re-enters via `recoverDefect` — a defect is the retry signal, and any
// genuinely-modeled `Err` still flows through untouched.
const retryOnce: ClientInterceptor = (args, next) => next().recoverDefect(() => next());

// `create` returns AsyncResult<TypedClient, never> — its only failures are
// defects, so `get()` (not `getOrThrow()`) is the extractor; it panics
// (rethrowing the defect's TechnicalError cause) if setup failed.
const client = await TypedClient.create({
contract: myContract,
client: temporalClient,
interceptors: [logging, retryOnce],
}).getOrThrow();
}).get();
```

An interceptor can also patch the invocation (`next({ input })`) or
Expand All @@ -356,11 +433,11 @@ const temporalClient = new Client({ connection });
const orderClient = await TypedClient.create({
contract: orderContract,
client: temporalClient,
}).getOrThrow();
}).get();
const inventoryClient = await TypedClient.create({
contract: inventoryContract,
client: temporalClient,
}).getOrThrow();
}).get();

// Both clients share the same connection and Temporal client instance
```
Expand Down Expand Up @@ -399,15 +476,15 @@ const temporalClient = new Client({ connection });
const orderClient = await TypedClient.create({
contract: orderContract,
client: temporalClient,
}).getOrThrow();
}).get();
const paymentClient = await TypedClient.create({
contract: paymentContract,
client: temporalClient,
}).getOrThrow();
}).get();
const inventoryClient = await TypedClient.create({
contract: inventoryContract,
client: temporalClient,
}).getOrThrow();
}).get();

// Each client is typed to its contract
await orderClient.executeWorkflow("processOrder", {/* ... */});
Expand Down Expand Up @@ -458,7 +535,7 @@ const temporalClient = new Client({ connection });
const client = await TypedClient.create({
contract: contract,
client: temporalClient,
}).getOrThrow();
}).get();

// ❌ Avoid - creating connections repeatedly
for (const order of orders) {
Expand All @@ -467,7 +544,7 @@ for (const order of orders) {
const client = await TypedClient.create({
contract: contract,
client: temporalClient,
}).getOrThrow();
}).get();
await client.executeWorkflow(/* ... */);
}
```
Expand Down Expand Up @@ -496,11 +573,20 @@ result.match({
// Handle success
updateDatabase(value);
},
err: (error) => {
// Handle error
logError(error);
notifySupport(error);
},
errCases: (matcher) =>
matcher.with(
tag("@temporal-contract/ContractError"),
tag("@temporal-contract/WorkflowNotFoundError"),
tag("@temporal-contract/WorkflowValidationError"),
tag("@temporal-contract/WorkflowAlreadyStartedError"),
tag("@temporal-contract/WorkflowFailedError"),
tag("@temporal-contract/WorkflowExecutionNotFoundError"),
(error) => {
// Handle error
logError(error);
notifySupport(error);
},
),
defect: (cause) => {
// Handle unexpected failure (bug)
logError(cause);
Expand Down
Loading
Loading