@ultimat3/action 31.48.0 → 31.50.0

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.
@@ -0,0 +1,48 @@
1
+ // The refusal responses every projected document states the same way: one `application/problem+json`
2
+ // envelope, and the rate-limit headers a 429 or a limited 200 carries. One copy, so the cookie
3
+ // document, a bearer mount's and its tenant listing can never drift apart.
4
+
5
+ import { PROBLEM_SCHEMA_NAME, schemaRef } from './naming';
6
+
7
+ export const RATE_LIMIT_HEADERS: Record<string, unknown> = {
8
+ 'RateLimit-Limit': {
9
+ description: 'Requests the bucket admits per window.',
10
+ schema: { type: 'integer' },
11
+ },
12
+ 'RateLimit-Remaining': {
13
+ description: 'Requests left in the current window.',
14
+ schema: { type: 'integer' },
15
+ },
16
+ 'RateLimit-Reset': {
17
+ description: 'Seconds until the bucket is full again.',
18
+ schema: { type: 'integer' },
19
+ },
20
+ };
21
+
22
+ export const RETRY_AFTER_HEADER: Record<string, unknown> = {
23
+ 'Retry-After': {
24
+ description: 'Seconds to wait before retrying.',
25
+ schema: { type: 'integer', minimum: 1 },
26
+ },
27
+ };
28
+
29
+ /** A refusal response: its description, any headers, and the shared Problem schema. */
30
+ export function problem(
31
+ description: string,
32
+ headers?: Record<string, unknown>,
33
+ ): Record<string, unknown> {
34
+ return {
35
+ description,
36
+ ...(headers === undefined ? {} : { headers }),
37
+ content: { 'application/problem+json': { schema: { $ref: schemaRef(PROBLEM_SCHEMA_NAME) } } },
38
+ };
39
+ }
40
+
41
+ /** The codes a 429 can carry here, named so a client knows which refusal it is reading. */
42
+ export function tooManyDescription(throttled: boolean, metered: boolean): string {
43
+ const codes = [
44
+ ...(throttled ? ['X_RATE_LIMITED'] : []),
45
+ ...(metered ? ['X_METER_EXCEEDED'] : []),
46
+ ].join(' or ');
47
+ return `${codes} — retry after Retry-After seconds`;
48
+ }
@@ -1,12 +1,12 @@
1
1
  /**
2
- * The record envelope, on the action's HTTP projection only. Derived from the output schema — an
3
- * action whose output references an entity row answers `{ data, records }` under
4
- * `x-ultimate-records: 1`; every other action's body is byte-identical to what it always was.
2
+ * The action's 200 on the HTTP projection. Derived from the output schema — an action whose output
3
+ * references an entity row answers `{ data, records }` under `x-ultimate-records: 1`; every other
4
+ * action's body is byte-identical to what it always was. Either names its instants by path.
5
5
  */
6
6
 
7
- import { encodeRecordEnvelope, RECORDS_HEADER } from '@ultimat3/core';
7
+ import { DATES_HEADER, encodeRecordEnvelope, RECORDS_HEADER } from '@ultimat3/core';
8
8
  import { hasEntityRows, rowsOf } from '@ultimat3/entity';
9
- import { jsonResponse } from '@ultimat3/http';
9
+ import { cappedWireDates, jsonResponse } from '@ultimat3/http';
10
10
  import type { StandardSchemaV1 } from '@ultimat3/schema';
11
11
 
12
12
  /** The header value that says "this body is an envelope". Presence alone is not enough. */
@@ -24,9 +24,29 @@ export function carriesRecords(output: StandardSchemaV1): boolean {
24
24
  return hasEntityRows(output);
25
25
  }
26
26
 
27
- /** The 200 for an action that carries records: the envelope, and the header that names it. */
27
+ /**
28
+ * The output's instants — `@ultimat3/core`'s `wire-dates.ts`, the rule `@ultimat3/query`'s
29
+ * `record-answer.ts` follows — so the typed client hands back the `Date` the output type promises.
30
+ * A header, never the body: an old client reads the ISO string it always read. Capped
31
+ * (`cappedWireDates`, 4 KB): an output needing one path per instant past that sends NO header —
32
+ * a proxy refuses a response whose headers outgrow its buffer — and is logged once per action.
33
+ */
34
+ function datesOf(result: unknown): { readonly headers: Record<string, string> } {
35
+ const dates = cappedWireDates(result);
36
+ return { headers: dates === undefined ? {} : { [DATES_HEADER]: dates } };
37
+ }
38
+
39
+ /** The 200 for an action that carries no records: the output itself. */
40
+ export function plainResponse(result: unknown): Response {
41
+ return jsonResponse(result, datesOf(result));
42
+ }
43
+
44
+ /**
45
+ * The 200 for an action that carries records: the envelope, and the header that names it. The
46
+ * paths are the DATA's, as on a read: the client revives the envelope's `data`, never `records`.
47
+ */
28
48
  export function recordResponse(output: StandardSchemaV1, result: unknown): Response {
29
- const response = jsonResponse(encodeRecordEnvelope(result, rowsOf(output, result)));
30
- response.headers.set(RECORDS_HEADER, ENVELOPED);
31
- return response;
49
+ return jsonResponse(encodeRecordEnvelope(result, rowsOf(output, result)), {
50
+ headers: { [RECORDS_HEADER]: ENVELOPED, ...datesOf(result).headers },
51
+ });
32
52
  }
package/src/tx-scope.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * The open database transaction, as this package needs it — **the only** file here that imports
3
3
  * `@ultimat3/db` (`tx-scope.test.ts`): when a write is durable, whether a transaction is OPEN and on
4
- * which client, a scope whose writes are never kept, and an executor that never joins one.
4
+ * which client, a scope whose writes are never kept, an executor that never joins one, and the
5
+ * one SQLSTATE an insert outside a transaction asks about.
5
6
  */
6
7
 
7
8
  // Type-only: `idempotency-postgres.ts` imports this module, and a runtime edge would be a cycle.
@@ -13,9 +14,12 @@ import {
13
14
  dbClientInstalled,
14
15
  liveTxConnection,
15
16
  outsideTransaction,
17
+ SQLSTATE,
18
+ sqlState,
16
19
  withTransaction,
17
20
  } from '@ultimat3/db';
18
21
  import { memoryJournal, memoryTransactor } from '@ultimat3/entity';
22
+ import { memoryTxOpen } from '@ultimat3/entity/internal/memory-tx';
19
23
 
20
24
  /** The mark a keyed run puts on the open root: its COMMIT carries the settle, abort or no abort. */
21
25
  export const carrySettleOnCommit = (): void => completeTransaction();
@@ -29,6 +33,10 @@ export const outsideTransactions = (executor: PgExecutor): PgExecutor => ({
29
33
  query: (text, values) => outsideTransaction(() => executor.query(text, values)),
30
34
  });
31
35
 
36
+ /** Whether `error` is Postgres' `unique_violation`, read through db's one SQLSTATE reader. */
37
+ export const isUniqueViolation = (error: unknown): boolean =>
38
+ sqlState(error) === SQLSTATE.uniqueViolation;
39
+
32
40
  /** The half of a transaction a deferred effect needs. `@ultimat3/db`'s `DbTx` satisfies it. */
33
41
  export interface CommitScope {
34
42
  /** Fired once the ROOT transaction has committed; dropped on rollback or a lost COMMIT. */
@@ -82,6 +90,23 @@ export function liveTransaction(): LiveTransaction | undefined {
82
90
  };
83
91
  }
84
92
 
93
+ /** The half of an open transaction a settle bound to it needs: its commit and its rollback. */
94
+ export type SettleScope = Pick<LiveTransaction, 'onCommit' | 'onRollback'>;
95
+
96
+ /**
97
+ * The OPEN transaction a settle rides — the SQL one (`liveTransaction`), else the open MEMORY one,
98
+ * the answer `openCommitScope` gives the bust. `undefined` outside both and for an ended scope, so
99
+ * a settle the body forgot to await is its own unit of work on either store, never a dropped one.
100
+ */
101
+ export function settleScope(): SettleScope | undefined {
102
+ const sql = liveTransaction();
103
+ if (sql !== undefined) return sql;
104
+ const memory = memoryJournal();
105
+ const onCommit = memory?.onCommit?.bind(memory);
106
+ if (memory === undefined || onCommit === undefined || !memoryTxOpen(memory)) return undefined;
107
+ return { onCommit, onRollback: (undo) => memory.onRollback(undo) };
108
+ }
109
+
85
110
  /**
86
111
  * Thrown inside the scope only to end it, and caught right outside: the one way a `withTransaction`
87
112
  * body asks for ROLLBACK. Never an `UltimateError`, because nothing but `inRolledBackScope` ever
package/src/validate.ts CHANGED
@@ -65,3 +65,23 @@ export async function validateOutput<S extends StandardSchemaV1>(
65
65
  }
66
66
  return result.value;
67
67
  }
68
+
69
+ /**
70
+ * A REPLAYED answer's parse. JSON has no `undefined`, so a store that keeps the answer as JSON (the
71
+ * Postgres store) hands back `null` for a handler that returned nothing — and an output schema
72
+ * that accepted `undefined` refused its own replay. A stored `null` the schema refuses is read as
73
+ * the `undefined` it stood for, when the schema takes that; any other refusal is the first one.
74
+ */
75
+ export async function validateReplayedOutput<S extends StandardSchemaV1>(
76
+ schema: S,
77
+ stored: unknown,
78
+ actionName: string,
79
+ ): Promise<InferOutput<S>> {
80
+ const result = await validateAsync(schema, stored);
81
+ if (result.issues === undefined) return result.value;
82
+ if (stored === null) {
83
+ const absent = await validateAsync(schema, undefined);
84
+ if (absent.issues === undefined) return absent.value;
85
+ }
86
+ throw new OutputInvalidError(actionName, formatIssues(result.issues).join('; '));
87
+ }