Skip to content

Open source alternative to Semrush and Ahrefs

Improve coverage of credits_exhausted event (#987)

Carter Smith5b2b64d43c64
diff --git a/src/server/auth/repositories/AuthRepository.ts b/src/server/auth/repositories/AuthRepository.ts
index 042716e1..820d7c22 100644
--- a/src/server/auth/repositories/AuthRepository.ts
+++ b/src/server/auth/repositories/AuthRepository.ts
@@ -100,6 +100,18 @@ async function getHostedUser(userId: string) {
});
}
+async function getOrganizationOwner(organizationId: string) {
+ const [owner] = await db
+ .select({ id: authUser.id, email: authUser.email })
+ .from(member)
+ .innerJoin(authUser, eq(authUser.id, member.userId))
+ .where(
+ and(eq(member.organizationId, organizationId), eq(member.role, "owner")),
+ )
+ .limit(1);
+ return owner ?? null;
+}
+
/** Names for a set of user ids in one query; missing ids are simply absent. */
async function getHostedUserNames(userIds: string[]) {
if (userIds.length === 0) return [];
@@ -327,6 +339,7 @@ export const AuthRepository = {
setProductUpdatesOptIn,
getHostedUser,
getHostedUserNames,
+ getOrganizationOwner,
hasPendingInvitationForEmail,
isAnalyticsOptedOut,
} as const;
diff --git a/src/server/billing/subscription.test.ts b/src/server/billing/subscription.test.ts
index dd333fdf..20a876b1 100644
--- a/src/server/billing/subscription.test.ts
+++ b/src/server/billing/subscription.test.ts
@@ -55,7 +55,12 @@ vi.mock("@/server/lib/posthog", () => ({
captureServerEvent: vi.fn(),
}));
+vi.mock("@/server/email/onboarding-drip", () => ({
+ sendCreditsExhaustedEvent: vi.fn(),
+}));
+
import { captureServerEvent } from "@/server/lib/posthog";
+import { sendCreditsExhaustedEvent } from "@/server/email/onboarding-drip";
import { AUTUMN_TRACK_RETRY_OPTIONS } from "@/server/billing/autumn";
import {
customerHasPaidPlan,
@@ -324,6 +329,7 @@ describe("reserveUsageCredits", () => {
credit_feature: "backlinks",
},
});
+ expect(sendCreditsExhaustedEvent).toHaveBeenCalledWith(customer);
});
it("retries a fail-open read once with the same lock, then fails closed", async () => {
diff --git a/src/server/billing/subscription.ts b/src/server/billing/subscription.ts
index 23a2fb4f..393adff1 100644
--- a/src/server/billing/subscription.ts
+++ b/src/server/billing/subscription.ts
@@ -305,7 +305,8 @@ export async function holdCredits(args: {
* the common case (monthly covers the batch) is a single Autumn request.
*
* Throws INSUFFICIENT_CREDITS when no call fits; `refusedCalls` lists the
- * ones that did not when some did. Either way the refusal event is emitted.
+ * ones that did not when some did. Either way the refusal event and the
+ * credits-exhausted email event are sent.
* The caller must settle every returned hold with `settleUsageCredits` once
* its calls' real cost is known.
*/
@@ -410,6 +411,9 @@ export async function reserveUsageCredits(args: {
topup_remaining: topupRemaining,
},
});
+ // Most users are refused while they still have a few credits left, so
+ // this, not the zero-balance gate, is where most of them run out.
+ await sendCreditsExhaustedEvent(args.customer);
}
if (holds.length === 0) throw new AppError("INSUFFICIENT_CREDITS");
return { holds, refusedCalls };
diff --git a/src/server/email/onboarding-drip.test.ts b/src/server/email/onboarding-drip.test.ts
new file mode 100644
index 00000000..9aeaecf9
--- /dev/null
+++ b/src/server/email/onboarding-drip.test.ts
@@ -0,0 +1,51 @@
+import { expect, it, vi } from "vitest";
+
+vi.mock("cloudflare:workers", () => ({
+ waitUntil: () => {
+ throw new Error("waitUntil() called outside a request context");
+ },
+}));
+vi.mock("@/server/lib/runtime-env", () => ({
+ getOptionalEnvValue: async () => "loops-key",
+}));
+vi.mock("@/db", () => ({
+ withPgClient: (fn: () => Promise<unknown>) => fn(),
+}));
+vi.mock("@/server/auth/repositories/AuthRepository", () => ({
+ AuthRepository: {
+ getOrganizationOwner: async () => ({ id: "owner", email: "[email protected]" }),
+ },
+}));
+vi.mock("@/server/email/loops-client", () => ({
+ sendLoopsEvent: vi.fn().mockResolvedValue(undefined),
+ updateLoopsContact: vi.fn(),
+}));
+
+import { sendLoopsEvent } from "@/server/email/loops-client";
+import { sendCreditsExhaustedEvent } from "./onboarding-drip";
+
+// Rank checks are refused for credits inside a Workflow step, where there is
+// no request context to hand the send to.
+it("still sends from a Workflow step, where waitUntil throws", async () => {
+ await sendCreditsExhaustedEvent({
+ userId: "user",
+ userEmail: "[email protected]",
+ organizationId: "org",
+ });
+
+ expect(vi.mocked(sendLoopsEvent).mock.calls[0][0]).toMatchObject({
+ payload: { eventName: "credits_exhausted" },
+ });
+});
+
+it("sends a scheduled check's refusal to the organization's owner", async () => {
+ await sendCreditsExhaustedEvent({
+ userId: "system",
+ userEmail: "[email protected]",
+ organizationId: "org",
+ });
+
+ expect(vi.mocked(sendLoopsEvent).mock.calls[0][0]).toMatchObject({
+ payload: { email: "[email protected]", userId: "owner" },
+ });
+});
diff --git a/src/server/email/onboarding-drip.ts b/src/server/email/onboarding-drip.ts
index efebfa5b..eb8efacb 100644
--- a/src/server/email/onboarding-drip.ts
+++ b/src/server/email/onboarding-drip.ts
@@ -39,9 +39,19 @@ export async function markOnboardingMilestone(
);
}
+// Scheduled rank and AI visibility checks run as this placeholder user
+// (scheduledRankChecks.ts, scheduledAiVisibility.ts), so a refusal on one of
+// them goes to the organization's owner.
+const SCHEDULED_RUN_USER_ID = "system";
+
export async function sendCreditsExhaustedEvent(
- recipient: OnboardingRecipient,
+ customer: OnboardingRecipient & { organizationId: string },
) {
+ const recipient =
+ customer.userId === SCHEDULED_RUN_USER_ID
+ ? await findOrganizationOwner(customer.organizationId)
+ : customer;
+ if (!recipient) return;
const key = `credits_exhausted:${recipient.userId}:${new Date().toISOString().slice(0, 10)}`;
await sendOnce(key, (apiKey) =>
sendLoopsEvent({
@@ -56,6 +66,27 @@ export async function sendCreditsExhaustedEvent(
);
}
+// Imported lazily, as in captureServerEvent: most importers only report
+// events and shouldn't load the database client. Scoped because Workflow
+// steps run outside a request's Postgres scope.
+async function findOrganizationOwner(
+ organizationId: string,
+): Promise<OnboardingRecipient | null> {
+ try {
+ const [{ withPgClient }, { AuthRepository }] = await Promise.all([
+ import("@/db"),
+ import("@/server/auth/repositories/AuthRepository"),
+ ]);
+ const owner = await withPgClient(() =>
+ AuthRepository.getOrganizationOwner(organizationId),
+ );
+ return owner ? { userId: owner.id, userEmail: owner.email } : null;
+ } catch (error) {
+ console.error("onboarding drip: organization owner lookup failed", error);
+ return null;
+ }
+}
+
// Some callers are hot paths (every request refused for credits), and Loops
// rate-limits the whole team, transactional emails included. So each isolate
// sends each update once.
@@ -69,9 +100,13 @@ async function sendOnce(
const apiKey = await getOptionalEnvValue("LOOPS_API_KEY");
if (!apiKey) return;
sentKeys.add(key);
- waitUntil(
- send(apiKey).catch((error: unknown) => {
- console.error(`onboarding drip: ${key} failed`, error);
- }),
- );
+ const work = send(apiKey).catch((error: unknown) => {
+ console.error(`onboarding drip: ${key} failed`, error);
+ });
+ try {
+ waitUntil(work);
+ } catch {
+ // No request context (Workflow step): wait for the send instead.
+ await work;
+ }
}
diff --git a/src/server/features/ai-visibility/services/aiVisibilityRuns.test.ts b/src/server/features/ai-visibility/services/aiVisibilityRuns.test.ts
index 66ddc8a3..28800483 100644
--- a/src/server/features/ai-visibility/services/aiVisibilityRuns.test.ts
+++ b/src/server/features/ai-visibility/services/aiVisibilityRuns.test.ts
@@ -5,6 +5,7 @@ import { AiVisibilityRepository as repo } from "../repositories/AiVisibilityRepo
import { runCheck } from "./aiVisibilityRuns";
import { getTracker } from "./aiVisibilityState";
import { configuration, customer } from "./aiVisibilityTestFixtures";
+import { sendCreditsExhaustedEvent } from "@/server/email/onboarding-drip";
const { testDb, workflow, hosted, credits } = await vi.hoisted(async () => {
const { createAiVisibilityTestDb } = await import("../aiVisibilityTestDb");
@@ -28,6 +29,9 @@ vi.mock("@/server/billing/subscription", () => ({
getOrCreateOrganizationCustomer: async () => ({ id: "organization" }),
getUsageCreditsRemaining: credits,
}));
+vi.mock("@/server/email/onboarding-drip", () => ({
+ sendCreditsExhaustedEvent: vi.fn(),
+}));
const projectId = "project";
const workflowStatus = (status: string) =>
@@ -123,6 +127,7 @@ describe("AI visibility checks", () => {
expect((await repo.getTracker(projectId))?.lastSkipReason).toBe(
"INSUFFICIENT_CREDITS",
);
+ expect(sendCreditsExhaustedEvent).toHaveBeenCalledWith(customer);
});
it("starts a check that top-up credits cover after research overdrew monthly credits", async () => {
diff --git a/src/server/features/ai-visibility/services/aiVisibilityRuns.ts b/src/server/features/ai-visibility/services/aiVisibilityRuns.ts
index d555ac5a..821b36cc 100644
--- a/src/server/features/ai-visibility/services/aiVisibilityRuns.ts
+++ b/src/server/features/ai-visibility/services/aiVisibilityRuns.ts
@@ -16,6 +16,7 @@ import {
type BillingCustomerContext,
} from "@/server/billing/subscription";
import { AppError } from "@/server/lib/errors";
+import { sendCreditsExhaustedEvent } from "@/server/email/onboarding-drip";
import type { AiRun } from "@/shared/ai-visibility";
import type { RunAiCheckInput } from "@/types/schemas/ai-visibility";
import { requireConfiguration } from "./aiVisibilityMutation";
@@ -114,6 +115,7 @@ export async function startRun(
await repo.updateTracker(config.tracker.id, {
lastSkipReason: "INSUFFICIENT_CREDITS",
});
+ await sendCreditsExhaustedEvent(billing);
throw new AppError(
"INSUFFICIENT_CREDITS",
"Not enough credits for this AI visibility check.",
diff --git a/src/server/features/ai-visibility/services/scheduledAiVisibility.test.ts b/src/server/features/ai-visibility/services/scheduledAiVisibility.test.ts
index 5b8d99fc..3650eac6 100644
--- a/src/server/features/ai-visibility/services/scheduledAiVisibility.test.ts
+++ b/src/server/features/ai-visibility/services/scheduledAiVisibility.test.ts
@@ -28,6 +28,9 @@ vi.mock("@/server/billing/subscription", () => ({
topupRemaining: 0,
}),
}));
+vi.mock("@/server/email/onboarding-drip", () => ({
+ sendCreditsExhaustedEvent: vi.fn(),
+}));
vi.mock("./aiVisibilityRetention", () => ({ pruneAiVisibility: vi.fn() }));
const due = "2026-09-01T06:00:00.000Z";
diff --git a/src/server/lib/audit/rendering-billing.test.ts b/src/server/lib/audit/rendering-billing.test.ts
index 4ff2ded6..1e5b1799 100644
--- a/src/server/lib/audit/rendering-billing.test.ts
+++ b/src/server/lib/audit/rendering-billing.test.ts
@@ -6,6 +6,7 @@ const mocks = vi.hoisted(() => ({
getUsageCreditsRemaining: vi.fn(),
holdCredits: vi.fn<typeof holdCredits>(),
finalizeHold: vi.fn<typeof finalizeHold>(),
+ sendCreditsExhaustedEvent: vi.fn(),
}));
vi.mock("@/server/lib/runtime-env", () => ({
isHostedServerAuthMode: mocks.isHosted,
@@ -17,6 +18,9 @@ vi.mock("@/server/billing/subscription", () => ({
finalizeHold: mocks.finalizeHold,
}));
vi.mock("@/server/lib/posthog", () => ({ captureServerEvent: vi.fn() }));
+vi.mock("@/server/email/onboarding-drip", () => ({
+ sendCreditsExhaustedEvent: mocks.sendCreditsExhaustedEvent,
+}));
import {
lockRenderingCredits,
@@ -96,6 +100,7 @@ describe("rendering credit lock", () => {
expect(error).toMatchObject({ code: "INSUFFICIENT_CREDITS" });
expect(String(error)).toContain("needs $0.39 of credits");
expect(mocks.holdCredits).not.toHaveBeenCalled();
+ expect(mocks.sendCreditsExhaustedEvent).toHaveBeenCalledWith(customer);
});
it("releases the monthly hold when the top-up hold is refused", async () => {
@@ -113,6 +118,7 @@ describe("rendering credit lock", () => {
await expect(lockFor100Pages()).rejects.toMatchObject({
code: "INSUFFICIENT_CREDITS",
});
+ expect(mocks.sendCreditsExhaustedEvent).toHaveBeenCalledWith(customer);
expect(mocks.finalizeHold).toHaveBeenCalledTimes(1);
expect(mocks.finalizeHold).toHaveBeenCalledWith(
monthlyLock,
diff --git a/src/server/lib/audit/rendering-billing.ts b/src/server/lib/audit/rendering-billing.ts
index 1ccb8cf4..49952bf1 100644
--- a/src/server/lib/audit/rendering-billing.ts
+++ b/src/server/lib/audit/rendering-billing.ts
@@ -6,6 +6,7 @@ import {
type BillingCustomerContext,
type UsageCreditHold,
} from "@/server/billing/subscription";
+import { sendCreditsExhaustedEvent } from "@/server/email/onboarding-drip";
import { AppError } from "@/server/lib/errors";
import { captureServerEvent } from "@/server/lib/posthog";
import { isHostedServerAuthMode } from "@/server/lib/runtime-env";
@@ -54,7 +55,6 @@ export async function lockRenderingCredits(input: {
// Clamp at 0: a balance can read negative after an overdraft.
const monthly = Math.min(Math.max(balances.monthlyRemaining, 0), required);
const topup = required - monthly;
- if (topup > Math.max(balances.topupRemaining, 0)) throw insufficient;
const properties = {
creditFeature: "site_audit",
@@ -63,6 +63,7 @@ export async function lockRenderingCredits(input: {
};
const locks: RenderingLock[] = [];
try {
+ if (topup > Math.max(balances.topupRemaining, 0)) throw insufficient;
for (const [featureId, credits] of [
[AUTUMN_SEO_DATA_BALANCE_FEATURE_ID, monthly],
[AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID, topup],
@@ -84,6 +85,7 @@ export async function lockRenderingCredits(input: {
}
} catch (error) {
await releaseRenderingLocks(locks);
+ if (error === insufficient) await sendCreditsExhaustedEvent(input.customer);
throw error;
}
return locks;
diff --git a/src/server/lib/dataforseo/client.test.ts b/src/server/lib/dataforseo/client.test.ts
index 408a2536..1464786b 100644
--- a/src/server/lib/dataforseo/client.test.ts
+++ b/src/server/lib/dataforseo/client.test.ts
@@ -71,6 +71,10 @@ vi.mock("@/server/lib/posthog", () => ({
captureServerEvent: vi.fn(),
}));
+vi.mock("@/server/email/onboarding-drip", () => ({
+ sendCreditsExhaustedEvent: vi.fn(),
+}));
+
// Mock every section module the client wraps so meterDataforseoCall's
// `execute()` resolves to a controllable fixture.
vi.mock("@/server/lib/dataforseo/labs", () => ({
diff --git a/src/server/workflows/RankCheckWorkflow.ts b/src/server/workflows/RankCheckWorkflow.ts
index 9fef811c..7bbd72dd 100644
--- a/src/server/workflows/RankCheckWorkflow.ts
+++ b/src/server/workflows/RankCheckWorkflow.ts
@@ -16,6 +16,7 @@ import { retryRankChecks } from "@/server/workflows/rankCheckRetries";
import { pgStep } from "@/server/workflows/pgStep";
import { createDataforseoClient } from "@/server/lib/dataforseo";
import { captureServerEvent } from "@/server/lib/posthog";
+import { sendCreditsExhaustedEvent } from "@/server/email/onboarding-drip";
import { AppError } from "@/server/lib/errors";
import { autumn } from "@/server/billing/autumn";
import {
@@ -117,6 +118,7 @@ async function prepareRankCheckKeywords(input: {
(monthlyCheck.balance?.remaining ?? 0) +
(topupCheck.balance?.remaining ?? 0);
if (available < costCredits) {
+ await sendCreditsExhaustedEvent(input.billingCustomer);
throw new AppError(
"INSUFFICIENT_CREDITS",
"Insufficient credits for rank check",