Skip to content

Open source alternative to Semrush and Ahrefs

Optimize billing page using Autumn events.aggregate (#999)

Carter Smith6047de439971
diff --git a/src/client/features/billing/BillingFeatureBreakdown.test.ts b/src/client/features/billing/BillingFeatureBreakdown.test.ts
deleted file mode 100644
index 3a9f039d..00000000
--- a/src/client/features/billing/BillingFeatureBreakdown.test.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-import { describe, expect, it, vi } from "vitest";
-
-vi.mock("@/serverFunctions/billing", () => ({
- getBillingUsageEvents: vi.fn(),
-}));
-
-import { getBillingFeatureBreakdownRows } from "./BillingFeatureBreakdown";
-
-describe("getBillingFeatureBreakdownRows", () => {
- it("prefers an explicit creditFeature (or its raw alias) over the path", () => {
- const rows = getBillingFeatureBreakdownRows([
- {
- timestamp: 0,
- value: 250,
- properties: {
- creditFeature: "rank_tracking",
- paths: ["v3/serp/google/organic/live/regular"],
- },
- },
- {
- timestamp: 0,
- value: 200,
- properties: {
- credit_feature: "local_seo",
- path: "v3/backlinks/summary/live",
- },
- },
- ]);
-
- expect(rows).toEqual([
- { label: "Rank Tracking", usd: 0.25 },
- { label: "Local SEO", usd: 0.2 },
- ]);
- });
-
- it("infers legacy events from DataForSEO paths", () => {
- const rows = getBillingFeatureBreakdownRows([
- {
- timestamp: 0,
- value: 500,
- properties: { paths: ["v3/backlinks/summary/live"] },
- },
- {
- timestamp: 0,
- value: 250,
- properties: {
- paths: ["v3/dataforseo_labs/google/domain_rank_overview/live"],
- },
- },
- {
- timestamp: 0,
- value: 125,
- properties: {
- paths: ["v3/ai_optimization/llm_mentions/search/live"],
- },
- },
- {
- timestamp: 0,
- value: 100,
- properties: { paths: ["backlinks/summary"] },
- },
- ]);
-
- expect(rows).toEqual([
- { label: "Backlinks", usd: 0.6 },
- { label: "Domain Overview", usd: 0.25 },
- { label: "AI Citations", usd: 0.125 },
- ]);
- });
-
- it("supports legacy JSON-encoded path groups", () => {
- const rows = getBillingFeatureBreakdownRows([
- {
- timestamp: 0,
- value: 300,
- properties: {
- paths: '["v3/ai_optimization/chat_gpt/llm_responses/live"]',
- },
- },
- {
- timestamp: 0,
- value: 200,
- properties: {
- paths: '["v3","ai_optimization","perplexity","llm_responses","live"]',
- },
- },
- ]);
-
- expect(rows).toEqual([{ label: "AI Prompt Responses", usd: 0.5 }]);
- });
-});
diff --git a/src/client/features/billing/BillingFeatureBreakdown.tsx b/src/client/features/billing/BillingFeatureBreakdown.tsx
index d0a7c8bd..29654363 100644
--- a/src/client/features/billing/BillingFeatureBreakdown.tsx
+++ b/src/client/features/billing/BillingFeatureBreakdown.tsx
@@ -1,124 +1,16 @@
-import { sort } from "remeda";
-import { autumnSeoDataCreditsToUsd } from "@/shared/billing";
-import {
- creditFeatureLabel,
- mapDataforseoPathToCreditFeature,
-} from "@/shared/billing-credit-features";
-import type { BillingUsageEvent } from "@/serverFunctions/billing";
+import type { BillingUsage } from "@/server/billing/usage";
import { QueryState } from "@/client/components/QueryState";
import { Skeleton } from "@/client/components/ui/skeleton";
import { BillingUsageSection } from "@/client/features/billing/BillingUsageSection";
-import { useBillingUsageEvents } from "@/client/features/billing/useBillingUsageEvents";
-
-type BillingUsageEventProperties = {
- creditFeature?: unknown;
- credit_feature?: unknown;
- path?: unknown;
- paths?: unknown;
-};
-
-type BillingFeatureBreakdownRow = {
- label: string;
- usd: number;
-};
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null;
-}
-
-function getPathSegmentsFromProperties(
- properties: BillingUsageEventProperties,
-): string[] | null {
- const paths = properties.paths ?? properties.path;
- if (Array.isArray(paths)) {
- const stringPaths = paths.filter(
- (value): value is string => typeof value === "string",
- );
- if (
- stringPaths.length > 1 &&
- stringPaths.every((segment) => !segment.includes("/"))
- ) {
- return stringPaths;
- }
-
- const path = stringPaths[0];
- if (!path) return null;
-
- const parsedPath = parseJsonEncodedPath(path);
- return parsedPath ?? path.split("/").filter(Boolean);
- }
-
- if (typeof paths !== "string") return null;
-
- const parsedPath = parseJsonEncodedPath(paths);
- return parsedPath ?? paths.split("/").filter(Boolean);
-}
-
-function parseJsonEncodedPath(path: string): string[] | null {
- if (!path.startsWith("[")) return null;
-
- try {
- const parsed: unknown = JSON.parse(path);
- if (!Array.isArray(parsed)) return null;
- const stringPaths = parsed.filter(
- (value): value is string => typeof value === "string",
- );
- if (
- stringPaths.length > 1 &&
- stringPaths.every((segment) => !segment.includes("/"))
- ) {
- return stringPaths;
- }
-
- const firstPath = stringPaths[0];
- return firstPath ? firstPath.split("/").filter(Boolean) : null;
- } catch {
- return null;
- }
-}
-
-function getCreditFeatureFromUsageEvent(
- event: BillingUsageEvent,
-): string | null {
- const properties = isRecord(event.properties) ? event.properties : {};
- const explicitFeature = properties.creditFeature ?? properties.credit_feature;
- if (typeof explicitFeature === "string" && explicitFeature.length > 0) {
- return explicitFeature;
- }
-
- const path = getPathSegmentsFromProperties(properties);
- return path ? mapDataforseoPathToCreditFeature(path) : null;
-}
-
-export function getBillingFeatureBreakdownRows(
- events: BillingUsageEvent[],
-): BillingFeatureBreakdownRow[] {
- const creditsByLabel = new Map<string, number>();
-
- for (const event of events) {
- const feature = getCreditFeatureFromUsageEvent(event);
- const label = feature ? creditFeatureLabel(feature) : "Other";
- creditsByLabel.set(label, (creditsByLabel.get(label) ?? 0) + event.value);
- }
-
- return sort(
- [...creditsByLabel.entries()]
- .map(([label, credits]) => ({
- label,
- usd: autumnSeoDataCreditsToUsd(credits),
- }))
- .filter((row) => row.usd > 0),
- (a, b) => b.usd - a.usd,
- );
-}
+import { useBillingUsage } from "@/client/features/billing/useBillingUsage";
export function BillingFeatureBreakdown() {
- const eventsQuery = useBillingUsageEvents();
+ const usageQuery = useBillingUsage();
return (
<BillingUsageSection title="Usage by feature">
<QueryState
- query={eventsQuery}
+ query={usageQuery}
errorFallback="Failed to load usage"
loading={
<div className="space-y-3">
@@ -128,14 +20,13 @@ export function BillingFeatureBreakdown() {
</div>
}
>
- {(events) => <BreakdownRows events={events} />}
+ {(usage) => <BreakdownRows rows={usage.features} />}
</QueryState>
</BillingUsageSection>
);
}
-function BreakdownRows({ events }: { events: BillingUsageEvent[] }) {
- const rows = getBillingFeatureBreakdownRows(events);
+function BreakdownRows({ rows }: { rows: BillingUsage["features"] }) {
const total = rows.reduce((sum, row) => sum + row.usd, 0);
if (rows.length === 0) {
diff --git a/src/client/features/billing/BillingUsageChart.test.ts b/src/client/features/billing/BillingUsageChart.test.ts
deleted file mode 100644
index b2892d57..00000000
--- a/src/client/features/billing/BillingUsageChart.test.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { createElement } from "react";
-import { renderToStaticMarkup } from "react-dom/server";
-import { describe, expect, it, vi } from "vitest";
-import { BillingUsageChart } from "./BillingUsageChart";
-
-const DAY_MS = 24 * 60 * 60 * 1000;
-
-vi.mock("@/client/features/billing/useBillingUsageEvents", () => ({
- BILLING_USAGE_DAYS: 30,
- useBillingUsageEvents: () => ({
- isPending: false,
- isError: false,
- data: [
- { timestamp: Date.now(), value: 20, properties: {} },
- // Older than the first bar: cached events after local midnight.
- {
- timestamp: Date.now() - 31 * DAY_MS - 60_000,
- value: 30,
- properties: {},
- },
- ],
- }),
-}));
-
-describe("BillingUsageChart", () => {
- it("counts every fetched event in the total, as the breakdown does", () => {
- const markup = renderToStaticMarkup(createElement(BillingUsageChart));
-
- expect(markup).toContain("$0.05");
- });
-});
diff --git a/src/client/features/billing/BillingUsageChart.tsx b/src/client/features/billing/BillingUsageChart.tsx
index 7e84a898..ae7c8b86 100644
--- a/src/client/features/billing/BillingUsageChart.tsx
+++ b/src/client/features/billing/BillingUsageChart.tsx
@@ -1,7 +1,5 @@
import { Bar, BarChart } from "recharts";
-import { sort } from "remeda";
-import { autumnSeoDataCreditsToUsd } from "@/shared/billing";
-import type { BillingUsageEvent } from "@/serverFunctions/billing";
+import type { BillingUsage } from "@/server/billing/usage";
import { QueryState } from "@/client/components/QueryState";
import {
ChartGrid,
@@ -16,34 +14,30 @@ import {
type ChartConfig,
} from "@/client/components/ui/chart";
import { BillingUsageSection } from "@/client/features/billing/BillingUsageSection";
-import {
- BILLING_USAGE_DAYS,
- useBillingUsageEvents,
-} from "@/client/features/billing/useBillingUsageEvents";
+import { useBillingUsage } from "@/client/features/billing/useBillingUsage";
const chartConfig = {
- credits: { label: "Usage", color: "#7c3aed" },
+ usd: { label: "Usage", color: "#7c3aed" },
} satisfies ChartConfig;
export function BillingUsageChart() {
- const eventsQuery = useBillingUsageEvents();
+ const usageQuery = useBillingUsage();
return (
<BillingUsageSection title="Usage">
<QueryState
- query={eventsQuery}
+ query={usageQuery}
errorFallback="Failed to load usage"
loading={<Skeleton className="h-40 w-full" />}
>
- {(events) => <UsageChart events={events} />}
+ {(usage) => <UsageChart days={usage.days} />}
</QueryState>
</BillingUsageSection>
);
}
-function UsageChart({ events }: { events: BillingUsageEvent[] }) {
- const chartData = binEventsByDay(events);
- const totalSpend = chartData.reduce((sum, d) => sum + d.credits, 0);
+function UsageChart({ days }: { days: BillingUsage["days"] }) {
+ const totalSpend = days.reduce((sum, day) => sum + day.usd, 0);
return (
<div className="space-y-3">
@@ -61,7 +55,7 @@ function UsageChart({ events }: { events: BillingUsageEvent[] }) {
) : (
<ChartContainer config={chartConfig} className="h-full">
<BarChart
- data={chartData}
+ data={days}
margin={{ top: 4, right: 0, bottom: 0, left: 0 }}
>
<ChartGrid />
@@ -82,8 +76,8 @@ function UsageChart({ events }: { events: BillingUsageEvent[] }) {
}
/>
<Bar
- dataKey="credits"
- fill="var(--color-credits)"
+ dataKey="usd"
+ fill="var(--color-usd)"
radius={[2, 2, 0, 0]}
maxBarSize={12}
/>
@@ -95,34 +89,6 @@ function UsageChart({ events }: { events: BillingUsageEvent[] }) {
);
}
-/**
- * One bar for each local day, from 30 days ago to today, in USD. An event
- * older than that (cached data after midnight) gets its own bar, so the
- * total still matches the per-feature breakdown.
- */
-function binEventsByDay(events: BillingUsageEvent[]) {
- const creditsByDay = new Map<number, number>();
- const day = new Date();
- day.setHours(0, 0, 0, 0);
- day.setDate(day.getDate() - BILLING_USAGE_DAYS);
- for (let i = 0; i <= BILLING_USAGE_DAYS; i++) {
- creditsByDay.set(day.getTime(), 0);
- day.setDate(day.getDate() + 1);
- }
-
- for (const event of events) {
- const eventDay = new Date(event.timestamp).setHours(0, 0, 0, 0);
- creditsByDay.set(eventDay, (creditsByDay.get(eventDay) ?? 0) + event.value);
- }
-
- return sort([...creditsByDay], ([a], [b]) => a - b).map(
- ([date, credits]) => ({
- date,
- credits: autumnSeoDataCreditsToUsd(credits),
- }),
- );
-}
-
function formatShortDate(timestamp: number) {
return new Date(timestamp).toLocaleDateString("en-US", {
month: "short",
diff --git a/src/client/features/billing/useBillingUsage.ts b/src/client/features/billing/useBillingUsage.ts
new file mode 100644
index 00000000..3aa1c4d7
--- /dev/null
+++ b/src/client/features/billing/useBillingUsage.ts
@@ -0,0 +1,17 @@
+import { queryOptions, useQuery } from "@tanstack/react-query";
+import { getBillingUsage } from "@/serverFunctions/billing";
+
+export const billingUsageQueryOptions = () => {
+ // Days are binned in the viewer's timezone.
+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
+ return queryOptions({
+ queryKey: ["billing", "usage", "30d", timezone],
+ queryFn: () => getBillingUsage({ data: { timezone } }),
+ staleTime: 60_000,
+ });
+};
+
+/** The last 30 days of usage, by day for the usage chart and by feature for the breakdown. */
+export function useBillingUsage() {
+ return useQuery(billingUsageQueryOptions());
+}
diff --git a/src/client/features/billing/useBillingUsageEvents.ts b/src/client/features/billing/useBillingUsageEvents.ts
deleted file mode 100644
index 68b5fc5c..00000000
--- a/src/client/features/billing/useBillingUsageEvents.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { queryOptions, useQuery } from "@tanstack/react-query";
-import { getBillingUsageEvents } from "@/serverFunctions/billing";
-
-export const BILLING_USAGE_DAYS = 30;
-const DAY_MS = 24 * 60 * 60 * 1000;
-
-export const billingUsageEventsQueryOptions = () =>
- queryOptions({
- queryKey: ["billing", "usage-events", `${BILLING_USAGE_DAYS}d`],
- queryFn: () => {
- const end = Date.now();
- return getBillingUsageEvents({
- data: { start: end - BILLING_USAGE_DAYS * DAY_MS, end },
- });
- },
- staleTime: 60_000,
- });
-
-/** The usage events of the last 30 days, for the usage chart and the per-feature breakdown. */
-export function useBillingUsageEvents() {
- return useQuery(billingUsageEventsQueryOptions());
-}
diff --git a/src/routes/_app/billing.tsx b/src/routes/_app/billing.tsx
index 14b44be3..d4a86709 100644
--- a/src/routes/_app/billing.tsx
+++ b/src/routes/_app/billing.tsx
@@ -30,7 +30,7 @@ import {
} from "@/client/features/billing/checkout";
import { BillingTabs } from "@/client/features/billing/BillingTabs";
import { parseTopUpAmount } from "@/client/features/billing/HostedBillingContentUtils";
-import { billingUsageEventsQueryOptions } from "@/client/features/billing/useBillingUsageEvents";
+import { billingUsageQueryOptions } from "@/client/features/billing/useBillingUsage";
import { useCreditBalance } from "@/client/features/billing/useCreditBalance";
import {
BASE_PLAN_OFFER,
@@ -62,7 +62,7 @@ export const Route = createFileRoute("/_app/billing")({
// a full load alongside the session check, without holding up navigation.
loader: () => {
prefetchBillingAccount();
- void queryClient.prefetchQuery(billingUsageEventsQueryOptions());
+ void queryClient.prefetchQuery(billingUsageQueryOptions());
prefetchUpgradeCheckout();
},
component: BillingPage,
diff --git a/src/server/billing/autumn.ts b/src/server/billing/autumn.ts
index f5eb2391..604411a2 100644
--- a/src/server/billing/autumn.ts
+++ b/src/server/billing/autumn.ts
@@ -56,6 +56,10 @@ export const autumn = {
update: (...args: Parameters<Autumn["customers"]["update"]>) =>
loadAutumn().then((client) => client.customers.update(...args)),
},
+ events: {
+ aggregate: (...args: Parameters<Autumn["events"]["aggregate"]>) =>
+ loadAutumn().then((client) => client.events.aggregate(...args)),
+ },
invoices: {
list: (...args: Parameters<Autumn["invoices"]["list"]>) =>
loadAutumn().then((client) => client.invoices.list(...args)),
diff --git a/src/server/billing/usage.test.ts b/src/server/billing/usage.test.ts
new file mode 100644
index 00000000..da77684c
--- /dev/null
+++ b/src/server/billing/usage.test.ts
@@ -0,0 +1,57 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const { aggregateMock } = vi.hoisted(() => ({ aggregateMock: vi.fn() }));
+
+vi.mock("@/server/billing/autumn", () => ({
+ autumn: { events: { aggregate: aggregateMock } },
+}));
+
+import { getOrganizationBillingUsage } from "./usage";
+
+beforeEach(() => {
+ aggregateMock.mockImplementation(async ({ groupBy }) =>
+ groupBy === "properties.creditFeature"
+ ? {
+ list: [
+ {
+ period: 1,
+ values: {},
+ groupedValues: {
+ usage_credits: { site_audit: 250, retired: 50, backlinks: -10 },
+ topup_credits: { site_audit: 100 },
+ },
+ },
+ ],
+ total: {
+ usage_credits: { count: 4, sum: 300 },
+ topup_credits: { count: 2, sum: 200 },
+ },
+ }
+ : {
+ list: [
+ { period: 1, values: { usage_credits: 300, topup_credits: 200 } },
+ { period: 2, values: { usage_credits: 0, topup_credits: 0 } },
+ ],
+ total: {},
+ },
+ );
+});
+
+describe("getOrganizationBillingUsage", () => {
+ it("totals both balances by day, and counts ungrouped events as Other", async () => {
+ await expect(
+ getOrganizationBillingUsage("org_1", "America/New_York"),
+ ).resolves.toEqual({
+ days: [
+ { date: 1, usd: 0.5 },
+ { date: 2, usd: 0 },
+ ],
+ // Other: 110 credits Autumn left ungrouped plus 50 of an unknown
+ // feature. Backlinks nets below zero after a refund and is hidden.
+ features: [
+ { label: "Site Audit", usd: 0.35 },
+ { label: "Other", usd: 0.16 },
+ ],
+ });
+ });
+});
diff --git a/src/server/billing/usage.ts b/src/server/billing/usage.ts
new file mode 100644
index 00000000..ce7e970e
--- /dev/null
+++ b/src/server/billing/usage.ts
@@ -0,0 +1,85 @@
+import { sort, sumBy } from "remeda";
+import {
+ AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
+ AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
+ autumnSeoDataCreditsToUsd,
+} from "@/shared/billing";
+import { creditFeatureLabel } from "@/shared/billing-credit-features";
+import { autumn } from "@/server/billing/autumn";
+
+const USAGE_DAYS = 30;
+const DAY_MS = 24 * 60 * 60 * 1000;
+const USAGE_FEATURE_IDS = [
+ AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
+ AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
+];
+
+/** The organization's usage over the last 30 days, in USD, as the billing
+ * page charts it. */
+export async function getOrganizationBillingUsage(
+ organizationId: string,
+ timezone: string,
+) {
+ const end = Date.now();
+ const params = {
+ customerId: organizationId,
+ featureId: USAGE_FEATURE_IDS,
+ customRange: { start: end - USAGE_DAYS * DAY_MS, end },
+ // One bin per day in the viewer's timezone, from 30 days ago to today.
+ binSize: "day" as const,
+ timezone,
+ };
+ const [byDay, byFeature] = await Promise.all([
+ autumn.events.aggregate(params),
+ autumn.events.aggregate({
+ ...params,
+ // Every billed usage event names its feature here. More groups than
+ // credit features, so Autumn never folds one into its own "Other".
+ groupBy: "properties.creditFeature",
+ maxGroups: 20,
+ }),
+ ]);
+
+ const creditsByLabel = new Map<string, number>();
+ const addCredits = (label: string, credits: number) =>
+ creditsByLabel.set(label, (creditsByLabel.get(label) ?? 0) + credits);
+ let groupedCredits = 0;
+ for (const bin of byFeature.list) {
+ for (const featureId of USAGE_FEATURE_IDS) {
+ const groups = bin.groupedValues?.[featureId] ?? {};
+ for (const [feature, credits] of Object.entries(groups)) {
+ addCredits(creditFeatureLabel(feature), credits);
+ groupedCredits += credits;
+ }
+ }
+ }
+ // Grouping drops events without a credit feature; they count as Other.
+ const totalCredits = sumBy(
+ USAGE_FEATURE_IDS,
+ (featureId) => byFeature.total[featureId]?.sum ?? 0,
+ );
+ addCredits("Other", totalCredits - groupedCredits);
+
+ return {
+ days: byDay.list.map((bin) => ({
+ date: bin.period,
+ usd: autumnSeoDataCreditsToUsd(
+ sumBy(USAGE_FEATURE_IDS, (featureId) => bin.values[featureId] ?? 0),
+ ),
+ })),
+ // Refunds can leave a feature at or below zero; those rows are hidden.
+ features: sort(
+ [...creditsByLabel]
+ .map(([label, credits]) => ({
+ label,
+ usd: autumnSeoDataCreditsToUsd(credits),
+ }))
+ .filter((row) => row.usd > 0),
+ (a, b) => b.usd - a.usd,
+ ),
+ };
+}
+
+export type BillingUsage = Awaited<
+ ReturnType<typeof getOrganizationBillingUsage>
+>;
diff --git a/src/serverFunctions/billing.ts b/src/serverFunctions/billing.ts
index 14bac037..745b7468 100644
--- a/src/serverFunctions/billing.ts
+++ b/src/serverFunctions/billing.ts
@@ -1,11 +1,7 @@
import { createServerFn } from "@tanstack/react-start";
import { getRequest } from "@tanstack/react-start/server";
import { z } from "zod";
-import {
- AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
- AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
- CHECKOUT_PLAN_IDS,
-} from "@/shared/billing";
+import { CHECKOUT_PLAN_IDS } from "@/shared/billing";
import { getOrganizationBillingAccount } from "@/server/billing/billing-account";
import {
createBillingPortalUrl,
@@ -16,14 +12,11 @@ import {
listOrganizationInvoices,
setOrganizationInvoiceEmails,
} from "@/server/billing/invoices";
-import { AppError } from "@/server/lib/errors";
-import {
- getRequiredEnvValue,
- isHostedServerAuthMode,
-} from "@/server/lib/runtime-env";
+import { getOrganizationBillingUsage } from "@/server/billing/usage";
import { getPublicOrigin } from "@/server/mcp/public-origin";
import { pinMetaCheckout } from "@/server/referrals/meta";
import { requireAuthenticatedContext } from "@/serverFunctions/middleware";
+import { timeZoneSchema } from "@/types/schemas/schedule-time";
export const getBillingAccount = createServerFn({ method: "POST" })
.middleware(requireAuthenticatedContext)
@@ -83,134 +76,9 @@ export const setInvoiceEmails = createServerFn({ method: "POST" })
setOrganizationInvoiceEmails(context, data.enabled),
);
-const AUTUMN_EVENTS_LIST_URL = "https://api.useautumn.com/v1/events.list";
-const EVENT_PAGE_LIMIT = 1000;
-// Autumn rate-limits events.list; back off on 429 before giving up.
-const AUTUMN_MAX_RETRIES = 3;
-const AUTUMN_RETRY_BACKOFF_MS = 250;
-// Cap a server-supplied Retry-After so a bogus value can't stall the Worker.
-const AUTUMN_MAX_RETRY_DELAY_MS = 5000;
-const BILLING_USAGE_FEATURE_IDS = [
- AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
- AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
-] as const;
-
-const billingUsageRangeSchema = z.object({
- start: z.number(),
- end: z.number(),
-});
-
-const billingUsagePropertySchema = z.json();
-
-const autumnEventSchema = z
- .object({
- timestamp: z.number(),
- value: z.number(),
- properties: z
- .record(z.string(), billingUsagePropertySchema)
- .optional()
- .default({}),
- })
- .passthrough();
-
-const autumnEventsListResponseSchema = z
- .object({
- list: z.array(autumnEventSchema),
- has_more: z.boolean().optional(),
- hasMore: z.boolean().optional(),
- })
- .passthrough();
-
-export type BillingUsageEvent = {
- timestamp: number;
- value: number;
- properties: Record<string, z.infer<typeof billingUsagePropertySchema>>;
-};
-
-export const getBillingUsageEvents = createServerFn({ method: "POST" })
+export const getBillingUsage = createServerFn({ method: "POST" })
.middleware(requireAuthenticatedContext)
- .validator(billingUsageRangeSchema)
- .handler(async ({ data, context }) => {
- if (!(await isHostedServerAuthMode())) {
- return [];
- }
-
- const events: BillingUsageEvent[] = [];
- let offset = 0;
-
- for (;;) {
- const page = await fetchAutumnEventsPage({
- customerId: context.organizationId,
- end: data.end,
- offset,
- start: data.start,
- });
-
- events.push(...page.list);
-
- if (!page.hasMore || page.list.length === 0) {
- return events;
- }
-
- offset += page.list.length;
- }
- });
-
-async function fetchAutumnEventsPage(args: {
- customerId: string;
- end: number;
- offset: number;
- start: number;
-}): Promise<{ list: BillingUsageEvent[]; hasMore: boolean }> {
- const secretKey = await getRequiredEnvValue("AUTUMN_SECRET_KEY");
-
- let response: Response;
- for (let attempt = 0; ; attempt++) {
- response = await fetch(AUTUMN_EVENTS_LIST_URL, {
- method: "POST",
- headers: {
- Accept: "application/json",
- Authorization: `Bearer ${secretKey}`,
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- customer_id: args.customerId,
- custom_range: {
- end: args.end,
- start: args.start,
- },
- feature_id: BILLING_USAGE_FEATURE_IDS,
- limit: EVENT_PAGE_LIMIT,
- offset: args.offset,
- }),
- });
-
- if (response.ok) break;
-
- if (response.status === 429 && attempt < AUTUMN_MAX_RETRIES) {
- const retryAfterHeader = response.headers.get("Retry-After");
- const retryAfter = retryAfterHeader ? Number(retryAfterHeader) : NaN;
- const delayMs = Number.isFinite(retryAfter)
- ? Math.min(retryAfter * 1000, AUTUMN_MAX_RETRY_DELAY_MS)
- : AUTUMN_RETRY_BACKOFF_MS * (attempt + 1);
- await new Promise((resolve) => setTimeout(resolve, delayMs));
- continue;
- }
-
- throw new AppError(
- response.status === 429 ? "RATE_LIMITED" : "INTERNAL_ERROR",
- `Autumn events.list failed with status ${response.status}`,
- );
- }
-
- const parsed = autumnEventsListResponseSchema.parse(await response.json());
-
- return {
- hasMore: parsed.has_more ?? parsed.hasMore ?? false,
- list: parsed.list.map((event) => ({
- timestamp: event.timestamp,
- value: event.value,
- properties: event.properties,
- })),
- };
-}
+ .validator(z.object({ timezone: timeZoneSchema }))
+ .handler(({ data, context }) =>
+ getOrganizationBillingUsage(context.organizationId, data.timezone),
+ );
diff --git a/src/types/schemas/schedule-time.ts b/src/types/schemas/schedule-time.ts
index 84969632..3c36bc39 100644
--- a/src/types/schemas/schedule-time.ts
+++ b/src/types/schemas/schedule-time.ts
@@ -9,6 +9,11 @@ function isTimeZone(timeZone: string): boolean {
}
}
+/** An IANA timezone name, e.g. "America/New_York". */
+export const timeZoneSchema = z
+ .string()
+ .refine(isTimeZone, "Unknown IANA timezone");
+
// A user-chosen run time for scheduled checks, in their own timezone. It only
// picks where the next_check_at anchor starts; the
// anchor is UTC and advances in fixed steps, so the timezone is not stored.
@@ -24,9 +29,7 @@ export const scheduleTimeSchema = z.object({
),
hour: z.number().int().min(0).max(23).describe("Hour, 0-23."),
minute: z.number().int().min(0).max(59).describe("Minute, 0-59."),
- timeZone: z
- .string()
- .refine(isTimeZone, "Unknown IANA timezone")
+ timeZone: timeZoneSchema
.optional()
.describe(
'IANA timezone the weekday, hour, and minute are in, e.g. "America/New_York". Defaults to UTC.',