@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 410 lines 13.9 KB
Raw
1 import * as transfer from "@distilled.cloud/aws/transfer";
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 { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12
13 export class ServerNotReady extends Data.TaggedError("ServerNotReady")<{
14 readonly message: string;
15 readonly cause?: unknown;
16 }> {}
17
18 export class ServerUnexpectedResponse extends Data.TaggedError("ServerUnexpectedResponse")<{
19 readonly message: string;
20 readonly cause?: unknown;
21 }> {}
22
23 export interface ServerProps {
24 /**
25 * File-transfer protocols the server exposes.
26 * @default ["SFTP"]
27 */
28 protocols?: transfer.Protocol[];
29 /**
30 * Storage domain the server serves files from. Changing it replaces the
31 * server.
32 * @default "S3"
33 */
34 domain?: transfer.Domain;
35 /**
36 * Where the server endpoint is hosted. `PUBLIC` is internet-facing;
37 * `VPC` places it inside a VPC (requires `endpointDetails`).
38 * @default "PUBLIC"
39 */
40 endpointType?: transfer.EndpointType;
41 /**
42 * VPC endpoint configuration (subnets, security groups, address
43 * allocations). Required when `endpointType` is `VPC`.
44 */
45 endpointDetails?: transfer.EndpointDetails;
46 /**
47 * How users authenticate. `SERVICE_MANAGED` stores SSH keys in Transfer
48 * Family; `API_GATEWAY`/`AWS_LAMBDA`/`AWS_DIRECTORY_SERVICE` delegate to a
49 * custom identity provider. Changing it replaces the server.
50 * @default "SERVICE_MANAGED"
51 */
52 identityProviderType?: transfer.IdentityProviderType;
53 /**
54 * Configuration for a custom identity provider (required unless
55 * `identityProviderType` is `SERVICE_MANAGED`).
56 */
57 identityProviderDetails?: transfer.IdentityProviderDetails;
58 /**
59 * IAM role ARN Transfer Family assumes to publish CloudWatch logs.
60 */
61 loggingRole?: string;
62 /**
63 * Name of the security policy (cipher/algorithm set) attached to the server.
64 */
65 securityPolicyName?: string;
66 /**
67 * Banner shown to clients before authentication (SFTP/FTPS only).
68 */
69 preAuthenticationLoginBanner?: string;
70 /**
71 * Banner shown to clients after authentication.
72 */
73 postAuthenticationLoginBanner?: string;
74 /**
75 * Protocol-specific settings (passive IP, TLS session resumption, etc.).
76 */
77 protocolDetails?: transfer.ProtocolDetails;
78 /**
79 * S3 storage options such as directory-listing optimization.
80 */
81 s3StorageOptions?: transfer.S3StorageOptions;
82 /**
83 * Workflows triggered on file upload.
84 */
85 workflowDetails?: transfer.WorkflowDetails;
86 /**
87 * CloudWatch Logs log-group ARNs the server streams structured logs to.
88 */
89 structuredLogDestinations?: string[];
90 /**
91 * IP address type of the endpoint.
92 * @default "IPV4"
93 */
94 ipAddressType?: transfer.IpAddressType;
95 /**
96 * User-defined tags for the server.
97 */
98 tags?: Record<string, string>;
99 }
100
101 export interface Server extends Resource<
102 "AWS.Transfer.Server",
103 ServerProps,
104 {
105 /**
106 * AWS-assigned server ID (e.g. `s-0123456789abcdef0`). Clients connect to
107 * `{serverId}.server.transfer.{region}.amazonaws.com`.
108 */
109 serverId: string;
110 /**
111 * ARN of the server.
112 */
113 arn: string;
114 /**
115 * Where the server endpoint is hosted (`PUBLIC` or `VPC`).
116 */
117 endpointType: string;
118 /**
119 * Storage domain the server serves files from (`S3` or `EFS`).
120 */
121 domain: string;
122 /**
123 * How users authenticate.
124 */
125 identityProviderType: string;
126 /**
127 * File-transfer protocols the server exposes.
128 */
129 protocols: string[];
130 /**
131 * Current lifecycle state (e.g. `ONLINE`, `STARTING`).
132 */
133 state: string | undefined;
134 /**
135 * Current tags reported for the server.
136 */
137 tags: Record<string, string>;
138 },
139 never,
140 Providers
141 > {}
142
143 /**
144 * An AWS Transfer Family server — a managed SFTP/FTPS/FTP/AS2 endpoint in
145 * front of S3 or EFS storage. A running server is billed hourly (plus data
146 * transfer), so create it only when needed and destroy it promptly.
147 * ### Creating a Server
148 * **Example:** Public SFTP Server (Service-Managed Users)
149 * ```typescript
150 * const server = yield* Server("Sftp", {
151 * protocols: ["SFTP"],
152 * domain: "S3",
153 * endpointType: "PUBLIC",
154 * identityProviderType: "SERVICE_MANAGED",
155 * });
156 * ```
157 *
158 * ### Adding Users
159 * **Example:** SFTP Server with a Service-Managed User
160 * ```typescript
161 * const server = yield* Server("Sftp", {
162 * protocols: ["SFTP"],
163 * identityProviderType: "SERVICE_MANAGED",
164 * });
165 *
166 * // Role Transfer Family assumes to access the S3 storage backend
167 * const role = yield* AWS.IAM.Role("TransferUserRole", {
168 * assumeRolePolicyDocument: {
169 * Version: "2012-10-17",
170 * Statement: [
171 * {
172 * Effect: "Allow",
173 * Principal: { Service: "transfer.amazonaws.com" },
174 * Action: ["sts:AssumeRole"],
175 * },
176 * ],
177 * },
178 * inlinePolicies: {
179 * s3: {
180 * Version: "2012-10-17",
181 * Statement: [
182 * {
183 * Effect: "Allow",
184 * Action: ["s3:ListBucket", "s3:GetObject", "s3:PutObject"],
185 * Resource: [bucket.bucketArn, Output.interpolate`${bucket.bucketArn}/*`],
186 * },
187 * ],
188 * },
189 * },
190 * });
191 *
192 * const user = yield* User("Alice", {
193 * serverId: server.serverId,
194 * userName: "alice",
195 * role: role.roleArn,
196 * homeDirectory: Output.interpolate`/${bucket.bucketName}/alice`,
197 * sshPublicKeyBody: "ssh-ed25519 AAAA...",
198 * });
199 * ```
200 *
201 * @resource
202 */
203 export const Server = Resource<Server>("AWS.Transfer.Server");
204
205 const toTagRecord = (
206 tags: Array<{ Key?: string; Value?: string }> | undefined,
207 ): Record<string, string> =>
208 Object.fromEntries(
209 (tags ?? [])
210 .filter(
211 (tag): tag is { Key: string; Value: string } =>
212 typeof tag.Key === "string" && typeof tag.Value === "string",
213 )
214 .map((tag) => [tag.Key, tag.Value]),
215 );
216
217 export const ServerProvider = () =>
218 Provider.effect(
219 Server,
220 Effect.gen(function* () {
221 const describe = Effect.fn(function* (serverId: string) {
222 const response = yield* transfer
223 .describeServer({ ServerId: serverId })
224 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
225 return response?.Server;
226 });
227
228 const readTags = Effect.fn(function* (arn: string) {
229 const response = yield* transfer
230 .listTagsForResource({ Arn: arn })
231 .pipe(Effect.orElseSucceed(() => undefined));
232 return toTagRecord(response?.Tags);
233 });
234
235 // Servers transition through STARTING before ONLINE; updateServer and
236 // deleteServer require a settled state. Budget ~7 minutes (10s x 42).
237 const waitUntilSettled = Effect.fn(function* (serverId: string) {
238 const settlePolicy = Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(42)]);
239 return yield* describe(serverId).pipe(
240 Effect.flatMap((server) => {
241 if (
242 server !== undefined &&
243 (server.State === "STARTING" || server.State === "STOPPING")
244 ) {
245 return Effect.fail(
246 new ServerNotReady({
247 message: `Transfer server '${serverId}' still settling (state: ${server.State})`,
248 }),
249 );
250 }
251 return Effect.succeed(server);
252 }),
253 Effect.retry({ schedule: settlePolicy }),
254 );
255 });
256
257 const toAttrs = Effect.fn(function* (server: transfer.DescribedServer) {
258 if (!server.ServerId) {
259 return yield* new ServerUnexpectedResponse({
260 message: "Transfer server is missing its ServerId",
261 });
262 }
263 return {
264 serverId: server.ServerId,
265 arn: server.Arn,
266 endpointType: server.EndpointType ?? "PUBLIC",
267 domain: server.Domain ?? "S3",
268 identityProviderType: server.IdentityProviderType ?? "SERVICE_MANAGED",
269 protocols: [...(server.Protocols ?? [])],
270 state: server.State,
271 tags: yield* readTags(server.Arn),
272 };
273 });
274
275 return {
276 stables: ["serverId", "arn"],
277
278 diff: Effect.fn(function* ({ olds, news }) {
279 if (!isResolved(news)) return undefined;
280 // Domain and identity-provider type are create-only.
281 if (
282 (news.domain ?? "S3") !== (olds?.domain ?? "S3") ||
283 (news.identityProviderType ?? "SERVICE_MANAGED") !==
284 (olds?.identityProviderType ?? "SERVICE_MANAGED")
285 ) {
286 return { action: "replace" } as const;
287 }
288 }),
289
290 read: Effect.fn(function* ({ id, output }) {
291 // ServerId is AWS-assigned, so a server can only be found via a
292 // previously-persisted output (like an auto-id VPC).
293 if (!output?.serverId) return undefined;
294 const server = yield* describe(output.serverId);
295 if (!server?.ServerId) return undefined;
296 const attrs = yield* toAttrs(server);
297 return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs);
298 }),
299
300 reconcile: Effect.fn(function* ({ id, news, output, session }) {
301 const internalTags = yield* createInternalTags(id);
302 const desiredTags = { ...internalTags, ...news.tags };
303
304 // 1. Observe — cloud state is authoritative (via the id cache).
305 let serverId = output?.serverId;
306 let observed = serverId ? yield* describe(serverId) : undefined;
307
308 // 2. Ensure — create if missing.
309 if (observed === undefined) {
310 const created = yield* transfer.createServer({
311 Protocols: news.protocols ?? ["SFTP"],
312 Domain: news.domain,
313 EndpointType: news.endpointType,
314 EndpointDetails: news.endpointDetails,
315 IdentityProviderType: news.identityProviderType,
316 IdentityProviderDetails: news.identityProviderDetails,
317 LoggingRole: news.loggingRole,
318 SecurityPolicyName: news.securityPolicyName,
319 PreAuthenticationLoginBanner: news.preAuthenticationLoginBanner,
320 PostAuthenticationLoginBanner: news.postAuthenticationLoginBanner,
321 ProtocolDetails: news.protocolDetails,
322 S3StorageOptions: news.s3StorageOptions,
323 WorkflowDetails: news.workflowDetails,
324 StructuredLogDestinations: news.structuredLogDestinations,
325 IpAddressType: news.ipAddressType,
326 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
327 Key,
328 Value,
329 })),
330 });
331 serverId = created.ServerId;
332 } else {
333 // 3. Sync — push mutable configuration. updateServer requires a
334 // settled server state.
335 yield* waitUntilSettled(serverId!);
336 yield* transfer.updateServer({
337 ServerId: serverId!,
338 Protocols: news.protocols,
339 EndpointType: news.endpointType,
340 EndpointDetails: news.endpointDetails,
341 IdentityProviderDetails: news.identityProviderDetails,
342 LoggingRole: news.loggingRole,
343 SecurityPolicyName: news.securityPolicyName,
344 PreAuthenticationLoginBanner: news.preAuthenticationLoginBanner,
345 PostAuthenticationLoginBanner: news.postAuthenticationLoginBanner,
346 ProtocolDetails: news.protocolDetails,
347 S3StorageOptions: news.s3StorageOptions,
348 WorkflowDetails: news.workflowDetails,
349 StructuredLogDestinations: news.structuredLogDestinations,
350 IpAddressType: news.ipAddressType,
351 });
352 }
353
354 // Wait for the server to settle so downstream User creation and the
355 // returned state are stable.
356 observed = yield* waitUntilSettled(serverId!);
357 if (!observed?.ServerId || !observed.Arn) {
358 return yield* new ServerUnexpectedResponse({
359 message: `Transfer server '${serverId}' not found after reconcile`,
360 });
361 }
362
363 // 3b. Sync tags — diff against OBSERVED cloud tags.
364 const arn = observed.Arn;
365 const observedTags = yield* readTags(arn);
366 const { upsert, removed } = diffTags(observedTags, desiredTags);
367 if (upsert.length > 0) {
368 yield* transfer.tagResource({ Arn: arn, Tags: upsert });
369 }
370 if (removed.length > 0) {
371 yield* transfer.untagResource({ Arn: arn, TagKeys: removed });
372 }
373
374 yield* session.note(observed.ServerId);
375 return yield* toAttrs(observed);
376 }),
377
378 delete: Effect.fn(function* ({ output }) {
379 yield* transfer
380 .deleteServer({ ServerId: output.serverId })
381 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
382 }),
383
384 list: () =>
385 transfer.listServers.pages({}).pipe(
386 Stream.runCollect,
387 Effect.map((chunk) =>
388 Array.from(chunk).flatMap((page) =>
389 (page.Servers ?? []).filter((server) => server.ServerId !== undefined),
390 ),
391 ),
392 Effect.flatMap(
393 Effect.forEach(
394 (server) =>
395 toAttrs({
396 Arn: server.Arn,
397 ServerId: server.ServerId,
398 Domain: server.Domain,
399 EndpointType: server.EndpointType,
400 IdentityProviderType: server.IdentityProviderType,
401 State: server.State,
402 LoggingRole: server.LoggingRole,
403 }),
404 { concurrency: 4 },
405 ),
406 ),
407 ),
408 };
409 }),
410 );