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
36 changes: 30 additions & 6 deletions examples/basic.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,38 @@
import { createDeadlineBudget } from "../src/index";
import { createDeadlineBudget } from "../src/index.js";

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
function abortableSleep(ms: number, signal: AbortSignal): Promise<void> {
return new Promise((resolve, reject) => {
if (signal.aborted) {
reject(signal.reason);
return;
}

const timeoutId = setTimeout(() => {
resolve();
}, ms);

signal.addEventListener(
"abort",
() => {
clearTimeout(timeoutId);
reject(signal.reason);
},
{ once: true }
);
});
}

async function main() {
const budget = createDeadlineBudget({ timeoutMs: 500 });

const result = await budget.run("basic-operation", { timeoutMs: 100 }, async () => {
await sleep(50);
return "Operation completed successfully";
});
const result = await budget.run(
"basic-operation",
{ timeoutMs: 100 },
async (signal) => {
await abortableSleep(50, signal);
return "Operation completed successfully";
}
);

console.log(result);
console.log("Remaining time:", budget.remainingMs(), "ms");
Expand Down
8 changes: 6 additions & 2 deletions examples/expired-deadline.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { createDeadlineBudget } from "../src/index";
import { createDeadlineBudget } from "../src/index.js";

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

async function main() {
const budget = createDeadlineBudget({ timeoutMs: 50 });
Expand Down
28 changes: 24 additions & 4 deletions examples/fallback.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,26 @@
import { createDeadlineBudget } from "../src/index";
import { createDeadlineBudget } from "../src/index.js";

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
function abortableSleep(ms: number, signal: AbortSignal): Promise<void> {
return new Promise((resolve, reject) => {
if (signal.aborted) {
reject(signal.reason);
return;
}

const timeoutId = setTimeout(() => {
resolve();
}, ms);

signal.addEventListener(
"abort",
() => {
clearTimeout(timeoutId);
reject(signal.reason);
},
{ once: true }
);
});
}

async function main() {
const budget = createDeadlineBudget({ timeoutMs: 500 });
Expand All @@ -11,8 +31,8 @@ async function main() {
timeoutMs: 100,
fallback: "Fallback result from cache",
},
async () => {
await sleep(300);
async (signal) => {
await abortableSleep(300, signal);
return "Real API result";
}
);
Expand Down
55 changes: 41 additions & 14 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,48 +7,75 @@ export type RunOptions<T> = {
fallback?: T;
};

export type DeadlineExceededReason = "budget already expired" | "step timeout";

export class DeadlineExceededError extends Error {
public readonly operationName: string;
public readonly deadlineReason: DeadlineExceededReason;

constructor(operationName: string, deadlineReason: DeadlineExceededReason) {
super(`[deadlinekit] "${operationName}" exceeded deadline: ${deadlineReason}`);

this.name = "DeadlineExceededError";
this.operationName = operationName;
this.deadlineReason = deadlineReason;

Object.setPrototypeOf(this, DeadlineExceededError.prototype);
}
}

export function isAbortError(error: unknown): boolean {
if (error instanceof DeadlineExceededError) {
return true;
}

if (error instanceof Error && error.name === "AbortError") {
return true;
}

return false;
}

export function createDeadlineBudget(options: DeadlineBudgetOptions) {
const startedAt = Date.now();
const deadlineAt = startedAt + options.timeoutMs;

function remainingMs() {
function remainingMs(): number {
return Math.max(0, deadlineAt - Date.now());
}

async function run<T>(
name: string,
runOptions: RunOptions<T>,
operation: () => Promise<T>
operation: (signal: AbortSignal) => Promise<T>
): Promise<T> {
const availableMs = remainingMs();
const timeoutMs = Math.min(runOptions.timeoutMs ?? availableMs, availableMs);

if (timeoutMs <= 0) {
if (availableMs <= 0) {
if ("fallback" in runOptions) {
return runOptions.fallback as T;
}

throw new Error(`Deadline exceeded before running operation: ${name}`);
throw new DeadlineExceededError(name, "budget already expired");
}

let timeoutId: ReturnType<typeof setTimeout>;
const timeoutMs = Math.min(runOptions.timeoutMs ?? availableMs, availableMs);
const controller = new AbortController();

const timeoutPromise = new Promise<T>((_, reject) => {
timeoutId = setTimeout(() => {
reject(new Error(`Operation timed out: ${name}`));
}, timeoutMs);
});
const timeoutId = setTimeout(() => {
controller.abort(new DeadlineExceededError(name, "step timeout"));
}, timeoutMs);

try {
return await Promise.race([operation(), timeoutPromise]);
return await operation(controller.signal);
} catch (error) {
if ("fallback" in runOptions) {
if ("fallback" in runOptions && isAbortError(error)) {
return runOptions.fallback as T;
}

throw error;
} finally {
clearTimeout(timeoutId!);
clearTimeout(timeoutId);
}
}

Expand Down
83 changes: 73 additions & 10 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,34 @@
import { describe, expect, it } from "vitest";
import { createDeadlineBudget } from "../src/index";
import {
createDeadlineBudget,
DeadlineExceededError,
isAbortError,
} from "../src/index.js";

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

function abortableSleep(ms: number, signal: AbortSignal): Promise<void> {
return new Promise((resolve, reject) => {
if (signal.aborted) {
reject(signal.reason);
return;
}

const timeoutId = setTimeout(() => {
resolve();
}, ms);

signal.addEventListener(
"abort",
() => {
clearTimeout(timeoutId);
reject(signal.reason);
},
{ once: true }
);
});
}

describe("createDeadlineBudget", () => {
it("returns a positive remaining time after creation", () => {
const budget = createDeadlineBudget({ timeoutMs: 100 });
Expand All @@ -29,24 +55,44 @@ describe("createDeadlineBudget", () => {
const result = await budget.run(
"fast-operation",
{ timeoutMs: 50 },
async () => {
await sleep(10);
async (signal) => {
await abortableSleep(10, signal);
return "success";
}
);

expect(result).toBe("success");
});

it("throws when the operation exceeds timeout", async () => {
it("passes an AbortSignal to the operation", async () => {
const budget = createDeadlineBudget({ timeoutMs: 100 });

const result = await budget.run(
"signal-operation",
{ timeoutMs: 50 },
async (signal) => {
expect(signal).toBeInstanceOf(AbortSignal);
expect(signal.aborted).toBe(false);
return "success";
}
);

expect(result).toBe("success");
});

it("throws DeadlineExceededError when the operation exceeds timeout", async () => {
const budget = createDeadlineBudget({ timeoutMs: 100 });

await expect(
budget.run("slow-operation", { timeoutMs: 10 }, async () => {
await sleep(50);
budget.run("slow-operation", { timeoutMs: 10 }, async (signal) => {
await abortableSleep(50, signal);
return "done";
})
).rejects.toThrow("Operation timed out: slow-operation");
).rejects.toMatchObject({
name: "DeadlineExceededError",
operationName: "slow-operation",
deadlineReason: "step timeout",
});
});

it("returns fallback when operation times out and fallback is provided", async () => {
Expand All @@ -58,8 +104,8 @@ describe("createDeadlineBudget", () => {
timeoutMs: 10,
fallback: "fallback-value",
},
async () => {
await sleep(50);
async (signal) => {
await abortableSleep(50, signal);
return "real-value";
}
);
Expand All @@ -76,7 +122,11 @@ describe("createDeadlineBudget", () => {
budget.run("expired-operation", {}, async () => {
return "should-not-run";
})
).rejects.toThrow("Deadline exceeded before running operation: expired-operation");
).rejects.toMatchObject({
name: "DeadlineExceededError",
operationName: "expired-operation",
deadlineReason: "budget already expired",
});
});

it("returns fallback when total deadline is already exceeded", async () => {
Expand All @@ -96,4 +146,17 @@ describe("createDeadlineBudget", () => {

expect(result).toBe("expired-fallback");
});

it("identifies DeadlineExceededError as an abort error", () => {
const error = new DeadlineExceededError("test-operation", "step timeout");

expect(isAbortError(error)).toBe(true);
});

it("identifies AbortError as an abort error", () => {
const error = new Error("The operation was aborted");
error.name = "AbortError";

expect(isAbortError(error)).toBe(true);
});
});
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022"],
"types": ["node"],
"rootDir": "src",
"outDir": "dist",
"declaration": true,
Expand Down
Loading