The best way to control Claude Code, Codex and more from any computer or phone

main
ts 557 lines 18 KB
Raw
1 import { Query, type UnwrapPlan } from "@distilled.cloud/core/query";
2 import {
3 Railway,
4 type AggregatedUsage,
5 type EstimatedUsage,
6 type MetricMeasurement,
7 type MetricTag,
8 type UsageLimit as RailwayUsageLimit,
9 type UsageLimitSetInput,
10 } from "@distilled.cloud/railway";
11 import { isResolved } from "alchemy/Diff";
12 import * as Provider from "alchemy/Provider";
13 import { Resource } from "alchemy/Resource";
14 import * as Data from "effect/Data";
15 import * as Effect from "effect/Effect";
16 import { RailwayEnvironment, resolveWorkspace } from "./Environment.ts";
17 import { waitUntilDeleted } from "./GraphQL.ts";
18 import type { Providers } from "./Providers.ts";
19
20 const usageFields = <E>(row: Query<AggregatedUsage, E>) => ({
21 measurement: row.measurement,
22 value: row.value,
23 tags: {
24 deploymentId: row.tags.deploymentId,
25 deploymentInstanceId: row.tags.deploymentInstanceId,
26 environmentId: row.tags.environmentId,
27 projectId: row.tags.projectId,
28 region: row.tags.region,
29 serviceId: row.tags.serviceId,
30 volumeId: row.tags.volumeId,
31 volumeInstanceId: row.tags.volumeInstanceId,
32 },
33 });
34 type UsageResultItem = UnwrapPlan<ReturnType<typeof usageFields>>;
35
36 const estimatedUsageFields = <E>(row: Query<EstimatedUsage, E>) => ({
37 measurement: row.measurement,
38 estimatedValue: row.estimatedValue,
39 projectId: row.projectId,
40 });
41 type EstimatedUsageResultItem = UnwrapPlan<ReturnType<typeof estimatedUsageFields>>;
42
43 const limitFields = <E>(limit: Query<RailwayUsageLimit, E>) => ({
44 id: limit.id,
45 customerId: limit.customerId,
46 softLimit: limit.softLimit,
47 hardLimit: limit.hardLimit,
48 isOverLimit: limit.isOverLimit,
49 });
50 type CloudLimit = UnwrapPlan<ReturnType<typeof limitFields>>;
51
52 /**
53 * A resource-valued prop: the resource itself, or an Effect that produces
54 * it (so `yield* Project(...)` and `Project(...)` both type-check).
55 */
56 type Ref<T> = T | Effect.Effect<T, never, Providers>;
57
58 export type { EstimatedUsageResultItem, MetricMeasurement, MetricTag, UsageResultItem };
59
60 /**
61 * Workspace identity a usage limit applies to. Accepts a
62 * `Railway.Project` (`workspaceId`), `{ workspaceId }`, or `{ id }`.
63 */
64 export type UsageLimitWorkspace = { readonly workspaceId?: string; readonly id?: string };
65
66 /**
67 * Project whose workspace a usage limit applies to. Accepts a
68 * `Railway.Project` or a `{ workspaceId, projectId? }` stub.
69 */
70 export type UsageLimitProject = { readonly workspaceId: string; readonly projectId?: string };
71
72 /**
73 * Dollar cap passed to `usageLimitSet`. A number is the soft limit.
74 */
75 export type UsageLimitAmount = {
76 readonly softLimitDollars: number;
77 readonly hardLimitDollars?: number;
78 };
79
80 export interface UsageQuery {
81 /**
82 * Project to query. Accepts a project id, a `Railway.Project`, or a
83 * `{ projectId }` stub. Omit for workspace-wide usage.
84 */
85 project?: string | { readonly projectId: string };
86 /**
87 * Workspace to query. Accepts a workspace id, `{ workspaceId }` /
88 * `{ id }`, or a `Railway.Project`. Defaults to the current token
89 * workspace.
90 */
91 workspace?: string | UsageLimitWorkspace;
92 /**
93 * Measurements to aggregate (`CPU_USAGE`, `MEMORY_USAGE_GB`, …).
94 */
95 measurements: ReadonlyArray<MetricMeasurement>;
96 /**
97 * Inclusive start of the window (RFC3339). Omit for the current
98 * billing period of the project owner.
99 */
100 startDate?: string;
101 /**
102 * Inclusive end of the window (RFC3339). Omit for now.
103 */
104 endDate?: string;
105 /**
106 * Tags to group by (`PROJECT_ID`, `SERVICE_ID`, …). Default is the
107 * whole project / workspace.
108 */
109 groupBy?: ReadonlyArray<MetricTag>;
110 /**
111 * Include deleted projects in the aggregation.
112 *
113 * @default false
114 */
115 includeDeleted?: boolean;
116 }
117
118 export interface EstimatedUsageQuery {
119 /**
120 * Project to estimate. Accepts a project id, a `Railway.Project`, or a
121 * `{ projectId }` stub. Omit for workspace-wide estimates.
122 */
123 project?: string | { readonly projectId: string };
124 /**
125 * Workspace to estimate. Defaults to the current token workspace.
126 */
127 workspace?: string | UsageLimitWorkspace;
128 /**
129 * Measurements to estimate (`CPU_USAGE`, `MEMORY_USAGE_GB`, …).
130 */
131 measurements: ReadonlyArray<MetricMeasurement>;
132 /**
133 * Include deleted projects in the estimate.
134 *
135 * @default false
136 */
137 includeDeleted?: boolean;
138 }
139
140 export interface UsageLimitProps {
141 /**
142 * Workspace whose customer this limit applies to. Accepts a
143 * `Railway.Project`, `{ workspaceId }`, or `{ id }`. Defaults to the
144 * current token's workspace. Changing it to a different workspace
145 * replaces the limit.
146 */
147 workspace?: Ref<UsageLimitWorkspace>;
148 /**
149 * Project whose workspace this limit applies to. Alternative to
150 * `workspace`. Changing it to a project in a different workspace
151 * replaces the limit.
152 */
153 project?: Ref<UsageLimitProject>;
154 /**
155 * Dollar cap. A number is `softLimitDollars`. Pass
156 * `{ softLimitDollars, hardLimitDollars }` for both. Updates in place
157 * via `usageLimitSet`.
158 */
159 limit: number | UsageLimitAmount;
160 }
161
162 export type UsageLimit = Resource<
163 "Railway.UsageLimit",
164 UsageLimitProps,
165 {
166 /** Railway usage-limit id. */
167 usageLimitId: string;
168 /** Stripe / Railway customer id the cap is set on. */
169 customerId: string;
170 /** Workspace the customer belongs to. */
171 workspaceId: string;
172 /** Project used to resolve the workspace, if one was passed. */
173 projectId: string | undefined;
174 /** Soft dollar cap (`usageLimitSet.softLimitDollars`). */
175 softLimitDollars: number;
176 /** Hard dollar cap, if set. */
177 hardLimitDollars: number | undefined;
178 /** Whether current spend is over the soft cap. */
179 isOverLimit: boolean;
180 },
181 never,
182 Providers
183 >;
184
185 const projectIdOf = (value: unknown): string | undefined => {
186 if (typeof value === "string" && value.length > 0) return value;
187 if (value === null || typeof value !== "object") return undefined;
188 const rec = value as { projectId?: unknown };
189 return typeof rec.projectId === "string" && rec.projectId.length > 0 ? rec.projectId : undefined;
190 };
191
192 const workspaceIdOf = (value: unknown): string | undefined => {
193 if (typeof value === "string" && value.length > 0) return value;
194 if (value === null || typeof value !== "object") return undefined;
195 const rec = value as { workspaceId?: unknown; id?: unknown };
196 if (typeof rec.workspaceId === "string" && rec.workspaceId.length > 0) {
197 return rec.workspaceId;
198 }
199 if (typeof rec.id === "string" && rec.id.length > 0) {
200 return rec.id;
201 }
202 return undefined;
203 };
204
205 const parseLimit = (limit: number | UsageLimitAmount): UsageLimitAmount => {
206 if (typeof limit === "number") {
207 return { softLimitDollars: limit };
208 }
209 return {
210 softLimitDollars: limit.softLimitDollars,
211 ...(limit.hardLimitDollars !== undefined ? { hardLimitDollars: limit.hardLimitDollars } : {}),
212 };
213 };
214
215 const readUsage = Query.fn(
216 (args: {
217 measurements: ReadonlyArray<MetricMeasurement>;
218 workspaceId: string;
219 projectId?: string;
220 startDate?: string;
221 endDate?: string;
222 groupBy?: ReadonlyArray<MetricTag>;
223 includeDeleted?: boolean;
224 }) => Railway.usage(args).pipe(Query.map(usageFields)),
225 );
226
227 const readEstimatedUsage = Query.fn(
228 (args: {
229 measurements: ReadonlyArray<MetricMeasurement>;
230 workspaceId: string;
231 projectId?: string;
232 includeDeleted?: boolean;
233 }) => Railway.estimatedUsage(args).pipe(Query.map(estimatedUsageFields)),
234 );
235
236 /**
237 * Billing usage for a project, workspace, or the current user.
238 *
239 * Pass `measurements`. Omit `startDate` / `endDate` for the current
240 * billing period. Omit `project` for the current workspace.
241 *
242 * @example Current workspace CPU
243 * ```typescript
244 * const rows = yield* Railway.usage({
245 * measurements: ["CPU_USAGE"],
246 * });
247 * ```
248 *
249 * @example Project window
250 * ```typescript
251 * const rows = yield* Railway.usage({
252 * project: site,
253 * measurements: ["CPU_USAGE", "MEMORY_USAGE_GB"],
254 * startDate: "2026-01-01T00:00:00.000Z",
255 * endDate: "2026-01-31T23:59:59.000Z",
256 * });
257 * ```
258 */
259 export const usage = Effect.fn(function* (query: UsageQuery) {
260 const projectId = projectIdOf(query.project);
261 const workspaceId = workspaceIdOf(query.workspace) ?? (yield* resolveWorkspace()).id;
262 const rows = yield* readUsage({
263 measurements: [...query.measurements],
264 workspaceId,
265 ...(projectId !== undefined ? { projectId } : {}),
266 ...(query.startDate !== undefined ? { startDate: query.startDate } : {}),
267 ...(query.endDate !== undefined ? { endDate: query.endDate } : {}),
268 ...(query.groupBy !== undefined ? { groupBy: [...query.groupBy] } : {}),
269 ...(query.includeDeleted !== undefined ? { includeDeleted: query.includeDeleted } : {}),
270 });
271 return rows ?? [];
272 });
273
274 /** Catalog helper. Alias of {@link usage}. */
275 export const Usage = usage;
276
277 /**
278 * Estimated total cost at the end of the current billing cycle.
279 *
280 * @example Workspace estimate
281 * ```typescript
282 * const rows = yield* Railway.estimatedUsage({
283 * measurements: ["CPU_USAGE"],
284 * });
285 * ```
286 */
287 export const estimatedUsage = Effect.fn(function* (query: EstimatedUsageQuery) {
288 const projectId = projectIdOf(query.project);
289 const workspaceId = workspaceIdOf(query.workspace) ?? (yield* resolveWorkspace()).id;
290 const rows = yield* readEstimatedUsage({
291 measurements: [...query.measurements],
292 workspaceId,
293 ...(projectId !== undefined ? { projectId } : {}),
294 ...(query.includeDeleted !== undefined ? { includeDeleted: query.includeDeleted } : {}),
295 });
296 return rows ?? [];
297 });
298
299 const resolveUsageLimitProps = (
300 props: UsageLimitProps | Effect.Effect<UsageLimitProps, never, Providers>,
301 ): Effect.Effect<UsageLimitProps, never, Providers> =>
302 Effect.gen(function* () {
303 const resolved = Effect.isEffect(props) ? yield* props : props;
304 if (globalThis.__ALCHEMY_RUNTIME__) return resolved;
305 const workspace =
306 resolved.workspace === undefined
307 ? undefined
308 : Effect.isEffect(resolved.workspace)
309 ? yield* resolved.workspace as Effect.Effect<UsageLimitWorkspace, never, Providers>
310 : resolved.workspace;
311 const project =
312 resolved.project === undefined
313 ? undefined
314 : Effect.isEffect(resolved.project)
315 ? yield* resolved.project as Effect.Effect<UsageLimitProject, never, Providers>
316 : resolved.project;
317 return { ...resolved, workspace, project };
318 });
319
320 const UsageLimitResource = Resource<UsageLimit>("Railway.UsageLimit");
321
322 /**
323 * A Railway.UsageLimit is a soft/hard dollar cap on a workspace
324 * customer. One limit per customer. `usageLimitRemove` is idempotent.
325 *
326 * @see https://docs.railway.com/reference/pricing
327 *
328 * ### Query usage
329 * {@link usage} is a catalog helper — not a resource. It returns
330 * aggregated rows for the current workspace (or a project).
331 *
332 * **Example:** Workspace usage
333 * ```typescript
334 * const rows = yield* Railway.usage({
335 * measurements: ["CPU_USAGE", "MEMORY_USAGE_GB"],
336 * });
337 * ```
338 *
339 * ### Set a limit
340 * Omit `workspace` / `project` to cap the current token workspace. A
341 * number is the soft dollar cap.
342 *
343 * **Example:** Soft cap
344 * ```typescript
345 * const cap = yield* Railway.UsageLimit("SpendCap", {
346 * limit: 50,
347 * });
348 * ```
349 *
350 * **Example:** Soft and hard
351 * ```typescript
352 * const cap = yield* Railway.UsageLimit("SpendCap", {
353 * project: site,
354 * limit: { softLimitDollars: 50, hardLimitDollars: 100 },
355 * });
356 * ```
357 *
358 * :::caution[Changing `workspace` or `project` to another workspace replaces the limit]
359 * The cap is removed from the old customer, then set on the new one.
360 * :::
361 *
362 * ### Module-scope declarations
363 * Resource-valued props accept the resource or an Effect producing it.
364 *
365 * **Example:** Module-scope limit
366 * ```typescript
367 * // src/billing.ts
368 * import * as Railway from "@alchemy.run/railway";
369 *
370 * export const Site = Railway.Project("Site");
371 * export const SpendCap = Railway.UsageLimit("SpendCap", {
372 * project: Site,
373 * limit: 50,
374 * });
375 * ```
376 *
377 * @resource
378 * @product Workspace
379 */
380 export const UsageLimit: typeof UsageLimitResource = Object.assign(
381 (id: string, props: UsageLimitProps | Effect.Effect<UsageLimitProps, never, Providers>) =>
382 UsageLimitResource(id, resolveUsageLimitProps(props)),
383 UsageLimitResource,
384 );
385
386 export class UsageLimitNotCreated extends Data.TaggedError("Railway.UsageLimitNotCreated")<{
387 customerId: string;
388 workspaceId: string;
389 }> {}
390
391 export class UsageLimitWorkspaceNotFound extends Data.TaggedError(
392 "Railway.UsageLimitWorkspaceNotFound",
393 )<{ workspaceId: string }> {}
394
395 const currentWorkspaceId = Effect.fn(function* () {
396 const env = yield* yield* RailwayEnvironment;
397 return env.workspaceId;
398 });
399
400 const readWorkspaceLimit = Query.fn((workspaceId: string) => {
401 const customer = Railway.workspace({ workspaceId }).customer;
402 return {
403 customer: { id: customer.id, usageLimit: customer.usageLimit.pipe(Query.map(limitFields)) },
404 };
405 });
406
407 const getWorkspace = (workspaceId: string) =>
408 readWorkspaceLimit(workspaceId).pipe(Effect.catchTag("RailwayNotFound", () => Effect.undefined));
409
410 const toAttrs = (
411 limit: CloudLimit,
412 fallback: { workspaceId: string; customerId: string; projectId?: string },
413 ): UsageLimit["Attributes"] => ({
414 usageLimitId: limit.id,
415 customerId: limit.customerId || fallback.customerId,
416 workspaceId: fallback.workspaceId,
417 projectId: fallback.projectId,
418 softLimitDollars: limit.softLimit,
419 hardLimitDollars: limit.hardLimit ?? undefined,
420 isOverLimit: limit.isOverLimit,
421 });
422
423 const observe = Effect.fn(function* (workspaceId: string) {
424 const workspace = yield* getWorkspace(workspaceId);
425 if (workspace === undefined) return undefined;
426 return {
427 workspace,
428 customerId: workspace.customer.id,
429 limit: workspace.customer.usageLimit ?? undefined,
430 };
431 });
432
433 const usageLimitSet = Query.fn((input: UsageLimitSetInput) => Railway.usageLimitSet({ input }));
434
435 const usageLimitRemove = Query.fn((customerId: string) =>
436 Railway.usageLimitRemove({ input: { customerId } }),
437 );
438
439 const setLimit = (input: {
440 customerId: string;
441 softLimitDollars: number;
442 hardLimitDollars?: number | null;
443 }) =>
444 usageLimitSet({
445 customerId: input.customerId,
446 softLimitDollars: input.softLimitDollars,
447 ...(input.hardLimitDollars !== undefined ? { hardLimitDollars: input.hardLimitDollars } : {}),
448 });
449
450 const resolveScope = Effect.fn(function* (input: {
451 news?: UsageLimitProps;
452 olds?: UsageLimitProps;
453 output?: UsageLimit["Attributes"];
454 }) {
455 const projectId =
456 projectIdOf(input.news?.project) ?? input.output?.projectId ?? projectIdOf(input.olds?.project);
457 const workspaceId =
458 workspaceIdOf(input.news?.workspace) ??
459 workspaceIdOf(input.news?.project) ??
460 input.output?.workspaceId ??
461 workspaceIdOf(input.olds?.workspace) ??
462 workspaceIdOf(input.olds?.project) ??
463 (yield* currentWorkspaceId());
464 return { workspaceId, projectId };
465 });
466
467 const waitUntilGone = (workspaceId: string, usageLimitId: string) =>
468 waitUntilDeleted(
469 "UsageLimit",
470 usageLimitId,
471 observe(workspaceId).pipe(
472 Effect.map((found) => {
473 if (found?.limit === undefined) return true;
474 return found.limit.id !== usageLimitId;
475 }),
476 ),
477 );
478
479 export const UsageLimitProvider = () =>
480 Provider.succeed(UsageLimit, {
481 stables: ["usageLimitId", "customerId", "workspaceId"],
482
483 diff: Effect.fn(function* ({ news, output }) {
484 if (news === undefined || !isResolved(news)) return undefined;
485 if (output === undefined) return undefined;
486 const nextWorkspace = workspaceIdOf(news.workspace) ?? workspaceIdOf(news.project);
487 if (nextWorkspace !== undefined && nextWorkspace !== output.workspaceId) {
488 return { action: "replace" as const };
489 }
490 return undefined;
491 }),
492
493 read: Effect.fn(function* ({ olds, output }) {
494 const { workspaceId, projectId } = yield* resolveScope({ olds, output });
495 const found = yield* observe(workspaceId);
496 if (found?.limit === undefined) return undefined;
497 return toAttrs(found.limit, { workspaceId, customerId: found.customerId, projectId });
498 }),
499
500 list: Effect.fn(function* () {
501 const workspaceId = yield* currentWorkspaceId();
502 const found = yield* observe(workspaceId);
503 if (found?.limit === undefined) return [];
504 return [toAttrs(found.limit, { workspaceId, customerId: found.customerId })];
505 }),
506
507 reconcile: Effect.fn(function* ({ news, output }) {
508 const props = news ?? ({} as UsageLimitProps);
509 const { workspaceId, projectId } = yield* resolveScope({ news: props, output });
510 const desired = parseLimit(props.limit ?? output?.softLimitDollars ?? 0);
511
512 let found = yield* observe(workspaceId);
513 if (found === undefined) {
514 return yield* new UsageLimitWorkspaceNotFound({ workspaceId });
515 }
516
517 const observed = found.limit;
518 const hardChanged =
519 desired.hardLimitDollars !== undefined
520 ? (observed?.hardLimit ?? undefined) !== desired.hardLimitDollars
521 : observed?.hardLimit != null;
522 const needsSet =
523 observed === undefined || observed.softLimit !== desired.softLimitDollars || hardChanged;
524
525 if (needsSet) {
526 yield* setLimit({
527 customerId: found.customerId,
528 softLimitDollars: desired.softLimitDollars,
529 ...(desired.hardLimitDollars !== undefined
530 ? { hardLimitDollars: desired.hardLimitDollars }
531 : observed?.hardLimit != null
532 ? { hardLimitDollars: null }
533 : {}),
534 }).pipe(Effect.catchTag("RailwayValidationError", () => Effect.void));
535 found = yield* observe(workspaceId);
536 }
537
538 if (found?.limit === undefined) {
539 return yield* new UsageLimitNotCreated({
540 customerId: found?.customerId ?? output?.customerId ?? "",
541 workspaceId,
542 });
543 }
544
545 return toAttrs(found.limit, { workspaceId, customerId: found.customerId, projectId });
546 }),
547
548 delete: Effect.fn(function* ({ output }) {
549 const customerId = output.customerId;
550 const workspaceId = output.workspaceId;
551 if (customerId.length === 0) return;
552 yield* usageLimitRemove(customerId);
553 if (workspaceId.length > 0 && output.usageLimitId.length > 0) {
554 yield* waitUntilGone(workspaceId, output.usageLimitId);
555 }
556 }),
557 });