Skip to content

Open source alternative to Semrush and Ahrefs

Show DataForSEO outages as provider problems, not internal errors (#899)

Carter Smithcb9ce9a93008
diff --git a/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx b/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx
index 600a17ac..3000977e 100644
--- a/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx
+++ b/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx
@@ -15,6 +15,7 @@ import { QueryState } from "@/client/components/QueryState";
import { SkeletonCard } from "@/client/components/SkeletonPresets";
import { Alert, AlertDescription } from "@/client/components/ui/alert";
import { useHostedPlanGate } from "@/client/features/billing/HostedPlanGate";
+import { getStandardErrorMessage } from "@/client/lib/error-messages";
import { captureClientEvent } from "@/client/lib/posthog";
import { FreePlanAlert } from "./FreePlanAlert";
import { RankTrackingDetailHeader } from "./RankTrackingDetailHeader";
@@ -259,7 +260,8 @@ export function RankTrackingDomainDetail({
<AlertDescription className="text-foreground">
<p>
<span className="font-medium">Last check failed.</span>{" "}
- {latestRun.errorMessage}
+ {latestRun.errorMessage &&
+ getStandardErrorMessage(new Error(latestRun.errorMessage))}
</p>
</AlertDescription>
</Alert>
diff --git a/src/server/lib/dataforseo/ai-tracking.ts b/src/server/lib/dataforseo/ai-tracking.ts
index b7b11aee..7b7bcd2d 100644
--- a/src/server/lib/dataforseo/ai-tracking.ts
+++ b/src/server/lib/dataforseo/ai-tracking.ts
@@ -5,6 +5,7 @@ import {
isTaskInProgress,
type DataforseoApiResponse,
type DataforseoTaskLike,
+ failedResponseError,
} from "@/server/lib/dataforseo/envelope";
import { AppError } from "@/server/lib/errors";
import {
@@ -112,10 +113,7 @@ export async function postAiTrackingTasks(
{ maxServerErrorRetries: 0 },
);
if (!response || response.status_code !== 20000) {
- throw new AppError(
- "INTERNAL_ERROR",
- response?.status_message || "DataForSEO task_post failed",
- );
+ throw failedResponseError(response, "DataForSEO task_post failed");
}
// Cost is summed over every entry, accepted or not, so anything DataForSEO
// charged is metered.
@@ -160,10 +158,7 @@ export async function fetchAiTrackingTaskResult(input: {
);
const task = response?.tasks?.[0];
if (!response || response.status_code !== 20000 || !task) {
- throw new AppError(
- "INTERNAL_ERROR",
- response?.status_message || "DataForSEO task_get failed",
- );
+ throw failedResponseError(response, "DataForSEO task_get failed");
}
if (isTaskInProgress(task)) return { status: "pending" };
return aiTrackingAnswer(task);
@@ -204,10 +199,7 @@ export async function fetchAiTrackingLiveAnswer(
});
const task = response?.tasks?.[0];
if (!response || response.status_code !== 20000 || !task) {
- throw new AppError(
- "INTERNAL_ERROR",
- response?.status_message || "DataForSEO live request failed",
- );
+ throw failedResponseError(response, "DataForSEO live request failed");
}
return {
data: aiTrackingAnswer(task),
diff --git a/src/server/lib/dataforseo/business.ts b/src/server/lib/dataforseo/business.ts
index 1c90bf44..fa64ea8d 100644
--- a/src/server/lib/dataforseo/business.ts
+++ b/src/server/lib/dataforseo/business.ts
@@ -10,6 +10,7 @@ import {
type DataforseoItemsTask,
type DataforseoResponseLike,
type DataforseoTaskLike,
+ failedResponseError,
} from "@/server/lib/dataforseo/envelope";
import { AppError } from "@/server/lib/errors";
@@ -278,10 +279,7 @@ export async function fetchBusinessDataTaskResult(input: {
const task = response?.tasks?.[0];
if (!response || response.status_code !== 20000 || !task) {
- throw new AppError(
- "INTERNAL_ERROR",
- response?.status_message || "DataForSEO task_get failed",
- );
+ throw failedResponseError(response, "DataForSEO task_get failed");
}
if (isTaskInProgress(task)) return { status: "pending", result: null };
diff --git a/src/server/lib/dataforseo/envelope.test.ts b/src/server/lib/dataforseo/envelope.test.ts
index 429b173a..8d4c537a 100644
--- a/src/server/lib/dataforseo/envelope.test.ts
+++ b/src/server/lib/dataforseo/envelope.test.ts
@@ -70,6 +70,16 @@ describe("assertOk", () => {
},
);
+ it("classifies a top-level 50000 'Internal Server Error.' as UPSTREAM_UNAVAILABLE", () => {
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ expect(() =>
+ assertOk({
+ status_code: 50000,
+ status_message: "Internal Server Error.",
+ }),
+ ).toThrow(expect.objectContaining({ code: "UPSTREAM_UNAVAILABLE" }));
+ });
+
it("uses the classifier for account failures before charging billed task metadata", () => {
const classify = vi.fn(
() =>
diff --git a/src/server/lib/dataforseo/envelope.ts b/src/server/lib/dataforseo/envelope.ts
index e8845e91..46fbe36f 100644
--- a/src/server/lib/dataforseo/envelope.ts
+++ b/src/server/lib/dataforseo/envelope.ts
@@ -174,13 +174,34 @@ const UPSTREAM_FAILURE_STATUS_CODES = new Set([
50402, // Target page took too long to respond.
]);
-function isUpstreamServerErrorTask(task: DataforseoTaskLike): boolean {
+function isUpstreamFailureStatus(statusCode: number | undefined): boolean {
return (
- task.status_code !== undefined &&
- UPSTREAM_FAILURE_STATUS_CODES.has(task.status_code)
+ statusCode !== undefined && UPSTREAM_FAILURE_STATUS_CODES.has(statusCode)
);
}
+/**
+ * Error for a response whose top-level status isn't a success. DataForSEO
+ * reports whole-request outages there too (a top-level 50000 "Internal Server
+ * Error."), so those classify as UPSTREAM_UNAVAILABLE exactly like a failed
+ * task does.
+ */
+export function failedResponseError<T extends DataforseoTaskLike>(
+ response: DataforseoResponseLike<T> | null,
+ fallbackMessage: string,
+): AppError {
+ const message = response?.status_message || fallbackMessage;
+ if (!isUpstreamFailureStatus(response?.status_code)) {
+ return new AppError("INTERNAL_ERROR", message);
+ }
+ // Warn for the same reason as the task-level branch in assertOk.
+ console.warn("dataforseo.upstream-response-failed", {
+ status: response?.status_code,
+ message,
+ });
+ return new AppError("UPSTREAM_UNAVAILABLE", message);
+}
+
/** Task lifecycle codes meaning "not done yet": Task Created / Task Handed /
* Task In Queue. A task_get returning one of these is pending, not failed. */
const TASK_IN_PROGRESS_STATUS_CODES = new Set([20100, 40601, 40602]);
@@ -209,7 +230,8 @@ type AssertOkOptions = {
* returns that (SDK-typed) task. The single status / billing ladder shared by
* every endpoint:
* - access / balance failure -> classified AppError
- * - DataForSEO's own backend erring (5xxxx) -> UPSTREAM_UNAVAILABLE
+ * - DataForSEO's own backend erring, on the response or the task ->
+ * UPSTREAM_UNAVAILABLE
* - charged-but-failed task (cost present) -> DataforseoChargedTaskError
*/
export function assertOk<T extends DataforseoTaskLike>(
@@ -229,7 +251,7 @@ export function assertOk<T extends DataforseoTaskLike>(
const message = response.status_message || "DataForSEO request failed";
throw (
classify?.(response.status_code, message, classifyPath ?? "") ??
- new AppError("INTERNAL_ERROR", message)
+ failedResponseError(response, message)
);
}
@@ -247,7 +269,7 @@ export function assertOk<T extends DataforseoTaskLike>(
if (classified) throw classified;
const detailedMessage = describeInvalidField(message, task);
- const isUpstreamFailure = isUpstreamServerErrorTask(task);
+ const isUpstreamFailure = isUpstreamFailureStatus(task.status_code);
// UPSTREAM_UNAVAILABLE is non-reportable, and the error handlers only log
// what they capture, so warn here to keep the provider's failure rate — and
// the only remaining record of the message — visible in Workers
diff --git a/src/server/lib/dataforseo/serp.ts b/src/server/lib/dataforseo/serp.ts
index 97aa0d1c..b3f3e495 100644
--- a/src/server/lib/dataforseo/serp.ts
+++ b/src/server/lib/dataforseo/serp.ts
@@ -13,6 +13,7 @@ import {
type DataforseoApiResponse,
type DataforseoItemsTask,
type DataforseoTaskLike,
+ failedResponseError,
} from "@/server/lib/dataforseo/envelope";
import { AppError } from "@/server/lib/errors";
@@ -260,10 +261,7 @@ export async function postRankCheckTasks(input: {
);
if (!response || response.status_code !== 20000) {
- throw new AppError(
- "INTERNAL_ERROR",
- response?.status_message || "DataForSEO task_post failed",
- );
+ throw failedResponseError(response, "DataForSEO task_post failed");
}
// One response entry per submitted task; accepted entries have status 20100
@@ -321,10 +319,7 @@ export async function fetchRankCheckTaskResult(input: {
);
const task = response?.tasks?.[0];
if (!response || response.status_code !== 20000 || !task) {
- throw new AppError(
- "INTERNAL_ERROR",
- response?.status_message || "DataForSEO task_get failed",
- );
+ throw failedResponseError(response, "DataForSEO task_get failed");
}
if (isTaskInProgress(task)) {
@@ -450,10 +445,7 @@ export async function postLocalSerpTasks(input: {
{ maxServerErrorRetries: 0 },
);
if (!response || response.status_code !== 20000) {
- throw new AppError(
- "INTERNAL_ERROR",
- response?.status_message || "DataForSEO task_post failed",
- );
+ throw failedResponseError(response, "DataForSEO task_post failed");
}
// Cost is summed over every entry, accepted or not, so anything DataForSEO
@@ -508,10 +500,7 @@ export async function fetchLocalSerpTaskResult(
>(`/v3/serp/google/maps/task_get/advanced/${encodeURIComponent(taskId)}`);
const task = response?.tasks?.[0];
if (!response || response.status_code !== 20000 || !task) {
- throw new AppError(
- "INTERNAL_ERROR",
- response?.status_message || "DataForSEO task_get failed",
- );
+ throw failedResponseError(response, "DataForSEO task_get failed");
}
if (isTaskInProgress(task)) return { status: "pending" };
diff --git a/src/server/mcp/instrumentation.ts b/src/server/mcp/instrumentation.ts
index a9dd9593..fb6dfa8e 100644
--- a/src/server/mcp/instrumentation.ts
+++ b/src/server/mcp/instrumentation.ts
@@ -7,6 +7,7 @@ import { captureServerError, captureServerEvent } from "@/server/lib/posthog";
import { shouldCaptureAppErrorCode } from "@/shared/error-codes";
import { type ToolContext } from "@/server/mcp/context";
import { incrementSelfHostMcpToolCallCount } from "@/server/lib/self-host-telemetry";
+import { toolErrorMessage } from "@/server/mcp/tool-error-message";
type ToolHandler<TArgs> = (
args: TArgs,
@@ -203,8 +204,11 @@ export function instrumentMcpToolHandler<TArgs>(
// The agent sees only the error message, and a bare INSUFFICIENT_CREDITS code
// gives it nothing to tell the user, so it tends to retry. Explain it instead,
// without promoting upgrades or purchases (the server instructions forbid
-// that); every other error passes through unchanged.
+// that). A provider outage gets the same note as per-item tool errors; every
+// other error passes through unchanged.
function agentFacingError(error: unknown, appError: AppError | null): unknown {
+ if (appError?.code === "UPSTREAM_UNAVAILABLE")
+ return new AppError("UPSTREAM_UNAVAILABLE", toolErrorMessage(appError));
if (appError?.code !== "INSUFFICIENT_CREDITS") return error;
const detail =
appError.message === appError.code ? "" : `${appError.message} `;
diff --git a/src/server/mcp/tool-error-message.ts b/src/server/mcp/tool-error-message.ts
index 048a9088..ba176326 100644
--- a/src/server/mcp/tool-error-message.ts
+++ b/src/server/mcp/tool-error-message.ts
@@ -1,12 +1,16 @@
import { AppError } from "@/server/lib/errors";
/**
- * Error text for a tool call that took a `locationName`. An unknown area
- * also tells the agent how to find a valid one.
+ * Error text an agent sees for a failed tool call. An unknown area also tells
+ * the agent how to find a valid one, and a provider outage gets the same
+ * note that it is the provider's problem, not the request's.
*/
export function toolErrorMessage(error: unknown): string {
const message = error instanceof Error ? error.message : String(error);
- return error instanceof AppError && error.code === "UNKNOWN_LOCATION"
- ? `${message} Call search_serp_locations and pass the returned locationName exactly.`
- : message;
+ if (!(error instanceof AppError)) return message;
+ if (error.code === "UNKNOWN_LOCATION")
+ return `${message} Call search_serp_locations and pass the returned locationName exactly.`;
+ if (error.code === "UPSTREAM_UNAVAILABLE")
+ return `${message} The data provider is temporarily unavailable; this is not a problem with the request.`;
+ return message;
}
diff --git a/src/server/workflows/rankCheckPaths.ts b/src/server/workflows/rankCheckPaths.ts
index abaee373..994ac15d 100644
--- a/src/server/workflows/rankCheckPaths.ts
+++ b/src/server/workflows/rankCheckPaths.ts
@@ -112,7 +112,10 @@ async function checkBatchLive(
const reason: unknown = outcome.reason;
const code = reason instanceof AppError ? reason.code : "UNKNOWN";
const message = reason instanceof Error ? reason.message : String(reason);
- firstError ??= message;
+ // Store the bare code so the app shows its provider-unavailable copy;
+ // DataForSEO's raw outage text ("Internal Server Error.") reads like our
+ // server broke.
+ firstError ??= code === "UPSTREAM_UNAVAILABLE" ? code : message;
// DataForSEO erring on its own side is a provider flake, not our bug: the
// keyword just misses this run and finalize reports it to the user. Every
// other rejection (no credits, bad API key) is ours and stays at error.
@@ -214,7 +217,6 @@ async function collectQueuedRound(
const completed: RankCheckResultWithDevice[] = [];
const stillPending: PostedRankCheckTask[] = [];
const failed: PostedRankCheckTask[] = [];
- let firstError: string | null = null;
for (let i = 0; i < tasks.length; i += TASK_GET_CONCURRENCY) {
const chunk = tasks.slice(i, i + TASK_GET_CONCURRENCY);
@@ -243,7 +245,8 @@ async function collectQueuedRound(
console.warn(
`[rank-check] ${ctx.runId} task ${task.taskId} failed: ${result.value.message}`,
);
- firstError ??= result.value.message;
+ // No run error here: every failed task gets a live retry, which
+ // records its own error if it fails too.
failed.push(task);
} else {
completed.push({ ...result.value.result, device: task.device });
@@ -251,9 +254,6 @@ async function collectQueuedRound(
});
}
- if (firstError) {
- await RankTrackingRepository.setRunErrorIfEmpty(ctx.runId, firstError);
- }
if (completed.length > 0) {
await RankTrackingRepository.insertSnapshots(
mapResultsToSnapshotRows(ctx.runId, completed),