Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

feat(api): read operational jobs from Bigtable (#4651)

Gergő Móriczad3188385c71
diff --git a/apps/api/src/controllers/v1/crawl-errors.ts b/apps/api/src/controllers/v1/crawl-errors.ts
index b8ad56762..514ce92be 100644
--- a/apps/api/src/controllers/v1/crawl-errors.ts
+++ b/apps/api/src/controllers/v1/crawl-errors.ts
@@ -11,6 +11,7 @@ import { configDotenv } from "dotenv";
import { and, eq } from "drizzle-orm";
import { dbRr } from "../../db/connection";
import * as schema from "../../db/schema";
+import { getCrawlJobAccess } from "../../lib/operational-job-access";
import { logger as _logger } from "../../lib/logger";
import { deserializeTransportableError } from "../../lib/error-serde";
import { TransportableError } from "../../lib/error";
@@ -76,37 +77,24 @@ export async function crawlErrorsController(
),
});
} else if (config.USE_DB_AUTHENTICATION) {
- // Check the requests table for the crawl/batch scrape request
- let request: (typeof schema.requests.$inferSelect)[];
+ const crawlTtlHours = req.acuc?.flags?.crawlTtlHours ?? 24;
+ let access;
try {
- request = await dbRr
- .select()
- .from(schema.requests)
- .where(eq(schema.requests.id, req.params.jobId))
- .limit(1);
+ access = await getCrawlJobAccess(req.params.jobId, crawlTtlHours);
} catch (requestError) {
_logger.error("Error getting request", { error: requestError });
throw requestError;
}
- const requestData = request?.[0];
-
- if (requestData && requestData.team_id !== req.auth.team_id) {
+ if (access && access.teamId !== req.auth.team_id) {
return res.status(403).json({ success: false, error: "Forbidden" });
}
- const crawlTtlHours = req.acuc?.flags?.crawlTtlHours ?? 24;
- const crawlTtlMs = crawlTtlHours * 60 * 60 * 1000;
-
- if (
- requestData &&
- new Date().valueOf() - new Date(requestData.created_at!).valueOf() >
- crawlTtlMs
- ) {
+ if (access && access.expiresAtMs <= Date.now()) {
return res.status(404).json({ success: false, error: "Job expired" });
}
- if (!request || request.length === 0) {
+ if (!access) {
return res.status(404).json({ success: false, error: "Job not found" });
}
diff --git a/apps/api/src/controllers/v1/scrape-status.ts b/apps/api/src/controllers/v1/scrape-status.ts
index 9b7ebc211..b547b80ba 100644
--- a/apps/api/src/controllers/v1/scrape-status.ts
+++ b/apps/api/src/controllers/v1/scrape-status.ts
@@ -1,8 +1,8 @@
import { Response } from "express";
-import { supabaseGetScrapeByIdOnlyData } from "../../lib/supabase-jobs";
import { getJob } from "./crawl-status";
import { logger as _logger } from "../../lib/logger";
import { getScrapeZDR } from "../../lib/zdr-helpers";
+import { getScrapeJobAccess } from "../../lib/operational-job-access";
export async function scrapeStatusController(req: any, res: any) {
const logger = _logger.child({
@@ -22,16 +22,16 @@ export async function scrapeStatusController(req: any, res: any) {
});
}
- const job = await supabaseGetScrapeByIdOnlyData(req.params.jobId, logger);
+ const access = await getScrapeJobAccess(req.params.jobId);
- if (!job) {
+ if (!access || access.expiresAtMs <= Date.now()) {
return res.status(404).json({
success: false,
error: "Job not found.",
});
}
- if (job?.team_id !== req.auth.team_id) {
+ if (access.teamId !== req.auth.team_id) {
return res.status(403).json({
success: false,
error: "You are not allowed to access this resource.",
diff --git a/apps/api/src/controllers/v2/__tests__/agent-status.test.ts b/apps/api/src/controllers/v2/__tests__/agent-status.test.ts
index ff38e9132..2badccd9d 100644
--- a/apps/api/src/controllers/v2/__tests__/agent-status.test.ts
+++ b/apps/api/src/controllers/v2/__tests__/agent-status.test.ts
@@ -3,15 +3,16 @@ import type { Response } from "express";
import { agentStatusController } from "../agent-status";
import { agentRequestSchema } from "../types";
import type { RequestWithAuth } from "../types";
-import {
- supabaseGetAgentByIdDirect,
- supabaseGetAgentRequestByIdDirect,
-} from "../../../lib/supabase-jobs";
+import { supabaseGetAgentByIdDirect } from "../../../lib/supabase-jobs";
+import { getAgentJobAccess } from "../../../lib/operational-job-access";
import { getJobFromGCS } from "../../../lib/gcs-jobs";
vi.mock("../../../lib/supabase-jobs", () => ({
supabaseGetAgentByIdDirect: vi.fn(),
- supabaseGetAgentRequestByIdDirect: vi.fn(),
+}));
+
+vi.mock("../../../lib/operational-job-access", () => ({
+ getAgentJobAccess: vi.fn(),
}));
vi.mock("../../../lib/gcs-jobs", () => ({
@@ -35,9 +36,9 @@ describe("agentStatusController", () => {
});
it("returns model from agent options", async () => {
- (supabaseGetAgentRequestByIdDirect as Mock).mockResolvedValue({
- team_id: "team-123",
- created_at: "2025-01-01T00:00:00Z",
+ (getAgentJobAccess as Mock).mockResolvedValue({
+ teamId: "team-123",
+ expiresAtMs: Date.now() + 60_000,
});
(supabaseGetAgentByIdDirect as Mock).mockResolvedValue({
id: "job-123",
@@ -57,9 +58,9 @@ describe("agentStatusController", () => {
});
it("defaults model to spark-1-pro when missing", async () => {
- (supabaseGetAgentRequestByIdDirect as Mock).mockResolvedValue({
- team_id: "team-123",
- created_at: "2025-01-01T00:00:00Z",
+ (getAgentJobAccess as Mock).mockResolvedValue({
+ teamId: "team-123",
+ expiresAtMs: Date.now() + 60_000,
});
(supabaseGetAgentByIdDirect as Mock).mockResolvedValue({
id: "job-123",
@@ -77,9 +78,9 @@ describe("agentStatusController", () => {
);
});
it("returns effort from agent options", async () => {
- (supabaseGetAgentRequestByIdDirect as Mock).mockResolvedValue({
- team_id: "team-123",
- created_at: "2025-01-01T00:00:00Z",
+ (getAgentJobAccess as Mock).mockResolvedValue({
+ teamId: "team-123",
+ expiresAtMs: Date.now() + 60_000,
});
(supabaseGetAgentByIdDirect as Mock).mockResolvedValue({
id: "job-123",
@@ -99,9 +100,9 @@ describe("agentStatusController", () => {
});
it("leaves effort undefined when the agent options omit it", async () => {
- (supabaseGetAgentRequestByIdDirect as Mock).mockResolvedValue({
- team_id: "team-123",
- created_at: "2025-01-01T00:00:00Z",
+ (getAgentJobAccess as Mock).mockResolvedValue({
+ teamId: "team-123",
+ expiresAtMs: Date.now() + 60_000,
});
(supabaseGetAgentByIdDirect as Mock).mockResolvedValue({
id: "job-123",
@@ -136,10 +137,10 @@ describe("agentStatusController", () => {
] as const)(
"reports a spark-2 job to %s as %s",
async (origin, expectedModel) => {
- (supabaseGetAgentRequestByIdDirect as Mock).mockResolvedValue({
- team_id: "team-123",
- created_at: "2025-01-01T00:00:00Z",
- origin,
+ (getAgentJobAccess as Mock).mockResolvedValue({
+ teamId: "team-123",
+ expiresAtMs: Date.now() + 60_000,
+ clientOrigin: origin,
});
(supabaseGetAgentByIdDirect as Mock).mockResolvedValue({
id: "job-123",
@@ -159,10 +160,10 @@ describe("agentStatusController", () => {
);
it("keeps a genuine spark-1 model truthful even for old python-sdk clients", async () => {
- (supabaseGetAgentRequestByIdDirect as Mock).mockResolvedValue({
- team_id: "team-123",
- created_at: "2025-01-01T00:00:00Z",
- origin: "[email protected]",
+ (getAgentJobAccess as Mock).mockResolvedValue({
+ teamId: "team-123",
+ expiresAtMs: Date.now() + 60_000,
+ clientOrigin: "[email protected]",
});
(supabaseGetAgentByIdDirect as Mock).mockResolvedValue({
id: "job-123",
diff --git a/apps/api/src/controllers/v2/agent-cancel.ts b/apps/api/src/controllers/v2/agent-cancel.ts
index 656106cd1..272f5f423 100644
--- a/apps/api/src/controllers/v2/agent-cancel.ts
+++ b/apps/api/src/controllers/v2/agent-cancel.ts
@@ -1,20 +1,20 @@
import { Response } from "express";
import { AgentCancelResponse, RequestWithAuth } from "./types";
-import {
- supabaseGetAgentByIdDirect,
- supabaseGetAgentRequestByIdDirect,
-} from "../../lib/supabase-jobs";
+import { supabaseGetAgentByIdDirect } from "../../lib/supabase-jobs";
import { config } from "../../config";
+import { getAgentJobAccess } from "../../lib/operational-job-access";
export async function agentCancelController(
req: RequestWithAuth<{ jobId: string }, AgentCancelResponse, any>,
res: Response<AgentCancelResponse>,
) {
- const agentRequest = await supabaseGetAgentRequestByIdDirect(
- req.params.jobId,
- );
+ const access = await getAgentJobAccess(req.params.jobId);
- if (!agentRequest || agentRequest.team_id !== req.auth.team_id) {
+ if (
+ !access ||
+ access.expiresAtMs <= Date.now() ||
+ access.teamId !== req.auth.team_id
+ ) {
return res.status(404).json({
success: false,
error: "Agent job not found",
diff --git a/apps/api/src/controllers/v2/agent-skill.ts b/apps/api/src/controllers/v2/agent-skill.ts
index ae291c134..e55735c8b 100644
--- a/apps/api/src/controllers/v2/agent-skill.ts
+++ b/apps/api/src/controllers/v2/agent-skill.ts
@@ -1,17 +1,19 @@
import { Response } from "express";
import { config } from "../../config";
-import { supabaseGetAgentRequestByIdDirect } from "../../lib/supabase-jobs";
+import { getAgentJobAccess } from "../../lib/operational-job-access";
import { AgentSkillResponse, RequestWithAuth } from "./types";
export async function agentSkillController(
req: RequestWithAuth<{ jobId: string }, AgentSkillResponse, any>,
res: Response<AgentSkillResponse>,
) {
- const agentRequest = await supabaseGetAgentRequestByIdDirect(
- req.params.jobId,
- );
+ const access = await getAgentJobAccess(req.params.jobId);
- if (!agentRequest || agentRequest.team_id !== req.auth.team_id) {
+ if (
+ !access ||
+ access.expiresAtMs <= Date.now() ||
+ access.teamId !== req.auth.team_id
+ ) {
return res.status(404).json({
success: false,
error: "Agent job not found",
diff --git a/apps/api/src/controllers/v2/agent-snapshot.ts b/apps/api/src/controllers/v2/agent-snapshot.ts
index 08cb130e7..ae3f342ee 100644
--- a/apps/api/src/controllers/v2/agent-snapshot.ts
+++ b/apps/api/src/controllers/v2/agent-snapshot.ts
@@ -1,6 +1,6 @@
import { Response } from "express";
import { config } from "../../config";
-import { supabaseGetAgentRequestByIdDirect } from "../../lib/supabase-jobs";
+import { getAgentJobAccess } from "../../lib/operational-job-access";
import { AgentSnapshotResponse, RequestWithAuth } from "./types";
export async function agentSnapshotController(
@@ -11,11 +11,13 @@ export async function agentSnapshotController(
>,
res: Response<AgentSnapshotResponse>,
) {
- const agentRequest = await supabaseGetAgentRequestByIdDirect(
- req.params.jobId,
- );
+ const access = await getAgentJobAccess(req.params.jobId);
- if (!agentRequest || agentRequest.team_id !== req.auth.team_id) {
+ if (
+ !access ||
+ access.expiresAtMs <= Date.now() ||
+ access.teamId !== req.auth.team_id
+ ) {
return res.status(404).json({
success: false,
error: "Agent job not found",
diff --git a/apps/api/src/controllers/v2/agent-status.ts b/apps/api/src/controllers/v2/agent-status.ts
index 77cfb532f..3de1a3d96 100644
--- a/apps/api/src/controllers/v2/agent-status.ts
+++ b/apps/api/src/controllers/v2/agent-status.ts
@@ -7,13 +7,11 @@ import {
AgentSuggestion,
RequestWithAuth,
} from "./types";
-import {
- supabaseGetAgentByIdDirect,
- supabaseGetAgentRequestByIdDirect,
-} from "../../lib/supabase-jobs";
+import { supabaseGetAgentByIdDirect } from "../../lib/supabase-jobs";
import { logger as _logger, logger } from "../../lib/logger";
import { getJobFromGCS } from "../../lib/gcs-jobs";
import { config } from "../../config";
+import { getAgentJobAccess } from "../../lib/operational-job-access";
// python-sdk versions before 4.37.1 validate the status response's `model`
// with pydantic as Literal["spark-1-pro", "spark-1-mini"], so any other value
@@ -91,11 +89,13 @@ export async function agentStatusController(
req: RequestWithAuth<{ jobId: string }, AgentStatusResponse, any>,
res: Response<AgentStatusResponse>,
) {
- const agentRequest = await supabaseGetAgentRequestByIdDirect(
- req.params.jobId,
- );
+ const access = await getAgentJobAccess(req.params.jobId);
- if (!agentRequest || agentRequest.team_id !== req.auth.team_id) {
+ if (
+ !access ||
+ access.expiresAtMs <= Date.now() ||
+ access.teamId !== req.auth.team_id
+ ) {
return res.status(404).json({
success: false,
error: "Agent job not found",
@@ -165,7 +165,7 @@ export async function agentStatusController(
if (
model !== "spark-1-pro" &&
model !== "spark-1-mini" &&
- isIncompatiblePythonSdkOrigin(agentRequest.origin)
+ isIncompatiblePythonSdkOrigin(access.clientOrigin)
) {
model = "spark-1-pro";
}
@@ -206,10 +206,7 @@ export async function agentStatusController(
suggestions,
pendingApproval,
exchange,
- expiresAt: new Date(
- new Date(agent?.created_at ?? agentRequest.created_at).getTime() +
- 1000 * 60 * 60 * 24,
- ).toISOString(),
+ expiresAt: new Date(access.expiresAtMs).toISOString(),
creditsUsed: agent?.credits_cost,
});
}
diff --git a/apps/api/src/controllers/v2/agent-trace.ts b/apps/api/src/controllers/v2/agent-trace.ts
index 5fd7044f2..7eb836f6a 100644
--- a/apps/api/src/controllers/v2/agent-trace.ts
+++ b/apps/api/src/controllers/v2/agent-trace.ts
@@ -1,7 +1,7 @@
import { Response } from "express";
import { config } from "../../config";
import { listActiveBrowserSessionsForRequest } from "../../lib/browser-sessions";
-import { supabaseGetAgentRequestByIdDirect } from "../../lib/supabase-jobs";
+import { getAgentJobAccess } from "../../lib/operational-job-access";
import { AgentTraceResponse, RequestWithAuth } from "./types";
const AGENT_BROWSER_VIEWPORT = { width: 1280, height: 720 } as const;
@@ -10,11 +10,13 @@ export async function agentTraceController(
req: RequestWithAuth<{ jobId: string }, AgentTraceResponse, any>,
res: Response<AgentTraceResponse>,
) {
- const agentRequest = await supabaseGetAgentRequestByIdDirect(
- req.params.jobId,
- );
+ const access = await getAgentJobAccess(req.params.jobId);
- if (!agentRequest || agentRequest.team_id !== req.auth.team_id) {
+ if (
+ !access ||
+ access.expiresAtMs <= Date.now() ||
+ access.teamId !== req.auth.team_id
+ ) {
return res.status(404).json({
success: false,
error: "Agent job not found",
diff --git a/apps/api/src/controllers/v2/crawl-errors.ts b/apps/api/src/controllers/v2/crawl-errors.ts
index b8ad56762..514ce92be 100644
--- a/apps/api/src/controllers/v2/crawl-errors.ts
+++ b/apps/api/src/controllers/v2/crawl-errors.ts
@@ -11,6 +11,7 @@ import { configDotenv } from "dotenv";
import { and, eq } from "drizzle-orm";
import { dbRr } from "../../db/connection";
import * as schema from "../../db/schema";
+import { getCrawlJobAccess } from "../../lib/operational-job-access";
import { logger as _logger } from "../../lib/logger";
import { deserializeTransportableError } from "../../lib/error-serde";
import { TransportableError } from "../../lib/error";
@@ -76,37 +77,24 @@ export async function crawlErrorsController(
),
});
} else if (config.USE_DB_AUTHENTICATION) {
- // Check the requests table for the crawl/batch scrape request
- let request: (typeof schema.requests.$inferSelect)[];
+ const crawlTtlHours = req.acuc?.flags?.crawlTtlHours ?? 24;
+ let access;
try {
- request = await dbRr
- .select()
- .from(schema.requests)
- .where(eq(schema.requests.id, req.params.jobId))
- .limit(1);
+ access = await getCrawlJobAccess(req.params.jobId, crawlTtlHours);
} catch (requestError) {
_logger.error("Error getting request", { error: requestError });
throw requestError;
}
- const requestData = request?.[0];
-
- if (requestData && requestData.team_id !== req.auth.team_id) {
+ if (access && access.teamId !== req.auth.team_id) {
return res.status(403).json({ success: false, error: "Forbidden" });
}
- const crawlTtlHours = req.acuc?.flags?.crawlTtlHours ?? 24;
- const crawlTtlMs = crawlTtlHours * 60 * 60 * 1000;
-
- if (
- requestData &&
- new Date().valueOf() - new Date(requestData.created_at!).valueOf() >
- crawlTtlMs
- ) {
+ if (access && access.expiresAtMs <= Date.now()) {
return res.status(404).json({ success: false, error: "Job expired" });
}
- if (!request || request.length === 0) {
+ if (!access) {
return res.status(404).json({ success: false, error: "Job not found" });
}
diff --git a/apps/api/src/controllers/v2/extract-status.ts b/apps/api/src/controllers/v2/extract-status.ts
index d13714104..7fa349076 100644
--- a/apps/api/src/controllers/v2/extract-status.ts
+++ b/apps/api/src/controllers/v2/extract-status.ts
@@ -9,10 +9,10 @@ import {
import {
supabaseGetAgentByIdDirect,
supabaseGetExtractByIdDirect,
- supabaseGetExtractRequestByIdDirect,
} from "../../lib/supabase-jobs";
import { logger as _logger } from "../../lib/logger";
import { getJobFromGCS } from "../../lib/gcs-jobs";
+import { getExtractJobAccess } from "../../lib/operational-job-access";
async function getExtractData(id: string): Promise<any> {
// Try GCS first if configured
@@ -34,18 +34,22 @@ export async function extractStatusController(
req: RequestWithAuth<{ jobId: string }, any, any>,
res: Response,
) {
- const extractRequest = config.USE_DB_AUTHENTICATION
- ? await supabaseGetExtractRequestByIdDirect(req.params.jobId)
+ const access = config.USE_DB_AUTHENTICATION
+ ? await getExtractJobAccess(req.params.jobId)
: null;
if (config.USE_DB_AUTHENTICATION) {
- if (!extractRequest || extractRequest.team_id !== req.auth.team_id) {
+ if (
+ !access ||
+ access.expiresAtMs <= Date.now() ||
+ access.teamId !== req.auth.team_id
+ ) {
return res.status(404).json({
success: false,
error: "Extract job not found",
});
}
- if (extractRequest.kind === "agent") {
+ if (access.kind === "agent") {
const agent = await supabaseGetAgentByIdDirect(req.params.jobId);
let data: any = undefined;
@@ -62,10 +66,7 @@ export async function extractStatusController(
: "failed",
error: agent?.error || undefined,
data,
- expiresAt: new Date(
- new Date(agent?.created_at ?? extractRequest.created_at).getTime() +
- 1000 * 60 * 60 * 24,
- ).toISOString(),
+ expiresAt: new Date(access.expiresAtMs).toISOString(),
creditsUsed: agent?.credits_cost,
});
}
@@ -90,9 +91,7 @@ export async function extractStatusController(
data,
status: dbExtract.is_successful ? "completed" : "failed",
error: dbExtract.error || undefined,
- expiresAt: new Date(
- new Date(dbExtract.created_at).getTime() + 1000 * 60 * 60 * 24,
- ).toISOString(),
+ expiresAt: new Date(access!.expiresAtMs).toISOString(),
});
}
}
@@ -102,9 +101,7 @@ export async function extractStatusController(
success: true,
data: [],
status: "processing",
- expiresAt: new Date(
- new Date(extractRequest.created_at).getTime() + 1000 * 60 * 60 * 24,
- ).toISOString(),
+ expiresAt: new Date(access!.expiresAtMs).toISOString(),
});
}
diff --git a/apps/api/src/controllers/v2/feedback/feedback-store.ts b/apps/api/src/controllers/v2/feedback/feedback-store.ts
index 67ef99d5e..5f113ddff 100644
--- a/apps/api/src/controllers/v2/feedback/feedback-store.ts
+++ b/apps/api/src/controllers/v2/feedback/feedback-store.ts
@@ -1,6 +1,12 @@
import { and, eq } from "drizzle-orm";
+import { config } from "../../../config";
import { db, dbRr } from "../../../db/connection";
import * as schema from "../../../db/schema";
+import {
+ readFeedbackJob,
+ type RefundClass,
+} from "../../../lib/feedback-job-store";
+import { logger } from "../../../lib/logger";
import { EndpointFeedbackEndpoint } from "../types";
import {
FeedbackJobRow,
@@ -39,6 +45,43 @@ export async function lookupFeedbackJob(
jobId: string,
dbTeamId: string,
): Promise<FeedbackJobRow | null> {
+ try {
+ const job = await readFeedbackJob(jobId);
+ if (job) {
+ const storedEndpoint = endpointForRefundClass(job.refundClass);
+ if (job.teamId !== dbTeamId || storedEndpoint !== endpoint) return null;
+
+ const feedbackWindowSec =
+ endpoint === "search"
+ ? config.SEARCH_FEEDBACK_MAX_AGE_SEC
+ : config.FEEDBACK_MAX_AGE_SEC;
+ return {
+ endpoint,
+ id: jobId,
+ request_id: job.requestId,
+ team_id: job.teamId,
+ credits_cost: job.creditsBilled,
+ created_at: new Date(
+ job.feedbackDeadlineMs - feedbackWindowSec * 1000,
+ ).toISOString(),
+ is_successful: job.succeeded,
+ options: null,
+ feedback_deadline_ms: job.feedbackDeadlineMs,
+ refund_class: job.refundClass,
+ zero_data_retention: job.zeroDataRetention,
+ };
+ }
+ } catch (error) {
+ logger.warn(
+ "Bigtable feedback job read failed; falling back to PostgreSQL",
+ {
+ error,
+ jobId,
+ endpoint,
+ },
+ );
+ }
+
const table = JOB_TABLES[endpoint] as any;
const [row] = await dbRr
.select({
@@ -68,6 +111,19 @@ export async function lookupFeedbackJob(
};
}
+function endpointForRefundClass(
+ refundClass: RefundClass,
+): EndpointFeedbackEndpoint {
+ switch (refundClass) {
+ case "search":
+ case "map":
+ case "parse":
+ return refundClass;
+ default:
+ return "scrape";
+ }
+}
+
export async function insertFeedback(params: {
feedbackId: string;
options: FeedbackRecordOptions;
diff --git a/apps/api/src/controllers/v2/feedback/internal-types.ts b/apps/api/src/controllers/v2/feedback/internal-types.ts
index e75bd95e0..c2e9e1446 100644
--- a/apps/api/src/controllers/v2/feedback/internal-types.ts
+++ b/apps/api/src/controllers/v2/feedback/internal-types.ts
@@ -5,6 +5,7 @@ import {
EndpointFeedbackResponse,
SearchFeedbackErrorCode,
} from "../types";
+import type { RefundClass } from "../../../lib/feedback-job-store";
export type FeedbackRating = "good" | "partial" | "bad";
@@ -32,6 +33,9 @@ export type FeedbackJobRow = {
created_at: string;
is_successful: boolean | null;
options: unknown;
+ feedback_deadline_ms?: number;
+ refund_class?: RefundClass;
+ zero_data_retention?: boolean;
};
export type FeedbackRecordOptions = {
diff --git a/apps/api/src/controllers/v2/feedback/record.ts b/apps/api/src/controllers/v2/feedback/record.ts
index e5e125d70..1334dab2c 100644
--- a/apps/api/src/controllers/v2/feedback/record.ts
+++ b/apps/api/src/controllers/v2/feedback/record.ts
@@ -162,6 +162,17 @@ function validateJob(
);
}
+ if (job.feedback_deadline_ms !== undefined) {
+ if (job.feedback_deadline_ms > Date.now()) return null;
+ const maxAgeSec = options.maxAgeSec ?? config.FEEDBACK_MAX_AGE_SEC;
+ return feedbackFailure(
+ 409,
+ "FEEDBACK_WINDOW_EXPIRED",
+ options.windowExpiredMessage ??
+ `Feedback must be submitted within ${maxAgeSec} seconds of the job.`,
+ );
+ }
+
const maxAgeSec = options.maxAgeSec ?? config.FEEDBACK_MAX_AGE_SEC;
const createdAtMs = new Date(job.created_at).getTime();
if (Number.isNaN(createdAtMs)) {
diff --git a/apps/api/src/controllers/v2/feedback/refund-policy.test.ts b/apps/api/src/controllers/v2/feedback/refund-policy.test.ts
new file mode 100644
index 000000000..9d7769aca
--- /dev/null
+++ b/apps/api/src/controllers/v2/feedback/refund-policy.test.ts
@@ -0,0 +1,39 @@
+import { computeRefundPolicy } from "./refund-policy";
+import type { FeedbackJobRow } from "./internal-types";
+
+vi.mock("../../../config", () => ({
+ config: { FEEDBACK_REFUND_ENABLED: true },
+}));
+
+function job(refundClass: FeedbackJobRow["refund_class"]): FeedbackJobRow {
+ return {
+ endpoint: "scrape",
+ id: "job-id",
+ request_id: "request-id",
+ team_id: "team-id",
+ credits_cost: 12,
+ created_at: new Date().toISOString(),
+ is_successful: true,
+ options: null,
+ refund_class: refundClass,
+ };
+}
+
+describe("precomputed feedback refund classes", () => {
+ it("uses the stored PDF policy without scrape options", () => {
+ expect(computeRefundPolicy(job("scrape_pdf"), "bad")).toMatchObject({
+ desiredRefund: 3,
+ policy: {
+ matchedReason: "scrape_pdf_feedback",
+ maxCredits: 10,
+ },
+ });
+ });
+
+ it("uses the stored basic scrape policy without scrape options", () => {
+ expect(computeRefundPolicy(job("scrape_basic"), "partial")).toMatchObject({
+ desiredRefund: 1,
+ policy: { matchedReason: "scrape_feedback" },
+ });
+ });
+});
diff --git a/apps/api/src/controllers/v2/feedback/refund-policy.ts b/apps/api/src/controllers/v2/feedback/refund-policy.ts
index cf0e557f4..ae94d0758 100644
--- a/apps/api/src/controllers/v2/feedback/refund-policy.ts
+++ b/apps/api/src/controllers/v2/feedback/refund-policy.ts
@@ -4,6 +4,7 @@ import {
FeedbackRating,
RefundPolicySnapshot,
} from "./internal-types";
+import type { RefundClass } from "../../../lib/feedback-job-store";
type RefundablePolicy =
| {
@@ -61,8 +62,8 @@ function none(
};
}
-function policyFor(job: FeedbackJobRow): RefundablePolicy {
- switch (job.endpoint) {
+function policyForRefundClass(refundClass: RefundClass): RefundablePolicy {
+ switch (refundClass) {
case "search":
return {
mode: "flat",
@@ -85,33 +86,27 @@ function policyFor(job: FeedbackJobRow): RefundablePolicy {
percent: 0.25,
maxCredits: 10,
};
- case "scrape":
- if (optionListIncludes(job.options, "parsers", "pdf")) {
- return {
- mode: "percentage_with_cap",
- reason: "scrape_pdf_feedback",
- ratings: ["partial", "bad"],
- percent: 0.25,
- maxCredits: 10,
- };
- }
-
- if (
- optionListIncludes(job.options, "formats", "json") ||
- optionListIncludes(job.options, "formats", "screenshot") ||
- hasActions(job.options)
- ) {
- return {
- mode: "percentage_with_cap",
- reason: optionListIncludes(job.options, "formats", "json")
+ case "scrape_pdf":
+ return {
+ mode: "percentage_with_cap",
+ reason: "scrape_pdf_feedback",
+ ratings: ["partial", "bad"],
+ percent: 0.25,
+ maxCredits: 10,
+ };
+ case "scrape_json":
+ case "scrape_addon":
+ return {
+ mode: "percentage_with_cap",
+ reason:
+ refundClass === "scrape_json"
? "scrape_json_feedback"
: "scrape_addon_feedback",
- ratings: ["partial", "bad"],
- percent: 0.25,
- maxCredits: 5,
- };
- }
-
+ ratings: ["partial", "bad"],
+ percent: 0.25,
+ maxCredits: 5,
+ };
+ case "scrape_basic":
return {
mode: "flat",
reason: "scrape_feedback",
@@ -121,6 +116,24 @@ function policyFor(job: FeedbackJobRow): RefundablePolicy {
}
}
+function policyFor(job: FeedbackJobRow): RefundablePolicy {
+ if (job.refund_class) return policyForRefundClass(job.refund_class);
+ if (job.endpoint !== "scrape") return policyForRefundClass(job.endpoint);
+ if (optionListIncludes(job.options, "parsers", "pdf")) {
+ return policyForRefundClass("scrape_pdf");
+ }
+ if (optionListIncludes(job.options, "formats", "json")) {
+ return policyForRefundClass("scrape_json");
+ }
+ if (
+ optionListIncludes(job.options, "formats", "screenshot") ||
+ hasActions(job.options)
+ ) {
+ return policyForRefundClass("scrape_addon");
+ }
+ return policyForRefundClass("scrape_basic");
+}
+
export function computeRefundPolicy(
job: FeedbackJobRow,
rating: FeedbackRating,
diff --git a/apps/api/src/controllers/v2/feedback/zdr-persistence.test.ts b/apps/api/src/controllers/v2/feedback/zdr-persistence.test.ts
index 6f7d8255e..d86d97b5c 100644
--- a/apps/api/src/controllers/v2/feedback/zdr-persistence.test.ts
+++ b/apps/api/src/controllers/v2/feedback/zdr-persistence.test.ts
@@ -176,4 +176,16 @@ describe("feedback ZDR persistence guards", () => {
),
).toBe(false);
});
+
+ it("does not let an override bypass a stored ZDR decision", () => {
+ expect(
+ shouldSkipPersistenceForJobZdr(
+ {
+ ...job("scrape", null),
+ zero_data_retention: true,
+ },
+ options("scrape", { skipZdrPersistence: false }),
+ ),
+ ).toBe(true);
+ });
});
diff --git a/apps/api/src/controllers/v2/feedback/zdr-persistence.ts b/apps/api/src/controllers/v2/feedback/zdr-persistence.ts
index 47e6ddfd5..33b5a1b34 100644
--- a/apps/api/src/controllers/v2/feedback/zdr-persistence.ts
+++ b/apps/api/src/controllers/v2/feedback/zdr-persistence.ts
@@ -38,6 +38,9 @@ export function shouldSkipPersistenceForJobZdr(
job: FeedbackJobRow,
options: FeedbackRecordOptions,
): boolean {
+ if (job.zero_data_retention !== undefined) {
+ return job.zero_data_retention;
+ }
if (options.skipZdrPersistence === false) return false;
if (job.endpoint === "search") {
diff --git a/apps/api/src/controllers/v2/scrape-status.ts b/apps/api/src/controllers/v2/scrape-status.ts
index 758f354ef..09f66647f 100644
--- a/apps/api/src/controllers/v2/scrape-status.ts
+++ b/apps/api/src/controllers/v2/scrape-status.ts
@@ -1,7 +1,7 @@
-import { supabaseGetScrapeByIdOnlyData } from "../../lib/supabase-jobs";
import { getJob } from "./crawl-status";
import { logger as _logger } from "../../lib/logger";
import { getScrapeZDR } from "../../lib/zdr-helpers";
+import { getScrapeJobAccess } from "../../lib/operational-job-access";
export async function scrapeStatusController(req: any, res: any) {
const uuidReg =
@@ -30,16 +30,16 @@ export async function scrapeStatusController(req: any, res: any) {
});
}
- const job = await supabaseGetScrapeByIdOnlyData(req.params.jobId, logger);
+ const access = await getScrapeJobAccess(req.params.jobId);
- if (!job) {
+ if (!access || access.expiresAtMs <= Date.now()) {
return res.status(404).json({
success: false,
error: "Job not found.",
});
}
- if (job?.team_id !== req.auth.team_id) {
+ if (access.teamId !== req.auth.team_id) {
return res.status(403).json({
success: false,
error: "You are not allowed to access this resource.",
diff --git a/apps/api/src/lib/feedback-job-store.ts b/apps/api/src/lib/feedback-job-store.ts
index 756287b05..a859ab2b0 100644
--- a/apps/api/src/lib/feedback-job-store.ts
+++ b/apps/api/src/lib/feedback-job-store.ts
@@ -18,6 +18,86 @@ export type RefundClass =
| "scrape_json"
| "scrape_addon";
+const REFUND_CLASSES: readonly RefundClass[] = [
+ "search",
+ "map",
+ "parse",
+ "scrape_basic",
+ "scrape_pdf",
+ "scrape_json",
+ "scrape_addon",
+];
+
+export type FeedbackJob = {
+ requestId: string;
+ teamId: string;
+ refundClass: RefundClass;
+ feedbackDeadlineMs: number;
+ succeeded: boolean;
+ creditsBilled: number;
+ zeroDataRetention: boolean;
+};
+
+function parseFeedbackJob(value: Buffer | string): FeedbackJob {
+ const parsed: unknown = JSON.parse(value.toString());
+ const row = parsed as Record<string, unknown>;
+ if (
+ !parsed ||
+ typeof parsed !== "object" ||
+ row.version !== 1 ||
+ typeof row.requestId !== "string" ||
+ typeof row.teamId !== "string" ||
+ typeof row.refundClass !== "string" ||
+ !REFUND_CLASSES.includes(row.refundClass as RefundClass) ||
+ typeof row.feedbackDeadlineMs !== "number" ||
+ !Number.isFinite(row.feedbackDeadlineMs) ||
+ typeof row.succeeded !== "boolean" ||
+ typeof row.creditsBilled !== "number" ||
+ !Number.isFinite(row.creditsBilled) ||
+ typeof row.zeroDataRetention !== "boolean"
+ ) {
+ throw new Error("Invalid Bigtable feedback job row");
+ }
+ return parsed as FeedbackJob;
+}
+
+export async function readFeedbackJob(
+ jobId: string,
+): Promise<FeedbackJob | null> {
+ const tableId = config.BIGTABLE_FEEDBACK_JOBS_TABLE;
+ if (!tableId) return null;
+
+ return withSpan("bigtable.feedback_job.read", async span => {
+ setSpanAttributes(span, {
+ "db.system": "bigtable",
+ "bigtable.table": tableId,
+ "bigtable.operation": "getRows",
+ });
+ const table = await getBigtableTable(tableId);
+ const [rows] = await table.getRows({
+ keys: [saltedUuidV7RowKey(jobId)],
+ filter: [{ column: { name: QUALIFIER, cellLimit: 1 } }],
+ });
+ const cells = rows[0]?.data?.[FAMILY]?.[QUALIFIER];
+ const cell = Array.isArray(cells) ? cells[0] : undefined;
+ if (cell?.value == null) {
+ setSpanAttributes(span, { "bigtable.read.outcome": "not_found" });
+ return null;
+ }
+
+ const job = parseFeedbackJob(cell.value);
+ if (job.feedbackDeadlineMs <= Date.now()) {
+ setSpanAttributes(span, { "bigtable.read.outcome": "expired" });
+ return job;
+ }
+ setSpanAttributes(span, {
+ "bigtable.read.outcome": "found",
+ "feedback.refund_class": job.refundClass,
+ });
+ return job;
+ });
+}
+
function scrapeRefundClass(options: ScrapeOptions): RefundClass {
if (
options.parsers?.some(
diff --git a/apps/api/src/lib/job-access-store.ts b/apps/api/src/lib/job-access-store.ts
index b514b2bb7..0c5275c46 100644
--- a/apps/api/src/lib/job-access-store.ts
+++ b/apps/api/src/lib/job-access-store.ts
@@ -18,10 +18,73 @@ export const API_JOB_KINDS = [
export type ApiJobKind = (typeof API_JOB_KINDS)[number];
+export type ApiJobAccess = {
+ teamId: string;
+ kind: ApiJobKind;
+ expiresAtMs: number;
+ clientOrigin?: string;
+};
+
export function isApiJobKind(kind: string): kind is ApiJobKind {
return API_JOB_KINDS.includes(kind as ApiJobKind);
}
+function parseApiJobAccess(value: Buffer | string): ApiJobAccess {
+ const parsed: unknown = JSON.parse(value.toString());
+ const row = parsed as Record<string, unknown>;
+ if (
+ !parsed ||
+ typeof parsed !== "object" ||
+ row.version !== 1 ||
+ typeof row.teamId !== "string" ||
+ typeof row.kind !== "string" ||
+ !isApiJobKind(row.kind) ||
+ typeof row.expiresAtMs !== "number" ||
+ !Number.isFinite(row.expiresAtMs) ||
+ (row.clientOrigin !== undefined && typeof row.clientOrigin !== "string")
+ ) {
+ throw new Error("Invalid Bigtable job access row");
+ }
+ return parsed as ApiJobAccess;
+}
+
+export async function readApiJobAccess(
+ id: string,
+): Promise<ApiJobAccess | null> {
+ const tableId = config.BIGTABLE_JOB_ACCESS_TABLE;
+ if (!tableId) return null;
+
+ return withSpan("bigtable.job_access.read", async span => {
+ setSpanAttributes(span, {
+ "db.system": "bigtable",
+ "bigtable.table": tableId,
+ "bigtable.operation": "getRows",
+ });
+ const table = await getBigtableTable(tableId);
+ const [rows] = await table.getRows({
+ keys: [saltedUuidV7RowKey(id)],
+ filter: [{ column: { name: QUALIFIER, cellLimit: 1 } }],
+ });
+ const cells = rows[0]?.data?.[FAMILY]?.[QUALIFIER];
+ const cell = Array.isArray(cells) ? cells[0] : undefined;
+ if (cell?.value == null) {
+ setSpanAttributes(span, { "bigtable.read.outcome": "not_found" });
+ return null;
+ }
+
+ const access = parseApiJobAccess(cell.value);
+ if (access.expiresAtMs <= Date.now()) {
+ setSpanAttributes(span, { "bigtable.read.outcome": "expired" });
+ return access;
+ }
+ setSpanAttributes(span, {
+ "bigtable.read.outcome": "found",
+ "job_access.kind": access.kind,
+ });
+ return access;
+ });
+}
+
export async function writeApiJobAccess(params: {
id: string;
teamId: string;
diff --git a/apps/api/src/lib/job-operational-stores.test.ts b/apps/api/src/lib/job-operational-stores.test.ts
index 92b5a8a74..51d670ff5 100644
--- a/apps/api/src/lib/job-operational-stores.test.ts
+++ b/apps/api/src/lib/job-operational-stores.test.ts
@@ -1,49 +1,58 @@
import { vi } from "vitest";
import type { MutationConstructorObj } from "@google-cloud/bigtable";
-const { mutate, getBigtableTable, mutableConfig, withSpan, spans } = vi.hoisted(
- () => {
- const spans: { name: string; options: any }[] = [];
- return {
- mutate: vi.fn<(mutations: MutationConstructorObj[]) => Promise<void>>(
- async () => {},
- ),
- getBigtableTable: vi.fn(),
- mutableConfig: {
- BIGTABLE_JOB_ACCESS_TABLE: "job-access",
- BIGTABLE_FEEDBACK_JOBS_TABLE: "feedback-jobs",
- SEARCH_FEEDBACK_MAX_AGE_SEC: 120,
- FEEDBACK_MAX_AGE_SEC: 180,
- } as {
- BIGTABLE_JOB_ACCESS_TABLE?: string;
- BIGTABLE_FEEDBACK_JOBS_TABLE?: string;
- SEARCH_FEEDBACK_MAX_AGE_SEC: number;
- FEEDBACK_MAX_AGE_SEC: number;
+const {
+ mutate,
+ getRows,
+ getBigtableTable,
+ mutableConfig,
+ setSpanAttributes,
+ withSpan,
+ spans,
+} = vi.hoisted(() => {
+ const spans: { name: string; options: any }[] = [];
+ return {
+ mutate: vi.fn<(mutations: MutationConstructorObj[]) => Promise<void>>(
+ async () => {},
+ ),
+ getRows: vi.fn(async () => [[]]),
+ setSpanAttributes: vi.fn(),
+ getBigtableTable: vi.fn(),
+ mutableConfig: {
+ BIGTABLE_JOB_ACCESS_TABLE: "job-access",
+ BIGTABLE_FEEDBACK_JOBS_TABLE: "feedback-jobs",
+ SEARCH_FEEDBACK_MAX_AGE_SEC: 120,
+ FEEDBACK_MAX_AGE_SEC: 180,
+ } as {
+ BIGTABLE_JOB_ACCESS_TABLE?: string;
+ BIGTABLE_FEEDBACK_JOBS_TABLE?: string;
+ SEARCH_FEEDBACK_MAX_AGE_SEC: number;
+ FEEDBACK_MAX_AGE_SEC: number;
+ },
+ withSpan: vi.fn(
+ async (name: string, fn: (span: any) => any, options?: any) => {
+ spans.push({ name, options });
+ return fn({});
},
- withSpan: vi.fn(
- async (name: string, fn: (span: any) => any, options?: any) => {
- spans.push({ name, options });
- return fn({});
- },
- ),
- spans,
- };
- },
-);
+ ),
+ spans,
+ };
+});
vi.mock("../config", () => ({ config: mutableConfig }));
vi.mock("./bigtable-client", () => ({ getBigtableTable }));
vi.mock("./otel-tracer", () => ({
withSpan,
- setSpanAttributes: vi.fn(),
+ setSpanAttributes,
}));
import {
API_JOB_KINDS,
isApiJobKind,
+ readApiJobAccess,
writeApiJobAccess,
} from "./job-access-store";
-import { writeFeedbackJob } from "./feedback-job-store";
+import { readFeedbackJob, writeFeedbackJob } from "./feedback-job-store";
import { saltedUuidV7RowKey } from "./bigtable-row-key";
import { scrapeOptions } from "../controllers/v2/types";
@@ -60,7 +69,7 @@ function writtenValue(): Record<string, string | number | boolean> {
describe("operational Bigtable stores", () => {
beforeEach(() => {
vi.clearAllMocks();
- getBigtableTable.mockResolvedValue({ mutate });
+ getBigtableTable.mockResolvedValue({ mutate, getRows });
mutableConfig.BIGTABLE_JOB_ACCESS_TABLE = "job-access";
mutableConfig.BIGTABLE_FEEDBACK_JOBS_TABLE = "feedback-jobs";
spans.length = 0;
@@ -105,6 +114,73 @@ describe("operational Bigtable stores", () => {
});
});
+ it("reads a job access row", async () => {
+ getRows.mockResolvedValueOnce([
+ [
+ {
+ data: {
+ j: {
+ v: [
+ {
+ value: Buffer.from(
+ JSON.stringify({
+ version: 1,
+ teamId: "team-id",
+ kind: "crawl",
+ expiresAtMs: Date.now() + 60_000,
+ }),
+ ),
+ },
+ ],
+ },
+ },
+ },
+ ],
+ ] as any);
+
+ await expect(readApiJobAccess(JOB_ID)).resolves.toMatchObject({
+ teamId: "team-id",
+ kind: "crawl",
+ });
+ expect(getRows).toHaveBeenCalledWith({
+ keys: [saltedUuidV7RowKey(JOB_ID)],
+ filter: [{ column: { name: "v", cellLimit: 1 } }],
+ });
+ });
+
+ it("reports a logically expired job access row", async () => {
+ const expiresAtMs = Date.now() - 1;
+ getRows.mockResolvedValueOnce([
+ [
+ {
+ data: {
+ j: {
+ v: [
+ {
+ value: Buffer.from(
+ JSON.stringify({
+ version: 1,
+ teamId: "team-id",
+ kind: "crawl",
+ expiresAtMs,
+ }),
+ ),
+ },
+ ],
+ },
+ },
+ },
+ ],
+ ] as any);
+
+ await expect(readApiJobAccess(JOB_ID)).resolves.toMatchObject({
+ expiresAtMs,
+ });
+ expect(setSpanAttributes).toHaveBeenCalledWith(expect.anything(), {
+ "bigtable.read.outcome": "expired",
+ });
+ });
+
it("limits job access rows to externally operable job kinds", () => {
expect(API_JOB_KINDS).toEqual([
"scrape",
@@ -213,4 +289,81 @@ describe("operational Bigtable stores", () => {
options: { zeroDataRetention: true },
});
});
+
+ it("reads precomputed feedback decisions", async () => {
+ const feedbackDeadlineMs = Date.now() + 60_000;
+ getRows.mockResolvedValueOnce([
+ [
+ {
+ data: {
+ f: {
+ v: [
+ {
+ value: Buffer.from(
+ JSON.stringify({
+ version: 1,
+ requestId: REQUEST_ID,
+ teamId: "team-id",
+ refundClass: "scrape_pdf",
+ feedbackDeadlineMs,
+ succeeded: true,
+ creditsBilled: 12,
+ zeroDataRetention: false,
+ }),
+ ),
+ },
+ ],
+ },
+ },
+ },
+ ],
+ ] as any);
+
+ await expect(readFeedbackJob(JOB_ID)).resolves.toEqual({
+ requestId: REQUEST_ID,
+ teamId: "team-id",
+ refundClass: "scrape_pdf",
+ feedbackDeadlineMs,
+ succeeded: true,
+ creditsBilled: 12,
+ zeroDataRetention: false,
+ });
+ });
+
+ it("reports a logically expired feedback decision", async () => {
+ const feedbackDeadlineMs = Date.now() - 1;
+ getRows.mockResolvedValueOnce([
+ [
+ {
+ data: {
+ f: {
+ v: [
+ {
+ value: Buffer.from(
+ JSON.stringify({
+ version: 1,
+ requestId: REQUEST_ID,
+ teamId: "team-id",
+ refundClass: "search",
+ feedbackDeadlineMs,
+ succeeded: true,
+ creditsBilled: 1,
+ zeroDataRetention: false,
+ }),
+ ),
+ },
+ ],
+ },
+ },
+ },
+ ],
+ ] as any);
+
+ await expect(readFeedbackJob(JOB_ID)).resolves.toMatchObject({
+ feedbackDeadlineMs,
+ });
+ expect(setSpanAttributes).toHaveBeenCalledWith(expect.anything(), {
+ "bigtable.read.outcome": "expired",
+ });
+ });
});
diff --git a/apps/api/src/lib/operational-job-access.test.ts b/apps/api/src/lib/operational-job-access.test.ts
new file mode 100644
index 000000000..92d9ce575
--- /dev/null
+++ b/apps/api/src/lib/operational-job-access.test.ts
@@ -0,0 +1,88 @@
+const {
+ readApiJobAccess,
+ supabaseGetAgentRequestByIdDirect,
+ supabaseGetCrawlRequestById,
+ supabaseGetExtractRequestByIdDirect,
+ supabaseGetScrapeById,
+} = vi.hoisted(() => ({
+ readApiJobAccess: vi.fn(),
+ supabaseGetAgentRequestByIdDirect: vi.fn(),
+ supabaseGetCrawlRequestById: vi.fn(),
+ supabaseGetExtractRequestByIdDirect: vi.fn(),
+ supabaseGetScrapeById: vi.fn(),
+}));
+
+vi.mock("./job-access-store", () => ({ readApiJobAccess }));
+vi.mock("./supabase-jobs", () => ({
+ supabaseGetAgentRequestByIdDirect,
+ supabaseGetCrawlRequestById,
+ supabaseGetExtractRequestByIdDirect,
+ supabaseGetScrapeById,
+}));
+
+import {
+ getAgentJobAccess,
+ getExtractJobAccess,
+ getScrapeJobAccess,
+} from "./operational-job-access";
+
+const JOB_ID = "019e6f45-7778-727d-adf0-0abe9d5062b6";
+
+describe("operational job access", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("returns the typed Bigtable record without querying PostgreSQL", async () => {
+ const access = {
+ teamId: "team-id",
+ kind: "agent",
+ clientOrigin: "[email protected]",
+ expiresAtMs: Date.now() + 60_000,
+ };
+ readApiJobAccess.mockResolvedValue(access);
+
+ await expect(getAgentJobAccess(JOB_ID)).resolves.toBe(access);
+ expect(supabaseGetAgentRequestByIdDirect).not.toHaveBeenCalled();
+ });
+
+ it("maps a PostgreSQL fallback into the operational access type", async () => {
+ readApiJobAccess.mockResolvedValue(null);
+ supabaseGetExtractRequestByIdDirect.mockResolvedValue({
+ id: JOB_ID,
+ team_id: "team-id",
+ kind: "extract",
+ origin: "api",
+ created_at: "2026-09-16T12:00:00.000Z",
+ unrelated_column: "not returned",
+ });
+
+ await expect(getExtractJobAccess(JOB_ID)).resolves.toEqual({
+ teamId: "team-id",
+ kind: "extract",
+ clientOrigin: "api",
+ expiresAtMs: new Date("2026-09-17T12:00:00.000Z").getTime(),
+ });
+ });
+
+ it("does not fall back when Bigtable has an expired record", async () => {
+ const access = {
+ teamId: "team-id",
+ kind: "scrape",
+ expiresAtMs: Date.now() - 1,
+ };
+ readApiJobAccess.mockResolvedValue(access);
+
+ await expect(getScrapeJobAccess(JOB_ID)).resolves.toBe(access);
+ expect(supabaseGetScrapeById).not.toHaveBeenCalled();
+ });
+
+ it("does not fall back when Bigtable has a different job kind", async () => {
+ readApiJobAccess.mockResolvedValue({
+ teamId: "team-id",
+ kind: "crawl",
+ expiresAtMs: Date.now() + 60_000,
+ });
+
+ await expect(getScrapeJobAccess(JOB_ID)).resolves.toBeNull();
+ expect(supabaseGetScrapeById).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/api/src/lib/operational-job-access.ts b/apps/api/src/lib/operational-job-access.ts
new file mode 100644
index 000000000..7ea7b0b3a
--- /dev/null
+++ b/apps/api/src/lib/operational-job-access.ts
@@ -0,0 +1,123 @@
+import { logger } from "./logger";
+import {
+ readApiJobAccess,
+ type ApiJobAccess,
+ type ApiJobKind,
+} from "./job-access-store";
+import {
+ supabaseGetAgentRequestByIdDirect,
+ supabaseGetCrawlRequestById,
+ supabaseGetExtractRequestByIdDirect,
+ supabaseGetScrapeById,
+} from "./supabase-jobs";
+
+const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
+
+export type OperationalJobAccess = {
+ teamId: string;
+ kind: ApiJobKind;
+ clientOrigin?: string;
+ expiresAtMs: number;
+};
+
+async function resolveOperationalJobAccess(params: {
+ id: string;
+ kinds: readonly ApiJobKind[];
+ fallback: () => Promise<OperationalJobAccess | null>;
+}): Promise<OperationalJobAccess | null> {
+ let access: ApiJobAccess | null = null;
+ try {
+ access = await readApiJobAccess(params.id);
+ } catch (error) {
+ logger.warn("Bigtable job access read failed; using legacy lookup", {
+ error,
+ jobId: params.id,
+ });
+ }
+
+ if (access) {
+ return params.kinds.includes(access.kind) ? access : null;
+ }
+
+ const fallback = await params.fallback();
+ return fallback && Number.isFinite(fallback.expiresAtMs) ? fallback : null;
+}
+
+export function getScrapeJobAccess(
+ id: string,
+): Promise<OperationalJobAccess | null> {
+ return resolveOperationalJobAccess({
+ id,
+ kinds: ["scrape"],
+ fallback: async () => {
+ const row = await supabaseGetScrapeById(id);
+ return row
+ ? {
+ teamId: row.team_id,
+ kind: "scrape",
+ expiresAtMs: new Date(row.created_at).getTime() + DEFAULT_TTL_MS,
+ }
+ : null;
+ },
+ });
+}
+
+export function getExtractJobAccess(
+ id: string,
+): Promise<OperationalJobAccess | null> {
+ return resolveOperationalJobAccess({
+ id,
+ kinds: ["extract", "agent"],
+ fallback: async () => {
+ const row = await supabaseGetExtractRequestByIdDirect(id);
+ if (!row || (row.kind !== "extract" && row.kind !== "agent")) return null;
+ return {
+ teamId: row.team_id,
+ kind: row.kind,
+ clientOrigin: row.origin ?? undefined,
+ expiresAtMs: new Date(row.created_at).getTime() + DEFAULT_TTL_MS,
+ };
+ },
+ });
+}
+
+export function getAgentJobAccess(
+ id: string,
+): Promise<OperationalJobAccess | null> {
+ return resolveOperationalJobAccess({
+ id,
+ kinds: ["agent"],
+ fallback: async () => {
+ const row = await supabaseGetAgentRequestByIdDirect(id);
+ if (!row) return null;
+ return {
+ teamId: row.team_id,
+ kind: "agent",
+ clientOrigin: row.origin ?? undefined,
+ expiresAtMs: new Date(row.created_at).getTime() + DEFAULT_TTL_MS,
+ };
+ },
+ });
+}
+
+export function getCrawlJobAccess(
+ id: string,
+ ttlHours: number,
+): Promise<OperationalJobAccess | null> {
+ return resolveOperationalJobAccess({
+ id,
+ kinds: ["crawl", "batch_scrape"],
+ fallback: async () => {
+ const row = await supabaseGetCrawlRequestById(id);
+ if (!row || (row.kind !== "crawl" && row.kind !== "batch_scrape")) {
+ return null;
+ }
+ return {
+ teamId: row.team_id,
+ kind: row.kind,
+ expiresAtMs:
+ new Date(row.created_at!).getTime() + ttlHours * 60 * 60 * 1000,
+ };
+ },
+ });
+}
diff --git a/apps/api/src/lib/supabase-jobs.ts b/apps/api/src/lib/supabase-jobs.ts
index 2a03788bf..44e3d4868 100644
--- a/apps/api/src/lib/supabase-jobs.ts
+++ b/apps/api/src/lib/supabase-jobs.ts
@@ -125,7 +125,7 @@ export const supabaseGetExtractByIdDirect = async (
export const supabaseGetExtractRequestByIdDirect = async (
extractId: string,
-): Promise<any> => {
+): Promise<typeof schema.requests.$inferSelect | null> => {
try {
const [data] = await db
.select()
@@ -145,7 +145,7 @@ export const supabaseGetExtractRequestByIdDirect = async (
export const supabaseGetAgentRequestByIdDirect = async (
agentId: string,
-): Promise<any> => {
+): Promise<typeof schema.requests.$inferSelect | null> => {
try {
const [data] = await db
.select()
@@ -160,6 +160,24 @@ export const supabaseGetAgentRequestByIdDirect = async (
}
};
+export const supabaseGetCrawlRequestById = async (requestId: string) => {
+ const [data] = await dbRr
+ .select({
+ team_id: schema.requests.team_id,
+ kind: schema.requests.kind,
+ created_at: schema.requests.created_at,
+ })
+ .from(schema.requests)
+ .where(
+ and(
+ eq(schema.requests.id, requestId),
+ inArray(schema.requests.kind, ["crawl", "batch_scrape"]),
+ ),
+ )
+ .limit(1);
+ return data ?? null;
+};
+
export const supabaseGetAgentByIdDirect = async (
agentId: string,
): Promise<any> => {