@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 421 lines 12.7 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 GetBillingAlerts,
4 GetBillingAlert,
5 CreateBillingAlert,
6 CreateBillingAlertActivate,
7 CreateBillingAlertArchive,
8 CreateBillingAlertDeactivate,
9 type BillingAlert as StripeBillingAlert,
10 type ThresholdsResourceUsageAlertFilterCustomer,
11 type ThresholdsResourceUsageThresholdConfig,
12 type ThresholdsResourceUsageThresholdConfigMeter,
13 } from "@distilled.cloud/stripe/stripe";
14 import { isResolved } from "alchemy/Diff";
15 import { createPhysicalName } from "alchemy/PhysicalName";
16 import * as Provider from "alchemy/Provider";
17 import { Resource } from "alchemy/Resource";
18 import * as Data from "effect/Data";
19 import * as Effect from "effect/Effect";
20 import { isMissingStripeResource } from "./missing.ts";
21 import type { Providers } from "./Providers.ts";
22
23 const TITLE_MAX_LENGTH = 256;
24 const LIST_PAGE_SIZE = 100;
25 const LIST_MAX_PAGES = 100;
26
27 /** The type of billing alert. Currently only usage-threshold alerts. */
28 export type AlertType = "usage_threshold";
29
30 /** Status of a billing alert. Archived alerts cannot be reactivated. */
31 export type AlertStatus = "active" | "archived" | "inactive";
32
33 /** Desired status for a managed alert. Archived is delete-only. */
34 export type AlertDesiredStatus = "active" | "inactive";
35
36 /** How a usage-threshold alert fires. */
37 export type AlertRecurrence = "one_time";
38
39 /** Restricts a usage-threshold alert to a single customer. */
40 export interface AlertUsageThresholdFilter {
41 /**
42 * Filter kind. Must be `customer`.
43 */
44 type: "customer";
45 /**
46 * Stripe Customer id (`cus_…`) this alert is limited to.
47 */
48 customer?: string;
49 }
50
51 /** Configuration for a usage-threshold billing alert. Create-only. */
52 export interface AlertUsageThreshold {
53 /**
54 * Usage value at which the alert fires. Create-only — changing it
55 * replaces the alert.
56 */
57 gte: number;
58 /**
59 * Id of the Billing Meter whose usage is monitored (`mtr_…`).
60 * Create-only — changing it replaces the alert.
61 */
62 meter: string;
63 /**
64 * How the alert behaves after firing.
65 * @default "one_time"
66 */
67 recurrence?: AlertRecurrence;
68 /**
69 * Optional filters that limit the alert's scope. Stripe currently
70 * accepts at most one `customer` filter. Create-only.
71 */
72 filters?: AlertUsageThresholdFilter[];
73 }
74
75 export interface AlertProps {
76 /**
77 * Title of the alert. If omitted, a unique title is generated from the
78 * stack, stage, and logical id. Create-only — changing it replaces the
79 * alert. Max 256 characters.
80 */
81 title?: string;
82 /**
83 * Type of alert to create.
84 * @default "usage_threshold"
85 */
86 alertType?: AlertType;
87 /**
88 * Usage-threshold configuration. Create-only — changing `gte`, `meter`,
89 * `recurrence`, or `filters` replaces the alert.
90 */
91 usageThreshold: AlertUsageThreshold;
92 /**
93 * Whether the alert can fire. `inactive` deactivates in place (and can
94 * be reactivated). Destroy archives the alert (irreversible).
95 * @default "active"
96 */
97 status?: AlertDesiredStatus;
98 }
99
100 export type Alert = Resource<
101 "Stripe.Alert",
102 AlertProps,
103 {
104 /** Stripe billing alert id (`alrt_…`). */
105 id: string;
106 /** Title of the alert. */
107 title: string;
108 /** Type of the alert. */
109 alertType: AlertType;
110 /** Status of the alert. */
111 status: AlertStatus;
112 /** Usage-threshold configuration, if set. */
113 usageThreshold: AlertUsageThreshold | undefined;
114 /** Whether the alert exists in live mode. */
115 livemode: boolean;
116 },
117 never,
118 Providers
119 >;
120
121 /**
122 * A Stripe Billing Alert — notifies you when a usage threshold on a
123 * [Billing Meter](https://docs.stripe.com/api/billing/meter) is crossed.
124 * `title`, `alertType`, and `usageThreshold` are immutable; changing them
125 * replaces the alert. `status` is changed with Stripe's activate/deactivate
126 * endpoints.
127 *
128 * Billing alerts have no metadata field and cannot be hard-deleted.
129 * Destroying this resource archives the alert (irreversible). Archived
130 * alerts leave the list API and cannot be reactivated.
131 *
132 * @see https://docs.stripe.com/api/billing/alert
133 *
134 * ### Creating an Alert
135 * **Example:** Usage threshold on a meter
136 * ```typescript
137 * const apiCalls = yield* Stripe.BillingMeter("api-calls", {
138 * displayName: "API Calls",
139 * eventName: "api_call",
140 * defaultAggregation: { formula: "sum" },
141 * });
142 * const highUsage = yield* Stripe.Alert("high-usage", {
143 * title: "API Request usage alert",
144 * usageThreshold: {
145 * gte: 10000,
146 * meter: apiCalls.id,
147 * recurrence: "one_time",
148 * },
149 * });
150 * ```
151 *
152 * **Example:** Limit the alert to one customer
153 * ```typescript
154 * const highUsage = yield* Stripe.Alert("high-usage", {
155 * title: "Customer API usage alert",
156 * usageThreshold: {
157 * gte: 1000,
158 * meter: apiCalls.id,
159 * recurrence: "one_time",
160 * filters: [{ type: "customer", customer: customer.id }],
161 * },
162 * });
163 * ```
164 *
165 * ### Updating an Alert
166 * **Example:** Deactivate without archiving
167 * ```typescript
168 * const highUsage = yield* Stripe.Alert("high-usage", {
169 * title: "API Request usage alert",
170 * usageThreshold: {
171 * gte: 10000,
172 * meter: apiCalls.id,
173 * recurrence: "one_time",
174 * },
175 * status: "inactive",
176 * });
177 * ```
178 *
179 * ### Archiving an Alert
180 * **Example:** Destroy archives rather than deleting
181 * ```typescript
182 * // stack.destroy() / resource removal archives the alert
183 * const highUsage = yield* Stripe.Alert("high-usage", {
184 * title: "API Request usage alert",
185 * usageThreshold: {
186 * gte: 10000,
187 * meter: apiCalls.id,
188 * recurrence: "one_time",
189 * },
190 * });
191 * ```
192 *
193 * @resource
194 * @product Billing
195 */
196 export const Alert = Resource<Alert>("Stripe.Alert");
197
198 export class AlertNotResolved extends Data.TaggedError("Stripe.AlertNotResolved")<{
199 title: string;
200 }> {}
201
202 type AlertAttributes = Alert["Attributes"];
203
204 const toTitle = (id: string, title: string | undefined, existing?: string) =>
205 Effect.gen(function* () {
206 return title ?? existing ?? (yield* createPhysicalName({ id, maxLength: TITLE_MAX_LENGTH }));
207 });
208
209 const toMeterId = (meter: ThresholdsResourceUsageThresholdConfigMeter): string =>
210 typeof meter === "string" ? meter : meter.id;
211
212 const toCustomerId = (
213 customer: ThresholdsResourceUsageAlertFilterCustomer | null,
214 ): string | undefined => {
215 if (customer == null) return undefined;
216 if (typeof customer === "string") return customer;
217 return customer.id;
218 };
219
220 const toUsageThreshold = (
221 config: ThresholdsResourceUsageThresholdConfig | null,
222 ): AlertUsageThreshold | undefined => {
223 if (config === null) return undefined;
224 const filters = (config.filters ?? []).map((filter) => {
225 const customer = toCustomerId(filter.customer);
226 return customer !== undefined ? { type: filter.type, customer } : { type: filter.type };
227 });
228 return {
229 gte: config.gte,
230 meter: toMeterId(config.meter),
231 recurrence: config.recurrence,
232 ...(filters.length > 0 ? { filters } : {}),
233 };
234 };
235
236 const toAttrs = (alert: StripeBillingAlert): AlertAttributes => ({
237 id: alert.id,
238 title: alert.title,
239 alertType: alert.alert_type,
240 status: alert.status ?? "active",
241 usageThreshold: toUsageThreshold(alert.usage_threshold),
242 livemode: alert.livemode,
243 });
244
245 const isMissingAlert = isMissingStripeResource;
246
247 const getById = (id: string) =>
248 GetBillingAlert({ id }).pipe(Effect.catchIf(isMissingAlert, () => Effect.undefined));
249
250 const listAlerts = Effect.fn(function* () {
251 const alerts: StripeBillingAlert[] = [];
252 let startingAfter: string | undefined;
253 for (let page = 0; page < LIST_MAX_PAGES; page++) {
254 const response = yield* GetBillingAlerts({
255 limit: LIST_PAGE_SIZE,
256 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
257 });
258 alerts.push(...response.data);
259 if (!response.has_more || response.data.length === 0) {
260 break;
261 }
262 startingAfter = response.data[response.data.length - 1]?.id;
263 if (startingAfter === undefined) {
264 break;
265 }
266 }
267 return alerts;
268 });
269
270 const findByTitle = Effect.fn(function* (title: string) {
271 const alerts = yield* listAlerts();
272 return alerts.find((alert) => alert.title === title);
273 });
274
275 const isArchived = (alert: StripeBillingAlert): boolean => alert.status === "archived";
276
277 const observe = Effect.fn(function* (input: { id?: string; title?: string }) {
278 if (input.id !== undefined) {
279 const byId = yield* getById(input.id);
280 if (byId !== undefined && !isArchived(byId)) return byId;
281 }
282 if (input.title !== undefined) {
283 return yield* findByTitle(input.title);
284 }
285 return undefined;
286 });
287
288 const filtersEqual = (
289 a: AlertUsageThresholdFilter[] | undefined,
290 b: AlertUsageThresholdFilter[] | undefined,
291 ): boolean => {
292 const left = a ?? [];
293 const right = b ?? [];
294 if (left.length !== right.length) return false;
295 for (let i = 0; i < left.length; i++) {
296 const other = right[i];
297 if (
298 other === undefined ||
299 left[i]?.type !== other.type ||
300 left[i]?.customer !== other.customer
301 ) {
302 return false;
303 }
304 }
305 return true;
306 };
307
308 const shouldReplace = (news: AlertProps, output: AlertAttributes | undefined): boolean => {
309 if (output === undefined) return false;
310 if (news.title !== undefined && news.title !== output.title) return true;
311 if (news.alertType !== undefined && news.alertType !== output.alertType) {
312 return true;
313 }
314 const current = output.usageThreshold;
315 if (current === undefined) return true;
316 if (news.usageThreshold.gte !== current.gte) return true;
317 if (news.usageThreshold.meter !== current.meter) return true;
318 const desiredRecurrence = news.usageThreshold.recurrence ?? "one_time";
319 if (desiredRecurrence !== current.recurrence) return true;
320 if (
321 news.usageThreshold.filters !== undefined &&
322 !filtersEqual(news.usageThreshold.filters, current.filters)
323 ) {
324 return true;
325 }
326 return false;
327 };
328
329 const toCreateUsageThreshold = (threshold: AlertUsageThreshold) => ({
330 gte: threshold.gte,
331 meter: threshold.meter,
332 recurrence: threshold.recurrence ?? "one_time",
333 ...(threshold.filters !== undefined
334 ? {
335 filters: threshold.filters.map((filter) => ({
336 type: filter.type,
337 ...(filter.customer !== undefined ? { customer: filter.customer } : {}),
338 })),
339 }
340 : {}),
341 });
342
343 export const AlertProvider = () =>
344 Provider.succeed(Alert, {
345 stables: ["id", "title", "alertType", "usageThreshold", "livemode"],
346
347 diff: Effect.fn(function* ({ news, output }) {
348 if (!isResolved(news)) return undefined;
349 if (shouldReplace(news, output)) {
350 return { action: "replace" } as const;
351 }
352 return undefined;
353 }),
354
355 read: Effect.fn(function* ({ output }) {
356 const existing = yield* observe({
357 id: output?.id,
358 title: output?.title,
359 });
360 if (existing === undefined) return undefined;
361 // Billing alerts have no metadata. Identity is the Stripe id and
362 // title; a match is treated as owned.
363 return toAttrs(existing);
364 }),
365
366 list: Effect.fn(function* () {
367 // No metadata on this resource. The list API returns active and
368 // inactive alerts; archived rows stay in Stripe but leave the list
369 // and must not re-enter nuke.
370 const alerts = yield* listAlerts();
371 return alerts.map(toAttrs);
372 }),
373
374 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
375 const title = yield* toTitle(id, news.title, output?.title);
376 const alertType = news.alertType ?? "usage_threshold";
377 const desiredStatus = news.status ?? "active";
378
379 let current = yield* observe({
380 id: output?.id,
381 title,
382 });
383 if (current !== undefined && shouldReplace(news, toAttrs(current))) {
384 current = undefined;
385 }
386
387 if (current === undefined) {
388 current = yield* CreateBillingAlert({
389 alert_type: alertType,
390 title,
391 usage_threshold: toCreateUsageThreshold(news.usageThreshold),
392 }).pipe(
393 withRequestOptions({
394 idempotencyKey: `alchemy-billing-alert-${instanceId}`,
395 }),
396 );
397 }
398
399 if (current === undefined) {
400 return yield* new AlertNotResolved({ title });
401 }
402
403 const currentStatus = current.status ?? "active";
404 if (currentStatus !== desiredStatus) {
405 current =
406 desiredStatus === "inactive"
407 ? yield* CreateBillingAlertDeactivate({ id: current.id })
408 : yield* CreateBillingAlertActivate({ id: current.id });
409 }
410
411 return toAttrs(current);
412 }),
413
414 delete: Effect.fn(function* ({ output }) {
415 const existing = yield* getById(output.id);
416 if (existing === undefined || existing.status === "archived") return;
417 yield* CreateBillingAlertArchive({ id: existing.id }).pipe(
418 Effect.catchIf(isMissingAlert, () => Effect.void),
419 );
420 }),
421 });