fix(api): address review feedback on delay normalization, JSON parsing, and lazy schemas [downstream-sync]

Fixes the five review findings from the previous commit:

- Normalize numeric-string crawl delays consistently in both getNextConcurrentJob and concurrentJobDone via shared parseCrawlDelay helper.
- Reject non-finite numbers (such as 1e400 -> Infinity) inside parseJsonString via JSON.parse reviver so robustFetch preserves strict JSON guarantees.
- Keep service/defaults.ts free of top-level runtime imports by lazily caching queueJobStore's Zod schemas on first use and keeping queueJobStore's JSDoc directly on queueJobStore.
- Remove the redundant second parse and unreachable fallback branch in scrape-worker.ts getStoredCrawlerOptions.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
This commit is contained in:
mogeryandcapy-ai[bot] committed 2026-11-26 21:49:33 +00:00
1 parent ed86a6c83e
commit afdabf1534
4 files changed
+89 -50

No files matched your search

+19 -10
View File
@@ -297,6 +297,21 @@ export async function removeCrawlConcurrencyLimitActiveJob(
await getRedisConnection().zrem(constructCrawlKey(crawl_id), id);
}
function parseCrawlDelay(rawDelay: unknown): number | undefined {
if (typeof rawDelay === "number") {
return Number.isFinite(rawDelay) ? rawDelay : undefined;
}
if (typeof rawDelay === "string") {
const trimmed = rawDelay.trim();
if (trimmed.length === 0) {
return undefined;
}
const parsed = Number(trimmed);
return Number.isFinite(parsed) ? parsed : undefined;
}
return undefined;
}
/**
* Grabs the next job from the team's concurrency limit queue. Handles crawl concurrency limits.
*
@@ -406,17 +421,11 @@ export async function getNextConcurrentJob(teamId: string): Promise<{
});
}
}
const rawDelay: unknown = sc?.crawlerOptions?.delay;
const delay =
typeof rawDelay === "number"
? rawDelay
: typeof rawDelay === "string" && rawDelay.trim().length > 0
? Number(rawDelay.trim())
: undefined;
const delay = parseCrawlDelay(sc?.crawlerOptions?.delay);
const maxCrawlConcurrency =
sc === null
? 1
: delay !== undefined && Number.isFinite(delay) && delay > 0
: delay !== undefined && delay > 0
? 1
: (sc.maxConcurrency ?? null);
@@ -520,8 +529,8 @@ export async function concurrentJobDone(job: NuQJob<ScrapeJobData>) {
);
const sc = await getCrawl(nextJob.job.data.crawl_id);
const delay = sc?.crawlerOptions?.delay;
if (typeof delay === "number") {
const delay = parseCrawlDelay(sc?.crawlerOptions?.delay);
if (delay !== undefined) {
await new Promise<void>(resolve => {
setTimeout(resolve, delay * 1000);
});
+9 -2
View File
@@ -10,10 +10,17 @@ const parsedJsonValueSchema = z.custom<StrictJsonValue>(() => true);
/**
* Parses a JSON string directly into a `StrictJsonValue` without an extra
* recursive validation walk, relying on `JSON.parse`'s output grammar.
* recursive validation walk, rejecting non-finite numbers such as `1e400`.
*/
export function parseJsonString(text: string): StrictJsonValue {
return parsedJsonValueSchema.parse(JSON.parse(text));
return parsedJsonValueSchema.parse(
JSON.parse(text, (_key, value: unknown) => {
if (typeof value === "number" && !Number.isFinite(value)) {
throw new SyntaxError("JSON numbers must be finite");
}
return value;
}),
);
}
/** Zod schema matching a plain JSON object (string keys mapped to JSON values). */
+49 -19
View File
@@ -4,7 +4,6 @@
* This file imports only module types so constructing default modules or
* describing a service never loads configuration, queues, or storage clients.
*/
import { z } from "zod";
import type { Document } from "../controllers/v2/types";
import type { JobKind } from "./hooks";
import type {
@@ -192,27 +191,49 @@ export function memoryUploads(): UploadsModule {
return { driver: () => driver };
}
let queueJobStoreSchemasPromise: Promise<{
singleUrlJobDataSchema: {
safeParse: (
value: unknown,
) =>
| { success: true; data: { mode: "single_urls"; team_id?: string } }
| { success: false };
};
singleUrlModeSchema: {
safeParse: (value: unknown) => { success: boolean };
};
storedDocumentSchema: {
safeParse: (
value: unknown,
) => { success: true; data: Document } | { success: false };
};
}> | null = null;
function getQueueJobStoreSchemas() {
queueJobStoreSchemasPromise ??= import("zod").then(({ z }) => ({
singleUrlJobDataSchema: z.object({
mode: z.literal("single_urls"),
team_id: z
.string()
.nullish()
.transform(value => value ?? undefined),
}),
singleUrlModeSchema: z.object({
mode: z.literal("single_urls"),
}),
storedDocumentSchema: z.custom<Document>(
value =>
typeof value === "object" && value !== null && !Array.isArray(value),
),
}));
return queueJobStoreSchemasPromise;
}
/**
* Default open-source job store backed by the job queue and Redis crawl state.
* Registration, terminal recording, and removal are no-ops because finished
* queue payloads stay inline; usage returns null.
*/
const singleUrlJobDataSchema = z.object({
mode: z.literal("single_urls"),
team_id: z
.string()
.nullish()
.transform(value => value ?? undefined),
});
const singleUrlModeSchema = z.object({
mode: z.literal("single_urls"),
});
const storedDocumentSchema = z.custom<Document>(
value => typeof value === "object" && value !== null && !Array.isArray(value),
);
export function queueJobStore(): JobStoreModule {
return {
storesResultsExternally(): boolean {
@@ -223,9 +244,14 @@ export function queueJobStore(): JobStoreModule {
async owner(id: string, kind: JobKind): Promise<JobOwner | null> {
if (kind === "scrape") {
const [{ scrapeQueue }, { normalizeOwnerId }] = await Promise.all([
const [
{ scrapeQueue },
{ normalizeOwnerId },
{ singleUrlJobDataSchema },
] = await Promise.all([
import("../services/worker/nuq-router.js"),
import("../lib/owner-id.js"),
getQueueJobStoreSchemas(),
]);
const job = await scrapeQueue.getJob(id);
if (!job) {
@@ -267,7 +293,11 @@ export function queueJobStore(): JobStoreModule {
if (kind !== "scrape") {
return null;
}
const { scrapeQueue } = await import("../services/worker/nuq-router.js");
const [{ scrapeQueue }, { singleUrlModeSchema, storedDocumentSchema }] =
await Promise.all([
import("../services/worker/nuq-router.js"),
getQueueJobStoreSchemas(),
]);
const job = await scrapeQueue.getJob(id);
if (!job) {
return null;
+12 -19
View File
@@ -110,13 +110,6 @@ const storedCrawlerObjectSchema = z.custom<StoredCrawlerOptions>(
value => typeof value === "object" && value !== null && !Array.isArray(value),
);
const storedCrawlerLegacyFieldsSchema = z.looseObject({
limit: z.unknown().optional(),
maxDepth: z.unknown().optional(),
sitemapOnly: z.unknown().optional(),
ignoreSitemap: z.unknown().optional(),
});
function parseLegacyNumber(value: unknown): number | undefined {
if (typeof value === "number") {
return Number.isFinite(value) ? value : undefined;
@@ -154,22 +147,22 @@ function getStoredCrawlerOptions(sc: StoredCrawl): StoredCrawlerOptions | null {
if (!parsedObj.success) {
return null;
}
const fields = storedCrawlerLegacyFieldsSchema.safeParse(sc.crawlerOptions);
if (!fields.success) {
return parsedObj.data;
}
const normalized: StoredCrawlerOptions = { ...parsedObj.data };
if (fields.data.limit !== undefined) {
normalized.limit = parseLegacyNumber(fields.data.limit);
const rawLimit: unknown = parsedObj.data.limit;
if (rawLimit !== undefined) {
normalized.limit = parseLegacyNumber(rawLimit);
}
if (fields.data.maxDepth !== undefined) {
normalized.maxDepth = parseLegacyNumber(fields.data.maxDepth);
const rawMaxDepth: unknown = parsedObj.data.maxDepth;
if (rawMaxDepth !== undefined) {
normalized.maxDepth = parseLegacyNumber(rawMaxDepth);
}
if (fields.data.sitemapOnly !== undefined) {
normalized.sitemapOnly = parseLegacyBoolean(fields.data.sitemapOnly);
const rawSitemapOnly: unknown = parsedObj.data.sitemapOnly;
if (rawSitemapOnly !== undefined) {
normalized.sitemapOnly = parseLegacyBoolean(rawSitemapOnly);
}
if (fields.data.ignoreSitemap !== undefined) {
normalized.ignoreSitemap = parseLegacyBoolean(fields.data.ignoreSitemap);
const rawIgnoreSitemap: unknown = parsedObj.data.ignoreSitemap;
if (rawIgnoreSitemap !== undefined) {
normalized.ignoreSitemap = parseLegacyBoolean(rawIgnoreSitemap);
}
return normalized;
}