@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 234 lines 8.76 KB
Raw
1 import * as Duration from "effect/Duration"
2 import * as Effect from "effect/Effect"
3 import * as Option from "effect/Option"
4 import * as Redacted from "effect/Redacted"
5 import * as EffectResult from "effect/Result"
6 import { ConnectionError, SqlError } from "effect/sql/SqlError"
7 import type { Duplex } from "node:stream"
8 import type { ConnectionOptions } from "node:tls"
9 import type { Config } from "../PgConnection.ts"
10 import type * as PgProtocol from "../PgProtocol.ts"
11
12 export interface ResolvedConfig {
13 readonly host: string
14 readonly port: number
15 readonly path: string | undefined
16 readonly ssl: boolean | ConnectionOptions
17 readonly sslOptional: boolean
18 readonly username: string
19 readonly password: Redacted.Redacted | Effect.Effect<Redacted.Redacted> | undefined
20 readonly connectTimeout: Duration.Duration
21 readonly keepAlive: number | undefined
22 readonly startupParameters: PgProtocol.StartupParameters
23 readonly stream: (() => Duplex) | undefined
24 readonly maxMessageSize: number | undefined
25 }
26
27 const configError = (message: string, cause?: unknown): SqlError =>
28 new SqlError({
29 reason: new ConnectionError({
30 cause: cause ?? new Error(message),
31 message: `PgConnection: ${message}`,
32 operation: "connect"
33 })
34 })
35
36 // Node truncates to whole seconds and libuv silently ignores zero, which would
37 // leave the OS defaults in place.
38 const keepAliveMillis = (input: Duration.Input): number | undefined => {
39 const duration = Duration.fromInput(input)
40 if (Option.isNone(duration)) return undefined
41 const seconds = Math.floor(Duration.toSeconds(duration.value))
42 return seconds >= 1 && seconds <= 0x7fffffff ? seconds * 1000 : undefined
43 }
44
45 export const resolveConfig = (options: Config): Effect.Effect<ResolvedConfig, SqlError> =>
46 Effect.suspend(() => {
47 const parsed: EffectResult.Result<UrlConfig, SqlError> = options.url !== undefined
48 ? parseUrl(Redacted.value(options.url))
49 : EffectResult.succeed({})
50 if (EffectResult.isFailure(parsed)) return Effect.fail(parsed.failure)
51 const url = parsed.success
52 const host = options.host ?? url.host ?? "localhost"
53 const port = options.port ?? url.port ?? 5432
54 const username = options.username ?? url.username ?? process.env.USER ?? process.env.USERNAME
55 if (username === undefined) {
56 return Effect.fail(configError("No username configured"))
57 }
58 const keepAlive = options.keepAlive === undefined ? undefined : keepAliveMillis(options.keepAlive)
59 if (options.keepAlive !== undefined && keepAlive === undefined) {
60 return Effect.fail(configError("keepAlive must be between 1 and 2147483647 seconds"))
61 }
62 const named: Record<string, string> = Object.create(null)
63 for (const [name, value] of Object.entries(options.startupParameters ?? {})) {
64 const key = name.toLowerCase()
65 if (key === "user" || key === "database" || key === "replication" || key === "options") {
66 return Effect.fail(configError(`Reserved startup parameter: "${name}"`))
67 }
68 if (key === "client_encoding") {
69 const encoding = value.toUpperCase()
70 if (encoding !== "UTF8" && encoding !== "UTF-8") {
71 return Effect.fail(configError("Startup parameter client_encoding must be UTF8 or UTF-8"))
72 }
73 named[key] = "UTF8"
74 } else {
75 named[key] = value
76 }
77 if (name === "" || name.includes("\0") || value.includes("\0")) {
78 return Effect.fail(
79 configError("Startup parameter names must be nonempty and names/values must not contain NUL")
80 )
81 }
82 }
83 const startupParameters: PgProtocol.StartupParameters = {
84 ...named,
85 user: username,
86 database: options.database ?? url.database,
87 application_name: options.applicationName ?? named.application_name ?? url.applicationName ?? "@effect/sql-pg",
88 options: options.startupOptions ?? url.options
89 }
90 for (const [name, value] of Object.entries(startupParameters)) {
91 if (value?.includes("\0")) {
92 return Effect.fail(configError(`Startup parameter "${name}" must not contain NUL`))
93 }
94 }
95 return Effect.succeed<ResolvedConfig>({
96 host,
97 port,
98 path: options.path ?? (host.startsWith("/") ? `${host}/.s.PGSQL.${port}` : undefined),
99 ssl: options.ssl ?? (url.ssl === "prefer" ? true : url.ssl ?? false),
100 sslOptional: options.ssl === undefined && url.ssl === "prefer",
101 username,
102 password: options.password ?? (url.password !== undefined ? Redacted.make(url.password) : undefined),
103 connectTimeout: Duration.fromInputUnsafe(options.connectTimeout ?? url.connectTimeout ?? Duration.seconds(5)),
104 keepAlive,
105 startupParameters,
106 stream: options.stream,
107 maxMessageSize: options.maxMessageSize
108 })
109 })
110
111 interface UrlConfig {
112 host?: string | undefined
113 port?: number | undefined
114 database?: string | undefined
115 username?: string | undefined
116 password?: string | undefined
117 applicationName?: string | undefined
118 options?: string | undefined
119 connectTimeout?: Duration.Duration | undefined
120 ssl?: boolean | "prefer" | undefined
121 }
122
123 const decodeComponent = (value: string, what: string): EffectResult.Result<string, SqlError> => {
124 try {
125 return EffectResult.succeed(decodeURIComponent(value))
126 } catch {
127 return EffectResult.fail(configError(`Invalid percent-encoding in URL ${what}`))
128 }
129 }
130
131 const parsePort = (value: string, what: string): EffectResult.Result<number, SqlError> => {
132 const port = Number(value)
133 return !Number.isInteger(port) || port < 1 || port > 65535
134 ? EffectResult.fail(configError(`Invalid port in URL ${what}: "${value}"`))
135 : EffectResult.succeed(port)
136 }
137
138 const parseUrl = (raw: string): EffectResult.Result<UrlConfig, SqlError> => {
139 let url: URL
140 try {
141 url = new URL(raw)
142 } catch (cause) {
143 return EffectResult.fail(configError("Invalid connection URL", cause))
144 }
145 if (url.protocol !== "postgres:" && url.protocol !== "postgresql:") {
146 return EffectResult.fail(configError(`Unsupported connection URL protocol: "${url.protocol}"`))
147 }
148
149 const config: UrlConfig = {}
150 if (url.hostname !== "") {
151 if (url.hostname.startsWith("[") && url.hostname.endsWith("]")) {
152 config.host = url.hostname.slice(1, -1)
153 } else {
154 const host = decodeComponent(url.hostname, "host")
155 if (EffectResult.isFailure(host)) return EffectResult.fail(host.failure)
156 config.host = host.success
157 }
158 }
159 if (url.port !== "") {
160 const port = parsePort(url.port, "authority")
161 if (EffectResult.isFailure(port)) return EffectResult.fail(port.failure)
162 config.port = port.success
163 }
164 if (url.username !== "") {
165 const username = decodeComponent(url.username, "username")
166 if (EffectResult.isFailure(username)) return EffectResult.fail(username.failure)
167 config.username = username.success
168 }
169 if (url.password !== "") {
170 const password = decodeComponent(url.password, "password")
171 if (EffectResult.isFailure(password)) return EffectResult.fail(password.failure)
172 config.password = password.success
173 }
174 const database = decodeComponent(url.pathname.replace(/^\//, ""), "database")
175 if (EffectResult.isFailure(database)) return EffectResult.fail(database.failure)
176 if (database.success !== "") config.database = database.success
177
178 for (const [key, value] of url.searchParams) {
179 switch (key) {
180 case "host":
181 config.host = value
182 break
183 case "port": {
184 const port = parsePort(value, "port parameter")
185 if (EffectResult.isFailure(port)) return EffectResult.fail(port.failure)
186 config.port = port.success
187 break
188 }
189 case "user":
190 config.username = value
191 break
192 case "password":
193 config.password = value
194 break
195 case "dbname":
196 config.database = value
197 break
198 case "application_name":
199 config.applicationName = value
200 break
201 case "options":
202 config.options = value
203 break
204 case "connect_timeout": {
205 const seconds = Number(value)
206 if (!Number.isInteger(seconds) || seconds < 0) {
207 return EffectResult.fail(configError(`Invalid connect_timeout in URL: "${value}"`))
208 }
209 config.connectTimeout = seconds === 0 ? Duration.infinity : Duration.seconds(seconds)
210 break
211 }
212 case "sslmode":
213 switch (value) {
214 case "disable":
215 config.ssl = false
216 break
217 case "require":
218 case "verify-ca":
219 case "verify-full":
220 config.ssl = true
221 break
222 case "prefer":
223 case "allow":
224 config.ssl = "prefer"
225 break
226 default:
227 return EffectResult.fail(configError(`Unrecognized sslmode in URL: "${value}"`))
228 }
229 break
230 // Unknown query parameters are ignored, matching libpq.
231 }
232 }
233 return EffectResult.succeed(config)
234 }