@effect/platform-deno 4.0.5 → 4.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/ai-docs/package.json +1 -1
  2. package/ai-docs/src/06_schedule/10_schedules.ts +5 -4
  3. package/ai-docs/tsconfig.json +3 -1
  4. package/dist/DenoChildProcessSpawner.d.ts.map +1 -1
  5. package/dist/DenoChildProcessSpawner.js +20 -6
  6. package/dist/DenoChildProcessSpawner.js.map +1 -1
  7. package/dist/DenoClusterSocket.d.ts.map +1 -1
  8. package/dist/DenoClusterSocket.js +4 -5
  9. package/dist/DenoClusterSocket.js.map +1 -1
  10. package/dist/DenoFileSystem.d.ts.map +1 -1
  11. package/dist/DenoFileSystem.js +3 -1
  12. package/dist/DenoFileSystem.js.map +1 -1
  13. package/dist/DenoHttpClient.d.ts +91 -4
  14. package/dist/DenoHttpClient.d.ts.map +1 -1
  15. package/dist/DenoHttpClient.js +89 -0
  16. package/dist/DenoHttpClient.js.map +1 -1
  17. package/dist/DenoHttpServer.d.ts +0 -6
  18. package/dist/DenoHttpServer.d.ts.map +1 -1
  19. package/dist/DenoHttpServer.js +84 -19
  20. package/dist/DenoHttpServer.js.map +1 -1
  21. package/dist/DenoRedis.d.ts +4 -3
  22. package/dist/DenoRedis.d.ts.map +1 -1
  23. package/dist/DenoRedis.js +21 -8
  24. package/dist/DenoRedis.js.map +1 -1
  25. package/dist/DenoRuntime.d.ts.map +1 -1
  26. package/dist/DenoRuntime.js +2 -6
  27. package/dist/DenoRuntime.js.map +1 -1
  28. package/dist/DenoWorkerRunner.js +2 -2
  29. package/dist/DenoWorkerRunner.js.map +1 -1
  30. package/dist/internal/error.d.ts.map +1 -1
  31. package/dist/internal/error.js +1 -0
  32. package/dist/internal/error.js.map +1 -1
  33. package/package.json +7 -7
  34. package/src/DenoChildProcessSpawner.ts +28 -11
  35. package/src/DenoClusterSocket.ts +10 -21
  36. package/src/DenoFileSystem.ts +8 -1
  37. package/src/DenoHttpClient.ts +128 -0
  38. package/src/DenoHttpServer.ts +100 -22
  39. package/src/DenoRedis.ts +30 -10
  40. package/src/DenoRuntime.ts +2 -7
  41. package/src/DenoWorkerRunner.ts +2 -2
  42. package/src/internal/error.ts +1 -0
@@ -181,27 +181,16 @@ export const layer = <
181
181
  * @since 4.0.0
182
182
  */
183
183
  export const layerK8sHttpClient: Layer.Layer<K8sHttpClient.K8sHttpClient> = K8sHttpClient.layer.pipe(
184
- Layer.provide(
185
- Layer.fresh(DenoHttpClient.layer).pipe(
186
- Layer.provide(Layer.effect(
187
- DenoHttpClient.Fetch,
188
- Effect.gen(function*() {
189
- const fs = yield* FileSystem.FileSystem
190
- const caCertOption = yield* fs.readFileString("/var/run/secrets/kubernetes.io/serviceaccount/ca.crt").pipe(
191
- Effect.option
192
- )
193
- if (Option.isNone(caCertOption)) {
194
- return globalThis.fetch
195
- }
196
-
197
- const client = yield* Effect.acquireRelease(
198
- Effect.sync(() => Deno.createHttpClient({ caCerts: [caCertOption.value] })),
199
- (client) => Effect.sync(() => client.close())
200
- )
201
- return ((input, init) => globalThis.fetch(input, { ...init, client } as any)) as typeof globalThis.fetch
202
- })
203
- ))
184
+ Layer.provide(Layer.unwrap(Effect.gen(function*() {
185
+ const fs = yield* FileSystem.FileSystem
186
+ const caCertOption = yield* fs.readFileString("/var/run/secrets/kubernetes.io/serviceaccount/ca.crt").pipe(
187
+ Effect.option
204
188
  )
205
- ),
189
+ if (Option.isNone(caCertOption)) {
190
+ return DenoHttpClient.layer
191
+ }
192
+
193
+ return DenoHttpClient.layerOptions({ caCerts: [caCertOption.value] })
194
+ }))),
206
195
  Layer.provide(DenoFileSystem.layer)
207
196
  )
@@ -122,7 +122,7 @@ const remove = removeFactory("remove")
122
122
  const makeTempDirectoryScoped: FileSystem.FileSystem["makeTempDirectoryScoped"] = (options) =>
123
123
  Effect.acquireRelease(
124
124
  makeTempDirectoryFactory("makeTempDirectoryScoped")(options),
125
- (directory) => Effect.orDie(removeFactory("makeTempDirectoryScoped")(directory, { recursive: true }))
125
+ (directory) => Effect.orDie(removeFactory("makeTempDirectoryScoped")(directory, { recursive: true, force: true }))
126
126
  )
127
127
 
128
128
  const openOptions = (flag: FileSystem.OpenFlag = "r", mode?: number): Deno.OpenOptions => {
@@ -422,6 +422,12 @@ const realPath: FileSystem.FileSystem["realPath"] = (path) => tryPromise("realPa
422
422
  const rename: FileSystem.FileSystem["rename"] = (oldPath, newPath) =>
423
423
  tryPromise("rename", oldPath, () => Deno.rename(oldPath, newPath))
424
424
 
425
+ const lstat: FileSystem.FileSystem["lstat"] = (path) =>
426
+ Effect.map(
427
+ tryPromise("lstat", path, () => Deno.lstat(path)),
428
+ makeFileInfo
429
+ )
430
+
425
431
  const stat: FileSystem.FileSystem["stat"] = (path) =>
426
432
  Effect.map(
427
433
  tryPromise("stat", path, () => Deno.stat(path)),
@@ -521,6 +527,7 @@ const makeFileSystem = Effect.map(Effect.serviceOption(FileSystem.WatchBackend),
521
527
  copyFile,
522
528
  glob,
523
529
  link,
530
+ lstat,
524
531
  makeDirectory,
525
532
  makeTempDirectory,
526
533
  makeTempDirectoryScoped,
@@ -1,10 +1,138 @@
1
1
  /**
2
+ * Deno HTTP client built on the fetch-based `HttpClient`.
3
+ *
4
+ * This module re-exports `effect/http/FetchHttpClient` and adds `makeClient`
5
+ * and `layerOptions`, which route every request through a `Deno.HttpClient`
6
+ * created from native `Deno.createHttpClient` options, such as a Unix domain
7
+ * socket transport or custom TLS certificates.
8
+ *
2
9
  * @stability unstable
3
10
  * @since 4.0.0
4
11
  */
12
+ import * as Context from "effect/Context"
13
+ import * as Effect from "effect/Effect"
14
+ import * as FetchHttpClient from "effect/http/FetchHttpClient"
15
+ import * as HttpClient from "effect/http/HttpClient"
16
+ import * as Layer from "effect/Layer"
17
+ import type * as Scope from "effect/Scope"
5
18
 
6
19
  /**
7
20
  * @category re-exports
8
21
  * @since 4.0.0
9
22
  */
10
23
  export * from "effect/http/FetchHttpClient"
24
+
25
+ /**
26
+ * Options accepted by `Deno.createHttpClient`, used by `makeClient` and
27
+ * `layerOptions`.
28
+ *
29
+ * **Details**
30
+ *
31
+ * Supported fields include `caCerts` for additional root certificates,
32
+ * `cert` and `key` for a client certificate in PEM format, `proxy` for an
33
+ * alternative transport (`http`, `https`, `socks5`, `tcp`, `unix` or `vsock`),
34
+ * `poolMaxIdlePerHost`, `poolIdleTimeout`, `http1`, `http2`, `allowHost` and
35
+ * `localAddress`.
36
+ *
37
+ * Deno has no option to skip certificate verification or to override the
38
+ * server name used for verification. Unix domain socket transports are not
39
+ * supported on Windows.
40
+ *
41
+ * @stability unstable
42
+ * @category models
43
+ * @since 4.0.6
44
+ */
45
+ export type Options = Parameters<typeof Deno.createHttpClient>[0]
46
+
47
+ /**
48
+ * Creates a `Deno.HttpClient` from the supplied options and closes it when
49
+ * the scope ends.
50
+ *
51
+ * **When to use**
52
+ *
53
+ * Use when you need the native client itself, for example to call `fetch`
54
+ * directly with `{ client }` or to share one client between several layers,
55
+ * with the same scoped cleanup `layerOptions` provides. Otherwise prefer
56
+ * `layerOptions`.
57
+ *
58
+ * @stability unstable
59
+ * @category constructors
60
+ * @since 4.0.6
61
+ */
62
+ export const makeClient = (options?: Options): Effect.Effect<Deno.HttpClient, never, Scope.Scope> =>
63
+ Effect.acquireRelease(
64
+ Effect.sync(() => Deno.createHttpClient(options ?? {})),
65
+ (client) => Effect.sync(() => client.close())
66
+ )
67
+
68
+ interface ClientRequestInit extends globalThis.RequestInit {
69
+ readonly client: Deno.HttpClient
70
+ }
71
+
72
+ /**
73
+ * Layer that provides an `HttpClient` sending every request through a
74
+ * `Deno.HttpClient` created with the supplied native options.
75
+ *
76
+ * **When to use**
77
+ *
78
+ * Use to send every request over a Unix domain socket with
79
+ * `{ proxy: { transport: "unix", path } }`, or over TLS with a custom CA and
80
+ * client certificate with `{ caCerts: [ca], cert, key }`.
81
+ *
82
+ * **Details**
83
+ *
84
+ * The native client is acquired in the layer's scope and closed when the
85
+ * scope ends. Before each request it is set as the `client` field of the
86
+ * `RequestInit` in effect for that request: the `RequestInit` service in the
87
+ * request context, or otherwise the one provided while building this layer.
88
+ * An application-wide `RequestInit` for `credentials`, `cache` or default
89
+ * headers therefore still applies, and only `client` is overridden. Method,
90
+ * headers, body and abort signal are set per request.
91
+ *
92
+ * **Example** (Sending requests over a Unix domain socket)
93
+ *
94
+ * ```ts
95
+ * import { DenoHttpClient } from "@effect/platform-deno"
96
+ *
97
+ * const DockerClient = DenoHttpClient.layerOptions({
98
+ * proxy: { transport: "unix", path: "/var/run/docker.sock" }
99
+ * })
100
+ * ```
101
+ *
102
+ * **Example** (Mutual TLS with a private CA)
103
+ *
104
+ * ```ts
105
+ * import { DenoHttpClient } from "@effect/platform-deno"
106
+ *
107
+ * declare const ca: string
108
+ * declare const cert: string
109
+ * declare const key: string
110
+ *
111
+ * const MtlsClient = DenoHttpClient.layerOptions({ caCerts: [ca], cert, key })
112
+ * ```
113
+ *
114
+ * @see {@link Options} for the accepted fields and limitations
115
+ * @see {@link makeClient} for acquiring the native client on its own
116
+ *
117
+ * @stability unstable
118
+ * @category layers
119
+ * @since 4.0.6
120
+ */
121
+ export const layerOptions = (options?: Options): Layer.Layer<HttpClient.HttpClient> =>
122
+ Layer.effect(HttpClient.HttpClient)(
123
+ Effect.gen(function*() {
124
+ const client = yield* makeClient(options)
125
+ const httpClient = yield* HttpClient.HttpClient
126
+ const defaults = Context.getOrUndefined(yield* Effect.context<never>(), FetchHttpClient.RequestInit)
127
+ return HttpClient.transformResponse(
128
+ httpClient,
129
+ Effect.updateContext((context: Context.Context<never>) => {
130
+ const init: ClientRequestInit = {
131
+ ...(Context.getOrUndefined(context, FetchHttpClient.RequestInit) ?? defaults),
132
+ client
133
+ }
134
+ return Context.add(context, FetchHttpClient.RequestInit, init)
135
+ })
136
+ )
137
+ })
138
+ ).pipe(Layer.provide(FetchHttpClient.layer))
@@ -1,9 +1,24 @@
1
1
  /**
2
2
  * Native Deno implementation of the Effect `HttpServer`.
3
3
  *
4
+ * `Deno.serve` can only upgrade requests to WebSocket, so other HTTP/1.1
5
+ * upgrades fail. Serve them with `NodeHttpServer` from
6
+ * `@effect/platform-node`, which runs on Deno's `node:http`.
7
+ *
8
+ * Over HTTP/1.1, `Deno.serve` can stop delivering the request body once the
9
+ * handler has returned a streamed response, so a handler that streams its
10
+ * response while still reading the request payload can stall
11
+ * (denoland/deno#36966).
12
+ *
13
+ * `Deno.serve` negotiates HTTP/2 on its own: over TLS with browsers, and in
14
+ * cleartext with clients that request it. Deno 2.8.3 to 2.9.2 panic and exit
15
+ * when an HTTP/2 client cancels a request while its handler is still running
16
+ * (denoland/deno#36053), so this package requires Deno 2.9.3 or newer.
17
+ *
4
18
  * @stability unstable
5
19
  * @since 4.0.0
6
20
  */
21
+ import * as Channel from "effect/Channel"
7
22
  import * as Config from "effect/Config"
8
23
  import type { ConfigError } from "effect/Config"
9
24
  import * as Context from "effect/Context"
@@ -11,7 +26,7 @@ import * as Duration from "effect/Duration"
11
26
  import * as Effect from "effect/Effect"
12
27
  import * as Fiber from "effect/Fiber"
13
28
  import type * as FileSystem from "effect/FileSystem"
14
- import { flow } from "effect/Function"
29
+ import { constVoid, flow } from "effect/Function"
15
30
  import * as Cookies from "effect/http/Cookies"
16
31
  import * as Etag from "effect/http/Etag"
17
32
  import * as FetchHttpClient from "effect/http/FetchHttpClient"
@@ -87,7 +102,10 @@ export const make = Effect.fnUntraced(function*(
87
102
  } = options
88
103
  const server = Deno.serve(
89
104
  serveOptions as Deno.ServeTcpOptions,
90
- (request, info) => currentHandler(request, info)
105
+ (request, info) =>
106
+ request.method === "CONNECT"
107
+ ? Promise.resolve(new Response(null, { status: 501 }))
108
+ : currentHandler(request, info)
91
109
  ) as Deno.HttpServer<Deno.NetAddr | Deno.UnixAddr>
92
110
 
93
111
  const shutdown = yield* Effect.promise(() => server.shutdown()).pipe(Effect.cached)
@@ -119,10 +137,17 @@ export const make = Effect.fnUntraced(function*(
119
137
  if (upgradedSources.has(denoRequest.source)) {
120
138
  return Effect.as(cancelResponseBody(response.body), upgradedResponse)
121
139
  }
122
- return Effect.flatMap(
123
- makeResponse(request, response, services, scope),
124
- (response) => Effect.sync(() => denoRequest.resolve(response))
125
- )
140
+ return Effect.matchCauseEffect(makeResponse(request, response, services, scope), {
141
+ onSuccess: (webResponse) => Effect.sync(() => denoRequest.resolve(webResponse)),
142
+ // Answer the request without waiting for body cleanup, which may never settle
143
+ onFailure: (cause) => {
144
+ denoRequest.resolve(new Response(undefined, { status: 500 }))
145
+ if (response.body._tag === "Raw" && response.body.body instanceof ReadableStream) {
146
+ cancelStreamUnsafe(response.body.body)
147
+ }
148
+ return Effect.failCause(cause)
149
+ }
150
+ })
126
151
  }, middleware)
127
152
 
128
153
  function handler(
@@ -160,6 +185,10 @@ const makeResponse = Effect.fnUntraced(function*(
160
185
  context: Context.Context<never>,
161
186
  scope: Scope.Scope
162
187
  ) {
188
+ if (ServerResponse.omitsBody(response, request.method === "HEAD")) {
189
+ yield* cancelResponseBody(response.body)
190
+ return ServerResponse.toWeb(response, { withoutBody: true })
191
+ }
163
192
  const fields: {
164
193
  headers: globalThis.Headers
165
194
  status?: number
@@ -176,11 +205,6 @@ const makeResponse = Effect.fnUntraced(function*(
176
205
  }
177
206
  if (response.statusText !== undefined) fields.statusText = response.statusText
178
207
 
179
- if (ServerResponse.omitsBody(response, request.method === "HEAD")) {
180
- yield* cancelResponseBody(response.body)
181
- return new Response(undefined, fields)
182
- }
183
- response = HttpEffect.scopeTransferToStream(response)
184
208
  const body = response.body
185
209
  switch (body._tag) {
186
210
  case "Empty":
@@ -188,24 +212,31 @@ const makeResponse = Effect.fnUntraced(function*(
188
212
  case "Uint8Array":
189
213
  case "Raw": {
190
214
  if (body.body instanceof Response) {
191
- for (const [key, value] of fields.headers.entries()) body.body.headers.set(key, value)
192
- return body.body
215
+ return ServerResponse.toWeb(response)
193
216
  }
194
217
  return new Response(body.body as any, fields)
195
218
  }
196
219
  case "FormData":
197
220
  return new Response(body.formData as any, fields)
198
- case "Stream":
221
+ case "Stream": {
222
+ // Validate the fields before the stream takes over the request scope, as only reading it would close the scope
223
+ // oxlint-disable-next-line no-new
224
+ new Response(new ReadableStream(), fields)
225
+ const stream = (HttpEffect.scopeTransferToStream(response).body as HttpBody.Stream).stream
199
226
  return new Response(
200
227
  Stream.toReadableStreamWith(
201
- Stream.unwrap(Effect.withFiber((fiber) => {
202
- Fiber.runIn(fiber, scope)
203
- return Effect.succeed(body.stream)
204
- })),
228
+ // Attach before transforming: startup can suspend. Register the request finalizer before the first pull.
229
+ Stream.fromChannel(Channel.fromTransform((upstream, streamScope) =>
230
+ Effect.withFiber((fiber) => {
231
+ Fiber.runIn(fiber, scope)
232
+ return Channel.toTransform(stream.channel)(upstream, streamScope)
233
+ })
234
+ )),
205
235
  context
206
236
  ),
207
237
  fields
208
238
  )
239
+ }
209
240
  }
210
241
  })
211
242
 
@@ -306,6 +337,8 @@ class DenoServerRequest extends Inspectable.Class implements ServerRequest.HttpS
306
337
  public resolve: (response: Response) => void
307
338
  public headersOverride?: Headers.Headers | undefined
308
339
  private remoteAddressOverride?: Option.Option<string> | undefined
340
+ private peerAddressOverride?: Option.Option<string> | undefined
341
+ readonly protocol: "http" | "https" | undefined
309
342
 
310
343
  constructor(
311
344
  source: Request,
@@ -314,7 +347,9 @@ class DenoServerRequest extends Inspectable.Class implements ServerRequest.HttpS
314
347
  url: string,
315
348
  websocketOptions: Deno.UpgradeWebSocketOptions | undefined,
316
349
  headersOverride?: Headers.Headers,
317
- remoteAddressOverride?: Option.Option<string>
350
+ remoteAddressOverride?: Option.Option<string>,
351
+ peerAddressOverride?: Option.Option<string>,
352
+ protocol?: "http" | "https"
318
353
  ) {
319
354
  super()
320
355
  this[ServerRequest.TypeId] = ServerRequest.TypeId
@@ -326,6 +361,8 @@ class DenoServerRequest extends Inspectable.Class implements ServerRequest.HttpS
326
361
  this.websocketOptions = websocketOptions
327
362
  this.headersOverride = headersOverride
328
363
  this.remoteAddressOverride = remoteAddressOverride
364
+ this.peerAddressOverride = peerAddressOverride
365
+ this.protocol = protocol
329
366
  }
330
367
  toJSON(): unknown {
331
368
  return IncomingMessage.inspect(this, {
@@ -338,6 +375,8 @@ class DenoServerRequest extends Inspectable.Class implements ServerRequest.HttpS
338
375
  readonly url?: string | undefined
339
376
  readonly headers?: Headers.Headers | undefined
340
377
  readonly remoteAddress?: Option.Option<string> | undefined
378
+ readonly peerAddress?: Option.Option<string> | undefined
379
+ readonly protocol?: "http" | "https" | undefined
341
380
  }) {
342
381
  return new DenoServerRequest(
343
382
  this.source,
@@ -346,7 +385,9 @@ class DenoServerRequest extends Inspectable.Class implements ServerRequest.HttpS
346
385
  options.url ?? this.url,
347
386
  this.websocketOptions,
348
387
  options.headers ?? this.headersOverride,
349
- "remoteAddress" in options ? options.remoteAddress : this.remoteAddressOverride
388
+ "remoteAddress" in options ? options.remoteAddress : this.remoteAddressOverride,
389
+ options.peerAddress ?? this.peerAddressOverride,
390
+ options.protocol ?? this.protocol
350
391
  )
351
392
  }
352
393
  get method(): HttpMethod {
@@ -360,8 +401,17 @@ class DenoServerRequest extends Inspectable.Class implements ServerRequest.HttpS
360
401
  ? Option.some(this.remoteAddr.hostname)
361
402
  : Option.none())
362
403
  }
404
+ get peerAddress(): Option.Option<string> {
405
+ return this.peerAddressOverride ?? this.remoteAddress
406
+ }
363
407
  get headers(): Headers.Headers {
364
- this.headersOverride ??= Headers.fromInput(this.source.headers)
408
+ if (this.headersOverride === undefined) {
409
+ const headers = Headers.fromInput(this.source.headers)
410
+ // Deno builds the URL from the request authority, ahead of Host.
411
+ // Preserve its raw form; URL.host lowercases names and strips default ports.
412
+ const host = urlAuthority(this.source.url)
413
+ this.headersOverride = host === undefined || headers.host === host ? headers : Headers.set(headers, "host", host)
414
+ }
365
415
  return this.headersOverride
366
416
  }
367
417
 
@@ -452,6 +502,20 @@ class DenoServerRequest extends Inspectable.Class implements ServerRequest.HttpS
452
502
  return this.arrayBufferEffect
453
503
  }
454
504
 
505
+ upgradeWith(
506
+ options: { readonly headers?: Headers.Input | undefined }
507
+ ): Effect.Effect<Socket.Socket, Error.HttpServerError> {
508
+ if (Object.keys(Headers.fromInput(options.headers)).length === 0) return this.upgrade
509
+ return Effect.fail(
510
+ new Error.HttpServerError({
511
+ reason: new Error.InternalError({
512
+ request: this,
513
+ description: "WebSocket upgrades do not support custom response headers"
514
+ })
515
+ })
516
+ )
517
+ }
518
+
455
519
  get upgrade(): Effect.Effect<Socket.Socket, Error.HttpServerError> {
456
520
  return Effect.flatMap(
457
521
  Effect.try({
@@ -461,7 +525,9 @@ class DenoServerRequest extends Inspectable.Class implements ServerRequest.HttpS
461
525
  reason: new Error.RequestParseError({
462
526
  request: this,
463
527
  cause,
464
- description: "Not an upgradeable ServerRequest"
528
+ description: isRawUpgrade(this.source)
529
+ ? "Deno.serve only supports WebSocket upgrades"
530
+ : "Not an upgradeable ServerRequest"
465
531
  })
466
532
  })
467
533
  }),
@@ -566,6 +632,11 @@ const upgradedResponse = ServerResponse.empty({ status: 101 })
566
632
  // Keyed by source so request copies from `modify` share the upgrade state.
567
633
  const upgradedSources = new WeakSet<Request>()
568
634
 
635
+ const isRawUpgrade = (request: Request): boolean => {
636
+ const protocol = request.headers.get("upgrade")
637
+ return protocol !== null && protocol.toLowerCase() !== "websocket"
638
+ }
639
+
569
640
  const cancelResponseBody = (body: HttpBody.HttpBody): Effect.Effect<void> => {
570
641
  if (body._tag === "Raw" && typeof ReadableStream !== "undefined" && body.body instanceof ReadableStream) {
571
642
  const stream = body.body
@@ -574,6 +645,10 @@ const cancelResponseBody = (body: HttpBody.HttpBody): Effect.Effect<void> => {
574
645
  return Effect.void
575
646
  }
576
647
 
648
+ const cancelStreamUnsafe = (stream: ReadableStream): void => {
649
+ void stream.cancel().catch(constVoid)
650
+ }
651
+
577
652
  const emptyReadableStream = new ReadableStream<Uint8Array>({
578
653
  start(controller) {
579
654
  controller.enqueue(new Uint8Array())
@@ -581,6 +656,9 @@ const emptyReadableStream = new ReadableStream<Uint8Array>({
581
656
  }
582
657
  })
583
658
 
659
+ const authorityPattern = /^[^:/?#]+:\/\/([^/?#]*)/
660
+ const urlAuthority = (url: string): string | undefined => authorityPattern.exec(url)?.[1]
661
+
584
662
  const removeHost = (url: string) => {
585
663
  if (url[0] === "/") return url
586
664
  const index = url.indexOf("/", url.indexOf("//") + 2)
package/src/DenoRedis.ts CHANGED
@@ -5,7 +5,8 @@
5
5
  * both the portable `Redis` service and the Deno-specific {@link DenoRedis}
6
6
  * service for direct access to the raw client. Unlike Bun's built-in client,
7
7
  * `@db/redis` connects eagerly using RESP2, so layer construction can fail
8
- * with a `RedisError`.
8
+ * with a `RedisError`. The layers also accept `Redis.PoolOptions` for the
9
+ * connections behind `Redis.reserve`.
9
10
  *
10
11
  * @stability unstable
11
12
  * @since 4.0.0
@@ -46,8 +47,10 @@ export class DenoRedis extends Context.Service<DenoRedis, {
46
47
  readonly use: <A>(f: (client: RedisClient) => Promise<A>) => Effect.Effect<A, Redis.RedisError>
47
48
  }>()("@effect/platform-deno/DenoRedis") {}
48
49
 
49
- const make = Effect.fnUntraced(function*(options: RedisOptions = {}) {
50
- const connectClient = () => {
50
+ const make = Effect.fnUntraced(function*(
51
+ { acquireTimeout, idleTimeout, maxConnections, minConnections, ...options }: RedisOptions & Redis.PoolOptions = {}
52
+ ) {
53
+ const connectClient = (overrides?: Partial<RedisConnectOptions>) => {
51
54
  const { url, ...connectOptions } = options
52
55
  const parsedUrl = url === undefined ? undefined : new URL(url)
53
56
  const { name, ...parsed } = url === undefined ? { hostname: "localhost" } : parseURL(url)
@@ -56,13 +59,14 @@ const make = Effect.fnUntraced(function*(options: RedisOptions = {}) {
56
59
  ...(name === undefined ? {} : { username: name }),
57
60
  ...(parsedUrl?.username ? { username: decodeURIComponent(parsedUrl.username) } : {}),
58
61
  ...(parsedUrl?.password ? { password: decodeURIComponent(parsedUrl.password) } : {}),
59
- ...Record.filter(connectOptions, Predicate.isNotUndefined)
62
+ ...Record.filter(connectOptions, Predicate.isNotUndefined),
63
+ ...overrides
60
64
  })
61
65
  }
62
66
 
63
67
  const client = yield* Effect.acquireRelease(
64
68
  Effect.tryPromise({
65
- try: connectClient,
69
+ try: () => connectClient(),
66
70
  catch: (cause) => new Redis.RedisError({ cause })
67
71
  }),
68
72
  (client) => Effect.sync(() => client.close())
@@ -74,12 +78,28 @@ const make = Effect.fnUntraced(function*(options: RedisOptions = {}) {
74
78
  catch: (cause) => new Redis.RedisError({ cause })
75
79
  })
76
80
 
77
- const redis = yield* Redis.make({
78
- send: <A = unknown>(command: string, ...args: ReadonlyArray<string>) =>
81
+ const sendWith =
82
+ (client: RedisClient) =>
83
+ <A = unknown>(command: string, ...args: ReadonlyArray<string>): Effect.Effect<A, Redis.RedisError> =>
79
84
  Effect.tryPromise({
80
85
  try: () => client.sendCommand(command, args as Array<string>) as Promise<A>,
81
86
  catch: (cause) => new Redis.RedisError({ cause })
82
- }),
87
+ })
88
+
89
+ const redis = yield* Redis.make({
90
+ send: sendWith(client),
91
+ connect: Effect.tryPromise({
92
+ // @db/redis re-executes commands after a reconnect, which could repeat
93
+ // a destructive blocking command whose reply was lost.
94
+ try: () => connectClient({ maxRetryCount: 0 }),
95
+ catch: (cause) => new Redis.RedisError({ cause })
96
+ }).pipe(
97
+ Effect.map((connection) => ({
98
+ send: sendWith(connection),
99
+ close: Effect.sync(() => connection.close())
100
+ }))
101
+ ),
102
+ pool: { acquireTimeout, idleTimeout, maxConnections, minConnections },
83
103
  subscribe: (channel, onMessage) =>
84
104
  Effect.acquireRelease(
85
105
  Effect.tryPromise({
@@ -134,7 +154,7 @@ const make = Effect.fnUntraced(function*(options: RedisOptions = {}) {
134
154
  * @since 4.0.0
135
155
  */
136
156
  export const layer = (
137
- options?: RedisOptions | undefined
157
+ options?: (RedisOptions & Redis.PoolOptions) | undefined
138
158
  ): Layer.Layer<Redis.Redis | DenoRedis, Redis.RedisError> => Layer.effectContext(make(options))
139
159
 
140
160
  /**
@@ -146,7 +166,7 @@ export const layer = (
146
166
  * @since 4.0.0
147
167
  */
148
168
  export const layerConfig = (
149
- options: Config.Wrap<RedisOptions>
169
+ options: Config.Wrap<RedisOptions & Redis.PoolOptions>
150
170
  ): Layer.Layer<Redis.Redis | DenoRedis, Redis.RedisError | Config.ConfigError> =>
151
171
  Layer.effectContext(
152
172
  Config.unwrap(options).pipe(
@@ -53,11 +53,8 @@ export const runMain: {
53
53
  let receivedSignal = false
54
54
 
55
55
  fiber.addObserver((exit) => {
56
- if (!receivedSignal) {
57
- Deno.removeSignalListener("SIGINT", onSigint)
58
- Deno.removeSignalListener("SIGTERM", onSigint)
59
- }
60
-
56
+ Deno.removeSignalListener("SIGINT", onSigint)
57
+ Deno.removeSignalListener("SIGTERM", onSigint)
61
58
  teardown(exit, (code) => {
62
59
  if (receivedSignal || code !== 0) {
63
60
  Deno.exit(code)
@@ -67,8 +64,6 @@ export const runMain: {
67
64
 
68
65
  function onSigint(): void {
69
66
  receivedSignal = true
70
- Deno.removeSignalListener("SIGINT", onSigint)
71
- Deno.removeSignalListener("SIGTERM", onSigint)
72
67
  fiber.interruptUnsafe(fiber.id)
73
68
  }
74
69
 
@@ -87,7 +87,7 @@ export const make = (self: MessagePort): WorkerRunner.WorkerRunnerPlatform["Serv
87
87
  closeLatch,
88
88
  new WorkerError({
89
89
  reason: new WorkerReceiveError({
90
- message: "An messageerror event was emitted",
90
+ message: "A messageerror event was emitted",
91
91
  cause: error.data
92
92
  })
93
93
  })
@@ -99,7 +99,7 @@ export const make = (self: MessagePort): WorkerRunner.WorkerRunnerPlatform["Serv
99
99
  new WorkerError({
100
100
  reason: new WorkerReceiveError({
101
101
  message: "An error event was emitted",
102
- cause: error.data
102
+ cause: error.error
103
103
  })
104
104
  })
105
105
  )
@@ -37,6 +37,7 @@ export const handleError = (
37
37
  break
38
38
 
39
39
  case "EACCES":
40
+ case "EPERM":
40
41
  tag = "PermissionDenied"
41
42
  break
42
43