@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 177 lines 5.36 KB
Raw
1 import type { FlyMachineService } from "@distilled.cloud/fly-io/machines";
2 import * as Data from "effect/Data";
3 import type { MachineService } from "./Machine.ts";
4
5 /** One port, or an inclusive port range, published on Fly's proxy. */
6 export interface PublishedPort {
7 protocol: string;
8 start: number;
9 end: number;
10 handlers: string[];
11 forceHttps: boolean;
12 }
13
14 export class ServicePortConflict extends Data.TaggedError("Fly.ServicePortConflict")<{
15 appName: string;
16 port: number;
17 protocol: string;
18 /** The two publishers of the port: Service logical ids or Machine ids. */
19 publishers: [string, string];
20 }> {
21 get message() {
22 return `Port ${this.port}/${this.protocol} in Fly App ${this.appName} is published by both ${this.publishers[0]} and ${this.publishers[1]}. Fly's proxy routes an App's traffic by port only, so give each Service in the App its own ports (\`services\`, or \`bindingPort\` for the plain-HTTP port Alchemy adds for bound callers).`;
23 }
24 }
25
26 const normalize = (entry: {
27 protocol?: string;
28 port?: number;
29 startPort?: number;
30 endPort?: number;
31 handlers?: string[];
32 forceHttps?: boolean;
33 }): PublishedPort[] => {
34 const start = entry.port ?? entry.startPort;
35 const end = entry.port ?? entry.endPort ?? entry.startPort;
36 if (start === undefined || end === undefined) return [];
37 return [
38 {
39 protocol: entry.protocol ?? "tcp",
40 start,
41 end,
42 handlers: entry.handlers ?? [],
43 forceHttps: entry.forceHttps === true,
44 },
45 ];
46 };
47
48 /** Published ports of observed or desired Fly Machine services. */
49 export const portsOfFly = (
50 services: readonly FlyMachineService[] | null | undefined,
51 ): PublishedPort[] =>
52 (services ?? []).flatMap((service) =>
53 (service.ports ?? []).flatMap((port) =>
54 normalize({
55 protocol: service.protocol,
56 port: port.port,
57 startPort: port.start_port,
58 endPort: port.end_port,
59 handlers: port.handlers,
60 forceHttps: port.force_https,
61 }),
62 ),
63 );
64
65 /**
66 * Published ports of a Service's `services` prop, falling back to the
67 * defaults: HTTP 80 (redirecting to HTTPS) and HTTPS 443 when public,
68 * plain HTTP 80 when private.
69 */
70 export const portsOfProps = (
71 services: readonly MachineService[] | undefined,
72 isPublic: boolean,
73 ): PublishedPort[] =>
74 services !== undefined
75 ? services.flatMap((service) =>
76 (service.ports ?? []).flatMap((port) => normalize({ protocol: service.protocol, ...port })),
77 )
78 : isPublic
79 ? [
80 {
81 protocol: "tcp",
82 start: 80,
83 end: 80,
84 handlers: ["http"],
85 forceHttps: true,
86 },
87 {
88 protocol: "tcp",
89 start: 443,
90 end: 443,
91 handlers: ["tls", "http"],
92 forceHttps: false,
93 },
94 ]
95 : [
96 {
97 protocol: "tcp",
98 start: 80,
99 end: 80,
100 handlers: ["http"],
101 forceHttps: false,
102 },
103 ];
104
105 const isPlainHttp = (port: PublishedPort) =>
106 port.start === port.end &&
107 port.protocol === "tcp" &&
108 port.handlers.includes("http") &&
109 !port.handlers.includes("tls") &&
110 !port.forceHttps;
111
112 /**
113 * The port bound callers use: the first plain-HTTP port, since Fly issues
114 * no certificate for `.flycast`. When the Service publishes ports but none
115 * of them is plain HTTP, Alchemy publishes `bindingPort` for bindings.
116 */
117 export const bindingPortOf = (
118 ports: readonly PublishedPort[],
119 bindingPort: number,
120 ): { port: number; added: boolean } | undefined => {
121 if (ports.length === 0) return undefined;
122 const others = ports.filter((port) => !(isPlainHttp(port) && port.start === bindingPort));
123 const plain = others.find(isPlainHttp);
124 if (plain !== undefined) return { port: plain.start, added: false };
125 return { port: bindingPort, added: true };
126 };
127
128 /** `ports` plus the binding port Alchemy adds, when it adds one. */
129 export const withBindingPort = (
130 ports: readonly PublishedPort[],
131 bindingPort: number,
132 ): PublishedPort[] => {
133 const binding = bindingPortOf(ports, bindingPort);
134 return binding?.added === true &&
135 !ports.some((port) => isPlainHttp(port) && port.start === bindingPort)
136 ? [
137 ...ports,
138 {
139 protocol: "tcp",
140 start: bindingPort,
141 end: bindingPort,
142 handlers: ["http"],
143 forceHttps: false,
144 },
145 ]
146 : [...ports];
147 };
148
149 const overlaps = (left: PublishedPort, right: PublishedPort) =>
150 left.protocol === right.protocol && left.start <= right.end && right.start <= left.end;
151
152 /**
153 * The first port two publishers share, if any. A publisher that lists the
154 * same port twice also conflicts with itself.
155 */
156 export const findPortConflict = (
157 appName: string,
158 publishers: ReadonlyArray<{ id: string; ports: readonly PublishedPort[] }>,
159 ): ServicePortConflict | undefined => {
160 const flat = publishers.flatMap((publisher) =>
161 publisher.ports.map((port) => ({ id: publisher.id, port })),
162 );
163 for (let i = 0; i < flat.length; i++) {
164 for (let j = i + 1; j < flat.length; j++) {
165 const left = flat[i]!;
166 const right = flat[j]!;
167 if (!overlaps(left.port, right.port)) continue;
168 return new ServicePortConflict({
169 appName,
170 port: Math.max(left.port.start, right.port.start),
171 protocol: left.port.protocol,
172 publishers: [left.id, right.id],
173 });
174 }
175 }
176 return undefined;
177 };