@ultimabase/http 0.5.0 → 0.6.0-canary.20261108151139

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,42 @@
1
1
  # @ultimabase/http
2
2
 
3
+ ## 0.6.0-canary.20261108151139
4
+
5
+ ### Minor Changes
6
+
7
+ - 2f1baf1: A database the server cannot use answers 503 `UNAVAILABLE` with `Retry-After: 1`, not 500 (D-335): every pool connection stayed busy, or the server cannot be reached. The reason is logged at `error`. `UNAVAILABLE` is now a kernel code.
8
+
9
+ ### Patch Changes
10
+
11
+ - a47bbc4: A storm of connections no longer fails. The server's connection queue holds 4096, and at most 8 connections open at once. A socket closed by a failure of the server now gets `1013`, which `graphql-ws` retries, where it got `4403`: `4403` now means refused, and only that. `liveFetch` reconnects at a random moment of its wait, so that clients cut together do not come back together.
12
+ - 3d7f654: A request costs up to 18 % less CPU: the server keeps its light response through CORS, the body limit and its headers. `Access-Control-Allow-Credentials` goes out only with an allowed origin, and a route's own `Vary` is kept.
13
+ - dfa430e: On Linux, a server takes connections 16 times faster when it is busy: with 2000 clients, the slowest
14
+ one waits about 2.5 s instead of about 18 s, and a health probe under 1 s instead of over 5 s.
15
+ - Updated dependencies [e97378e]
16
+ - Updated dependencies [778bbbc]
17
+ - Updated dependencies [2bccedd]
18
+ - Updated dependencies [f808da8]
19
+ - Updated dependencies [7c20553]
20
+ - Updated dependencies [2f1baf1]
21
+ - Updated dependencies [4ff9d42]
22
+ - Updated dependencies [41b5dca]
23
+ - Updated dependencies [703ed93]
24
+ - Updated dependencies [76509c3]
25
+ - Updated dependencies [a6394ba]
26
+ - Updated dependencies [41b5dca]
27
+ - Updated dependencies [41b5dca]
28
+ - Updated dependencies [d6ec5d4]
29
+ - Updated dependencies [0a6de4d]
30
+ - Updated dependencies [1644bb1]
31
+ - Updated dependencies [12edcfd]
32
+ - Updated dependencies [a479bca]
33
+ - Updated dependencies [0102aa8]
34
+ - Updated dependencies [7a8d0d8]
35
+ - Updated dependencies [e3d051f]
36
+ - Updated dependencies [6140b2b]
37
+ - Updated dependencies [0699e37]
38
+ - ultimabase@0.6.0-canary.20261108151139
39
+
3
40
  ## 0.5.0
4
41
 
5
42
  ### Patch Changes
package/dist/app.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"app.d.ts","sourceRoot":"","sources":["../src/app.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAA;AAM3B,OAAO,KAAK,EAAE,MAAM,EAAa,MAAM,EAAE,MAAM,YAAY,CAAA;AAG3D,OAAO,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AAEpD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAKzC,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,cAAc,CAAA;AAGxC;;;GAGG;AACH,MAAM,MAAM,OAAO,GAAG;IAAE,SAAS,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,CAAA;AAExE,uEAAuE;AACvE,MAAM,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,CAAA;AAElC,yFAAyF;AACzF,MAAM,WAAW,OAAO;IACvB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAA;CAC3B;AAED,6CAA6C;AAC7C,MAAM,WAAW,WAAW;IAC3B,2CAA2C;IAC3C,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;IACnC,0EAA0E;IAC1E,QAAQ,CAAC,IAAI,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;IACjC,8BAA8B;IAC9B,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAA;IACtB,iCAAiC;IACjC,QAAQ,CAAC,SAAS,CAAC,E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S,IAAI,EAAE,CAAA;IAC/B,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAA;CAC3B,EACD,QAAQ,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,MAAM,CAAC,EAC/C,MAAM,EAAE,MAAM,GACZ,IAAI,CAAC,OAAO,CAAC,CA8If"}
package/dist/app.js CHANGED
@@ -28,6 +28,7 @@ const statuses = new Map([
28
28
  ['INVALID_CREDENTIALS', 401],
29
29
  ['TOO_MANY_ATTEMPTS', 429],
30
30
  ['CONFLICT', 409],
31
+ ['UNAVAILABLE', 503],
31
32
  ['INTERNAL', 500],
32
33
  ]);
33
34
  /** Hono's way to refuse a request, with its status (D-108). */
@@ -52,8 +53,8 @@ function failed(error, c, logger) {
52
53
  const { code, message, details } = error;
53
54
  // An application's own code is a client error (D-72).
54
55
  const status = statuses.get(code) ?? 400;
55
- // Its details say when to retry, in seconds (D-113).
56
- if (code === 'TOO_MANY_ATTEMPTS' &&
56
+ // Its details say when to retry, in seconds (D-113, D-335).
57
+ if ((code === 'TOO_MANY_ATTEMPTS' || code === 'UNAVAILABLE') &&
57
58
  typeof details === 'object' &&
58
59
  details !== null) {
59
60
  const wait = Reflect.get(details, 'retryAfter');
@@ -92,6 +93,23 @@ const form = /^(application\/x-www-form-urlencoded|multipart\/form-data|text\/pl
92
93
  * one, and the development log cannot print one (D-108).
93
94
  */
94
95
  const pathOf = (request) => getPath(request).replaceAll(/[\p{Cc}\u2028\u2029]/gu, (char) => encodeURIComponent(char));
96
+ /**
97
+ * Sets a header of an answered request on the response itself: `c.header` would
98
+ * copy it, and the copy, unlike the adapter's own response, sends its body
99
+ * through a stream. A response of `fetch` or `Response.redirect` keeps its
100
+ * headers: that one is copied.
101
+ */
102
+ function stamp(c, name, value, append = false) {
103
+ try {
104
+ if (append)
105
+ c.res.headers.append(name, value);
106
+ else
107
+ c.res.headers.set(name, value);
108
+ }
109
+ catch {
110
+ c.header(name, value, { append });
111
+ }
112
+ }
95
113
  /**
96
114
  * Reads `NODE_ENV` once, when the application starts. The application's
97
115
  * routes come before those plugins mounted (D-107).
@@ -107,7 +125,7 @@ export function appOf(options, mounted, { probes, gates, rateLimit, }, identify,
107
125
  app.use(async (c, next) => {
108
126
  await next();
109
127
  if (!c.res.headers.has('cache-control'))
110
- c.header('cache-control', 'no-store');
128
+ stamp(c, 'cache-control', 'no-store');
111
129
  });
112
130
  // Each request once answered, outside production (D-108).
113
131
  if (local) {
@@ -136,17 +154,17 @@ export function appOf(options, mounted, { probes, gates, rateLimit, }, identify,
136
154
  app.use(async (c, next) => {
137
155
  // Hono's `cors` answers every OPTIONS: a route's own runs, unless the
138
156
  // request is a preflight.
139
- const asked = c.req.header('access-control-request-method');
140
- if (c.req.method !== 'OPTIONS' || asked !== undefined) {
157
+ if (c.req.method === 'OPTIONS' &&
158
+ c.req.header('access-control-request-method') !== undefined) {
141
159
  return preflight(c, next);
142
160
  }
143
161
  await next();
144
162
  const origin = allowed(c.req.header('origin') ?? '');
145
163
  if (origin !== null) {
146
- c.header('access-control-allow-origin', origin);
147
- c.header('access-control-allow-credentials', 'true');
164
+ stamp(c, 'access-control-allow-origin', origin);
165
+ stamp(c, 'access-control-allow-credentials', 'true');
148
166
  }
149
- c.header('vary', 'Origin', { append: true });
167
+ stamp(c, 'vary', 'Origin', true);
150
168
  });
151
169
  // Before the gates and the caller: a flood reads no session (D-218).
152
170
  app.use(async (c, next) => {
@@ -179,13 +197,11 @@ export function appOf(options, mounted, { probes, gates, rateLimit, }, identify,
179
197
  }
180
198
  await next();
181
199
  });
182
- const limit = bodyLimit({
183
- maxSize,
184
- onError: (c) => c.json({
185
- code: 'PAYLOAD_TOO_LARGE',
186
- message: `The body is over ${maxSize} bytes.`,
187
- }, 413),
188
- });
200
+ const tooLarge = (c) => c.json({
201
+ code: 'PAYLOAD_TOO_LARGE',
202
+ message: `The body is over ${maxSize} bytes.`,
203
+ }, 413);
204
+ const limit = bodyLimit({ maxSize, onError: tooLarge });
189
205
  // The routes of the mounts that read their own body, by method: their
190
206
  // `use` and `all` match any request, so they never lift the limit (D-153).
191
207
  const unlimited = new Hono();
@@ -196,11 +212,18 @@ export function appOf(options, mounted, { probes, gates, rateLimit, }, identify,
196
212
  }
197
213
  }
198
214
  app.use(async (c, next) => {
215
+ if (c.req.method === 'GET' || c.req.method === 'HEAD')
216
+ return next();
199
217
  const [matched] = unlimited.router.match(c.req.method, c.req.path);
200
218
  if (matched.length > 0)
201
- await next();
202
- else
219
+ return next();
220
+ // Hono's limit opens the body to read this header.
221
+ const declared = c.req.header('content-length');
222
+ if (declared === undefined ||
223
+ c.req.header('transfer-encoding') !== undefined) {
203
224
  return limit(c, next);
225
+ }
226
+ return Number(declared) > maxSize ? tooLarge(c) : next();
204
227
  });
205
228
  app.use(async (c, next) => {
206
229
  hold(c, await identify(c.req.raw), addressOf(c.env));
@@ -0,0 +1,14 @@
1
+ /** The parts of a live message that say what it costs. */
2
+ type Costed = {
3
+ readonly kind: string;
4
+ readonly rows?: readonly unknown[];
5
+ readonly changes?: readonly unknown[];
6
+ };
7
+ /** What a live read sent since its client's buffer was last not full. */
8
+ export declare class Backlog {
9
+ #private;
10
+ /** Whether `message` is sent, or dropped until the window comes again. */
11
+ takes(full: boolean, message: Costed): boolean;
12
+ }
13
+ export {};
14
+ //# sourceMappingURL=backlog.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backlog.d.ts","sourceRoot":"","sources":["../src/backlog.ts"],"names":[],"mappings":"AAGA,0DAA0D;AAC1D,KAAK,MAAM,GAAG;IACb,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,IAAI,CAAC,EAAE,SAAS,OAAO,EAAE,CAAA;IAClC,QAAQ,CAAC,OAAO,CAAC,EAAE,SAAS,OAAO,EAAE,CAAA;CACrC,CAAA;AAED,yEAAyE;AACzE,qBAAa,OAAO;;IAInB,0EAA0E;IAC1E,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAS7C;CACD"}
@@ -0,0 +1,20 @@
1
+ // What a client whose buffer is full is still sent (D-254): its changes, as long
2
+ // as they cost less than the whole window it would get instead.
3
+ /** What a live read sent since its client's buffer was last not full. */
4
+ export class Backlog {
5
+ #shown = 0;
6
+ #cost = 0;
7
+ /** Whether `message` is sent, or dropped until the window comes again. */
8
+ takes(full, message) {
9
+ if (!full) {
10
+ this.#cost = 0;
11
+ if (message.rows !== undefined)
12
+ this.#shown = message.rows.length;
13
+ return true;
14
+ }
15
+ if (message.changes === undefined)
16
+ return false;
17
+ this.#cost += message.changes.length + 1;
18
+ return this.#cost <= this.#shown;
19
+ }
20
+ }
package/dist/index.d.ts CHANGED
@@ -50,7 +50,7 @@ export interface Http extends PluginTypes {
50
50
  readonly name: 'http';
51
51
  readonly appOptions: HttpOptions;
52
52
  readonly api: HttpApi;
53
- readonly errors: 'BAD_REQUEST' | 'BAD_USER_INPUT' | 'PAYLOAD_TOO_LARGE' | 'UNAVAILABLE' | 'UNSUPPORTED_MEDIA_TYPE';
53
+ readonly errors: 'BAD_REQUEST' | 'BAD_USER_INPUT' | 'PAYLOAD_TOO_LARGE' | 'UNSUPPORTED_MEDIA_TYPE';
54
54
  }
55
55
  /** The application's HTTP server (D-66, D-106). */
56
56
  export declare const httpPlugin: PluginOf<Http>;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAU,QAAQ,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AAG/D,OAAO,KAAK,EAAW,WAAW,EAAW,MAAM,EAAE,MAAM,UAAU,CAAA;AAIrE,OAAO,KAAK,EAAU,UAAU,EAAE,MAAM,aAAa,CAAA;AAIrD,OAAO,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAS,MAAM,cAAc,CAAA;AAGvE,YAAY,EAAE,OAAO,EAAE,WAAW,EAA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AAC,KAAK,CAAC,EAAE,KAAK,CAAA;KAAE,GAClC,IAAI,CAAA;IACP;;;OAGG;IACH,aAAa,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAA;IACrC;;;OAGG;IACH,KAAK,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI,CAAA;IAC9B;;;;OAIG;IACH,IAAI,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,CAAA;IACtB,0EAA0E;IAC1E,GAAG,IAAI,MAAM,CAAA;CACb;AAED,sCAAsC;AACtC,MAAM,WAAW,IAAK,SAAQ,WAAW;IACxC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,UAAU,EAAE,WAAW,CAAA;IAChC,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAA;IACrB,QAAQ,CAAC,MAAM,EACZ,aAAa,GACb,gBAAgB,GAChB,mBAAmB,GACnB,wBAAwB,CAAA;CAC3B;AA+ID,mDAAmD;AACnD,eAAO,MAAM,UAAU,EAAE,QAAQ,CAAC,IAAI,CAAe,CAAA;AAIrD;;;GAGG;AACH,eAAO,MAAM,MAAM,QAAO,MAIvB,CAAA"}
@@ -1,5 +1,6 @@
1
1
  export type { Args, At, Change, Limits, Page, Pagination, Relay, } from './pages.ts';
2
- export { applied, connection, countedPage, pageArgs, pageOf, readsNoRow, rowOf, rowsOf, } from './pages.ts';
2
+ export { applied, endsOf, connection, countedPage, pageArgs, pageOf, readsNoRow, rowOf, rowsOf, } from './pages.ts';
3
+ export { Backlog } from './backlog.ts';
3
4
  export type { Node, Served, ServedOneOf } from './transport.ts';
4
5
  export { badInput, backOf, declared, isNode, jsonSchemaOf, oneOfsOf, plural, readable, readableOneOfs, readableVirtuals, run, } from './transport.ts';
5
6
  //# sourceMappingURL=internal.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"internal.d.ts","sourceRoot":"","sources":["../src/internal.ts"],"names":[],"mappings":"AAEA,YAAY,EACX,IAAI,EACJ,EAAE,EACF,MAAM,EACN,MAAM,EACN,IAAI,EACJ,UAAU,EACV,KAAK,GACL,MAAM,YAAY,CAAA;AACnB,OAAO,EACN,OAAO,EACP,UAAU,EACV,WAAW,EACX,QAAQ,EACR,MAAM,EACN,UAAU,EACV,KAAK,EACL,MAAM,GACN,MAAM,YAAY,CAAA;AACnB,YAAY,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAC/D,OAAO,EACN,QAAQ,EACR,MAAM,EACN,QAAQ,EACR,MAAM,EACN,YAAY,EACZ,QAAQ,EACR,MAAM,EACN,QAAQ,EACR,cAAc,EACd,gBAAgB,EAChB,GAAG,GACH,MAAM,gBAAgB,CAAA"}
1
+ {"version":3,"file":"internal.d.ts","sourceRoot":"","sources":["../src/internal.ts"],"names":[],"mappings":"AAEA,YAAY,EACX,IAAI,EACJ,EAAE,EACF,MAAM,EACN,MAAM,EACN,IAAI,EACJ,UAAU,EACV,KAAK,GACL,MAAM,YAAY,CAAA;AACnB,OAAO,EACN,OAAO,EACP,MAAM,EACN,UAAU,EACV,WAAW,EACX,QAAQ,EACR,MAAM,EACN,UAAU,EACV,KAAK,EACL,MAAM,GACN,MAAM,YAAY,CAAA;AACnB,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,YAAY,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAC/D,OAAO,EACN,QAAQ,EACR,MAAM,EACN,QAAQ,EACR,MAAM,EACN,YAAY,EACZ,QAAQ,EACR,MAAM,EACN,QAAQ,EACR,cAAc,EACd,gBAAgB,EAChB,GAAG,GACH,MAAM,gBAAgB,CAAA"}
package/dist/internal.js CHANGED
@@ -1,2 +1,3 @@
1
- export { applied, connection, countedPage, pageArgs, pageOf, readsNoRow, rowOf, rowsOf, } from './pages.js';
1
+ export { applied, endsOf, connection, countedPage, pageArgs, pageOf, readsNoRow, rowOf, rowsOf, } from './pages.js';
2
+ export { Backlog } from './backlog.js';
2
3
  export { badInput, backOf, declared, isNode, jsonSchemaOf, oneOfsOf, plural, readable, readableOneOfs, readableVirtuals, run, } from './transport.js';
package/dist/pages.d.ts CHANGED
@@ -43,6 +43,11 @@ export type Connection<N> = {
43
43
  };
44
44
  /** The rows of a Relay read, without the one read to look ahead. */
45
45
  export declare function connection<N>(rows: readonly Row[], page: Relay, node: (row: Row) => N): Connection<N>;
46
+ /**
47
+ * The first and last of `ids` as rows: a live window's page info without the
48
+ * rows between (D-253).
49
+ */
50
+ export declare const endsOf: (ids: readonly string[]) => readonly Row[];
46
51
  /** Whether a counted page reads no row: `first` or `last` 0, no cursor (D-226). */
47
52
  export declare const readsNoRow: (page: Page) => boolean;
48
53
  /** A page read as its count alone, which tells whether rows follow (D-226). */
@@ -1 +1 @@
1
- {"version":3,"file":"pages.d.ts","sourceRoot":"","sources":["../src/pages.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,YAAY,CAAA;AAIrC,oDAAoD;AACpD,MAAM,MAAM,IAAI,GAAG;IAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CAAE,CAAA;AAEtD,wEAAwE;AACxE,MAAM,MAAM,EAAE,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,CAAA;AAEzC,iDAAiD;AACjD,MAAM,MAAM,UAAU,GAAG,YAAY,GAAG,MAAM,CAAA;AAE9C,yEAAyE;AACzE,MAAM,MAAM,MAAM,GAAG;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,KAAK,EAAE;QAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAA;CACzC,CAAA;AA+CD,0DAA0D;AAC1D,MAAM,MAAM,KAAK,GAAG;IACnB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,CAAA;IACjC,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AAO,MAAM,MAAM,QAAS,SAAS,MAAM,EAAE,KAAG,SAAS,GAAG,EAClC,CAAA;AAE1B,mFAAmF;AACnF,eAAO,MAAM,UAAU,SAAU,IAAI,KAAG,OACoB,CAAA;AAE5D,+EAA+E;AAC/E,wBAAgB,WAAW,CAAC,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,GAAG,UAAU,CAAC,KAAK,CAAC,CAWzE;AAED,kDAAkD;AAClD,wBAAgB,MAAM,CAAC,KAAK,EAAE,OAAO,GAAG,SAAS,GAAG,EAAE,CAErD;AAED,eAAO,MAAM,KAAK,UAAW,OAAO,KAAG,GAAG,GAAG,SACZ,CAAA;AAEjC,kFAAkF;AAClF,MAAM,MAAM,MAAM,CAAC,CAAC,IACjB;IAAE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAC3B;IAAE,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAAA;AAExD,yEAAyE;AACzE,wBAAgB,OAAO,CAAC,CAAC,SAAS;IAAE,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;CAAE,EAAE,CAAC,EAC3D,MAAM,EAAE,SAAS,CAAC,EAAE,EACpB,OAAO,EAAE,SAAS,MAAM,CAAC,CAAC,CAAC,EAAE,EAC7B,IAAI,EAAE,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,GACpB,CAAC,EAAE,CAgBL"}
package/dist/pages.js CHANGED
@@ -100,6 +100,11 @@ export function connection(rows, page, node) {
100
100
  },
101
101
  };
102
102
  }
103
+ /**
104
+ * The first and last of `ids` as rows: a live window's page info without the
105
+ * rows between (D-253).
106
+ */
107
+ export const endsOf = (ids) => ids.map((id) => ({ id }));
103
108
  /** Whether a counted page reads no row: `first` or `last` 0, no cursor (D-226). */
104
109
  export const readsNoRow = (page) => page.relay?.size === 0 && page.read['cursor'] === undefined;
105
110
  /** A page read as its count alone, which tells whether rows follow (D-226). */
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,WAAW,CAAA;AAEvC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAA;AACtD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAA;AAGxC,iDAAiD;AACjD,wBAAgB,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAWzD;AAED,gFAAgF;AAChF,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAM9D;AAED,4EAA4E;AAC5E,wBAAgB,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAI1D;AAED,wBAAsB,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAqB7E;AAED,iDAAiD;AACjD,wBAAgB,QAAQ,CACvB,KAAK,EAAE,UAAU,CAAC,OAAO,kBAAkB,CAAC,CAAC,CAAC,CAAC,GAC7C,MAAM,CAWR;AAKD;;;GAGG;AACH,wBAAsB,MAAM,CAC3B,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,GAChC,OAAO,CAAC,IAAI,CAAC,CAiBf"}
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,WAAW,CAAA;AAMvC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAA;AACtD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAA;AAGxC,iDAAiD;AACjD,wBAAgB,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAWzD;AAED,gFAAgF;AAChF,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAM9D;AAED,4EAA4E;AAC5E,wBAAgB,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAI1D;AAyDD,wBAAsB,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAsB7E;AAED,iDAAiD;AACjD,wBAAgB,QAAQ,CACvB,KAAK,EAAE,UAAU,CAAC,OAAO,kBAAkB,CAAC,CAAC,CAAC,CAAC,GAC7C,MAAM,CAWR;AAKD;;;GAGG;AACH,wBAAsB,MAAM,CAC3B,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,GAChC,OAAO,CAAC,IAAI,CAAC,CAef"}
package/dist/server.js CHANGED
@@ -1,4 +1,9 @@
1
+ // The port the server listens on, and its listening (D-106); the body
2
+ // limit and the drain (D-223); its connection queue (D-276); its listeners
3
+ // (D-292).
4
+ import cluster from 'node:cluster';
1
5
  import { createServer } from 'node:http';
6
+ import { createServer as createListener, } from 'node:net';
2
7
  import { getRequestListener } from '@hono/node-server';
3
8
  import { Refused } from 'ultimabase';
4
9
  /** The `port` option, then `PORT`, then 3000. */
@@ -29,7 +34,19 @@ export function drainOf(option) {
29
34
  return ms;
30
35
  throw new Refused(`drain is ${ms}, not a whole number of milliseconds.`);
31
36
  }
32
- export async function listening(server, port) {
37
+ /** The connections waiting to be accepted; the system caps it at its own. */
38
+ const backlog = 4096;
39
+ /**
40
+ * The sockets listening on the port. Node accepts one connection per turn of
41
+ * its event loop and per socket, so a busy server takes connections this many
42
+ * times faster (D-292). The system shares them out, on Linux only; workers of
43
+ * a cluster already share theirs.
44
+ */
45
+ const listeners = process.platform === 'linux' && cluster.isPrimary ? 16 : 1;
46
+ /** The listeners of each server beside itself. */
47
+ const others = new WeakMap();
48
+ /** `listener` on `port`, refused in words when another process holds it. */
49
+ async function bound(listener, port, reusePort) {
33
50
  await new Promise((done, fail) => {
34
51
  const refused = (error) => {
35
52
  const code = Reflect.get(error, 'code');
@@ -37,14 +54,49 @@ export async function listening(server, port) {
37
54
  ? new Error(`Port ${port} is in use: stop the process that holds it, or set PORT.`, { cause: error })
38
55
  : error);
39
56
  };
40
- server.once('error', refused);
41
- server.listen(port, () => {
42
- server.off('error', refused);
57
+ listener.once('error', refused);
58
+ listener.listen({ port, backlog, reusePort }, () => {
59
+ listener.off('error', refused);
43
60
  done();
44
61
  });
45
62
  });
46
- const address = server.address();
63
+ }
64
+ /** Closed, once its connections have ended. */
65
+ async function shut(listener) {
66
+ await new Promise((done, fail) => {
67
+ listener.close((error) => {
68
+ if (error === undefined)
69
+ done();
70
+ else
71
+ fail(error);
72
+ });
73
+ });
74
+ }
75
+ const boundPort = (listener, port) => {
76
+ const address = listener.address();
47
77
  return typeof address === 'object' && address !== null ? address.port : port;
78
+ };
79
+ export async function listening(server, port) {
80
+ if (listeners === 1) {
81
+ await bound(server, port, false);
82
+ return boundPort(server, port);
83
+ }
84
+ // Sharing the port lets a second process in, so it must be free first.
85
+ if (port !== 0) {
86
+ const alone = createListener();
87
+ await bound(alone, port, false);
88
+ await shut(alone);
89
+ }
90
+ await bound(server, port, true);
91
+ const at = boundPort(server, port);
92
+ const rest = Array.from({ length: listeners - 1 }, () =>
93
+ // As `node:http` makes its own, whose connections it then takes.
94
+ createListener({ allowHalfOpen: true, noDelay: true }, (socket) => {
95
+ server.emit('connection', socket);
96
+ }));
97
+ others.set(server, rest);
98
+ await Promise.all(rest.map((listener) => bound(listener, at, true)));
99
+ return at;
48
100
  }
49
101
  /** A Node server for `fetch`, Hono's handler. */
50
102
  export function serverOf(fetch) {
@@ -67,21 +119,18 @@ const grace = 10_000;
67
119
  * sockets plugins took (D-59), 10 seconds at most (D-106).
68
120
  */
69
121
  export async function closed(server, logger, taken) {
70
- let cutting;
71
- await new Promise((done, fail) => {
72
- server.close((error) => {
73
- clearTimeout(cutting);
74
- if (error === undefined)
75
- done();
76
- else
77
- fail(error);
78
- });
122
+ const cutting = setTimeout(() => {
123
+ logger.warn(`Stopped ${grace / 1000} s after stop began: closed the requests still running.`);
124
+ server.closeAllConnections();
125
+ for (const socket of taken.keys())
126
+ socket.destroy();
127
+ }, grace);
128
+ try {
129
+ const closing = [server, ...(others.get(server) ?? [])].map(shut);
79
130
  server.closeIdleConnections();
80
- cutting = setTimeout(() => {
81
- logger.warn(`Stopped ${grace / 1000} s after stop began: closed the requests still running.`);
82
- server.closeAllConnections();
83
- for (const socket of taken.keys())
84
- socket.destroy();
85
- }, grace);
86
- });
131
+ await Promise.all(closing);
132
+ }
133
+ finally {
134
+ clearTimeout(cutting);
135
+ }
87
136
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimabase/http",
3
- "version": "0.5.0",
3
+ "version": "0.6.0-canary.20261108151139",
4
4
  "description": "An HTTP server for UltimaBase: Hono routes that read the caller, CORS and a body limit.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -38,10 +38,10 @@
38
38
  "ipaddr.js": "2.5.0"
39
39
  },
40
40
  "peerDependencies": {
41
- "ultimabase": "^0.5.0"
41
+ "ultimabase": "0.6.0-canary.20261108151139"
42
42
  },
43
43
  "devDependencies": {
44
- "ultimabase": "0.5.0",
44
+ "ultimabase": "0.6.0-canary.20261108151139",
45
45
  "vite": "8.3.4",
46
46
  "vitest": "5.0.5"
47
47
  }
package/src/app.ts CHANGED
@@ -82,6 +82,7 @@ const statuses: ReadonlyMap<string, ContentfulStatusCode> = new Map<
82
82
  ['INVALID_CREDENTIALS', 401],
83
83
  ['TOO_MANY_ATTEMPTS', 429],
84
84
  ['CONFLICT', 409],
85
+ ['UNAVAILABLE', 503],
85
86
  ['INTERNAL', 500],
86
87
  ])
87
88
 
@@ -106,9 +107,9 @@ function failed(error: unknown, c: Context, logger: Logger): Response {
106
107
  const { code, message, details } = error
107
108
  // An application's own code is a client error (D-72).
108
109
  const status = statuses.get(code) ?? 400
109
- // Its details say when to retry, in seconds (D-113).
110
+ // Its details say when to retry, in seconds (D-113, D-335).
110
111
  if (
111
- code === 'TOO_MANY_ATTEMPTS' &&
112
+ (code === 'TOO_MANY_ATTEMPTS' || code === 'UNAVAILABLE') &&
112
113
  typeof details === 'object' &&
113
114
  details !== null
114
115
  ) {
@@ -158,6 +159,21 @@ const pathOf = (request: Request): string =>
158
159
  encodeURIComponent(char),
159
160
  )
160
161
 
162
+ /**
163
+ * Sets a header of an answered request on the response itself: `c.header` would
164
+ * copy it, and the copy, unlike the adapter's own response, sends its body
165
+ * through a stream. A response of `fetch` or `Response.redirect` keeps its
166
+ * headers: that one is copied.
167
+ */
168
+ function stamp(c: Context, name: string, value: string, append = false): void {
169
+ try {
170
+ if (append) c.res.headers.append(name, value)
171
+ else c.res.headers.set(name, value)
172
+ } catch {
173
+ c.header(name, value, { append })
174
+ }
175
+ }
176
+
161
177
  /**
162
178
  * Reads `NODE_ENV` once, when the application starts. The application's
163
179
  * routes come before those plugins mounted (D-107).
@@ -187,7 +203,7 @@ export function appOf(
187
203
  app.use(async (c, next) => {
188
204
  await next()
189
205
  if (!c.res.headers.has('cache-control'))
190
- c.header('cache-control', 'no-store')
206
+ stamp(c, 'cache-control', 'no-store')
191
207
  })
192
208
  // Each request once answered, outside production (D-108).
193
209
  if (local) {
@@ -215,17 +231,19 @@ export function appOf(
215
231
  app.use(async (c, next) => {
216
232
  // Hono's `cors` answers every OPTIONS: a route's own runs, unless the
217
233
  // request is a preflight.
218
- const asked = c.req.header('access-control-request-method')
219
- if (c.req.method !== 'OPTIONS' || asked !== undefined) {
234
+ if (
235
+ c.req.method === 'OPTIONS' &&
236
+ c.req.header('access-control-request-method') !== undefined
237
+ ) {
220
238
  return preflight(c, next)
221
239
  }
222
240
  await next()
223
241
  const origin = allowed(c.req.header('origin') ?? '')
224
242
  if (origin !== null) {
225
- c.header('access-control-allow-origin', origin)
226
- c.header('access-control-allow-credentials', 'true')
243
+ stamp(c, 'access-control-allow-origin', origin)
244
+ stamp(c, 'access-control-allow-credentials', 'true')
227
245
  }
228
- c.header('vary', 'Origin', { append: true })
246
+ stamp(c, 'vary', 'Origin', true)
229
247
  })
230
248
  // Before the gates and the caller: a flood reads no session (D-218).
231
249
  app.use(async (c, next) => {
@@ -263,17 +281,15 @@ export function appOf(
263
281
  }
264
282
  await next()
265
283
  })
266
- const limit = bodyLimit({
267
- maxSize,
268
- onError: (c) =>
269
- c.json(
270
- {
271
- code: 'PAYLOAD_TOO_LARGE',
272
- message: `The body is over ${maxSize} bytes.`,
273
- },
274
- 413,
275
- ),
276
- })
284
+ const tooLarge = (c: Context) =>
285
+ c.json(
286
+ {
287
+ code: 'PAYLOAD_TOO_LARGE',
288
+ message: `The body is over ${maxSize} bytes.`,
289
+ },
290
+ 413,
291
+ )
292
+ const limit = bodyLimit({ maxSize, onError: tooLarge })
277
293
  // The routes of the mounts that read their own body, by method: their
278
294
  // `use` and `all` match any request, so they never lift the limit (D-153).
279
295
  const unlimited = new Hono()
@@ -283,9 +299,18 @@ export function appOf(
283
299
  }
284
300
  }
285
301
  app.use(async (c, next) => {
302
+ if (c.req.method === 'GET' || c.req.method === 'HEAD') return next()
286
303
  const [matched] = unlimited.router.match(c.req.method, c.req.path)
287
- if (matched.length > 0) await next()
288
- else return limit(c, next)
304
+ if (matched.length > 0) return next()
305
+ // Hono's limit opens the body to read this header.
306
+ const declared = c.req.header('content-length')
307
+ if (
308
+ declared === undefined ||
309
+ c.req.header('transfer-encoding') !== undefined
310
+ ) {
311
+ return limit(c, next)
312
+ }
313
+ return Number(declared) > maxSize ? tooLarge(c) : next()
289
314
  })
290
315
  app.use(async (c, next) => {
291
316
  hold(c, await identify(c.req.raw), addressOf(c.env))
package/src/backlog.ts ADDED
@@ -0,0 +1,27 @@
1
+ // What a client whose buffer is full is still sent (D-254): its changes, as long
2
+ // as they cost less than the whole window it would get instead.
3
+
4
+ /** The parts of a live message that say what it costs. */
5
+ type Costed = {
6
+ readonly kind: string
7
+ readonly rows?: readonly unknown[]
8
+ readonly changes?: readonly unknown[]
9
+ }
10
+
11
+ /** What a live read sent since its client's buffer was last not full. */
12
+ export class Backlog {
13
+ #shown = 0
14
+ #cost = 0
15
+
16
+ /** Whether `message` is sent, or dropped until the window comes again. */
17
+ takes(full: boolean, message: Costed): boolean {
18
+ if (!full) {
19
+ this.#cost = 0
20
+ if (message.rows !== undefined) this.#shown = message.rows.length
21
+ return true
22
+ }
23
+ if (message.changes === undefined) return false
24
+ this.#cost += message.changes.length + 1
25
+ return this.#cost <= this.#shown
26
+ }
27
+ }
package/src/index.ts CHANGED
@@ -71,7 +71,6 @@ export interface Http extends PluginTypes {
71
71
  | 'BAD_REQUEST'
72
72
  | 'BAD_USER_INPUT'
73
73
  | 'PAYLOAD_TOO_LARGE'
74
- | 'UNAVAILABLE'
75
74
  | 'UNSUPPORTED_MEDIA_TYPE'
76
75
  }
77
76
 
package/src/internal.ts CHANGED
@@ -11,6 +11,7 @@ export type {
11
11
  } from './pages.ts'
12
12
  export {
13
13
  applied,
14
+ endsOf,
14
15
  connection,
15
16
  countedPage,
16
17
  pageArgs,
@@ -19,6 +20,7 @@ export {
19
20
  rowOf,
20
21
  rowsOf,
21
22
  } from './pages.ts'
23
+ export { Backlog } from './backlog.ts'
22
24
  export type { Node, Served, ServedOneOf } from './transport.ts'
23
25
  export {
24
26
  badInput,
package/src/pages.ts CHANGED
@@ -163,6 +163,13 @@ export function connection<N>(
163
163
  }
164
164
  }
165
165
 
166
+ /**
167
+ * The first and last of `ids` as rows: a live window's page info without the
168
+ * rows between (D-253).
169
+ */
170
+ export const endsOf = (ids: readonly string[]): readonly Row[] =>
171
+ ids.map((id) => ({ id }))
172
+
166
173
  /** Whether a counted page reads no row: `first` or `last` 0, no cursor (D-226). */
167
174
  export const readsNoRow = (page: Page): boolean =>
168
175
  page.relay?.size === 0 && page.read['cursor'] === undefined
package/src/server.ts CHANGED
@@ -1,7 +1,13 @@
1
1
  // The port the server listens on, and its listening (D-106); the body
2
- // limit and the drain (D-223).
2
+ // limit and the drain (D-223); its connection queue (D-276); its listeners
3
+ // (D-292).
4
+ import cluster from 'node:cluster'
3
5
  import type { Server } from 'node:http'
4
6
  import { createServer } from 'node:http'
7
+ import {
8
+ createServer as createListener,
9
+ type Server as Listener,
10
+ } from 'node:net'
5
11
  import type { Duplex } from 'node:stream'
6
12
  import { getRequestListener } from '@hono/node-server'
7
13
  import type { Logger } from 'ultimabase'
@@ -37,7 +43,26 @@ export function drainOf(option: number | undefined): number {
37
43
  throw new Refused(`drain is ${ms}, not a whole number of milliseconds.`)
38
44
  }
39
45
 
40
- export async function listening(server: Server, port: number): Promise<number> {
46
+ /** The connections waiting to be accepted; the system caps it at its own. */
47
+ const backlog = 4096
48
+
49
+ /**
50
+ * The sockets listening on the port. Node accepts one connection per turn of
51
+ * its event loop and per socket, so a busy server takes connections this many
52
+ * times faster (D-292). The system shares them out, on Linux only; workers of
53
+ * a cluster already share theirs.
54
+ */
55
+ const listeners = process.platform === 'linux' && cluster.isPrimary ? 16 : 1
56
+
57
+ /** The listeners of each server beside itself. */
58
+ const others = new WeakMap<Server, readonly Listener[]>()
59
+
60
+ /** `listener` on `port`, refused in words when another process holds it. */
61
+ async function bound(
62
+ listener: Listener,
63
+ port: number,
64
+ reusePort: boolean,
65
+ ): Promise<void> {
41
66
  await new Promise<void>((done, fail) => {
42
67
  const refused = (error: Error) => {
43
68
  const code: unknown = Reflect.get(error, 'code')
@@ -50,16 +75,53 @@ export async function listening(server: Server, port: number): Promise<number> {
50
75
  : error,
51
76
  )
52
77
  }
53
- server.once('error', refused)
54
- server.listen(port, () => {
55
- server.off('error', refused)
78
+ listener.once('error', refused)
79
+ listener.listen({ port, backlog, reusePort }, () => {
80
+ listener.off('error', refused)
56
81
  done()
57
82
  })
58
83
  })
59
- const address = server.address()
84
+ }
85
+
86
+ /** Closed, once its connections have ended. */
87
+ async function shut(listener: Listener): Promise<void> {
88
+ await new Promise<void>((done, fail) => {
89
+ listener.close((error) => {
90
+ if (error === undefined) done()
91
+ else fail(error)
92
+ })
93
+ })
94
+ }
95
+
96
+ const boundPort = (listener: Listener, port: number) => {
97
+ const address = listener.address()
60
98
  return typeof address === 'object' && address !== null ? address.port : port
61
99
  }
62
100
 
101
+ export async function listening(server: Server, port: number): Promise<number> {
102
+ if (listeners === 1) {
103
+ await bound(server, port, false)
104
+ return boundPort(server, port)
105
+ }
106
+ // Sharing the port lets a second process in, so it must be free first.
107
+ if (port !== 0) {
108
+ const alone = createListener()
109
+ await bound(alone, port, false)
110
+ await shut(alone)
111
+ }
112
+ await bound(server, port, true)
113
+ const at = boundPort(server, port)
114
+ const rest = Array.from({ length: listeners - 1 }, () =>
115
+ // As `node:http` makes its own, whose connections it then takes.
116
+ createListener({ allowHalfOpen: true, noDelay: true }, (socket) => {
117
+ server.emit('connection', socket)
118
+ }),
119
+ )
120
+ others.set(server, rest)
121
+ await Promise.all(rest.map((listener) => bound(listener, at, true)))
122
+ return at
123
+ }
124
+
63
125
  /** A Node server for `fetch`, Hono's handler. */
64
126
  export function serverOf(
65
127
  fetch: Parameters<typeof getRequestListener>[0],
@@ -88,20 +150,18 @@ export async function closed(
88
150
  logger: Logger,
89
151
  taken: ReadonlyMap<Duplex, string>,
90
152
  ): Promise<void> {
91
- let cutting: NodeJS.Timeout | undefined
92
- await new Promise<void>((done, fail) => {
93
- server.close((error) => {
94
- clearTimeout(cutting)
95
- if (error === undefined) done()
96
- else fail(error)
97
- })
153
+ const cutting = setTimeout(() => {
154
+ logger.warn(
155
+ `Stopped ${grace / 1000} s after stop began: closed the requests still running.`,
156
+ )
157
+ server.closeAllConnections()
158
+ for (const socket of taken.keys()) socket.destroy()
159
+ }, grace)
160
+ try {
161
+ const closing = [server, ...(others.get(server) ?? [])].map(shut)
98
162
  server.closeIdleConnections()
99
- cutting = setTimeout(() => {
100
- logger.warn(
101
- `Stopped ${grace / 1000} s after stop began: closed the requests still running.`,
102
- )
103
- server.closeAllConnections()
104
- for (const socket of taken.keys()) socket.destroy()
105
- }, grace)
106
- })
163
+ await Promise.all(closing)
164
+ } finally {
165
+ clearTimeout(cutting)
166
+ }
107
167
  }