@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, 04:45 UTC

main
ts 195 lines 6.68 KB
Raw
1 import { createPhysicalName } from "alchemy/PhysicalName";
2 import { createInternalTags, diffTags, hasTags, type Tags } from "alchemy/Tags";
3 import * as Effect from "effect/Effect";
4
5 /**
6 * Fly App has no labels. Ownership is stamped onto Machine
7 * `config.metadata` (and encoded into Volume/Secret names) as
8 * `alchemy.stack` / `alchemy.stage` / `alchemy.id`.
9 *
10 * Names here are Fly-prefixed so `export *` from this module does not
11 * collide with Hetzner Labels or `alchemy/src/Ref.ts`.
12 */
13 export const ALCHEMY_METADATA_PREFIX = "alchemy.";
14
15 export const alchemyMetadataKeys = {
16 stack: "alchemy.stack",
17 stage: "alchemy.stage",
18 id: "alchemy.id",
19 type: "alchemy.type",
20 replica: "alchemy.replica",
21 instance: "alchemy.instance",
22 fqn: "alchemy.fqn",
23 baseName: "alchemy.base-name",
24 generation: "alchemy.generation",
25 workload: "alchemy.workload",
26 sequence: "alchemy.sequence",
27 count: "alchemy.count",
28 image: "alchemy.image",
29 containerImageSet: "alchemy.container-image-set",
30 phase: "alchemy.phase",
31 protocol: "alchemy.deployment-protocol",
32 roles: "alchemy.readiness-roles",
33 role: "alchemy.readiness-role",
34 predecessors: "alchemy.predecessors",
35 restored: "alchemy.idle-policy-restored",
36 checkedInstance: "alchemy.checked-instance",
37 secretsVersion: "alchemy.min-secrets-version",
38 } as const;
39
40 export type FlyAlchemyType = "Fly.Machine" | "Fly.Service";
41
42 const TAG_PREFIX = "alchemy::";
43
44 export const toMetadataKey = (tagKey: string): string =>
45 tagKey.startsWith(TAG_PREFIX)
46 ? `${ALCHEMY_METADATA_PREFIX}${tagKey.slice(TAG_PREFIX.length)}`
47 : tagKey;
48
49 export const toTagKeyFromMetadata = (metadataKey: string): string =>
50 metadataKey.startsWith(ALCHEMY_METADATA_PREFIX)
51 ? `${TAG_PREFIX}${metadataKey.slice(ALCHEMY_METADATA_PREFIX.length)}`
52 : metadataKey;
53
54 export const toMachineMetadata = (
55 tags: Record<string, string> | null | undefined,
56 ): Record<string, string> =>
57 Object.fromEntries(Object.entries(tags ?? {}).map(([key, value]) => [toMetadataKey(key), value]));
58
59 export const fromMachineMetadata = (
60 metadata: Record<string, string> | null | undefined,
61 ): Record<string, string> =>
62 Object.fromEntries(
63 Object.entries(metadata ?? {}).map(([key, value]) => [toTagKeyFromMetadata(key), value]),
64 );
65
66 export const createInternalMetadata = Effect.fn(function* (id: string) {
67 return toMachineMetadata(yield* createInternalTags(id));
68 });
69
70 /**
71 * Stamp alchemy ownership plus `alchemy.type` onto Machine config.metadata.
72 */
73 export const createMachineMetadata = Effect.fn(function* (id: string, type: FlyAlchemyType) {
74 return {
75 ...(yield* createInternalMetadata(id)),
76 [alchemyMetadataKeys.type]: type,
77 };
78 });
79
80 export const stripInternalMetadata = (
81 metadata: Record<string, string> | null | undefined,
82 ): Record<string, string> =>
83 Object.fromEntries(
84 Object.entries(metadata ?? {}).filter(([key]) => !key.startsWith(ALCHEMY_METADATA_PREFIX)),
85 );
86
87 export const hasAlchemyMetadata = Effect.fn(function* (id: string, metadata: Tags | undefined) {
88 const expected = yield* createInternalMetadata(id);
89 return hasTags(expected, metadata);
90 });
91
92 /** True when observed Machine metadata was stamped by Alchemy. */
93 export const isAlchemyOwnedMetadata = (
94 metadata: Record<string, string | undefined> | null | undefined,
95 ): boolean => {
96 const stack = metadata?.[alchemyMetadataKeys.stack];
97 return stack !== undefined && stack.length > 0;
98 };
99
100 /**
101 * Diff observed Machine metadata against desired. Always pass **observed**
102 * cloud metadata as `oldMetadata` — never `olds.metadata` or
103 * `output.metadata` — so adoption converges.
104 */
105 export const diffMachineMetadata = diffTags;
106
107 /**
108 * Fly App names: `createPhysicalName({ lowercase: true, maxLength: 30 })`,
109 * then force a leading letter (`f` prefix if needed). Globally unique.
110 */
111 export const createFlyAppName = Effect.fn(function* (id: string) {
112 const raw = yield* createPhysicalName({
113 id,
114 lowercase: true,
115 maxLength: 30,
116 });
117 return /^[a-z]/.test(raw) ? raw : `f${raw}`.slice(0, 30);
118 });
119
120 /**
121 * Volume / Secret / SecretKey physical names use the same shape as App
122 * names so `list()` can recognize alchemy-owned rows without labels.
123 *
124 * Fly Volume names reject hyphens (`[a-z0-9_]`, max 30). Use
125 * {@link createFlyVolumeName} for Volumes.
126 */
127 export const createFlyResourceName = createFlyAppName;
128
129 /**
130 * Fly Volume names: same physical-name shape as App, but underscore
131 * delimited. Fly rejects hyphens (`[a-z0-9_]`, max 30).
132 */
133 export const createFlyVolumeName = Effect.fn(function* (id: string) {
134 const raw = yield* createPhysicalName({
135 id,
136 lowercase: true,
137 maxLength: 30,
138 delimiter: "_",
139 });
140 // createPhysicalName keeps hyphens in the stack/stage prefix; Fly
141 // Volume names only allow [a-z0-9_].
142 return sanitizeFlyVolumeName(raw);
143 });
144
145 /**
146 * Sanitize a user-supplied Fly App / Volume / Secret name: lowercase,
147 * DNS-compatible (`[a-z0-9-]`), force a leading letter, max 30 chars.
148 */
149 export const sanitizeFlyAppName = (name: string): string => {
150 const lowered = name
151 .toLowerCase()
152 .replace(/[^a-z0-9-]+/g, "-")
153 .replace(/-+/g, "-")
154 .replace(/^-+|-+$/g, "");
155 const clipped = lowered.length > 30 ? lowered.slice(0, 30).replace(/-+$/g, "") : lowered;
156 const raw = clipped.length === 0 ? "f" : clipped;
157 return /^[a-z]/.test(raw) ? raw : `f${raw}`.slice(0, 30);
158 };
159
160 /**
161 * Sanitize a user-supplied Fly Volume name: lowercase alphanumeric and
162 * underscores only, force a leading letter, max 30 chars.
163 */
164 export const sanitizeFlyVolumeName = (name: string): string => {
165 const lowered = name
166 .toLowerCase()
167 .replace(/[^a-z0-9_]+/g, "_")
168 .replace(/_+/g, "_")
169 .replace(/^_+|_+$/g, "");
170 const clipped = lowered.length > 30 ? lowered.slice(0, 30).replace(/_+$/g, "") : lowered;
171 const raw = clipped.length === 0 ? "f" : clipped;
172 return /^[a-z]/.test(raw) ? raw : `f${raw}`.slice(0, 30);
173 };
174
175 /**
176 * True when `name` matches the `createPhysicalName` + leading-letter shape
177 * used for alchemy-owned Fly Apps / Volumes / Secrets / SecretKeys.
178 *
179 * Untruncated names end with a hyphen (App) or underscore (Volume) plus
180 * an 8–16 char RFC4648 base32 instance suffix. Truncated 30-char names
181 * keep that suffix (the human prefix is what gets cut).
182 */
183 export const matchesAlchemyPhysicalName = (name: string | undefined): boolean => {
184 if (name === undefined || name.length === 0 || name.length > 30) {
185 return false;
186 }
187 if (!/^[a-z][a-z0-9_-]*$/.test(name)) return false;
188 const parts = name.split(/[-_]/);
189 const last = parts.at(-1) ?? "";
190 if (parts.length >= 2 && last.length >= 8 && last.length <= 16 && /^[a-z2-7]+$/.test(last)) {
191 return true;
192 }
193 const compact = name.replaceAll("-", "").replaceAll("_", "");
194 return name.length === 30 && /[a-z2-7]{16}$/.test(compact);
195 };