UNPKG

@convex-dev/workpool

Version:

A Convex component for managing async work.

79 lines 2.22 kB
import { v } from "convex/values"; import { logLevel } from "./logging.js"; export const fnType = v.union(v.literal("action"), v.literal("mutation"), v.literal("query")); export const DEFAULT_MAX_PARALLELISM = 10; const SEGMENT_MS = 100; export const SECOND = 1000; export const MINUTE = 60 * SECOND; export const HOUR = 60 * MINUTE; export const DAY = 24 * HOUR; export const YEAR = 365 * DAY; export function toSegment(ms) { return BigInt(Math.floor(ms / SEGMENT_MS)); } export function getCurrentSegment() { return toSegment(Date.now()); } export function getNextSegment() { return toSegment(Date.now()) + 1n; } export function fromSegment(segment) { return Number(segment) * SEGMENT_MS; } export const config = v.object({ maxParallelism: v.number(), logLevel, }); export const retryBehavior = v.object({ maxAttempts: v.number(), initialBackoffMs: v.number(), base: v.number(), }); // This ensures that the type satisfies the schema. const _ = {}; export const vResultValidator = v.union(v.object({ kind: v.literal("success"), returnValue: v.any(), }), v.object({ kind: v.literal("failed"), error: v.string(), }), v.object({ kind: v.literal("canceled"), })); export const onComplete = v.object({ fnHandle: v.string(), // mutation context: v.optional(v.any()), }); export const status = v.union(v.union(v.object({ state: v.literal("pending"), previousAttempts: v.number(), }), v.object({ state: v.literal("running"), previousAttempts: v.number(), }), v.object({ state: v.literal("finished"), }))); export function boundScheduledTime(ms, console) { if (ms < Date.now() - YEAR) { console.error("scheduled time is too old, defaulting to now", ms); return Date.now(); } if (ms > Date.now() + 4 * YEAR) { console.error("scheduled time is too far in the future, defaulting to 1 year from now", ms); return Date.now() + YEAR; } return ms; } /** * Returns the smaller of two bigint values. */ export function min(a, b) { return a > b ? b : a; } /** * Returns the larger of two bigint values. */ export function max(a, b) { return a < b ? b : a; } //# sourceMappingURL=shared.js.map