@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 426 lines 13.2 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 GetBillingMeters,
4 GetBillingMeter,
5 CreateBillingMeter,
6 UpdateBillingMeter,
7 CreateBillingMeterDeactivate,
8 CreateBillingMeterReactivate,
9 type BillingMeter as StripeBillingMeter,
10 } from "@distilled.cloud/stripe/stripe";
11 import { isResolved } from "alchemy/Diff";
12 import { createPhysicalName } from "alchemy/PhysicalName";
13 import * as Provider from "alchemy/Provider";
14 import { Resource } from "alchemy/Resource";
15 import * as Data from "effect/Data";
16 import * as Effect from "effect/Effect";
17 import { isMissingStripeResource } from "./missing.ts";
18 import type { Providers } from "./Providers.ts";
19
20 const DISPLAY_NAME_MAX_LENGTH = 250;
21 const EVENT_NAME_MAX_LENGTH = 100;
22 const LIST_PAGE_SIZE = 100;
23 const LIST_MAX_PAGES = 100;
24
25 /** How meter events are aggregated over a billing period. */
26 export type BillingMeterAggregationFormula = "count" | "last" | "sum";
27
28 /** The meter's status. Inactive meters reject events and cannot attach to a price. */
29 export type BillingMeterStatus = "active" | "inactive";
30
31 /** Pre-aggregation window for meter events, if any. */
32 export type BillingMeterEventTimeWindow = "day" | "hour";
33
34 /** How a meter event is mapped to a Stripe customer. */
35 export type BillingMeterCustomerMappingType = "by_id";
36
37 export interface BillingMeterDefaultAggregation {
38 /**
39 * Aggregation formula applied to events over the billing period.
40 */
41 formula: BillingMeterAggregationFormula;
42 }
43
44 export interface BillingMeterCustomerMapping {
45 /**
46 * Key in the meter event payload used to map the event to a customer.
47 */
48 eventPayloadKey: string;
49 /**
50 * Mapping method. Must be `by_id`.
51 * @default "by_id"
52 */
53 type?: BillingMeterCustomerMappingType;
54 }
55
56 export interface BillingMeterValueSettings {
57 /**
58 * Key in the usage event payload used as this meter's value (e.g.
59 * `"bytes_used"`).
60 */
61 eventPayloadKey: string;
62 }
63
64 export interface BillingMeterProps {
65 /**
66 * The meter's name. Not visible to the customer. If omitted, a unique
67 * name is generated from the stack, stage, and logical id. Mutable.
68 */
69 displayName?: string;
70 /**
71 * Name of the meter event used to record usage. Corresponds with the
72 * `event_name` field on meter events. If omitted, a unique name is
73 * generated. Create-only — changing it replaces the meter. Stripe
74 * event names are unique per account, including deactivated meters.
75 */
76 eventName?: string;
77 /**
78 * How events are aggregated over a billing period. Create-only.
79 */
80 defaultAggregation: BillingMeterDefaultAggregation;
81 /**
82 * How a meter event is mapped to a customer. Create-only. Defaults to
83 * `{ type: "by_id", eventPayloadKey: "stripe_customer_id" }`.
84 */
85 customerMapping?: BillingMeterCustomerMapping;
86 /**
87 * Pre-aggregation window for meter events. Create-only.
88 */
89 eventTimeWindow?: BillingMeterEventTimeWindow;
90 /**
91 * How to calculate a meter event's value. Create-only. Defaults to
92 * `{ eventPayloadKey: "value" }`.
93 */
94 valueSettings?: BillingMeterValueSettings;
95 /**
96 * Whether the meter accepts events and can attach to a price.
97 * @default "active"
98 */
99 status?: BillingMeterStatus;
100 }
101
102 export type BillingMeter = Resource<
103 "Stripe.BillingMeter",
104 BillingMeterProps,
105 {
106 /** Stripe billing meter id (`mtr_…`). */
107 id: string;
108 /** The meter's name. Not visible to the customer. */
109 displayName: string;
110 /** Name of the meter event used to record usage. */
111 eventName: string;
112 /** How events are aggregated over a billing period. */
113 defaultAggregation: BillingMeterDefaultAggregation;
114 /** How a meter event is mapped to a customer. */
115 customerMapping: BillingMeterCustomerMapping;
116 /** Pre-aggregation window for meter events, if any. */
117 eventTimeWindow: BillingMeterEventTimeWindow | undefined;
118 /** How to calculate a meter event's value. */
119 valueSettings: BillingMeterValueSettings;
120 /** Whether the meter accepts events and can attach to a price. */
121 status: BillingMeterStatus;
122 /** Unix timestamp when the meter was created. */
123 created: number;
124 /** Unix timestamp when the meter was last updated. */
125 updated: number;
126 /** Whether the meter exists in live mode. */
127 livemode: boolean;
128 },
129 never,
130 Providers
131 >;
132
133 /**
134 * A Stripe Billing Meter — how usage events are aggregated over a billing
135 * period for usage-based prices. `eventName`, `defaultAggregation`,
136 * `customerMapping`, `eventTimeWindow`, and `valueSettings` are immutable.
137 * Changing `eventName` replaces the meter. Display name updates in place;
138 * `status` is changed with Stripe's activate/deactivate endpoints.
139 *
140 * Billing meters have no metadata field and cannot be hard-deleted.
141 * Destroying this resource deactivates the meter. Deactivated meters
142 * still occupy their `eventName`, so a later deploy with the same event
143 * name reactivates the existing meter.
144 *
145 * @see https://docs.stripe.com/api/billing/meter
146 *
147 * ### Creating a Billing Meter
148 * **Example:** Sum aggregation
149 * ```typescript
150 * const apiCalls = yield* Stripe.BillingMeter("api-calls", {
151 * displayName: "API Calls",
152 * eventName: "api_call",
153 * defaultAggregation: { formula: "sum" },
154 * });
155 * ```
156 *
157 * **Example:** Count with custom value key
158 * ```typescript
159 * const tokens = yield* Stripe.BillingMeter("tokens", {
160 * displayName: "Tokens",
161 * eventName: "token_used",
162 * defaultAggregation: { formula: "count" },
163 * valueSettings: { eventPayloadKey: "tokens" },
164 * customerMapping: {
165 * type: "by_id",
166 * eventPayloadKey: "stripe_customer_id",
167 * },
168 * });
169 * ```
170 *
171 * ### Updating a Billing Meter
172 * **Example:** Rename the meter
173 * ```typescript
174 * const apiCalls = yield* Stripe.BillingMeter("api-calls", {
175 * displayName: "API Calls (updated)",
176 * eventName: "api_call",
177 * defaultAggregation: { formula: "sum" },
178 * });
179 * ```
180 *
181 * ### Deactivating a Billing Meter
182 * **Example:** Destroy deactivates rather than deleting
183 * ```typescript
184 * // stack.destroy() / resource removal calls deactivate
185 * const apiCalls = yield* Stripe.BillingMeter("api-calls", {
186 * displayName: "API Calls",
187 * eventName: "api_call",
188 * defaultAggregation: { formula: "sum" },
189 * });
190 * ```
191 *
192 * @resource
193 * @product Billing
194 */
195 export const BillingMeter = Resource<BillingMeter>("Stripe.BillingMeter");
196
197 export class BillingMeterNotResolved extends Data.TaggedError("Stripe.BillingMeterNotResolved")<{
198 eventName: string;
199 }> {}
200
201 type BillingMeterAttributes = BillingMeter["Attributes"];
202
203 const toDisplayName = (id: string, displayName: string | undefined, existing?: string) =>
204 Effect.gen(function* () {
205 return (
206 displayName ??
207 existing ??
208 (yield* createPhysicalName({ id, maxLength: DISPLAY_NAME_MAX_LENGTH }))
209 );
210 });
211
212 const toEventName = (id: string, eventName: string | undefined, existing?: string) =>
213 Effect.gen(function* () {
214 return (
215 eventName ??
216 existing ??
217 (yield* createPhysicalName({
218 id,
219 maxLength: EVENT_NAME_MAX_LENGTH,
220 lowercase: true,
221 delimiter: "_",
222 }))
223 );
224 });
225
226 const toAttrs = (meter: StripeBillingMeter): BillingMeterAttributes => ({
227 id: meter.id,
228 displayName: meter.display_name,
229 eventName: meter.event_name,
230 defaultAggregation: { formula: meter.default_aggregation.formula },
231 customerMapping: {
232 eventPayloadKey: meter.customer_mapping.event_payload_key,
233 type: meter.customer_mapping.type,
234 },
235 eventTimeWindow: meter.event_time_window ?? undefined,
236 valueSettings: {
237 eventPayloadKey: meter.value_settings.event_payload_key,
238 },
239 status: meter.status,
240 created: meter.created,
241 updated: meter.updated,
242 livemode: meter.livemode,
243 });
244
245 const isMissingMeter = isMissingStripeResource;
246
247 const getById = (id: string) =>
248 GetBillingMeter({ id }).pipe(Effect.catchIf(isMissingMeter, () => Effect.undefined));
249
250 const listByStatus = Effect.fn(function* (status: BillingMeterStatus) {
251 const meters: StripeBillingMeter[] = [];
252 let startingAfter: string | undefined;
253 for (let page = 0; page < LIST_MAX_PAGES; page++) {
254 const response = yield* GetBillingMeters({
255 status,
256 limit: LIST_PAGE_SIZE,
257 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
258 });
259 meters.push(...response.data);
260 if (!response.has_more || response.data.length === 0) {
261 break;
262 }
263 startingAfter = response.data[response.data.length - 1]?.id;
264 if (startingAfter === undefined) {
265 break;
266 }
267 }
268 return meters;
269 });
270
271 const listAllMeters = Effect.fn(function* () {
272 const [active, inactive] = yield* Effect.all([listByStatus("active"), listByStatus("inactive")], {
273 concurrency: 2,
274 });
275 const seen = new Set<string>();
276 const meters: StripeBillingMeter[] = [];
277 for (const meter of [...active, ...inactive]) {
278 if (seen.has(meter.id)) continue;
279 seen.add(meter.id);
280 meters.push(meter);
281 }
282 return meters;
283 });
284
285 const findByEventName = Effect.fn(function* (eventName: string) {
286 const meters = yield* listAllMeters();
287 const matches = meters.filter((meter) => meter.event_name === eventName);
288 matches.sort((a, b) => b.created - a.created);
289 return matches[0];
290 });
291
292 const observe = Effect.fn(function* (input: { id?: string; eventName?: string }) {
293 if (input.id !== undefined) {
294 const byId = yield* getById(input.id);
295 if (byId !== undefined) return byId;
296 }
297 if (input.eventName !== undefined) {
298 return yield* findByEventName(input.eventName);
299 }
300 return undefined;
301 });
302
303 const shouldReplace = (
304 news: BillingMeterProps,
305 output: BillingMeterAttributes | undefined,
306 ): boolean => {
307 if (output === undefined) return false;
308 if (news.eventName !== undefined && news.eventName !== output.eventName) {
309 return true;
310 }
311 return false;
312 };
313
314 export const BillingMeterProvider = () =>
315 Provider.succeed(BillingMeter, {
316 stables: [
317 "id",
318 "eventName",
319 "defaultAggregation",
320 "customerMapping",
321 "eventTimeWindow",
322 "valueSettings",
323 "created",
324 "livemode",
325 ],
326
327 diff: Effect.fn(function* ({ news, output }) {
328 if (!isResolved(news)) return undefined;
329 if (shouldReplace(news, output)) {
330 return { action: "replace" } as const;
331 }
332 return undefined;
333 }),
334
335 read: Effect.fn(function* ({ output }) {
336 const existing = yield* observe({
337 id: output?.id,
338 eventName: output?.eventName,
339 });
340 if (existing === undefined) return undefined;
341 // Billing meters have no metadata. Identity is the Stripe id and the
342 // unique event_name; a match is treated as owned.
343 return toAttrs(existing);
344 }),
345
346 list: Effect.fn(function* () {
347 // No metadata on this resource. Default list is active meters;
348 // deactivated rows stay in Stripe (event_name remains reserved) but
349 // must not re-enter nuke.
350 const meters = yield* listByStatus("active");
351 return meters.map(toAttrs);
352 }),
353
354 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
355 const displayName = yield* toDisplayName(id, news.displayName, output?.displayName);
356 const eventName = yield* toEventName(id, news.eventName, output?.eventName);
357 const desiredStatus = news.status ?? "active";
358
359 let current = yield* observe({
360 id: output?.id,
361 eventName,
362 });
363 if (current !== undefined && shouldReplace(news, toAttrs(current))) {
364 current = undefined;
365 }
366
367 if (current === undefined) {
368 current = yield* CreateBillingMeter({
369 display_name: displayName,
370 event_name: eventName,
371 default_aggregation: { formula: news.defaultAggregation.formula },
372 ...(news.customerMapping !== undefined
373 ? {
374 customer_mapping: {
375 event_payload_key: news.customerMapping.eventPayloadKey,
376 type: news.customerMapping.type ?? "by_id",
377 },
378 }
379 : {}),
380 ...(news.eventTimeWindow !== undefined
381 ? { event_time_window: news.eventTimeWindow }
382 : {}),
383 ...(news.valueSettings !== undefined
384 ? {
385 value_settings: {
386 event_payload_key: news.valueSettings.eventPayloadKey,
387 },
388 }
389 : {}),
390 }).pipe(
391 withRequestOptions({
392 idempotencyKey: `alchemy-billing-meter-${instanceId}`,
393 }),
394 );
395 }
396
397 if (current === undefined) {
398 return yield* new BillingMeterNotResolved({ eventName });
399 }
400
401 const displayNameChanged = current.display_name !== displayName;
402 if (displayNameChanged) {
403 current = yield* UpdateBillingMeter({
404 id: current.id,
405 display_name: displayName,
406 });
407 }
408
409 if (current.status !== desiredStatus) {
410 current =
411 desiredStatus === "inactive"
412 ? yield* CreateBillingMeterDeactivate({ id: current.id })
413 : yield* CreateBillingMeterReactivate({ id: current.id });
414 }
415
416 return toAttrs(current);
417 }),
418
419 delete: Effect.fn(function* ({ output }) {
420 const existing = yield* getById(output.id);
421 if (existing === undefined || existing.status === "inactive") return;
422 yield* CreateBillingMeterDeactivate({ id: existing.id }).pipe(
423 Effect.catchIf(isMissingMeter, () => Effect.void),
424 );
425 }),
426 });