@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 198 lines 7.87 KB
Raw
1 import * as Neon from "@distilled.cloud/neon";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import type { Providers } from "./Providers.ts";
9
10 export interface OrganizationSpendingLimitProps {
11 /** Existing Neon organization ID. Restore and remove this control before changing organizations. */
12 orgId: string;
13 /** Positive integer monthly alert threshold in cents; zero and null are not supported. */
14 spendingLimitCents: number;
15 }
16
17 export interface OrganizationSpendingLimitAttributes {
18 /** Organization whose billing alert is managed. */
19 orgId: string;
20 /** Observed monthly threshold in cents, or null when no threshold is configured. */
21 spendingLimitCents: number | null;
22 /** Original threshold captured before adoption; null means Alchemy created the threshold. */
23 initialSpendingLimitCents: number | null;
24 /** Last managed threshold, retained across refreshes to detect external changes on destroy. */
25 managedSpendingLimitCents: number | null;
26 }
27
28 export interface OrganizationSpendingLimit extends Resource<
29 "Neon.OrganizationSpendingLimit",
30 OrganizationSpendingLimitProps,
31 OrganizationSpendingLimitAttributes,
32 never,
33 Providers
34 > {}
35
36 /**
37 * Manage an ALERT-ONLY monthly spending threshold on an existing organization.
38 * Neon emails at 80% and 100%; reaching the threshold NEVER stops compute or
39 * enforces a hard budget. Requires an organization admin on Launch or Scale.
40 * This resource does not create or delete organizations.
41 *
42 * Existing thresholds require explicit, preferably resource-scoped adoption.
43 * The engine durably captures the original threshold, including an absent
44 * (null) threshold, before the first write; destroy restores it. A newly created
45 * threshold is removed on destroy. All initial props must resolve during
46 * planning so that this snapshot can be persisted before reconciliation.
47 * Initial unresolved props or missing snapshots fail safely without mutation;
48 * first deploy with resolved values, then update using dependent values.
49 * Restore and remove this control before targeting another organization.
50 * Replacement generations without a snapshot also fail safely; use a new
51 * logical ID to plan a baseline for another organization before managing it.
52 * Cleanup refuses external drift rather than overwriting somebody else's policy.
53 * Keep the state store: losing it loses the ownership and restoration record.
54 * The API has no conditional writes; serialize management of each organization.
55 *
56 * ### Set a billing alert
57 * **Example:** Adopt only this organization's existing threshold
58 * ```typescript
59 * const alert = yield* Neon.OrganizationSpendingLimit("BillingAlert", {
60 * orgId: "org-example-12345678",
61 * spendingLimitCents: 10000,
62 * }).pipe(Alchemy.adopt(true));
63 * ```
64 *
65 * @resource
66 * @product Organization
67 */
68 export const OrganizationSpendingLimit = Resource<OrganizationSpendingLimit>(
69 "Neon.OrganizationSpendingLimit",
70 );
71
72 export class InvalidOrganizationSpendingLimit extends Data.TaggedError(
73 "InvalidOrganizationSpendingLimit",
74 )<{
75 /** Invalid configuration or unsafe cleanup condition. */
76 message: string;
77 }> {}
78
79 /** @internal */
80 export const validateOrganizationSpendingLimit = (props: OrganizationSpendingLimitProps) =>
81 /^[a-z0-9-]{1,60}$/.test(props.orgId) &&
82 Number.isSafeInteger(props.spendingLimitCents) &&
83 props.spendingLimitCents > 0
84 ? Effect.void
85 : Effect.fail(
86 new InvalidOrganizationSpendingLimit({
87 message: "An organization ID and a positive safe integer threshold in cents are required",
88 }),
89 );
90
91 const observe = (orgId: string) =>
92 Neon.getOrganizationSpendingLimit({ org_id: orgId }).pipe(
93 Effect.map((value) => value.spending_limit_cents),
94 );
95
96 /** Preserve the original baseline and last managed value across refreshes. @internal */
97 export const organizationSpendingLimitSnapshot = (
98 orgId: string,
99 spendingLimitCents: number | null,
100 output?: OrganizationSpendingLimitAttributes,
101 ): OrganizationSpendingLimitAttributes => {
102 if (output) return { ...output, spendingLimitCents };
103 const snapshot = {
104 orgId,
105 spendingLimitCents,
106 initialSpendingLimitCents: spendingLimitCents,
107 managedSpendingLimitCents: spendingLimitCents,
108 };
109 return spendingLimitCents === null ? snapshot : Unowned(snapshot);
110 };
111
112 export const OrganizationSpendingLimitProvider = () =>
113 Provider.succeed(OrganizationSpendingLimit, {
114 nuke: { singleton: true },
115 stables: ["orgId", "initialSpendingLimitCents"],
116 diff: Effect.fn(function* ({ olds, news, output }) {
117 if (!isResolved(news)) return;
118 if (news.orgId !== (output?.orgId ?? olds.orgId)) {
119 return yield* new InvalidOrganizationSpendingLimit({
120 message:
121 "Restore and remove the existing spending control before changing organizations; the new organization requires a separately persisted baseline",
122 });
123 }
124 yield* validateOrganizationSpendingLimit(news);
125 if ((yield* observe(news.orgId)) !== news.spendingLimitCents) {
126 return { action: "update" } as const;
127 }
128 }),
129 read: Effect.fn(function* ({ olds, output }) {
130 const orgId = output?.orgId ?? olds?.orgId;
131 if (!orgId) return;
132 const value = yield* observe(orgId);
133 return organizationSpendingLimitSnapshot(orgId, value, output);
134 }),
135 reconcile: Effect.fn(function* ({ news, output, olds }) {
136 yield* validateOrganizationSpendingLimit(news);
137 if (
138 !output ||
139 output.initialSpendingLimitCents === undefined ||
140 output.managedSpendingLimitCents === undefined
141 ) {
142 return yield* new InvalidOrganizationSpendingLimit({
143 message:
144 "A persisted spending baseline is required before mutation; resolve all initial props during planning",
145 });
146 }
147 if (output.orgId !== news.orgId) {
148 return yield* new InvalidOrganizationSpendingLimit({
149 message: "Organization identity changed without replacement",
150 });
151 }
152 const observed = yield* observe(news.orgId);
153 if (
154 !olds &&
155 observed !== output.managedSpendingLimitCents &&
156 observed !== news.spendingLimitCents
157 ) {
158 return yield* new InvalidOrganizationSpendingLimit({
159 message: "Spending threshold changed since its adoption baseline was captured",
160 });
161 }
162 if (observed !== news.spendingLimitCents) {
163 yield* Neon.setOrganizationSpendingLimit({
164 org_id: news.orgId,
165 spending_limit_cents: news.spendingLimitCents,
166 });
167 }
168 const value = yield* observe(news.orgId);
169 if (value !== news.spendingLimitCents) {
170 return yield* new InvalidOrganizationSpendingLimit({
171 message: "Spending threshold changed during reconciliation",
172 });
173 }
174 return {
175 orgId: news.orgId,
176 spendingLimitCents: value,
177 initialSpendingLimitCents: output.initialSpendingLimitCents,
178 managedSpendingLimitCents: news.spendingLimitCents,
179 };
180 }),
181 delete: Effect.fn(function* ({ output, olds }) {
182 const observed = yield* observe(output.orgId);
183 if (observed === output.initialSpendingLimitCents) return;
184 if (observed !== output.managedSpendingLimitCents && observed !== olds.spendingLimitCents) {
185 return yield* new InvalidOrganizationSpendingLimit({
186 message: "Refusing to overwrite an externally changed spending threshold during cleanup",
187 });
188 }
189 if (output.initialSpendingLimitCents === null) {
190 yield* Neon.deleteOrganizationSpendingLimit({ org_id: output.orgId });
191 } else {
192 yield* Neon.setOrganizationSpendingLimit({
193 org_id: output.orgId,
194 spending_limit_cents: output.initialSpendingLimitCents,
195 });
196 }
197 }),
198 });