Skip to content

Commit a609217

Browse files
authored
feat(cloud): add Autumn billing integration (#152)
* feat(cloud): add Autumn billing integration with tiered pricing Integrate Autumn as the billing/entitlements layer over Stripe. Three tiers: Free (5k executions/mo), Hobby ($10/seat, 50k), and Professional ($40/seat, 100k) with $1/10k overage top-ups. Fire-and-forget execution tracking via the Autumn SDK. * style: format * refactor(billing): use useListPlans customerEligibility instead of manual sub parsing * style: format * fix(billing): sanitize Autumn error responses, remove any types * style: format
1 parent c89589f commit a609217

13 files changed

Lines changed: 807 additions & 9 deletions

File tree

‎apps/cloud/@useautumn-sdk.d.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// AUTO-GENERATED by atmn pull
2+
// DO NOT EDIT MANUALLY
3+
4+
import type {} from "@useautumn/sdk";
5+
6+
declare module "@useautumn/sdk" {
7+
// Features
8+
export const seats: Feature;
9+
10+
// Plans
11+
export const professional: Plan;
12+
13+
// Base types
14+
export type Feature = import("./autumn.config").Feature;
15+
export type Plan = import("./autumn.config").Plan;
16+
}

‎apps/cloud/autumn.config.ts‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
import { feature, item, plan } from "atmn";
2+
3+
// Features
4+
export const seats = feature({
5+
id: "seats",
6+
name: "Seats",
7+
type: "metered",
8+
consumable: false,
9+
});
10+
11+
export const executions = feature({
12+
id: "executions",
13+
name: "Executions",
14+
type: "metered",
15+
consumable: true,
16+
});
17+
18+
// Plans
19+
export const free = plan({
20+
id: "free",
21+
name: "Free",
22+
autoEnable: true,
23+
items: [
24+
item({
25+
featureId: executions.id,
26+
included: 5000,
27+
reset: { interval: "month" },
28+
}),
29+
],
30+
});
31+
32+
export const hobby = plan({
33+
id: "hobby",
34+
name: "Hobby",
35+
price: {
36+
amount: 10,
37+
interval: "month",
38+
},
39+
items: [
40+
item({
41+
featureId: seats.id,
42+
included: 1,
43+
price: {
44+
amount: 10,
45+
billingUnits: 1,
46+
billingMethod: "usage_based",
47+
interval: "month",
48+
},
49+
}),
50+
item({
51+
featureId: executions.id,
52+
included: 50000,
53+
reset: { interval: "month" },
54+
}),
55+
],
56+
});
57+
58+
export const professional = plan({
59+
id: "professional",
60+
name: "Professional",
61+
price: {
62+
amount: 40,
63+
interval: "month",
64+
},
65+
items: [
66+
item({
67+
featureId: seats.id,
68+
included: 1,
69+
price: {
70+
amount: 40,
71+
billingUnits: 1,
72+
billingMethod: "usage_based",
73+
interval: "month",
74+
},
75+
}),
76+
item({
77+
featureId: executions.id,
78+
included: 100000,
79+
reset: { interval: "month" },
80+
}),
81+
],
82+
});
83+
84+
// Overage add-on
85+
export const executionTopUp = plan({
86+
id: "execution-top-up",
87+
name: "Execution Top-Up",
88+
addOn: true,
89+
items: [
90+
item({
91+
featureId: executions.id,
92+
price: {
93+
amount: 1,
94+
billingUnits: 10000,
95+
billingMethod: "prepaid",
96+
interval: "month",
97+
},
98+
}),
99+
],
100+
});

‎apps/cloud/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
"@tanstack/react-start": "catalog:",
4141
"@workos-inc/node": "^8.11.1",
4242
"agents": "^0.10.0",
43+
"autumn-js": "^1.2.8",
4344
"drizzle-orm": "catalog:",
4445
"effect": "catalog:",
4546
"jose": "^5.6.3",

‎apps/cloud/src/api.ts‎

Lines changed: 95 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import {
1111
HttpServer,
1212
} from "@effect/platform";
1313
import { Effect, Layer } from "effect";
14+
import { Autumn } from "autumn-js";
15+
import { autumnHandler } from "autumn-js/backend";
1416

1517
import { CoreExecutorApi } from "@executor/api";
1618
import { CoreHandlers, ExecutorService, ExecutionEngineService } from "@executor/api/server";
@@ -155,6 +157,21 @@ const buildProtectedHandler = (
155157
// ---------------------------------------------------------------------------
156158

157159
const isAuthPath = (pathname: string): boolean => pathname.startsWith("/auth/");
160+
const isAutumnPath = (pathname: string): boolean => pathname.startsWith("/autumn/");
161+
const isExecutionPath = (pathname: string): boolean =>
162+
pathname === "/executions" || /^\/executions\/[^/]+\/resume$/.test(pathname);
163+
164+
// ---------------------------------------------------------------------------
165+
// Autumn billing — lazy-initialized SDK for fire-and-forget tracking
166+
// ---------------------------------------------------------------------------
167+
168+
let _autumn: Autumn | null = null;
169+
const getAutumn = () => {
170+
if (!_autumn && server.AUTUMN_SECRET_KEY) {
171+
_autumn = new Autumn({ secretKey: server.AUTUMN_SECRET_KEY });
172+
}
173+
return _autumn;
174+
};
158175

159176
/**
160177
* Resolve the user's organization for executor creation. Reads from the
@@ -170,9 +187,67 @@ const lookupOrgForRequest = (request: Request) =>
170187
return yield* users.use((s) => s.getOrganization(result.organizationId!));
171188
});
172189

190+
// ---------------------------------------------------------------------------
191+
// Autumn billing proxy — authenticates the session, then forwards to Autumn
192+
// ---------------------------------------------------------------------------
193+
194+
const handleAutumnRequest = async (request: Request): Promise<Response> => {
195+
const program = Effect.gen(function* () {
196+
const workos = yield* WorkOSAuth;
197+
const result = yield* workos.authenticateRequest(request);
198+
199+
if (!result || !result.organizationId) {
200+
return Response.json({ error: "Unauthorized" }, { status: 401 });
201+
}
202+
203+
const url = new URL(request.url);
204+
const body =
205+
request.method !== "GET" && request.method !== "HEAD"
206+
? yield* Effect.promise(() => request.json())
207+
: undefined;
208+
209+
const { statusCode, response } = yield* Effect.promise(() =>
210+
autumnHandler({
211+
request: {
212+
url: url.pathname,
213+
method: request.method,
214+
body,
215+
},
216+
customerId: result.organizationId,
217+
customerData: {
218+
name: result.email,
219+
email: result.email,
220+
},
221+
clientOptions: {
222+
secretKey: server.AUTUMN_SECRET_KEY,
223+
},
224+
pathPrefix: "/autumn",
225+
}),
226+
);
227+
228+
if (statusCode >= 400) {
229+
console.error("[autumn] upstream error:", statusCode, response);
230+
return Response.json({ error: "Billing request failed" }, { status: statusCode });
231+
}
232+
233+
return Response.json(response, { status: statusCode });
234+
});
235+
236+
return Effect.runPromise(program.pipe(Effect.provide(SharedServices), Effect.scoped)).catch(
237+
(err) => {
238+
console.error("[autumn] request failed:", err instanceof Error ? err.stack : err);
239+
return Response.json({ error: "Internal server error" }, { status: 500 });
240+
},
241+
);
242+
};
243+
173244
export const handleApiRequest = async (request: Request): Promise<Response> => {
174245
const pathname = new URL(request.url).pathname;
175246

247+
if (isAutumnPath(pathname)) {
248+
return handleAutumnRequest(request);
249+
}
250+
176251
if (isAuthPath(pathname)) {
177252
const handler = createNonProtectedHandler();
178253
try {
@@ -190,7 +265,8 @@ export const handleApiRequest = async (request: Request): Promise<Response> => {
190265

191266
const codeExecutor = makeDynamicWorkerExecutor({ loader: env.LOADER });
192267
const handler = yield* buildProtectedHandler(org.id, org.name, codeExecutor);
193-
return yield* Effect.promise(() => handler.handler(request));
268+
const response = yield* Effect.promise(() => handler.handler(request));
269+
return { response, orgId: org.id };
194270
});
195271

196272
const result = await Effect.runPromise(
@@ -203,7 +279,24 @@ export const handleApiRequest = async (request: Request): Promise<Response> => {
203279
{ status: 403 },
204280
);
205281
}
206-
return result;
282+
283+
// Fire-and-forget: track execution usage
284+
if (isExecutionPath(pathname) && result.response.ok) {
285+
const autumn = getAutumn();
286+
if (autumn) {
287+
autumn
288+
.track({
289+
customerId: result.orgId,
290+
featureId: "executions",
291+
value: 1,
292+
})
293+
.catch((err) => {
294+
console.error("[billing] track failed:", err);
295+
});
296+
}
297+
}
298+
299+
return result.response;
207300
} catch (err) {
208301
console.error("[api] request failed:", err instanceof Error ? err.stack : err);
209302
return Response.json(

‎apps/cloud/src/env.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ const serverShape = {
1111
WORKOS_CLIENT_ID: Env.string("WORKOS_CLIENT_ID"),
1212
WORKOS_COOKIE_PASSWORD: Env.string("WORKOS_COOKIE_PASSWORD"),
1313
VITE_PUBLIC_SITE_URL: Env.stringOr("VITE_PUBLIC_SITE_URL", ""),
14+
AUTUMN_SECRET_KEY: Env.stringOr("AUTUMN_SECRET_KEY", ""),
1415
};
1516

1617
type SharedEnv = Readonly<{
@@ -25,6 +26,7 @@ type ServerEnv = SharedEnv &
2526
WORKOS_CLIENT_ID: string;
2627
WORKOS_COOKIE_PASSWORD: string;
2728
VITE_PUBLIC_SITE_URL: string;
29+
AUTUMN_SECRET_KEY: string;
2830
}>;
2931

3032
type WebEnv = Readonly<Record<string, never>>;

0 commit comments

Comments
 (0)