better-result-cf-workflows 0.0.1 → 0.0.3
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/dist/codec.d.ts +21 -0
- package/dist/codec.js +142 -0
- package/dist/index.d.ts +5 -0
- package/{vitest.config.ts → dist/index.js} +3 -15
- package/dist/step/compat.d.ts +32 -0
- package/{src/index.ts → dist/step/compat.js} +1 -13
- package/dist/step/do.d.ts +5 -0
- package/dist/step/do.js +80 -0
- package/dist/step/index.d.ts +10 -0
- package/{src/step/wait-for-event.ts → dist/step/index.js} +11 -20
- package/dist/step/wait-for-event.d.ts +8 -0
- package/{tests/utils.ts → dist/step/wait-for-event.js} +13 -16
- package/dist/wf-class.d.ts +16 -0
- package/dist/wf-class.js +46 -0
- package/package.json +8 -3
- package/.forgejo/workflows/lint_test.yaml +0 -27
- package/.forgejo/workflows/main.yaml +0 -13
- package/.forgejo/workflows/pr.yaml +0 -8
- package/.husky/pre-commit +0 -1
- package/.oxfmtrc.json +0 -6
- package/.oxlintrc.json +0 -29
- package/.vscode/settings.json +0 -3
- package/CONTRIBUTING.md +0 -14
- package/pnpm-workspace.yaml +0 -3
- package/src/codec.ts +0 -191
- package/src/step/compat.ts +0 -70
- package/src/step/do.ts +0 -124
- package/src/step/index.ts +0 -36
- package/src/wf-class.ts +0 -73
- package/tests/translation.test.ts +0 -72
- package/tests/tsconfig.json +0 -7
- package/tests/wf-class.test.ts +0 -105
- package/tests/worker-configuration.d.ts +0 -16564
- package/tests/workflows.ts +0 -56
- package/tests/wrangler.test.jsonc +0 -12
- package/tsconfig.json +0 -16
- package/tsconfig.tsbuildinfo +0 -1
package/src/codec.ts
DELETED
|
@@ -1,191 +0,0 @@
|
|
|
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
|
-
|
|
8
|
-
import {
|
|
9
|
-
AnyTaggedError,
|
|
10
|
-
Panic,
|
|
11
|
-
StandardSchemaV1,
|
|
12
|
-
TaggedError,
|
|
13
|
-
TaggedErrorInstance,
|
|
14
|
-
} from "better-result"
|
|
15
|
-
import { NonRetryableError } from "cloudflare:workflows"
|
|
16
|
-
import { z } from "zod/mini"
|
|
17
|
-
|
|
18
|
-
export type ErrCodec<E extends AnyTaggedError> = {
|
|
19
|
-
encode: StandardSchemaV1<E, string>
|
|
20
|
-
decode: StandardSchemaV1<string, E>
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export type InferErrorsFromErrCodec<T extends ErrCodec<AnyTaggedError>> =
|
|
24
|
-
T extends ErrCodec<infer E> ? E : never
|
|
25
|
-
|
|
26
|
-
type GenericTaggedErrorClass<T extends string> = abstract new (
|
|
27
|
-
...args: never[]
|
|
28
|
-
) => TaggedErrorInstance<T, unknown>
|
|
29
|
-
|
|
30
|
-
/** Creates a result codec that passes on the OK value directly and encodes the tagged errors
|
|
31
|
-
* To remain error identity, all errors must be passed in by value in the errors variable
|
|
32
|
-
*
|
|
33
|
-
* NOTE: The codec returned does not verify the shape of the parameters - so do not use this result codec outside of a workflow
|
|
34
|
-
* A workflow's RPC boundaries are *basically* trustworthy.
|
|
35
|
-
* Technically, your code may change as you wait on old workflows, but there is virtually nothing you can do about this.
|
|
36
|
-
*/
|
|
37
|
-
export function errorMapCodec<E extends string>(errors: {
|
|
38
|
-
[K in E]: GenericTaggedErrorClass<K>
|
|
39
|
-
}): ErrCodec<TaggedErrorInstance<E, unknown>> {
|
|
40
|
-
// @ts-expect-error we are using unknown here for efficiency
|
|
41
|
-
// but this codec is only ever used for result error serialization/deserialization
|
|
42
|
-
// so its fine
|
|
43
|
-
const zodCodec: z.ZodMiniCodec<
|
|
44
|
-
z.ZodMiniString<string>,
|
|
45
|
-
z.ZodMiniCustom<TaggedErrorInstance<E, unknown>, TaggedErrorInstance<E, unknown>>
|
|
46
|
-
> = z.codec(z.string(), z.unknown(), {
|
|
47
|
-
// @ts-expect-error see above comment
|
|
48
|
-
encode: (v: TaggedErrorInstance) => {
|
|
49
|
-
return JSON.stringify(v.toJSON())
|
|
50
|
-
},
|
|
51
|
-
decode: (v, ctx) => {
|
|
52
|
-
let json: unknown
|
|
53
|
-
try {
|
|
54
|
-
json = JSON.parse(v)
|
|
55
|
-
} catch (err) {
|
|
56
|
-
ctx.issues.push({
|
|
57
|
-
code: "invalid_format",
|
|
58
|
-
format: "json",
|
|
59
|
-
input: v,
|
|
60
|
-
// @ts-expect-error err.message isn't know to ts, but cmon
|
|
61
|
-
message: err?.message,
|
|
62
|
-
continue: false,
|
|
63
|
-
})
|
|
64
|
-
return z.NEVER
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
if (typeof json !== "object" || Array.isArray(json) || json === null) {
|
|
68
|
-
ctx.issues.push({
|
|
69
|
-
code: "invalid_type",
|
|
70
|
-
expected: "object",
|
|
71
|
-
input: json,
|
|
72
|
-
continue: false,
|
|
73
|
-
})
|
|
74
|
-
|
|
75
|
-
return z.NEVER
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
if (!("_tag" in json) || typeof json["_tag"] !== "string") {
|
|
79
|
-
ctx.issues.push({
|
|
80
|
-
code: "invalid_type",
|
|
81
|
-
expected: "string",
|
|
82
|
-
input: "_tag" in json ? json["_tag"] : undefined,
|
|
83
|
-
continue: false,
|
|
84
|
-
path: ["_tag"],
|
|
85
|
-
})
|
|
86
|
-
|
|
87
|
-
return z.NEVER
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
if (!(json["_tag"] in errors)) {
|
|
91
|
-
ctx.issues.push({
|
|
92
|
-
code: "custom",
|
|
93
|
-
input: json["_tag"],
|
|
94
|
-
continue: false,
|
|
95
|
-
path: ["_tag"],
|
|
96
|
-
message: "Unknown tag",
|
|
97
|
-
})
|
|
98
|
-
|
|
99
|
-
return z.NEVER
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
const cls = errors[json["_tag"] as keyof typeof errors]
|
|
103
|
-
|
|
104
|
-
// @ts-expect-error we obviously did not give types to the error
|
|
105
|
-
// in fact, this is strictly un-safe
|
|
106
|
-
// however, since we are purely using this for workflow rpc encoding, this will work
|
|
107
|
-
// we are not navigating trust boundaries, we ARE navigating network but only on a technicality
|
|
108
|
-
// lets not bother ourselves with (in this case) pointless safety
|
|
109
|
-
return new cls(json)
|
|
110
|
-
},
|
|
111
|
-
})
|
|
112
|
-
|
|
113
|
-
return {
|
|
114
|
-
encode: z.invertCodec(zodCodec),
|
|
115
|
-
decode: zodCodec,
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
// fun discovery: so if you have a custom error class (even one thats not a tagged error)
|
|
120
|
-
// outside of RPC, that error will look like a normal error class. Even if you set the error.name!
|
|
121
|
-
// So the error's message will look like {err name}: {err message}
|
|
122
|
-
// From that, the decision to move forward is to JSONify the data & encode/decode it. Easy :3
|
|
123
|
-
|
|
124
|
-
async function wrapStdSchema<In, Out>(
|
|
125
|
-
codec: StandardSchemaV1<In, Out>,
|
|
126
|
-
value: unknown,
|
|
127
|
-
): Promise<Out | Panic> {
|
|
128
|
-
try {
|
|
129
|
-
const stdResult = await codec["~standard"].validate(value)
|
|
130
|
-
if (stdResult.issues) {
|
|
131
|
-
return new Panic({
|
|
132
|
-
message: "invalid error has been returned",
|
|
133
|
-
cause: stdResult.issues,
|
|
134
|
-
})
|
|
135
|
-
}
|
|
136
|
-
return stdResult.value
|
|
137
|
-
} catch (err) {
|
|
138
|
-
return new Panic({ message: "decoder threw while decoding an error!", cause: err })
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
export async function encodeErr<E extends AnyTaggedError>(
|
|
143
|
-
codec: ErrCodec<E>,
|
|
144
|
-
value: unknown,
|
|
145
|
-
errClass: ErrorConstructor | typeof NonRetryableError = Error,
|
|
146
|
-
): Promise<Error> {
|
|
147
|
-
if (TaggedError.is(value)) {
|
|
148
|
-
const res = await wrapStdSchema(codec.encode, value)
|
|
149
|
-
if (Panic.is(res)) {
|
|
150
|
-
value = res
|
|
151
|
-
} else {
|
|
152
|
-
return new errClass(res)
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
if (Panic.is(value)) {
|
|
157
|
-
return new errClass(JSON.stringify(value.toJSON()))
|
|
158
|
-
} else {
|
|
159
|
-
return new errClass(
|
|
160
|
-
JSON.stringify(new Panic({ message: "Unknown error happened", cause: value }).toJSON()),
|
|
161
|
-
)
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
export async function decodeErr<E extends AnyTaggedError>(
|
|
166
|
-
codec: ErrCodec<E>,
|
|
167
|
-
value: unknown,
|
|
168
|
-
): Promise<Panic | E> {
|
|
169
|
-
if (Panic.is(value) || TaggedError.is(value)) {
|
|
170
|
-
return value as Panic | E
|
|
171
|
-
}
|
|
172
|
-
if (!(value instanceof Error)) {
|
|
173
|
-
return new Panic({ message: "Unknown error given to decoder", cause: value })
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
// a codec may or may not use JSON for encoding. However, a Panic definitely uses JSON
|
|
177
|
-
// so lets test for that first
|
|
178
|
-
try {
|
|
179
|
-
const json = JSON.parse(value.message)
|
|
180
|
-
if (typeof json !== "object" || json === null || !("_tag" in json)) {
|
|
181
|
-
return new Panic({ message: "Non-tagged error given in json", cause: json })
|
|
182
|
-
}
|
|
183
|
-
if (json["_tag"] === "Panic") {
|
|
184
|
-
return new Panic(json)
|
|
185
|
-
}
|
|
186
|
-
} catch {
|
|
187
|
-
// who knows that this can mean - maybe the codec just isn't a json guy
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
return await wrapStdSchema(codec.decode, value.message)
|
|
191
|
-
}
|
package/src/step/compat.ts
DELETED
|
@@ -1,70 +0,0 @@
|
|
|
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
|
-
|
|
8
|
-
import { AnyTaggedError, Panic, Result } from "better-result"
|
|
9
|
-
import {
|
|
10
|
-
WorkflowBackoff,
|
|
11
|
-
WorkflowDelayDuration,
|
|
12
|
-
WorkflowRollbackContext,
|
|
13
|
-
WorkflowStepConfig,
|
|
14
|
-
WorkflowStepContext,
|
|
15
|
-
WorkflowStepRollbackConfig,
|
|
16
|
-
WorkflowStepRollbackOptions,
|
|
17
|
-
} from "cloudflare:workers"
|
|
18
|
-
|
|
19
|
-
export type ResultWorkflowDynamicDelayContext<E extends AnyTaggedError> = {
|
|
20
|
-
ctx: WorkflowStepContext<ResultWorkflowDelayFunction<E>>
|
|
21
|
-
error: E | Panic
|
|
22
|
-
}
|
|
23
|
-
export type ResultWorkflowDelayFunction<E extends AnyTaggedError> = (
|
|
24
|
-
input: ResultWorkflowDynamicDelayContext<E>,
|
|
25
|
-
) => WorkflowDelayDuration | Promise<WorkflowDelayDuration>
|
|
26
|
-
|
|
27
|
-
export type ResultWorkflowRetryConfig<E extends AnyTaggedError> = {
|
|
28
|
-
shouldRetry?: (err: E) => boolean | { [K in E as K["_tag"]]: boolean | ((err: K) => boolean) }
|
|
29
|
-
limit: number
|
|
30
|
-
delay: WorkflowDelayDuration | number | ResultWorkflowDelayFunction<E>
|
|
31
|
-
backoff?: WorkflowBackoff
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export type ResultWorkflowStepConfig<
|
|
35
|
-
T extends Rpc.Serializable<T>,
|
|
36
|
-
E extends AnyTaggedError,
|
|
37
|
-
> = Omit<WorkflowStepConfig, "retries"> & {
|
|
38
|
-
callback: (ctx: WorkflowStepContext) => Promise<Result<T, E>>
|
|
39
|
-
retries?: ResultWorkflowRetryConfig<E>
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
export type ResultWorkflowRollbackContext<
|
|
43
|
-
T extends Rpc.Serializable<T>,
|
|
44
|
-
E extends AnyTaggedError,
|
|
45
|
-
> = Omit<WorkflowRollbackContext<T>, "error"> & {
|
|
46
|
-
error: E | Panic
|
|
47
|
-
}
|
|
48
|
-
type ResultWorkflowRollbackHandler<T extends Rpc.Serializable<T>, E extends AnyTaggedError> = (
|
|
49
|
-
ctx: ResultWorkflowRollbackContext<T, E>,
|
|
50
|
-
) => Promise<Result<void, E>>
|
|
51
|
-
type ResultWorkflowStepRollbackConfig<E extends AnyTaggedError> = Omit<
|
|
52
|
-
WorkflowStepRollbackConfig,
|
|
53
|
-
"retries"
|
|
54
|
-
> & {
|
|
55
|
-
retries?: ResultWorkflowRetryConfig<E>
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
export type ResultWorkflowStepRollbackOptions<
|
|
59
|
-
T extends Rpc.Serializable<T>,
|
|
60
|
-
E extends AnyTaggedError,
|
|
61
|
-
> = Omit<WorkflowStepRollbackOptions, "rollback" | "rollbackConfig"> & {
|
|
62
|
-
rollback: ResultWorkflowRollbackHandler<T, E>
|
|
63
|
-
rollbackConfig?: ResultWorkflowStepRollbackConfig<E>
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
export type ResultDoFunction = <T extends Rpc.Serializable<T>, E extends AnyTaggedError>(
|
|
67
|
-
name: string,
|
|
68
|
-
config: ResultWorkflowStepConfig<T, E>,
|
|
69
|
-
rollback?: ResultWorkflowStepRollbackOptions<T, E>,
|
|
70
|
-
) => Promise<Result<T, E>>
|
package/src/step/do.ts
DELETED
|
@@ -1,124 +0,0 @@
|
|
|
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
|
-
|
|
8
|
-
import { AnyTaggedError, Panic, Result } from "better-result"
|
|
9
|
-
import { WorkflowDynamicDelayContext, WorkflowStep, WorkflowStepConfig } from "cloudflare:workers"
|
|
10
|
-
import { decodeErr, encodeErr, ErrCodec } from "../codec"
|
|
11
|
-
import { NonRetryableError } from "cloudflare:workflows"
|
|
12
|
-
import {
|
|
13
|
-
ResultDoFunction,
|
|
14
|
-
ResultWorkflowDelayFunction,
|
|
15
|
-
ResultWorkflowRetryConfig,
|
|
16
|
-
ResultWorkflowStepConfig,
|
|
17
|
-
ResultWorkflowStepRollbackOptions,
|
|
18
|
-
} from "./compat"
|
|
19
|
-
|
|
20
|
-
function transformRetries<E extends AnyTaggedError>(
|
|
21
|
-
codec: ErrCodec<E>,
|
|
22
|
-
retryConfig: ResultWorkflowRetryConfig<E> | undefined,
|
|
23
|
-
): WorkflowStepConfig["retries"] {
|
|
24
|
-
if (!retryConfig) {
|
|
25
|
-
return undefined
|
|
26
|
-
}
|
|
27
|
-
// @ts-expect-error ts just does not recognize that the delay function im giving it es the real deal
|
|
28
|
-
return {
|
|
29
|
-
...retryConfig,
|
|
30
|
-
...(retryConfig.delay instanceof Function && {
|
|
31
|
-
delay: async (ctx: WorkflowDynamicDelayContext) => {
|
|
32
|
-
return (retryConfig.delay as ResultWorkflowDelayFunction<E>)({
|
|
33
|
-
...ctx,
|
|
34
|
-
error: ctx.error && (await decodeErr(codec, ctx.error)),
|
|
35
|
-
})
|
|
36
|
-
},
|
|
37
|
-
}),
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
async function wrapExecution<T extends Rpc.Serializable<T>, E extends AnyTaggedError>(
|
|
42
|
-
codec: ErrCodec<E>,
|
|
43
|
-
retryConfig: ResultWorkflowRetryConfig<E> | undefined,
|
|
44
|
-
cb: () => Promise<Result<T, E>>,
|
|
45
|
-
): Promise<T> {
|
|
46
|
-
let res: Result<T, E>
|
|
47
|
-
try {
|
|
48
|
-
res = await cb()
|
|
49
|
-
} catch (err) {
|
|
50
|
-
throw await encodeErr(
|
|
51
|
-
codec,
|
|
52
|
-
new Panic({ message: "Unknown error thrown during execution", cause: err }),
|
|
53
|
-
)
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
if (res.isErr()) {
|
|
57
|
-
throw await encodeErr(
|
|
58
|
-
codec,
|
|
59
|
-
res.error,
|
|
60
|
-
!retryConfig?.shouldRetry || retryConfig.shouldRetry(res.error) ? Error : NonRetryableError,
|
|
61
|
-
)
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
return res.value
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
export function resultDo(
|
|
68
|
-
ogDo: WorkflowStep["do"],
|
|
69
|
-
getErrCodec: () => ErrCodec<AnyTaggedError>,
|
|
70
|
-
): ResultDoFunction {
|
|
71
|
-
return async <T extends Rpc.Serializable<T>, E extends AnyTaggedError>(
|
|
72
|
-
name: string,
|
|
73
|
-
config: ResultWorkflowStepConfig<T, E>,
|
|
74
|
-
rollback?: ResultWorkflowStepRollbackOptions<T, E>,
|
|
75
|
-
) => {
|
|
76
|
-
const errCodec = getErrCodec() as ErrCodec<E>
|
|
77
|
-
|
|
78
|
-
const cfConfig: WorkflowStepConfig = {
|
|
79
|
-
...config,
|
|
80
|
-
retries: config.retries && transformRetries(errCodec, config.retries),
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
// @ts-expect-error cb causes failures
|
|
84
|
-
delete cfConfig["callback"]
|
|
85
|
-
|
|
86
|
-
try {
|
|
87
|
-
const resOk = await ogDo<T>(
|
|
88
|
-
name,
|
|
89
|
-
cfConfig,
|
|
90
|
-
async (ctx) => {
|
|
91
|
-
return await wrapExecution(errCodec, config.retries, async () => {
|
|
92
|
-
return config.callback(ctx)
|
|
93
|
-
})
|
|
94
|
-
},
|
|
95
|
-
rollback && {
|
|
96
|
-
...rollback,
|
|
97
|
-
rollback: async (inp): Promise<void> => {
|
|
98
|
-
return await wrapExecution(errCodec, config.retries, async () => {
|
|
99
|
-
return await rollback.rollback({
|
|
100
|
-
...inp,
|
|
101
|
-
error: await decodeErr(errCodec, inp.error),
|
|
102
|
-
})
|
|
103
|
-
})
|
|
104
|
-
},
|
|
105
|
-
rollbackConfig: {
|
|
106
|
-
...rollback.rollbackConfig,
|
|
107
|
-
retries:
|
|
108
|
-
rollback.rollbackConfig?.retries &&
|
|
109
|
-
transformRetries(errCodec, rollback.rollbackConfig?.retries),
|
|
110
|
-
},
|
|
111
|
-
},
|
|
112
|
-
)
|
|
113
|
-
|
|
114
|
-
return Result.ok(resOk)
|
|
115
|
-
} catch (err) {
|
|
116
|
-
const parsed = await decodeErr(errCodec, err)
|
|
117
|
-
if (Panic.is(parsed)) {
|
|
118
|
-
throw parsed
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
return Result.err(parsed)
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
}
|
package/src/step/index.ts
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
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
|
-
|
|
8
|
-
import { WorkflowStep, WorkflowStepEvent } from "cloudflare:workers"
|
|
9
|
-
import { ErrCodec } from "../codec"
|
|
10
|
-
import { AnyTaggedError, Result } from "better-result"
|
|
11
|
-
import { ResultDoFunction } from "./compat"
|
|
12
|
-
import { StepEventTimeoutErr, wrapStepWaitForEvent } from "./wait-for-event"
|
|
13
|
-
import { resultDo } from "./do"
|
|
14
|
-
|
|
15
|
-
export type ResultStep = Omit<WorkflowStep, "do" | "waitForEvent"> & {
|
|
16
|
-
do: ResultDoFunction
|
|
17
|
-
waitForEvent(
|
|
18
|
-
...args: Parameters<WorkflowStep["waitForEvent"]>
|
|
19
|
-
): Promise<Result<WorkflowStepEvent<unknown>, StepEventTimeoutErr>>
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export function wrapStep(
|
|
23
|
-
step: WorkflowStep,
|
|
24
|
-
getErrCodec: () => ErrCodec<AnyTaggedError>,
|
|
25
|
-
): ResultStep {
|
|
26
|
-
const ogDo = step.do
|
|
27
|
-
const ogWaitForEvent = step.waitForEvent
|
|
28
|
-
|
|
29
|
-
// @ts-expect-error we are wrapping this shit :)
|
|
30
|
-
step.do = resultDo(ogDo, getErrCodec)
|
|
31
|
-
// @ts-expect-error we are wrapping this shit :3
|
|
32
|
-
step.waitForEvent = wrapStepWaitForEvent(ogWaitForEvent)
|
|
33
|
-
|
|
34
|
-
// @ts-expect-error obviously ts wouldn't like this :3
|
|
35
|
-
return step
|
|
36
|
-
}
|
package/src/wf-class.ts
DELETED
|
@@ -1,73 +0,0 @@
|
|
|
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
|
-
|
|
8
|
-
import { AnyTaggedError, Err, Panic, Result } from "better-result"
|
|
9
|
-
import { WorkflowEntrypoint, WorkflowEvent, WorkflowStep } from "cloudflare:workers"
|
|
10
|
-
import { encodeErr, ErrCodec } from "./codec"
|
|
11
|
-
import { ResultStep, wrapStep } from "./step"
|
|
12
|
-
|
|
13
|
-
export type ResultGenerator<T, E extends AnyTaggedError> = AsyncGenerator<
|
|
14
|
-
Err<never, E>,
|
|
15
|
-
Result<T, E>,
|
|
16
|
-
unknown
|
|
17
|
-
>
|
|
18
|
-
|
|
19
|
-
export abstract class ResultWorkflowEntrypoint<
|
|
20
|
-
SupportedErrors extends AnyTaggedError,
|
|
21
|
-
FinalSuccess extends Rpc.Serializable<FinalSuccess> = Rpc.Serializable<unknown>,
|
|
22
|
-
Env = unknown,
|
|
23
|
-
T extends Rpc.Serializable<T> | unknown = unknown,
|
|
24
|
-
> extends WorkflowEntrypoint<Env, T> {
|
|
25
|
-
/** Since the Result class and tagged error classes are not RPC serializable, you need a result codec for returning data
|
|
26
|
-
* from steps. The provided errorMapCodec function will likely do you just fine!
|
|
27
|
-
*/
|
|
28
|
-
abstract errorCodec: ErrCodec<SupportedErrors>
|
|
29
|
-
|
|
30
|
-
constructor(ctx: ExecutionContext, env: Env) {
|
|
31
|
-
super(ctx, env)
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
async run(event: Readonly<WorkflowEvent<T>>, step: WorkflowStep): Promise<unknown> {
|
|
35
|
-
const resultStep = wrapStep(step, () => this.errorCodec)
|
|
36
|
-
|
|
37
|
-
let error: Panic | SupportedErrors
|
|
38
|
-
try {
|
|
39
|
-
const res = await Result.gen(this.execute.bind(this, event, resultStep))
|
|
40
|
-
if (res.isOk()) {
|
|
41
|
-
return await this.onFinalSuccess(resultStep, res.value)
|
|
42
|
-
}
|
|
43
|
-
error = res.error
|
|
44
|
-
} catch (err) {
|
|
45
|
-
if (Panic.is(err)) {
|
|
46
|
-
error = err
|
|
47
|
-
} else {
|
|
48
|
-
error = new Panic({ message: "Workflow implementation threw", cause: err })
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
const err = await this.onFinalError(resultStep, error)
|
|
53
|
-
if (err === null) {
|
|
54
|
-
return null
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
// I cannot for the
|
|
58
|
-
throw await encodeErr(this.errorCodec, err)
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
abstract execute(
|
|
62
|
-
event: Readonly<WorkflowEvent<T>>,
|
|
63
|
-
step: ResultStep,
|
|
64
|
-
): ResultGenerator<FinalSuccess, SupportedErrors>
|
|
65
|
-
|
|
66
|
-
async onFinalError(step: ResultStep, err: SupportedErrors | Panic): Promise<Error | null> {
|
|
67
|
-
return err
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
async onFinalSuccess(step: ResultStep, v: FinalSuccess): Promise<unknown> {
|
|
71
|
-
return v
|
|
72
|
-
}
|
|
73
|
-
}
|
|
@@ -1,72 +0,0 @@
|
|
|
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
|
-
|
|
8
|
-
import { describe, test, expect, vi } from "vitest"
|
|
9
|
-
import { createWf } from "./utils"
|
|
10
|
-
import { GenericErr, TestWorkflow } from "./workflows"
|
|
11
|
-
import { Result } from "better-result"
|
|
12
|
-
|
|
13
|
-
describe("step.do", () => {
|
|
14
|
-
test("success", async () => {
|
|
15
|
-
let res: Result<{ success: true }, GenericErr>
|
|
16
|
-
const spy = vi
|
|
17
|
-
.spyOn(TestWorkflow.prototype, "execute")
|
|
18
|
-
.mockImplementation(async function* (_, step) {
|
|
19
|
-
res = await step.do("random", {
|
|
20
|
-
callback: async () => {
|
|
21
|
-
return Result.ok({ success: true })
|
|
22
|
-
},
|
|
23
|
-
})
|
|
24
|
-
return res
|
|
25
|
-
})
|
|
26
|
-
|
|
27
|
-
await using wf = await createWf()
|
|
28
|
-
|
|
29
|
-
await wf.waitForStatus("complete")
|
|
30
|
-
|
|
31
|
-
expect(spy).toHaveBeenCalled()
|
|
32
|
-
expect(await wf.getOutput()).toEqual({ success: true })
|
|
33
|
-
|
|
34
|
-
// @ts-ignore it doesn't know we set it
|
|
35
|
-
expect(res.andThen).not.toBeUndefined()
|
|
36
|
-
// @ts-expect-error
|
|
37
|
-
expect(res.value).toEqual({ success: true })
|
|
38
|
-
})
|
|
39
|
-
|
|
40
|
-
test("error", async () => {
|
|
41
|
-
let res: Result<void, GenericErr>
|
|
42
|
-
const spy = vi
|
|
43
|
-
.spyOn(TestWorkflow.prototype, "execute")
|
|
44
|
-
// @ts-expect-error -- shim
|
|
45
|
-
.mockImplementation(async function* (_, step) {
|
|
46
|
-
// this is outside the RPC boundary
|
|
47
|
-
res = await step.do("random", {
|
|
48
|
-
callback: async () => {
|
|
49
|
-
return Result.err(new GenericErr())
|
|
50
|
-
},
|
|
51
|
-
retries: {
|
|
52
|
-
limit: 0,
|
|
53
|
-
delay: "0 seconds",
|
|
54
|
-
},
|
|
55
|
-
})
|
|
56
|
-
return res
|
|
57
|
-
})
|
|
58
|
-
|
|
59
|
-
await using wf = await createWf()
|
|
60
|
-
|
|
61
|
-
await wf.waitForStatus("errored")
|
|
62
|
-
|
|
63
|
-
expect(spy).toHaveBeenCalled()
|
|
64
|
-
|
|
65
|
-
// @ts-ignore it doesn't know we set it
|
|
66
|
-
expect(res.andThen).not.toBeUndefined()
|
|
67
|
-
// @ts-expect-error
|
|
68
|
-
expect(res.error).not.toBeUndefined()
|
|
69
|
-
// @ts-expect-error
|
|
70
|
-
expect(res.error).toBeInstanceOf(GenericErr)
|
|
71
|
-
})
|
|
72
|
-
})
|
package/tests/tsconfig.json
DELETED
package/tests/wf-class.test.ts
DELETED
|
@@ -1,105 +0,0 @@
|
|
|
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
|
-
|
|
8
|
-
import { describe, test, vi, expect } from "vitest"
|
|
9
|
-
import { Panic, Result, TaggedError } from "better-result"
|
|
10
|
-
import { TestWorkflow } from "./workflows"
|
|
11
|
-
import { createWf } from "./utils"
|
|
12
|
-
|
|
13
|
-
class GenericErr extends TaggedError("GenericErr") {}
|
|
14
|
-
|
|
15
|
-
describe("ResultWorkflowEntrypoint", () => {
|
|
16
|
-
describe("run", () => {
|
|
17
|
-
test("generator", async () => {
|
|
18
|
-
const firstStep = vi
|
|
19
|
-
.spyOn(TestWorkflow.prototype, "stepImpl")
|
|
20
|
-
.mockResolvedValue(Result.ok({ success: true }))
|
|
21
|
-
vi.spyOn(TestWorkflow.prototype, "stepImpl2").mockResolvedValue(Result.err(new GenericErr()))
|
|
22
|
-
|
|
23
|
-
await using wf = await createWf()
|
|
24
|
-
|
|
25
|
-
await wf.waitForStatus("errored")
|
|
26
|
-
|
|
27
|
-
expect(firstStep).toHaveBeenCalled()
|
|
28
|
-
|
|
29
|
-
const err = await wf.getError()
|
|
30
|
-
expect(err.message).toEqual(expect.stringContaining("GenericErr"))
|
|
31
|
-
})
|
|
32
|
-
|
|
33
|
-
test("execution throw", async () => {
|
|
34
|
-
vi.spyOn(TestWorkflow.prototype, "stepImpl").mockThrow(new Panic({ message: "Mocked throw" }))
|
|
35
|
-
|
|
36
|
-
await using wf = await createWf()
|
|
37
|
-
|
|
38
|
-
await wf.waitForStatus("errored")
|
|
39
|
-
|
|
40
|
-
const output = await wf.getError()
|
|
41
|
-
expect(output.message).toEqual(expect.stringContaining("_tag"))
|
|
42
|
-
expect(output.message).toEqual(expect.stringContaining("Panic"))
|
|
43
|
-
})
|
|
44
|
-
})
|
|
45
|
-
|
|
46
|
-
describe("onFinalError", () => {
|
|
47
|
-
test("run in case execute returns error", async () => {
|
|
48
|
-
const errSpy = vi.spyOn(TestWorkflow.prototype, "onFinalError")
|
|
49
|
-
vi.spyOn(TestWorkflow.prototype, "stepImpl").mockResolvedValue(Result.err(new GenericErr()))
|
|
50
|
-
await using wf = await createWf()
|
|
51
|
-
|
|
52
|
-
await wf.waitForStatus("errored")
|
|
53
|
-
|
|
54
|
-
expect(errSpy).toHaveBeenCalled()
|
|
55
|
-
})
|
|
56
|
-
|
|
57
|
-
test("run in case execute returns panic", async () => {
|
|
58
|
-
const errSpy = vi.spyOn(TestWorkflow.prototype, "onFinalError")
|
|
59
|
-
vi.spyOn(TestWorkflow.prototype, "stepImpl").mockResolvedValue(
|
|
60
|
-
// @ts-expect-error shoehorn!!
|
|
61
|
-
new Panic({ message: "Random panic" }),
|
|
62
|
-
)
|
|
63
|
-
await using wf = await createWf()
|
|
64
|
-
|
|
65
|
-
await wf.waitForStatus("errored")
|
|
66
|
-
|
|
67
|
-
expect(errSpy).toHaveBeenCalled()
|
|
68
|
-
})
|
|
69
|
-
|
|
70
|
-
test("run in case execute throws", async () => {
|
|
71
|
-
const errSpy = vi.spyOn(TestWorkflow.prototype, "onFinalError")
|
|
72
|
-
vi.spyOn(TestWorkflow.prototype, "stepImpl").mockThrow(new Panic({ message: "Random panic" }))
|
|
73
|
-
await using wf = await createWf()
|
|
74
|
-
|
|
75
|
-
await wf.waitForStatus("errored")
|
|
76
|
-
|
|
77
|
-
expect(errSpy).toHaveBeenCalled()
|
|
78
|
-
})
|
|
79
|
-
|
|
80
|
-
test("does not rollback on null", async () => {
|
|
81
|
-
const errSpy = vi.spyOn(TestWorkflow.prototype, "onFinalError").mockResolvedValue(null)
|
|
82
|
-
vi.spyOn(TestWorkflow.prototype, "stepImpl").mockThrow(new Panic({ message: "Random panic" }))
|
|
83
|
-
await using wf = await createWf()
|
|
84
|
-
|
|
85
|
-
await wf.waitForStatus("complete")
|
|
86
|
-
|
|
87
|
-
expect(errSpy).toHaveBeenCalled()
|
|
88
|
-
})
|
|
89
|
-
})
|
|
90
|
-
|
|
91
|
-
describe("onFinalSuccess", () => {
|
|
92
|
-
test("run in case execute returns success", async () => {
|
|
93
|
-
const spy = vi.spyOn(TestWorkflow.prototype, "onFinalSuccess")
|
|
94
|
-
vi.spyOn(TestWorkflow.prototype, "stepImpl").mockResolvedValueOnce(
|
|
95
|
-
Result.ok({ success: true }),
|
|
96
|
-
)
|
|
97
|
-
|
|
98
|
-
await using wf = await createWf()
|
|
99
|
-
|
|
100
|
-
await wf.waitForStatus("complete")
|
|
101
|
-
|
|
102
|
-
expect(spy).toHaveBeenCalled()
|
|
103
|
-
})
|
|
104
|
-
})
|
|
105
|
-
})
|