Skip to content

Open source alternative to Semrush and Ahrefs

Save site audits before checking the site's redirects (EVE-440) (#989)

Carter Smithbe89e9e747b3
diff --git a/src/client/features/dashboard/DashboardPage.tsx b/src/client/features/dashboard/DashboardPage.tsx
index 59013b06..a34c230d 100644
--- a/src/client/features/dashboard/DashboardPage.tsx
+++ b/src/client/features/dashboard/DashboardPage.tsx
@@ -47,19 +47,8 @@ export function DashboardPage({
const overviewQuery = useQuery({
queryKey: ["dashboardOverview", projectId],
queryFn: () => getDashboardOverview({ data: { projectId } }),
- refetchInterval: (query) => {
- const audit = query.state.data?.audit;
- if (audit?.status === "running") return 3000;
- // Onboarding starts a new site's first audit in the background, so it
- // can appear just after the dashboard loads. Keep checking for a minute.
- if (
- audit === null &&
- activationQuery.data?.domain &&
- query.state.dataUpdateCount < 20
- )
- return 3000;
- return false;
- },
+ refetchInterval: (query) =>
+ query.state.data?.audit?.status === "running" ? 3000 : false,
});
const activation = activationQuery.data;
diff --git a/src/server/features/audit/repositories/AuditRepository.ts b/src/server/features/audit/repositories/AuditRepository.ts
index e326df8d..42215685 100644
--- a/src/server/features/audit/repositories/AuditRepository.ts
+++ b/src/server/features/audit/repositories/AuditRepository.ts
@@ -48,6 +48,18 @@ async function createAudit(data: {
});
}
+/** Records where the crawl really starts, once the workflow has probed the site. */
+async function updateAuditStart(
+ auditId: string,
+ startUrl: string,
+ config: AuditConfig,
+) {
+ await db
+ .update(audits)
+ .set({ startUrl, config: JSON.stringify(config) })
+ .where(eq(audits.id, auditId));
+}
+
async function updateAuditProgress(
auditId: string,
workflowInstanceId: string,
@@ -407,6 +419,7 @@ async function deleteAuditForProject(auditId: string, projectId: string) {
export const AuditRepository = {
createAudit,
+ updateAuditStart,
updateAuditProgress,
completeAudit,
failAudit,
diff --git a/src/server/features/audit/services/AuditService.crawlerAccess.test.ts b/src/server/features/audit/services/AuditService.crawlerAccess.test.ts
index 0e95bd9b..dbff50f8 100644
--- a/src/server/features/audit/services/AuditService.crawlerAccess.test.ts
+++ b/src/server/features/audit/services/AuditService.crawlerAccess.test.ts
@@ -1,4 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { SealedCrawlerAccess } from "@/server/features/audit/services/CrawlerCredentialService";
const {
SECRET,
@@ -19,8 +20,15 @@ const {
>(),
usageMock: vi.fn(),
findCredentialMock: vi.fn(),
- workflowCreateMock:
- vi.fn<(options: { params: { access?: unknown } }) => Promise<void>>(),
+ workflowCreateMock: vi.fn<
+ (options: {
+ params: {
+ startUrl: string;
+ config: { maxPages: number; lighthouseStrategy: "none" };
+ access?: SealedCrawlerAccess | null;
+ };
+ }) => Promise<void>
+ >(),
}));
vi.mock("cloudflare:workers", () => ({
@@ -41,6 +49,7 @@ vi.mock("@/server/billing/subscription", () => ({
vi.mock("@/server/features/audit/repositories/AuditRepository", () => ({
AuditRepository: {
createAudit: createAuditMock,
+ updateAuditStart: vi.fn(),
getAuditUsageForOrganization: usageMock,
},
}));
@@ -59,6 +68,7 @@ vi.mock("@/server/lib/audit/progress-kv", () => ({ AuditProgressKV: {} }));
import { symmetricEncrypt } from "better-auth/crypto";
import { AuditService } from "@/server/features/audit/services/AuditService";
+import { resolveAuditStart } from "@/server/workflows/siteAuditStart";
async function credentialRow(expiresAt: string | null) {
return {
@@ -92,7 +102,21 @@ const input = {
limitTier: "self_hosted" as const,
};
-describe("startAudit crawler access", () => {
+// Starts the audit, then runs the workflow's first step on what it was given.
+async function startAndResolve() {
+ await AuditService.startAudit(input);
+ const { params } = workflowCreateMock.mock.calls[0][0];
+ return resolveAuditStart({
+ auditId: "audit-1",
+ organizationId: "org-1",
+ projectId: "project-1",
+ startUrl: params.startUrl,
+ config: params.config,
+ access: params.access,
+ });
+}
+
+describe("audit crawler access", () => {
beforeEach(async () => {
usageMock.mockResolvedValue({ runningCount: 0, capacityUnits: 0 });
findCredentialMock.mockResolvedValue([await credentialRow(null)]);
@@ -118,16 +142,16 @@ describe("startAudit crawler access", () => {
});
it("records the Shopify platform and keeps the signature encrypted at rest", async () => {
- await AuditService.startAudit(input);
+ const resolved = await startAndResolve();
expect(probeSignature()).toBe("sig1=:abc:");
- const config = createAuditMock.mock.calls[0][0].config;
- expect(config.sitePlatform).toBe("shopify");
- expect(config.crawlerCredentialId).toBe("cred-1");
- // Both the audit row's config and the workflow params are persisted, so
- // neither may carry the plaintext values.
+ expect(resolved.config.sitePlatform).toBe("shopify");
+ expect(resolved.config.crawlerCredentialId).toBe("cred-1");
+ // The audit row's config, the workflow params and the step result are all
+ // persisted, so none may carry the plaintext values.
const params = workflowCreateMock.mock.calls[0][0].params;
- expect(JSON.stringify([config, params])).not.toContain("sig1");
+ const rowConfig = createAuditMock.mock.calls[0][0].config;
+ expect(JSON.stringify([rowConfig, params, resolved])).not.toContain("sig1");
expect(params.access).toMatchObject({ host: "store.example.com" });
});
@@ -137,11 +161,9 @@ describe("startAudit crawler access", () => {
Promise.resolve(new Response(null, { status: 429 })),
);
- await AuditService.startAudit(input);
+ const resolved = await startAndResolve();
- expect(createAuditMock.mock.calls[0][0].config.sitePlatform).toBe(
- "shopify",
- );
+ expect(resolved.config.sitePlatform).toBe("shopify");
});
it("does not replay an expired signature", async () => {
@@ -149,7 +171,7 @@ describe("startAudit crawler access", () => {
await credentialRow("2020-01-01T00:00:00.000Z"),
]);
- await AuditService.startAudit(input);
+ await startAndResolve();
expect(probeSignature()).toBeNull();
expect(
diff --git a/src/server/features/audit/services/AuditService.rendering.test.ts b/src/server/features/audit/services/AuditService.rendering.test.ts
index 57892eed..00870d70 100644
--- a/src/server/features/audit/services/AuditService.rendering.test.ts
+++ b/src/server/features/audit/services/AuditService.rendering.test.ts
@@ -26,8 +26,6 @@ vi.mock("@/server/lib/audit/rendering-billing", () => ({
}));
vi.mock("@/server/lib/audit/url-policy", () => ({
normalizeAndValidateStartUrl: async (url: string) => url,
- resolveStartUrlRedirects: async (url: string) => ({ url }),
- isShopifyHost: async () => false,
}));
vi.mock("@/server/features/audit/services/CrawlerCredentialService", () => ({
CrawlerCredentialService: {
diff --git a/src/server/features/audit/services/AuditService.ts b/src/server/features/audit/services/AuditService.ts
index 07fc69bc..366c2bc4 100644
--- a/src/server/features/audit/services/AuditService.ts
+++ b/src/server/features/audit/services/AuditService.ts
@@ -28,11 +28,7 @@ import {
type AuditConfig,
type LighthouseStrategy,
} from "@/server/lib/audit/types";
-import {
- isShopifyHost,
- normalizeAndValidateStartUrl,
- resolveStartUrlRedirects,
-} from "@/server/lib/audit/url-policy";
+import { normalizeAndValidateStartUrl } from "@/server/lib/audit/url-policy";
import { reconcileRunningAudit } from "@/server/features/audit/services/auditReconciler";
import { isHostedServerAuthMode } from "@/server/lib/runtime-env";
@@ -82,44 +78,19 @@ async function startAudit(input: {
const auditId = crypto.randomUUID();
const organizationId = input.billingCustomer.organizationId;
- const requestedUrl = await normalizeAndValidateStartUrl(input.startUrl);
- // The probe itself can be rate limited, so it carries the credential too.
- let credential = await CrawlerCredentialService.resolveCrawlerAccess(
+ // The site itself is first contacted by the workflow's first step
+ // (resolveAuditStart), so starting an audit never waits on a slow site.
+ const startUrl = await normalizeAndValidateStartUrl(input.startUrl);
+ const credential = await CrawlerCredentialService.resolveCrawlerAccess(
organizationId,
input.projectId,
- new URL(requestedUrl).hostname,
- );
- // Anchor the audit to the site's real origin: a start domain that 301s
- // elsewhere (…net -> …com, apex -> www) would otherwise dead-end after
- // one page at the same-origin crawl boundary.
- const probe = await resolveStartUrlRedirects(
- requestedUrl,
- await CrawlerCredentialService.openCrawlerAccess(credential?.sealed),
+ new URL(startUrl).hostname,
);
- const startUrl = probe.url;
- const startHost = new URL(startUrl).hostname;
- if (startHost !== new URL(requestedUrl).hostname) {
- credential = await CrawlerCredentialService.resolveCrawlerAccess(
- organizationId,
- input.projectId,
- startHost,
- );
- }
const config: AuditConfig = {
maxPages,
lighthouseStrategy,
renderJavaScript,
- // Shopify storefronts answer with `powered-by: Shopify`; knowing this is
- // what lets a rendered crawl read throttled pages and the report explain
- // an unrendered one. A throttled probe sees no header, but a saved
- // signature is always Shopify's, and so is a host in Shopify's range.
- sitePlatform:
- credential ||
- probe.poweredBy?.toLowerCase().includes("shopify") ||
- (await isShopifyHost(startHost))
- ? "shopify"
- : undefined,
crawlerCredentialId: credential?.id,
};
diff --git a/src/server/workflows/SiteAuditWorkflow.test.ts b/src/server/workflows/SiteAuditWorkflow.test.ts
index e285771a..3943990f 100644
--- a/src/server/workflows/SiteAuditWorkflow.test.ts
+++ b/src/server/workflows/SiteAuditWorkflow.test.ts
@@ -34,6 +34,9 @@ vi.mock("@/server/features/audit/repositories/AuditRepository", () => ({
failAudit: mocks.failAudit,
},
}));
+vi.mock("@/server/workflows/siteAuditStart", () => ({
+ resolveAuditStart: async (input: object) => ({ ...input, access: null }),
+}));
vi.mock("@/server/features/audit/services/CrawlerCredentialService", () => ({
CrawlerCredentialService: { openCrawlerAccess: vi.fn() },
}));
diff --git a/src/server/workflows/SiteAuditWorkflow.ts b/src/server/workflows/SiteAuditWorkflow.ts
index 479f94cf..041b5491 100644
--- a/src/server/workflows/SiteAuditWorkflow.ts
+++ b/src/server/workflows/SiteAuditWorkflow.ts
@@ -24,10 +24,12 @@ import {
import type { AuditConfig } from "@/server/lib/audit/types";
import { captureServerError, captureServerEvent } from "@/server/lib/posthog";
import { runAuditPhases } from "@/server/workflows/siteAuditWorkflowPhases";
+import { resolveAuditStart } from "@/server/workflows/siteAuditStart";
import { pgStep } from "@/server/workflows/pgStep";
import {
DB_STEP,
SETTLE_RENDERING_STEP,
+ START_URL_STEP,
} from "@/server/workflows/auditStepConfigs";
import type { RenderUsage } from "@/shared/audit-rendering";
@@ -61,8 +63,7 @@ export class SiteAuditWorkflow extends WorkflowEntrypoint<Env, AuditParams> {
event: WorkflowEvent<AuditParams>,
step: WorkflowStep,
) {
- const { auditId, billingCustomer, projectId, startUrl, config, access } =
- event.payload;
+ const { auditId, billingCustomer, projectId } = event.payload;
// Summed from checkpointed chunk results, so a replay rebuilds it exactly.
const renderUsage: RenderUsage = {
cloudflareAttempts: 0,
@@ -88,6 +89,23 @@ export class SiteAuditWorkflow extends WorkflowEntrypoint<Env, AuditParams> {
}
});
+ // Probing the site happens here, not when the audit starts, so a
+ // slow site never delays the response that starts the audit.
+ const { startUrl, config, access } = await pgStep(
+ step,
+ "resolve-start-url",
+ START_URL_STEP,
+ () =>
+ resolveAuditStart({
+ auditId,
+ organizationId: billingCustomer.organizationId,
+ projectId,
+ startUrl: event.payload.startUrl,
+ config: event.payload.config,
+ access: event.payload.access,
+ }),
+ );
+
await runAuditPhases(step, {
auditId,
workflowInstanceId: event.instanceId,
@@ -150,7 +168,7 @@ export class SiteAuditWorkflow extends WorkflowEntrypoint<Env, AuditParams> {
failed_phase: runningAudit?.currentPhase,
pages_crawled: runningAudit?.pagesCrawled,
pages_total: runningAudit?.pagesTotal,
- run_lighthouse: config.lighthouseStrategy !== "none",
+ run_lighthouse: event.payload.config.lighthouseStrategy !== "none",
},
});
});
diff --git a/src/server/workflows/auditStepConfigs.ts b/src/server/workflows/auditStepConfigs.ts
index cb1f83b0..9bafa5fe 100644
--- a/src/server/workflows/auditStepConfigs.ts
+++ b/src/server/workflows/auditStepConfigs.ts
@@ -9,6 +9,12 @@ import type { WorkflowStepConfig } from "cloudflare:workers";
* step now has a timeout sized to its real work and a small retry budget.
*/
+/** Redirect probe of the start URL: up to 5 hops at 10s each. */
+export const START_URL_STEP: WorkflowStepConfig = {
+ retries: { limit: 2, delay: "5 seconds", backoff: "exponential" },
+ timeout: "2 minutes",
+};
+
/** Robots + sitemap walk (bounded at 300 docs / 15s per fetch internally). */
export const DISCOVERY_STEP: WorkflowStepConfig = {
retries: { limit: 2, delay: "5 seconds", backoff: "exponential" },
diff --git a/src/server/workflows/siteAuditStart.ts b/src/server/workflows/siteAuditStart.ts
new file mode 100644
index 00000000..4ab7ce3b
--- /dev/null
+++ b/src/server/workflows/siteAuditStart.ts
@@ -0,0 +1,59 @@
+import { AuditRepository } from "@/server/features/audit/repositories/AuditRepository";
+import {
+ CrawlerCredentialService,
+ type SealedCrawlerAccess,
+} from "@/server/features/audit/services/CrawlerCredentialService";
+import type { AuditConfig } from "@/server/lib/audit/types";
+import {
+ isShopifyHost,
+ resolveStartUrlRedirects,
+} from "@/server/lib/audit/url-policy";
+
+/**
+ * The audit workflow's first step. Anchors the audit to the site's real
+ * origin: a start domain that 301s elsewhere (…net -> …com, apex -> www)
+ * would otherwise dead-end after one page at the same-origin crawl boundary.
+ */
+export async function resolveAuditStart(input: {
+ auditId: string;
+ organizationId: string;
+ projectId: string;
+ startUrl: string;
+ config: AuditConfig;
+ access?: SealedCrawlerAccess | null;
+}) {
+ // The probe itself can be rate limited, so it carries the credential too.
+ const probe = await resolveStartUrlRedirects(
+ input.startUrl,
+ await CrawlerCredentialService.openCrawlerAccess(input.access),
+ );
+ const startUrl = probe.url;
+ const startHost = new URL(startUrl).hostname;
+ let access = input.access ?? null;
+ let crawlerCredentialId = input.config.crawlerCredentialId;
+ if (startHost !== new URL(input.startUrl).hostname) {
+ const credential = await CrawlerCredentialService.resolveCrawlerAccess(
+ input.organizationId,
+ input.projectId,
+ startHost,
+ );
+ access = credential?.sealed ?? null;
+ crawlerCredentialId = credential?.id;
+ }
+ const config: AuditConfig = {
+ ...input.config,
+ // Shopify storefronts answer with `powered-by: Shopify`; knowing this is
+ // what lets a rendered crawl read throttled pages and the report explain
+ // an unrendered one. A throttled probe sees no header, but a saved
+ // signature is always Shopify's, and so is a host in Shopify's range.
+ sitePlatform:
+ access ||
+ probe.poweredBy?.toLowerCase().includes("shopify") ||
+ (await isShopifyHost(startHost))
+ ? "shopify"
+ : undefined,
+ crawlerCredentialId,
+ };
+ await AuditRepository.updateAuditStart(input.auditId, startUrl, config);
+ return { startUrl, config, access };
+}