Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

context.cancel & rename errors & lazy fetch #8

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
9 changes: 2 additions & 7 deletions src/client/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { NotifyResponse, Waiter } from "../types";
import { Client as QStashClient } from "@upstash/qstash";
import { makeGetWaitersRequest, makeNotifyRequest } from "./utils";
import { makeCancelRequest, makeGetWaitersRequest, makeNotifyRequest } from "./utils";

type ClientConfig = ConstructorParameters<typeof QStashClient>[0];

Expand Down Expand Up @@ -37,12 +37,7 @@ export class Client {
* @returns true if workflow is succesfully deleted. Otherwise throws QStashError
*/
public async cancel({ workflowRunId }: { workflowRunId: string }) {
const result = (await this.client.http.request({
path: ["v2", "workflows", "runs", `${workflowRunId}?cancel=true`],
method: "DELETE",
parseResponseAsJson: false,
})) as { error: string } | undefined;
return result ?? true;
return await makeCancelRequest(this.client.http, workflowRunId);
}

/**
Expand Down
24 changes: 23 additions & 1 deletion src/client/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Client } from "@upstash/qstash";
import { NotifyResponse, Waiter } from "../types";
import { NotifyResponse, RawStep, Waiter } from "../types";
import { WorkflowLogger } from "../logger";

export const makeNotifyRequest = async (
requester: Client["http"],
Expand All @@ -25,3 +26,24 @@ export const makeGetWaitersRequest = async (
})) as Required<Waiter>[];
return result;
};

export const makeCancelRequest = async (requester: Client["http"], workflowRunId: string) => {
const result = (await requester.request({
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does /v2/workflows/runs/ID retturns empty response on successfull cancellation? Don't we get any response?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, it returns empty response.

path: ["v2", "workflows", "runs", `${workflowRunId}?cancel=true`],
method: "DELETE",
parseResponseAsJson: false,
})) as { error: string } | undefined;
return result ?? true;
};

export const getSteps = async (
requester: Client["http"],
workflowRunId: string,
debug?: WorkflowLogger
): Promise<RawStep[]> => {
await debug?.log("INFO", "ENDPOINT_START", "Pulling steps from QStash.");
return (await requester.request({
path: ["v2", "workflows", "runs", workflowRunId],
parseResponseAsJson: true,
})) as RawStep[];
};
28 changes: 14 additions & 14 deletions src/context/auto-executor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { MOCK_QSTASH_SERVER_URL, mockQStashServer, WORKFLOW_ENDPOINT } from "../
import { nanoid } from "../utils";
import { AutoExecutor } from "./auto-executor";
import type { Step } from "../types";
import { QStashWorkflowAbort, QStashWorkflowError } from "../error";
import { WorkflowAbort, WorkflowError } from "../error";

class SpyAutoExecutor extends AutoExecutor {
public declare getParallelCallState;
Expand Down Expand Up @@ -106,7 +106,7 @@ describe("auto-executor", () => {
const throws = context.run("attemptCharge", () => {
return { input: context.requestPayload, success: false };
});
expect(throws).rejects.toThrowError(QStashWorkflowAbort);
expect(throws).rejects.toThrowError(WorkflowAbort);
},
responseFields: {
status: 200,
Expand Down Expand Up @@ -195,7 +195,7 @@ describe("auto-executor", () => {
context.sleep("sleep for some time", 123),
context.sleepUntil("sleep until next day", 123_123),
]);
expect(throws).rejects.toThrowError(QStashWorkflowAbort);
expect(throws).rejects.toThrowError(WorkflowAbort);
},
responseFields: {
status: 200,
Expand Down Expand Up @@ -262,7 +262,7 @@ describe("auto-executor", () => {
context.sleep("sleep for some time", 123),
context.sleepUntil("sleep until next day", 123_123),
]);
expect(throws).rejects.toThrowError(QStashWorkflowAbort);
expect(throws).rejects.toThrowError(WorkflowAbort);
},
responseFields: {
status: 200,
Expand Down Expand Up @@ -314,7 +314,7 @@ describe("auto-executor", () => {
context.sleep("sleep for some time", 123),
context.sleepUntil("sleep until next day", 123_123),
]);
expect(throws).rejects.toThrowError(QStashWorkflowAbort);
expect(throws).rejects.toThrowError(WorkflowAbort);
},
responseFields: {
status: 200,
Expand Down Expand Up @@ -366,7 +366,7 @@ describe("auto-executor", () => {
context.sleep("sleep for some time", 123),
context.sleepUntil("sleep until next day", 123_123),
]);
expect(throws).rejects.toThrowError(QStashWorkflowAbort);
expect(throws).rejects.toThrowError(WorkflowAbort);
},
responseFields: {
status: 200,
Expand Down Expand Up @@ -434,7 +434,7 @@ describe("auto-executor", () => {
return true;
});
expect(throws).rejects.toThrow(
new QStashWorkflowError(
new WorkflowError(
"Incompatible step name. Expected 'wrongName', got 'attemptCharge' from the request"
)
);
Expand All @@ -443,7 +443,7 @@ describe("auto-executor", () => {
const context = getContext([initialStep, singleStep]);
const throws = context.sleep("attemptCharge", 10);
expect(throws).rejects.toThrow(
new QStashWorkflowError(
new WorkflowError(
"Incompatible step type. Expected 'SleepFor', got 'Run' from the request"
)
);
Expand All @@ -460,7 +460,7 @@ describe("auto-executor", () => {
context.sleepUntil("sleep until next day", 123_123),
]);
expect(throws).rejects.toThrow(
new QStashWorkflowError(
new WorkflowError(
"Incompatible step name. Expected 'wrongName', got 'sleep for some time' from the request"
)
);
Expand All @@ -474,7 +474,7 @@ describe("auto-executor", () => {
context.sleepUntil("sleep until next day", 123_123),
]);
expect(throws).rejects.toThrow(
new QStashWorkflowError(
new WorkflowError(
"Incompatible step type. Expected 'SleepUntil', got 'SleepFor' from the request"
)
);
Expand All @@ -490,7 +490,7 @@ describe("auto-executor", () => {
context.sleep("wrongName", 10), // wrong step name
context.sleepUntil("sleep until next day", 123_123),
]);
expect(throws).rejects.toThrowError(QStashWorkflowAbort);
expect(throws).rejects.toThrowError(WorkflowAbort);
});
test("step type", () => {
const context = getContext([initialStep, ...parallelSteps.slice(0, 3)]);
Expand All @@ -500,7 +500,7 @@ describe("auto-executor", () => {
context.sleepUntil("sleep for some time", 10), // wrong step type
context.sleepUntil("sleep until next day", 123_123),
]);
expect(throws).rejects.toThrowError(QStashWorkflowAbort);
expect(throws).rejects.toThrowError(WorkflowAbort);
});
});

Expand All @@ -514,7 +514,7 @@ describe("auto-executor", () => {
context.sleepUntil("sleep until next day", 123_123),
]);
expect(throws).rejects.toThrowError(
new QStashWorkflowError(
new WorkflowError(
"Incompatible steps detected in parallel execution: Incompatible step name. Expected 'wrongName', got 'sleep for some time' from the request\n" +
' > Step Names from the request: ["sleep for some time","sleep until next day"]\n' +
' Step Types from the request: ["SleepFor","SleepUntil"]\n' +
Expand All @@ -532,7 +532,7 @@ describe("auto-executor", () => {
context.sleepUntil("sleep until next day", 123_123),
]);
expect(throws).rejects.toThrowError(
new QStashWorkflowError(
new WorkflowError(
"Incompatible steps detected in parallel execution: Incompatible step type. Expected 'SleepUntil', got 'SleepFor' from the request\n" +
' > Step Names from the request: ["sleep for some time","sleep until next day"]\n' +
' Step Types from the request: ["SleepFor","SleepUntil"]\n' +
Expand Down
36 changes: 18 additions & 18 deletions src/context/auto-executor.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { QStashWorkflowAbort, QStashWorkflowError } from "../error";
import { WorkflowAbort, WorkflowError } from "../error";
import type { WorkflowContext } from "./context";
import type { StepFunction, ParallelCallState, Step, WaitRequest } from "../types";
import { type BaseLazyStep } from "./steps";
Expand Down Expand Up @@ -39,14 +39,14 @@ export class AutoExecutor {
*
* If a function is already executing (this.executingStep), this
* means that there is a nested step which is not allowed. In this
* case, addStep throws QStashWorkflowError.
* case, addStep throws WorkflowError.
*
* @param stepInfo step plan to add
* @returns result of the step function
*/
public async addStep<TResult>(stepInfo: BaseLazyStep<TResult>) {
if (this.executingStep) {
throw new QStashWorkflowError(
throw new WorkflowError(
"A step can not be run inside another step." +
` Tried to run '${stepInfo.stepName}' inside '${this.executingStep}'`
);
Expand Down Expand Up @@ -159,7 +159,7 @@ export class AutoExecutor {

if (parallelCallState !== "first" && plannedParallelStepCount !== parallelSteps.length) {
// user has added/removed a parallel step
throw new QStashWorkflowError(
throw new WorkflowError(
`Incompatible number of parallel steps when call state was '${parallelCallState}'.` +
` Expected ${parallelSteps.length}, got ${plannedParallelStepCount} from the request.`
);
Expand Down Expand Up @@ -194,7 +194,7 @@ export class AutoExecutor {
*/
const planStep = this.steps.at(-1);
if (!planStep || planStep.targetStep === undefined) {
throw new QStashWorkflowError(
throw new WorkflowError(
`There must be a last step and it should have targetStep larger than 0.` +
`Received: ${JSON.stringify(planStep)}`
);
Expand All @@ -217,10 +217,10 @@ export class AutoExecutor {
);
await this.submitStepsToQStash([resultStep]);
} catch (error) {
if (error instanceof QStashWorkflowAbort) {
if (error instanceof WorkflowAbort) {
throw error;
}
throw new QStashWorkflowError(
throw new WorkflowError(
`Error submitting steps to QStash in partial parallel step execution: ${error}`
);
}
Expand All @@ -235,7 +235,7 @@ export class AutoExecutor {
* This call to the API should be discarded: no operations are to be made. Parallel steps which are still
* running will finish and call QStash eventually.
*/
throw new QStashWorkflowAbort("discarded parallel");
throw new WorkflowAbort("discarded parallel");
}
case "last": {
/**
Expand Down Expand Up @@ -312,7 +312,7 @@ export class AutoExecutor {
private async submitStepsToQStash(steps: Step[]) {
// if there are no steps, something went wrong. Raise exception
if (steps.length === 0) {
throw new QStashWorkflowError(
throw new WorkflowError(
`Unable to submit steps to QStash. Provided list is empty. Current step: ${this.stepCount}`
);
}
Expand Down Expand Up @@ -359,7 +359,7 @@ export class AutoExecutor {
parseResponseAsJson: false,
});

throw new QStashWorkflowAbort(steps[0].stepName, steps[0]);
throw new WorkflowAbort(steps[0].stepName, steps[0]);
}

const result = await this.context.qstashClient.batchJSON(
Expand Down Expand Up @@ -415,7 +415,7 @@ export class AutoExecutor {
});

// if the steps are sent successfully, abort to stop the current request
throw new QStashWorkflowAbort(steps[0].stepName, steps[0]);
throw new WorkflowAbort(steps[0].stepName, steps[0]);
}

/**
Expand Down Expand Up @@ -448,7 +448,7 @@ export class AutoExecutor {
) {
return result[index] as TResult;
} else {
throw new QStashWorkflowError(
throw new WorkflowError(
`Unexpected parallel call result while executing step ${index}: '${result}'. Expected ${lazyStepList.length} many items`
);
}
Expand All @@ -465,22 +465,22 @@ export class AutoExecutor {
* from the incoming request; compare the step names and types to make sure
* that they are the same.
*
* Raises `QStashWorkflowError` if there is a difference.
* Raises `WorkflowError` if there is a difference.
*
* @param lazyStep lazy step created during execution
* @param stepFromRequest step parsed from incoming request
*/
const validateStep = (lazyStep: BaseLazyStep, stepFromRequest: Step): void => {
// check step name
if (lazyStep.stepName !== stepFromRequest.stepName) {
throw new QStashWorkflowError(
throw new WorkflowError(
`Incompatible step name. Expected '${lazyStep.stepName}',` +
` got '${stepFromRequest.stepName}' from the request`
);
}
// check type name
if (lazyStep.stepType !== stepFromRequest.stepType) {
throw new QStashWorkflowError(
throw new WorkflowError(
`Incompatible step type. Expected '${lazyStep.stepType}',` +
` got '${stepFromRequest.stepType}' from the request`
);
Expand All @@ -491,7 +491,7 @@ const validateStep = (lazyStep: BaseLazyStep, stepFromRequest: Step): void => {
* validates that each lazy step and step from request has the same step
* name and type using `validateStep` method.
*
* If there is a difference, raises `QStashWorkflowError` with information
* If there is a difference, raises `WorkflowError` with information
* about the difference.
*
* @param lazySteps list of lazy steps created during parallel execution
Expand All @@ -503,12 +503,12 @@ const validateParallelSteps = (lazySteps: BaseLazyStep[], stepsFromRequest: Step
validateStep(lazySteps[index], stepFromRequest);
}
} catch (error) {
if (error instanceof QStashWorkflowError) {
if (error instanceof WorkflowError) {
const lazyStepNames = lazySteps.map((lazyStep) => lazyStep.stepName);
const lazyStepTypes = lazySteps.map((lazyStep) => lazyStep.stepType);
const requestStepNames = stepsFromRequest.map((step) => step.stepName);
const requestStepTypes = stepsFromRequest.map((step) => step.stepType);
throw new QStashWorkflowError(
throw new WorkflowError(
`Incompatible steps detected in parallel execution: ${error.message}` +
`\n > Step Names from the request: ${JSON.stringify(requestStepNames)}` +
`\n Step Types from the request: ${JSON.stringify(requestStepTypes)}` +
Expand Down
Loading