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

main
ts 185 lines 5.85 KB
Raw
1 import * as ps from "@distilled.cloud/planetscale";
2 import * as Effect from "effect/Effect";
3 import * as Schedule from "effect/Schedule";
4 import { PlanetscaleConflict, pollUntil } from "../Util.ts";
5
6 /**
7 * Available PlanetScale MySQL (Vitess) cluster sizes.
8 *
9 * `PS_*` sizes are backed by network-attached storage (NAS) and can be
10 * specified either as the short size (`"PS_10"`) or the API SKU
11 * (`"PS_10_AWS_X86"`)
12 *
13 * @see https://planetscale.com/docs/concepts/planetscale-skus
14 */
15 export type MySQLClusterSize =
16 | "PS_DEV"
17 | "PS_5"
18 | "PS_10"
19 | "PS_20"
20 | "PS_40"
21 | "PS_80"
22 | "PS_160"
23 | "PS_320"
24 | "PS_400"
25 | "PS_640"
26 | "PS_700"
27 | "PS_900"
28 | "PS_1280"
29 | "PS_1400"
30 | "PS_1800"
31 | "PS_2100"
32 | "PS_2560"
33 | "PS_2700"
34 | "PS_2800"
35 | (string & {});
36
37 /**
38 * Polls keyspaces in a branch until the named keyspace reports
39 * `resizing === false` (i.e. any in-flight resize has completed).
40 */
41 export const waitForKeyspaceReady = Effect.fn(function* (
42 organization: string,
43 database: string,
44 branch: string,
45 keyspace: string,
46 ) {
47 yield* pollUntil(
48 `keyspace "${keyspace}" not resizing`,
49 ps.listKeyspaces({ organization, database, branch }),
50 (page) => {
51 const ks = page.data.find((x) => x.name === keyspace);
52 // If keyspace is missing, treat as ready (caller will re-check)
53 return ks ? !ks.resizing : true;
54 },
55 );
56 });
57
58 /**
59 * Observes the default keyspace of a branch. The default keyspace usually
60 * shares the database's name, but a renamed database keeps its original
61 * keyspace name, so prefer the `default` flag and fall back to name
62 * matching.
63 */
64 const observeDefaultKeyspace = Effect.fn(function* (
65 organization: string,
66 database: string,
67 branch: string,
68 ) {
69 const keyspaces = yield* ps.listKeyspaces({
70 organization,
71 database,
72 branch,
73 page: 1,
74 per_page: 100,
75 });
76 return keyspaces.data.find((x) => x.default) ?? keyspaces.data.find((x) => x.name === database);
77 });
78
79 /**
80 * Observes the total replica count of a branch's default keyspace, or
81 * `undefined` when the branch or keyspace does not exist (yet).
82 */
83 export const observeDefaultKeyspaceReplicas = Effect.fn(function* (
84 organization: string,
85 database: string,
86 branch: string,
87 ) {
88 return yield* observeDefaultKeyspace(organization, database, branch).pipe(
89 Effect.map((keyspace) => keyspace?.replicas),
90 Effect.catchTag("NotFound", () => Effect.undefined),
91 );
92 });
93
94 /**
95 * Ensures the default keyspace of a MySQL production branch has the
96 * expected cluster size and (optionally) total replica count, driving
97 * PlanetScale's in-place keyspace resize lifecycle when it doesn't.
98 * Cluster sizes can only be configured on production branches. Returns
99 * the final observed keyspace.
100 */
101 export const ensureMySQLProductionBranchClusterSize = Effect.fn(function* (
102 organization: string,
103 database: string,
104 branch: string,
105 expectedClusterSize: MySQLClusterSize,
106 expectedReplicas?: number,
107 ) {
108 let keyspace = yield* observeDefaultKeyspace(organization, database, branch);
109 if (!keyspace) {
110 return yield* Effect.die(`No default keyspace found for branch ${branch}`);
111 }
112
113 yield* waitForKeyspaceReady(organization, database, branch, keyspace.name);
114
115 if (keyspace.cluster_name !== expectedClusterSize) {
116 yield* ps.updateBranchClusterConfig({
117 organization,
118 database,
119 branch,
120 cluster_size: expectedClusterSize,
121 });
122 yield* waitForKeyspaceReady(organization, database, branch, keyspace.name);
123 // Re-observe so the replica sync below diffs against the post-resize
124 // keyspace state.
125 keyspace = (yield* observeDefaultKeyspace(organization, database, branch)) ?? keyspace;
126 }
127
128 // Sync replicas — MySQL databases cannot configure replicas at
129 // creation time (the API rejects the `replicas` param for mysql), so
130 // the desired total replica count is converged in place via a keyspace
131 // resize request.
132 if (expectedReplicas !== undefined && keyspace.replicas !== expectedReplicas) {
133 // Each cluster size includes a fixed number of replicas (2 for
134 // production PS_* sizes); the resize API only accepts the count of
135 // additional replicas beyond that.
136 const includedReplicas = keyspace.replicas - keyspace.extra_replicas;
137 const extraReplicas = expectedReplicas - includedReplicas;
138 if (extraReplicas < 0) {
139 return yield* new PlanetscaleConflict({
140 message:
141 `Cannot set replicas to ${expectedReplicas} on keyspace "${keyspace.name}": ` +
142 `cluster size ${keyspace.cluster_name} always includes ${includedReplicas} replicas. ` +
143 `Set replicas to ${includedReplicas} or more (or omit it).`,
144 });
145 }
146
147 const resize = yield* ps
148 .updateKeyspaceResizeRequest({
149 organization,
150 database,
151 branch,
152 keyspace: keyspace.name,
153 extra_replicas: extraReplicas,
154 })
155 .pipe(
156 // A prior resize (e.g. the cluster-size change above) can still
157 // be finalizing after the keyspace reports `resizing: false`;
158 // PlanetScale rejects new resize requests during that window.
159 Effect.retry({
160 while: (e): boolean =>
161 e._tag === "UnprocessableEntity" && e.message.includes("resize in progress"),
162 schedule: Schedule.max([Schedule.spaced("5 seconds"), Schedule.recurs(120)]),
163 }),
164 );
165
166 yield* pollUntil(
167 `keyspace "${keyspace.name}" resize completed`,
168 ps.listKeyspaceResizeRequests({
169 organization,
170 database,
171 branch,
172 keyspace: keyspace.name,
173 }),
174 (page) => {
175 const request = page.data.find((r) => r.id === resize.id);
176 // If the request is missing, treat as settled (caller re-observes).
177 return request ? request.state === "completed" : true;
178 },
179 );
180
181 keyspace = (yield* observeDefaultKeyspace(organization, database, branch)) ?? keyspace;
182 }
183
184 return keyspace;
185 });