better-result-cf-workflows 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,101 @@
1
- # Temporary Holding Version
1
+ # better-result + Cloudflare Workflows
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Cloudflare Workflows are a great product for making durable & long-running workloads. Built-in retries, sleeps, etc are great.
4
+
5
+ What frustrates me personally is that I'm a fan of [better-result](https://github.com/dmmulroy/better-result) & in order to do retries, you need to fricking throw! So, this library is there to fix that, along with a few other goodies you may enjoy.
6
+
7
+ ## Basic Setup
8
+
9
+ The idea is that instead of extending & implementing `WorkflowEntrypoint`, you have to extend & implement this package's `ResultWorkflowEntrypoint`.
10
+
11
+ ```ts
12
+ class TestErr extends TaggedError("TestErr")<{}> {}
13
+
14
+ const errorCodec = errorMapCodec({ TestErr })
15
+
16
+ export class TestWf extends ResultWorkflowEntrypoint<InferErrorsFromErrCodec<typeof errorCodec>> {
17
+ errorCodec = errorCodec
18
+
19
+ async *execute(step) {
20
+ const banger = yield* step.do("Step Execution", async () => Result.ok("yay! I'm a result!"))
21
+ return Result.ok(banger)
22
+ }
23
+ }
24
+ ```
25
+
26
+ Notable differences:
27
+
28
+ - Instead of the `run` method, you have to implement the `execute` method.
29
+ - The `execute` method method is a generator (so you gotta use the `*` notation above), but also means you can use the `yield` syntax of `Result.gen`. Pro tip: if you are getting syntax errors because of the `*`, try putting a `;` at the end of the your last statement.
30
+ - `step.do` has less variants - it only allows the complex variant, with & without the rollback options
31
+ - `step.do`'s methods (callback & rollback) _**must**_ return a `Result`.
32
+
33
+ ## Extra goods
34
+
35
+ This workflow class has callbacks! If you implement `onFinalError` or `onFinalSuccess`, you can execute a callback on your "final" error or "final" success.
36
+
37
+ ## Full Reference
38
+
39
+ For the most part, this library tries to keep the original `step` & `workflow` implementation. So in theory, new features should "just work". On top of the original, the following changes are done:
40
+
41
+ ### ResultWorkflowEntrypoint Class
42
+
43
+ To implement this class, you must implement the `*execute` method, and the `errorCodec` property. The error codec property is just a serialization & deserialization method for your errors. My personal suggestion is that you use the provided `errorMapCodec`, though if you really need a more strict version you may implement your own.
44
+
45
+ The first generic argument of the `ResultWorkflowEntrypoint` must list out all the possible errors.
46
+
47
+ You may implement `onFinalError(step, error): Promise<Result>` and `onFinalSuccess(step, value): Promise<Result>` - these are callbacks that get executed on a "final" error or on a final success. The return value from these methods is used for the workflow's output/error field. The step API is provided there so that you can do external work, if needed.
48
+
49
+ The `onFinalError` is run before rollback. If the returned value is `null`, then the output of the workflow will be null, the workflow will be considered "complete" (not errored), and the rollbacks will not run.
50
+
51
+ ### Step API
52
+
53
+ `step.do` requires this format: `step.do(stepName: string, config: ResultWorkflowStepConfig, rollback?: ResultWorkflowStepRollbackOptions)`. So, no "simplified" syntax is available. For example.
54
+
55
+ ```ts
56
+ await step.do(
57
+ "Step Name",
58
+ {
59
+ callback: async () => {
60
+ return await apiClient.billUser()
61
+ },
62
+ retries: {
63
+ shouldRetry: {
64
+ APITimeout: true,
65
+ APIInternalError: true,
66
+ APIExpectedError: (err) => {
67
+ // we have a special agreement about coffee & tea
68
+ return err.status === 418
69
+ },
70
+ },
71
+ },
72
+ },
73
+ {
74
+ rollback: async (ctx) => {
75
+ if (!ctx.error) {
76
+ return
77
+ }
78
+
79
+ return await apiClient.refundUser()
80
+ },
81
+ },
82
+ )
83
+ ```
84
+
85
+ - `step.do`'s functions (callback, rollback) must return a result. The errors of the result must be part of `ResultWorkflowEntrypoint`'s supported tagged errors (ie. part of the error codec & part of the first generic argument of the class)
86
+ - `step.do`'s retry config supports a `shouldRetry`, which can take either a method `(e: SupportedError | Panic) => boolean` or a an object. The key of that object is the tags of the supported errors, and the value can either be a boolean, indicating if you should retry on that error, or a callback that is executed on that error. In the object form, if the error is a `Panic`, it will be automatically retried.
87
+ - If either callback or rollback throws, that is considered a defect and that error is transformed into a `Panic`. Please note that class identity of the `cause` may not be preserved outside the step's execution context (so outside callback/rollback and outside the shouldRetry methods)
88
+ - `step.waitForEvent` will return a `Result<WorkflowStepEvent<unknown>, TimeoutErr>`. Note that it does NOT support passing in a generic value for it's success result - you must do parsing on that.
89
+
90
+ ### Error Codec
91
+
92
+ An error codec is needed for classes to be passed through RPC boundaries. The default codec, `errorMapCodec`, accepts an object where the keys are the tags of the supported errors and the values are the classes associated with that tag. So this does not support multiple tagged error classes having the same tag. It does not do any schema checks or conversion - it uses the built in `toJSON` method for serialization & deserialization. This also means that tagged error's values need to be RPC serializable, and class identity may not be preserved for values.
93
+
94
+ In case you want to implement schema validation or sub-class identity preservation, you need to implement your own. Luckily, it is not that hard: an error codec is just an object with an encode & a decode property, both of which are standard schemas (eg. zod).
95
+
96
+ If the error codec returns an unsuccessful response or throws, it is considered a defect & a Panic will be resized.
97
+
98
+ ## Dirty Details
99
+
100
+ - The original `step.do`'s callback is a RPC binding. That means that thrown errors and returned results have to be RPC serializable. Part of that means that means that errors & returned data loses class identity when returned to your workflow. In order to avoid that, I implemented a custom serializer for your errors, so class identity (and therefore `.is`, `instanceof`, etc) is preserved. To complete this however, we need a codec, so you must implement `errorCodec` on your `ResultWorkflowEntrypoint`
101
+ - The original `step.do`'s retry mechanism relies on a `throw`. To implement this, the returned `Err` result is actually thrown under the hood with a wrapping error.
@@ -0,0 +1,21 @@
1
+ import { AnyTaggedError, Panic, StandardSchemaV1, TaggedErrorInstance } from "better-result";
2
+ import { NonRetryableError } from "cloudflare:workflows";
3
+ export type ErrCodec<E extends AnyTaggedError> = {
4
+ encode: StandardSchemaV1<E, string>;
5
+ decode: StandardSchemaV1<string, E>;
6
+ };
7
+ export type InferErrorsFromErrCodec<T extends ErrCodec<AnyTaggedError>> = T extends ErrCodec<infer E> ? E : never;
8
+ type GenericTaggedErrorClass<T extends string> = abstract new (...args: never[]) => TaggedErrorInstance<T, unknown>;
9
+ /** Creates a result codec that passes on the OK value directly and encodes the tagged errors
10
+ * To remain error identity, all errors must be passed in by value in the errors variable
11
+ *
12
+ * NOTE: The codec returned does not verify the shape of the parameters - so do not use this result codec outside of a workflow
13
+ * A workflow's RPC boundaries are *basically* trustworthy.
14
+ * Technically, your code may change as you wait on old workflows, but there is virtually nothing you can do about this.
15
+ */
16
+ export declare function errorMapCodec<E extends string>(errors: {
17
+ [K in E]: GenericTaggedErrorClass<K>;
18
+ }): ErrCodec<TaggedErrorInstance<E, unknown>>;
19
+ export declare function encodeErr<E extends AnyTaggedError>(codec: ErrCodec<E>, value: unknown, errClass?: ErrorConstructor | typeof NonRetryableError): Promise<Error>;
20
+ export declare function decodeErr<E extends AnyTaggedError>(codec: ErrCodec<E>, value: unknown): Promise<Panic | E>;
21
+ export {};
@@ -0,0 +1,142 @@
1
+ /*
2
+ * This file is part of better-result-cf-workflows.
3
+ * better-result-cf-workflows is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
4
+ * better-result-cf-workflows is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
5
+ * You should have received a copy of the GNU General Public License along with better-result-cf-workflows. If not, see <https://www.gnu.org/licenses/>.
6
+ */
7
+ import { Panic, TaggedError, } from "better-result";
8
+ import { z } from "zod/mini";
9
+ /** Creates a result codec that passes on the OK value directly and encodes the tagged errors
10
+ * To remain error identity, all errors must be passed in by value in the errors variable
11
+ *
12
+ * NOTE: The codec returned does not verify the shape of the parameters - so do not use this result codec outside of a workflow
13
+ * A workflow's RPC boundaries are *basically* trustworthy.
14
+ * Technically, your code may change as you wait on old workflows, but there is virtually nothing you can do about this.
15
+ */
16
+ export function errorMapCodec(errors) {
17
+ // @ts-expect-error we are using unknown here for efficiency
18
+ // but this codec is only ever used for result error serialization/deserialization
19
+ // so its fine
20
+ const zodCodec = z.codec(z.string(), z.unknown(), {
21
+ // @ts-expect-error see above comment
22
+ encode: (v) => {
23
+ return JSON.stringify(v.toJSON());
24
+ },
25
+ decode: (v, ctx) => {
26
+ let json;
27
+ try {
28
+ json = JSON.parse(v);
29
+ }
30
+ catch (err) {
31
+ ctx.issues.push({
32
+ code: "invalid_format",
33
+ format: "json",
34
+ input: v,
35
+ // @ts-expect-error err.message isn't know to ts, but cmon
36
+ message: err?.message,
37
+ continue: false,
38
+ });
39
+ return z.NEVER;
40
+ }
41
+ if (typeof json !== "object" || Array.isArray(json) || json === null) {
42
+ ctx.issues.push({
43
+ code: "invalid_type",
44
+ expected: "object",
45
+ input: json,
46
+ continue: false,
47
+ });
48
+ return z.NEVER;
49
+ }
50
+ if (!("_tag" in json) || typeof json["_tag"] !== "string") {
51
+ ctx.issues.push({
52
+ code: "invalid_type",
53
+ expected: "string",
54
+ input: "_tag" in json ? json["_tag"] : undefined,
55
+ continue: false,
56
+ path: ["_tag"],
57
+ });
58
+ return z.NEVER;
59
+ }
60
+ if (!(json["_tag"] in errors)) {
61
+ ctx.issues.push({
62
+ code: "custom",
63
+ input: json["_tag"],
64
+ continue: false,
65
+ path: ["_tag"],
66
+ message: "Unknown tag",
67
+ });
68
+ return z.NEVER;
69
+ }
70
+ const cls = errors[json["_tag"]];
71
+ // @ts-expect-error we obviously did not give types to the error
72
+ // in fact, this is strictly un-safe
73
+ // however, since we are purely using this for workflow rpc encoding, this will work
74
+ // we are not navigating trust boundaries, we ARE navigating network but only on a technicality
75
+ // lets not bother ourselves with (in this case) pointless safety
76
+ return new cls(json);
77
+ },
78
+ });
79
+ return {
80
+ encode: z.invertCodec(zodCodec),
81
+ decode: zodCodec,
82
+ };
83
+ }
84
+ // fun discovery: so if you have a custom error class (even one thats not a tagged error)
85
+ // outside of RPC, that error will look like a normal error class. Even if you set the error.name!
86
+ // So the error's message will look like {err name}: {err message}
87
+ // From that, the decision to move forward is to JSONify the data & encode/decode it. Easy :3
88
+ async function wrapStdSchema(codec, value) {
89
+ try {
90
+ const stdResult = await codec["~standard"].validate(value);
91
+ if (stdResult.issues) {
92
+ return new Panic({
93
+ message: "invalid error has been returned",
94
+ cause: stdResult.issues,
95
+ });
96
+ }
97
+ return stdResult.value;
98
+ }
99
+ catch (err) {
100
+ return new Panic({ message: "decoder threw while decoding an error!", cause: err });
101
+ }
102
+ }
103
+ export async function encodeErr(codec, value, errClass = Error) {
104
+ if (TaggedError.is(value)) {
105
+ const res = await wrapStdSchema(codec.encode, value);
106
+ if (Panic.is(res)) {
107
+ value = res;
108
+ }
109
+ else {
110
+ return new errClass(res);
111
+ }
112
+ }
113
+ if (Panic.is(value)) {
114
+ return new errClass(JSON.stringify(value.toJSON()));
115
+ }
116
+ else {
117
+ return new errClass(JSON.stringify(new Panic({ message: "Unknown error happened", cause: value }).toJSON()));
118
+ }
119
+ }
120
+ export async function decodeErr(codec, value) {
121
+ if (Panic.is(value) || TaggedError.is(value)) {
122
+ return value;
123
+ }
124
+ if (!(value instanceof Error)) {
125
+ return new Panic({ message: "Unknown error given to decoder", cause: value });
126
+ }
127
+ // a codec may or may not use JSON for encoding. However, a Panic definitely uses JSON
128
+ // so lets test for that first
129
+ try {
130
+ const json = JSON.parse(value.message);
131
+ if (typeof json !== "object" || json === null || !("_tag" in json)) {
132
+ return new Panic({ message: "Non-tagged error given in json", cause: json });
133
+ }
134
+ if (json["_tag"] === "Panic") {
135
+ return new Panic(json);
136
+ }
137
+ }
138
+ catch {
139
+ // who knows that this can mean - maybe the codec just isn't a json guy
140
+ }
141
+ return await wrapStdSchema(codec.decode, value.message);
142
+ }
@@ -0,0 +1,5 @@
1
+ export { ResultWorkflowEntrypoint } from "./wf-class";
2
+ export { errorMapCodec, ErrCodec, InferErrorsFromErrCodec } from "./codec";
3
+ export { StepEventTimeoutErr } from "./step/wait-for-event";
4
+ export { ResultStep } from "./step/index";
5
+ export { ResultWorkflowDelayFunction, ResultWorkflowDynamicDelayContext, ResultWorkflowRetryConfig, ResultWorkflowRollbackContext, ResultWorkflowStepConfig, ResultWorkflowStepRollbackOptions, } from "./step/compat";
@@ -0,0 +1,9 @@
1
+ /*
2
+ * This file is part of better-result-cf-workflows.
3
+ * better-result-cf-workflows is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
4
+ * better-result-cf-workflows is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
5
+ * You should have received a copy of the GNU General Public License along with better-result-cf-workflows. If not, see <https://www.gnu.org/licenses/>.
6
+ */
7
+ export { ResultWorkflowEntrypoint } from "./wf-class";
8
+ export { errorMapCodec } from "./codec";
9
+ export { StepEventTimeoutErr } from "./step/wait-for-event";
@@ -0,0 +1,32 @@
1
+ import { AnyTaggedError, Panic, Result } from "better-result";
2
+ import { WorkflowBackoff, WorkflowDelayDuration, WorkflowRollbackContext, WorkflowStepConfig, WorkflowStepContext, WorkflowStepRollbackConfig, WorkflowStepRollbackOptions } from "cloudflare:workers";
3
+ export type ResultWorkflowDynamicDelayContext<E extends AnyTaggedError> = {
4
+ ctx: WorkflowStepContext<ResultWorkflowDelayFunction<E>>;
5
+ error: E | Panic;
6
+ };
7
+ export type ResultWorkflowDelayFunction<E extends AnyTaggedError> = (input: ResultWorkflowDynamicDelayContext<E>) => WorkflowDelayDuration | Promise<WorkflowDelayDuration>;
8
+ export type ResultWorkflowRetryConfig<E extends AnyTaggedError> = {
9
+ shouldRetry?: (err: E) => boolean | {
10
+ [K in E as K["_tag"]]: boolean | ((err: K) => boolean);
11
+ };
12
+ limit: number;
13
+ delay: WorkflowDelayDuration | number | ResultWorkflowDelayFunction<E>;
14
+ backoff?: WorkflowBackoff;
15
+ };
16
+ export type ResultWorkflowStepConfig<T extends Rpc.Serializable<T>, E extends AnyTaggedError> = Omit<WorkflowStepConfig, "retries"> & {
17
+ callback: (ctx: WorkflowStepContext) => Promise<Result<T, E>>;
18
+ retries?: ResultWorkflowRetryConfig<E>;
19
+ };
20
+ export type ResultWorkflowRollbackContext<T extends Rpc.Serializable<T>, E extends AnyTaggedError> = Omit<WorkflowRollbackContext<T>, "error"> & {
21
+ error: E | Panic;
22
+ };
23
+ type ResultWorkflowRollbackHandler<T extends Rpc.Serializable<T>, E extends AnyTaggedError> = (ctx: ResultWorkflowRollbackContext<T, E>) => Promise<Result<void, E>>;
24
+ type ResultWorkflowStepRollbackConfig<E extends AnyTaggedError> = Omit<WorkflowStepRollbackConfig, "retries"> & {
25
+ retries?: ResultWorkflowRetryConfig<E>;
26
+ };
27
+ export type ResultWorkflowStepRollbackOptions<T extends Rpc.Serializable<T>, E extends AnyTaggedError> = Omit<WorkflowStepRollbackOptions, "rollback" | "rollbackConfig"> & {
28
+ rollback: ResultWorkflowRollbackHandler<T, E>;
29
+ rollbackConfig?: ResultWorkflowStepRollbackConfig<E>;
30
+ };
31
+ export type ResultDoFunction = <T extends Rpc.Serializable<T>, E extends AnyTaggedError>(name: string, config: ResultWorkflowStepConfig<T, E>, rollback?: ResultWorkflowStepRollbackOptions<T, E>) => Promise<Result<T, E>>;
32
+ export {};
@@ -0,0 +1,7 @@
1
+ /*
2
+ * This file is part of better-result-cf-workflows.
3
+ * better-result-cf-workflows is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
4
+ * better-result-cf-workflows is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
5
+ * You should have received a copy of the GNU General Public License along with better-result-cf-workflows. If not, see <https://www.gnu.org/licenses/>.
6
+ */
7
+ export {};
@@ -0,0 +1,5 @@
1
+ import { AnyTaggedError } from "better-result";
2
+ import { WorkflowStep } from "cloudflare:workers";
3
+ import { ErrCodec } from "../codec";
4
+ import { ResultDoFunction } from "./compat";
5
+ export declare function resultDo(ogDo: WorkflowStep["do"], getErrCodec: () => ErrCodec<AnyTaggedError>): ResultDoFunction;
@@ -0,0 +1,80 @@
1
+ /*
2
+ * This file is part of better-result-cf-workflows.
3
+ * better-result-cf-workflows is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
4
+ * better-result-cf-workflows is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
5
+ * You should have received a copy of the GNU General Public License along with better-result-cf-workflows. If not, see <https://www.gnu.org/licenses/>.
6
+ */
7
+ import { Panic, Result } from "better-result";
8
+ import { decodeErr, encodeErr } from "../codec";
9
+ import { NonRetryableError } from "cloudflare:workflows";
10
+ function transformRetries(codec, retryConfig) {
11
+ if (!retryConfig) {
12
+ return undefined;
13
+ }
14
+ // @ts-expect-error ts just does not recognize that the delay function im giving it es the real deal
15
+ return {
16
+ ...retryConfig,
17
+ ...(retryConfig.delay instanceof Function && {
18
+ delay: async (ctx) => {
19
+ return retryConfig.delay({
20
+ ...ctx,
21
+ error: ctx.error && (await decodeErr(codec, ctx.error)),
22
+ });
23
+ },
24
+ }),
25
+ };
26
+ }
27
+ async function wrapExecution(codec, retryConfig, cb) {
28
+ let res;
29
+ try {
30
+ res = await cb();
31
+ }
32
+ catch (err) {
33
+ throw await encodeErr(codec, new Panic({ message: "Unknown error thrown during execution", cause: err }));
34
+ }
35
+ if (res.isErr()) {
36
+ throw await encodeErr(codec, res.error, !retryConfig?.shouldRetry || retryConfig.shouldRetry(res.error) ? Error : NonRetryableError);
37
+ }
38
+ return res.value;
39
+ }
40
+ export function resultDo(ogDo, getErrCodec) {
41
+ return async (name, config, rollback) => {
42
+ const errCodec = getErrCodec();
43
+ const cfConfig = {
44
+ ...config,
45
+ retries: config.retries && transformRetries(errCodec, config.retries),
46
+ };
47
+ // @ts-expect-error cb causes failures
48
+ delete cfConfig["callback"];
49
+ try {
50
+ const resOk = await ogDo(name, cfConfig, async (ctx) => {
51
+ return await wrapExecution(errCodec, config.retries, async () => {
52
+ return config.callback(ctx);
53
+ });
54
+ }, rollback && {
55
+ ...rollback,
56
+ rollback: async (inp) => {
57
+ return await wrapExecution(errCodec, config.retries, async () => {
58
+ return await rollback.rollback({
59
+ ...inp,
60
+ error: await decodeErr(errCodec, inp.error),
61
+ });
62
+ });
63
+ },
64
+ rollbackConfig: {
65
+ ...rollback.rollbackConfig,
66
+ retries: rollback.rollbackConfig?.retries &&
67
+ transformRetries(errCodec, rollback.rollbackConfig?.retries),
68
+ },
69
+ });
70
+ return Result.ok(resOk);
71
+ }
72
+ catch (err) {
73
+ const parsed = await decodeErr(errCodec, err);
74
+ if (Panic.is(parsed)) {
75
+ throw parsed;
76
+ }
77
+ return Result.err(parsed);
78
+ }
79
+ };
80
+ }
@@ -0,0 +1,10 @@
1
+ import { WorkflowStep, WorkflowStepEvent } from "cloudflare:workers";
2
+ import { ErrCodec } from "../codec";
3
+ import { AnyTaggedError, Result } from "better-result";
4
+ import { ResultDoFunction } from "./compat";
5
+ import { StepEventTimeoutErr } from "./wait-for-event";
6
+ export type ResultStep = Omit<WorkflowStep, "do" | "waitForEvent"> & {
7
+ do: ResultDoFunction;
8
+ waitForEvent(...args: Parameters<WorkflowStep["waitForEvent"]>): Promise<Result<WorkflowStepEvent<unknown>, StepEventTimeoutErr>>;
9
+ };
10
+ export declare function wrapStep(step: WorkflowStep, getErrCodec: () => ErrCodec<AnyTaggedError>): ResultStep;
@@ -0,0 +1,18 @@
1
+ /*
2
+ * This file is part of better-result-cf-workflows.
3
+ * better-result-cf-workflows is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
4
+ * better-result-cf-workflows is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
5
+ * You should have received a copy of the GNU General Public License along with better-result-cf-workflows. If not, see <https://www.gnu.org/licenses/>.
6
+ */
7
+ import { wrapStepWaitForEvent } from "./wait-for-event";
8
+ import { resultDo } from "./do";
9
+ export function wrapStep(step, getErrCodec) {
10
+ const ogDo = step.do;
11
+ const ogWaitForEvent = step.waitForEvent;
12
+ // @ts-expect-error we are wrapping this shit :)
13
+ step.do = resultDo(ogDo, getErrCodec);
14
+ // @ts-expect-error we are wrapping this shit :3
15
+ step.waitForEvent = wrapStepWaitForEvent(ogWaitForEvent);
16
+ // @ts-expect-error obviously ts wouldn't like this :3
17
+ return step;
18
+ }
@@ -0,0 +1,8 @@
1
+ import { Result } from "better-result";
2
+ import { WorkflowStep, WorkflowStepEvent } from "cloudflare:workers";
3
+ declare const StepEventTimeoutErr_base: import("better-result").TaggedErrorClass<"StepEventTimeoutErr">;
4
+ export declare class StepEventTimeoutErr extends StepEventTimeoutErr_base {
5
+ }
6
+ export type ResultWaitForEventFunction = (...args: Parameters<WorkflowStep["waitForEvent"]>) => Promise<Result<WorkflowStepEvent<unknown>, StepEventTimeoutErr>>;
7
+ export declare function wrapStepWaitForEvent(ogWaitForEvent: WorkflowStep["waitForEvent"]): ResultWaitForEventFunction;
8
+ export {};
@@ -0,0 +1,20 @@
1
+ /*
2
+ * This file is part of better-result-cf-workflows.
3
+ * better-result-cf-workflows is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
4
+ * better-result-cf-workflows is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
5
+ * You should have received a copy of the GNU General Public License along with better-result-cf-workflows. If not, see <https://www.gnu.org/licenses/>.
6
+ */
7
+ import { Result, TaggedError } from "better-result";
8
+ export class StepEventTimeoutErr extends TaggedError("StepEventTimeoutErr") {
9
+ }
10
+ export function wrapStepWaitForEvent(ogWaitForEvent) {
11
+ return async (...args) => {
12
+ try {
13
+ const res = await ogWaitForEvent(...args);
14
+ return Result.ok(res);
15
+ }
16
+ catch {
17
+ return Result.err(new StepEventTimeoutErr());
18
+ }
19
+ };
20
+ }
@@ -0,0 +1,16 @@
1
+ import { AnyTaggedError, Err, Panic, Result } from "better-result";
2
+ import { WorkflowEntrypoint, WorkflowEvent, WorkflowStep } from "cloudflare:workers";
3
+ import { ErrCodec } from "./codec";
4
+ import { ResultStep } from "./step";
5
+ export type ResultGenerator<T, E extends AnyTaggedError> = AsyncGenerator<Err<never, E>, Result<T, E>, unknown>;
6
+ export declare abstract class ResultWorkflowEntrypoint<SupportedErrors extends AnyTaggedError, FinalSuccess extends Rpc.Serializable<FinalSuccess> = Rpc.Serializable<unknown>, Env = unknown, T extends Rpc.Serializable<T> | unknown = unknown> extends WorkflowEntrypoint<Env, T> {
7
+ /** Since the Result class and tagged error classes are not RPC serializable, you need a result codec for returning data
8
+ * from steps. The provided errorMapCodec function will likely do you just fine!
9
+ */
10
+ abstract errorCodec: ErrCodec<SupportedErrors>;
11
+ constructor(ctx: ExecutionContext, env: Env);
12
+ run(event: Readonly<WorkflowEvent<T>>, step: WorkflowStep): Promise<unknown>;
13
+ abstract execute(event: Readonly<WorkflowEvent<T>>, step: ResultStep): ResultGenerator<FinalSuccess, SupportedErrors>;
14
+ onFinalError(step: ResultStep, err: SupportedErrors | Panic): Promise<Error | null>;
15
+ onFinalSuccess(step: ResultStep, v: FinalSuccess): Promise<unknown>;
16
+ }
@@ -0,0 +1,46 @@
1
+ /*
2
+ * This file is part of better-result-cf-workflows.
3
+ * better-result-cf-workflows is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
4
+ * better-result-cf-workflows is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
5
+ * You should have received a copy of the GNU General Public License along with better-result-cf-workflows. If not, see <https://www.gnu.org/licenses/>.
6
+ */
7
+ import { Panic, Result } from "better-result";
8
+ import { WorkflowEntrypoint } from "cloudflare:workers";
9
+ import { encodeErr } from "./codec";
10
+ import { wrapStep } from "./step";
11
+ export class ResultWorkflowEntrypoint extends WorkflowEntrypoint {
12
+ constructor(ctx, env) {
13
+ super(ctx, env);
14
+ }
15
+ async run(event, step) {
16
+ const resultStep = wrapStep(step, () => this.errorCodec);
17
+ let error;
18
+ try {
19
+ const res = await Result.gen(this.execute.bind(this, event, resultStep));
20
+ if (res.isOk()) {
21
+ return await this.onFinalSuccess(resultStep, res.value);
22
+ }
23
+ error = res.error;
24
+ }
25
+ catch (err) {
26
+ if (Panic.is(err)) {
27
+ error = err;
28
+ }
29
+ else {
30
+ error = new Panic({ message: "Workflow implementation threw", cause: err });
31
+ }
32
+ }
33
+ const err = await this.onFinalError(resultStep, error);
34
+ if (err === null) {
35
+ return null;
36
+ }
37
+ // I cannot for the
38
+ throw await encodeErr(this.errorCodec, err);
39
+ }
40
+ async onFinalError(step, err) {
41
+ return err;
42
+ }
43
+ async onFinalSuccess(step, v) {
44
+ return v;
45
+ }
46
+ }