@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 130 lines 5.19 KB
Raw
1 /**
2 * Releasing a Web Function's egress network connector once nothing serves
3 * through it. Shared by `AWS.Lambda.WebFunction` (its built-in endpoint) and
4 * `AWS.Lambda.WebFunctionEndpoint`: whichever endpoint moves off the last
5 * revision that used the connector cleans it up in the same deploy.
6 *
7 * NOT exported from `index.ts`.
8 */
9 import * as iam from "@distilled.cloud/aws/iam";
10 import * as lambdacore from "@distilled.cloud/aws/lambda-core";
11 import * as LambdaWeb from "@distilled.cloud/aws/lambda-web";
12 import type { ScopedPlanStatusSession } from "alchemy/Report";
13 import * as Effect from "effect/Effect";
14 import * as Schedule from "effect/Schedule";
15 import * as Stream from "effect/Stream";
16 import { getConnector, waitForDeleted } from "./NetworkConnectorLifecycle.ts";
17
18 /** Inline policy on the egress operator role. */
19 export const EGRESS_POLICY = "AlchemyWebFunctionEgress";
20
21 /** `arn:…:network-connector:<id>:<version>` → `arn:…:network-connector:<id>`. */
22 const unversioned = (connectorArn: string) => connectorArn.slice(0, connectorArn.lastIndexOf(":"));
23
24 /** Whether two version-qualified ARNs name the same connector. */
25 export const sameConnector = (a: string | undefined, b: string | undefined) =>
26 a !== undefined && b !== undefined && unversioned(a) === unversioned(b);
27
28 /** The connector a revision routes egress through, if any. */
29 export const connectorOfRevision = (functionName: string, revisionId: string) =>
30 LambdaWeb.getWebFunctionRevision({ functionName, revisionId }).pipe(
31 Effect.map((revision) => revision.serviceConfig.egressNetworkConnectorArn),
32 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
33 );
34
35 /**
36 * Delete the operator role Alchemy created for a connector: same name as the
37 * connector, with the egress inline policy.
38 */
39 export const deleteOperatorRole = (roleName: string) =>
40 Effect.gen(function* () {
41 yield* iam
42 .deleteRolePolicy({ RoleName: roleName, PolicyName: EGRESS_POLICY })
43 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
44 yield* iam.deleteRole({ RoleName: roleName }).pipe(
45 Effect.catchTag("NoSuchEntityException", () => Effect.void),
46 Effect.retry({
47 while: (e) =>
48 e._tag === "DeleteConflictException" || e._tag === "ConcurrentModificationException",
49 schedule: Schedule.spaced("2 seconds"),
50 times: 10,
51 }),
52 );
53 });
54
55 /**
56 * Delete a connector and wait until its network interfaces are gone, then
57 * its operator role (Lambda uses the role to remove the interfaces).
58 */
59 export const deleteConnectorAndRole = (connectorId: string, session: ScopedPlanStatusSession) =>
60 Effect.gen(function* () {
61 const connector = yield* getConnector(connectorId);
62 if (connector === undefined) return;
63 yield* lambdacore.deleteNetworkConnector({ Identifier: connector.Id }).pipe(
64 // Conflict: another endpoint of the same deploy is already deleting it.
65 Effect.catchTag(
66 ["ResourceNotFoundException", "ResourceConflictException"],
67 () => Effect.void,
68 ),
69 );
70 yield* waitForDeleted(connector.Id, session);
71 // Only the role Alchemy made for this connector (it shares the name).
72 const roleName = connector.OperatorRole?.split("/").pop();
73 if (roleName !== undefined && roleName === connector.Name) {
74 yield* deleteOperatorRole(roleName);
75 }
76 });
77
78 /**
79 * Release the connector a function's endpoint stopped using, once no
80 * endpoint serves a revision that references it. Unused revisions that
81 * still reference it are deleted first, as Lambda requires before a
82 * connector goes. A connector still in use is left for the endpoint that
83 * moves last.
84 */
85 export const releaseEgressConnector = Effect.fn(function* ({
86 functionName,
87 connectorArn,
88 session,
89 }: {
90 functionName: string;
91 connectorArn: string;
92 session: ScopedPlanStatusSession;
93 }) {
94 const connector = unversioned(connectorArn);
95 const references = (arn: string | undefined) =>
96 arn !== undefined && unversioned(arn) === connector;
97
98 const endpoints = yield* LambdaWeb.listWebFunctionEndpoints.items({ functionName }).pipe(
99 Stream.runCollect,
100 Effect.map((chunk) => Array.from(chunk)),
101 );
102 const served = new Set(
103 endpoints.flatMap((e) =>
104 e.revisionWeights.filter((w) => w.weight > 0).map((w) => w.revisionId),
105 ),
106 );
107 for (const revisionId of served) {
108 if (references(yield* connectorOfRevision(functionName, revisionId))) return;
109 }
110
111 const revisions = yield* LambdaWeb.listWebFunctionRevisions.items({ functionName }).pipe(
112 Stream.runCollect,
113 Effect.map((chunk) => Array.from(chunk)),
114 );
115 for (const revision of revisions) {
116 if (served.has(revision.revisionId)) continue;
117 if (references(yield* connectorOfRevision(functionName, revision.revisionId))) {
118 yield* LambdaWeb.deleteWebFunctionRevision({
119 functionName,
120 revisionId: revision.revisionId,
121 }).pipe(
122 // Conflict: started serving again in the meantime, so leave it.
123 Effect.catchTag(["ResourceNotFoundException", "ConflictException"], () => Effect.void),
124 );
125 }
126 }
127
128 yield* session.note(`Releasing unused network connector ${connector.split(":").pop()}`);
129 yield* deleteConnectorAndRole(connector.split(":").pop()!, session);
130 });