@revenexx/app-sdk 1.1.0 → 1.3.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.
package/README.md CHANGED
@@ -94,8 +94,28 @@ if (!placed) {
94
94
  `updateIf` makes the call throw — the client does not emulate it as a read
95
95
  followed by a write, because that is the race.
96
96
 
97
- The same holds for a numeric guard: `updateIf(id, { committed: seen }, { committed: seen + amount })`,
98
- retried on `null`, is an optimistic budget commit.
97
+ The same holds for a numeric guard. Read, compute, write only if nobody wrote in
98
+ between, and retry on `null`: that is an atomic decrement without a lost update.
99
+
100
+ ```js
101
+ async function reserve(db, budgetId, amount, attempts = 5) {
102
+ for (let i = 0; i < attempts; i++) {
103
+ const budget = await db.budgets.get(budgetId);
104
+ if (!budget) throw notFound('no such budget');
105
+ if (budget.available < amount) throw conflict('not enough budget left');
106
+ const next = await db.budgets.updateIf(
107
+ budgetId,
108
+ { available: budget.available }, // the value we based the decision on
109
+ { available: budget.available - amount },
110
+ );
111
+ if (next) return next; // our write won
112
+ }
113
+ throw conflict('the budget kept changing — try again');
114
+ }
115
+ ```
116
+
117
+ Two concurrent `reserve` calls cannot both spend the same amount: the second one's
118
+ condition no longer holds, it gets `null`, re-reads, and decides again.
99
119
 
100
120
  ### Permissions
101
121
 
@@ -228,6 +248,47 @@ GET /products?sku=in.(a,b)
228
248
  Value lists are not supported by the generic list; a route that needs one reads
229
249
  its own parameter (`queryParams`, or a hand-written list).
230
250
 
251
+ ### The trash in one call
252
+
253
+ An entity with `trash: true` in `schema.json` gets the routes a trash needs from
254
+ `mountTrash` (PE-1022):
255
+
256
+ ```js
257
+ const refs = createGatewayCounter();
258
+ const trash = mountTrash(app, db.organizations, {
259
+ path: '/organizations',
260
+ children: [{ name: 'contacts', repo: db.contacts, column: 'organization_id' }],
261
+ guard: (org) => (org.is_default ? { reason: 'the default organization stays' } : null),
262
+ blockers: async (org, c) => [
263
+ await refs.blocker(c, { path: '/v1/orders/open_orders', where: { organization_id: org.id }, reason: 'open orders' }),
264
+ ],
265
+ });
266
+ ```
267
+
268
+ - `DELETE /organizations/{id}` on a live row puts it into the trash with its live
269
+ children, as one group (`trash_batch`), recording `deleted_by` / `deleted_by_id`
270
+ from `c.actor`. `guard` reasons refuse it (`409 trash_blocked`).
271
+ - The same `DELETE` on a trashed row deletes it for good: the group's children
272
+ first, then the row. `blockers` reasons refuse it (`409 delete_blocked`);
273
+ `canDeleteForGood` can require its own permission (`403 not_permitted`).
274
+ - `POST /organizations/{id}/restore` brings back the row and the children of its
275
+ group. A child trashed on its own stays in the trash; a row whose `parent` is
276
+ in the trash is refused (`409 parent_in_trash`).
277
+ - `trash.purge(c)` is the scheduled job: it reads `trash_retention_days` through
278
+ the gateway (`GET /v1/audit/settings`, 90 when unset; `REVENEXX_AUDIT_SETTINGS_URL`
279
+ overrides the URL), and deletes for good what is older, through the same
280
+ `blockers`. A blocked row stays, with its reason in the result and in
281
+ `purge_blocked_reason`, which `trash: true` creates (`purgeReasonColumn: false`
282
+ for an entity without it). If the retention cannot be read the run is skipped —
283
+ it never guesses a shorter retention.
284
+
285
+ The PHP SDK has the same as `Trash::mount` and `GatewayCounter`.
286
+
287
+ A check that throws, and a cross-app count the gateway does not answer, block.
288
+ Declare `on: ["trash"]` / `on: ["restore"]` emits in the manifest to have
289
+ Baseline publish `*.trashed` / `*.restored` transactionally; `events` here is for
290
+ an App-fired summary per purge run.
291
+
231
292
  ### Constraint violations
232
293
 
233
294
  A database constraint doing its job is not a server fault. The data adapters
@@ -295,6 +356,8 @@ on the wording:
295
356
  | `undefined_condition` | 400 | a `where` entry left `undefined`, on any read or `updateIf` |
296
357
  | `unknown_filter`, `unsupported_filter_operator`, `invalid_value` | 400 | a mounted list's querystring |
297
358
  | `missing_parameter` | 400 | a `mountCrud` route without its path parameter |
359
+ | `trash_blocked`, `delete_blocked`, `already_in_trash`, `not_in_trash`, `parent_in_trash` | 409 | `mountTrash` routes |
360
+ | `not_permitted` | 403 | `mountTrash`'s final delete when `canDeleteForGood` refuses |
298
361
  | `no_route` / `method_not_allowed` | 404 / 405 | the router |
299
362
  | `internal_error` | 500 | anything thrown that is not an `HttpError` |
300
363
  | `unique_violation`, `exclusion_violation`, `foreign_key_violation`, `not_null_violation`, `check_violation`, `invalid_value`, `bad_request`, `data_error` | 409 / 400 / 500 | the data plane (table above) |
@@ -382,6 +445,46 @@ acting person from the context token's claims — those describe the calling
382
445
  *system*, which in a theme site is the theme's service user — and never from the
383
446
  request body, which is the caller's own word about itself.
384
447
 
448
+ ## The market a request is for
449
+
450
+ The gateway forwards the caller's market as `X-Revenexx-Market` and sets the
451
+ country that market ships from as `X-Revenexx-Market-Country` (the market's
452
+ `ship_from_country`, looked up and cached by the gateway). The country is
453
+ gateway-injected: whatever a caller sends under that name never reaches an App.
454
+
455
+ ```ts
456
+ app.post('/orders', async (c) => {
457
+ c.market; // { code: 'dach', country: 'AT' }
458
+ const from = c.body.sender_country ?? c.market.country ?? null;
459
+ });
460
+ ```
461
+
462
+ Either field is `null` when the gateway did not send it, a country is never
463
+ read without a market, and a value that is not an upper-case ISO 3166-1
464
+ alpha-2 code is ignored. A document prints its addresses for the sender
465
+ country: its own sender address when it has one, else `c.market.country`.
466
+ An App calling another App through the gateway sends `X-Revenexx-Market` on;
467
+ the gateway sets the country on that hop again.
468
+
469
+ ## Record history
470
+
471
+ The gateway may send a signed, short-lived envelope as `X-Revenexx-Audit` naming
472
+ the person behind a call. The `runtime` adapter passes it on to the data plane
473
+ unchanged with every request, and Baseline uses it to name that person in the
474
+ record history. There is nothing to do in an App: the SDK never reads it, `c.actor`
475
+ does not change, and a call without one is attributed to the token's subject as
476
+ before. Configuring the `remote` adapter by hand, pass it as `audit`.
477
+
478
+ A client may also say what a change is and why in `X-Revenexx-Audit-Note`
479
+ (URI-encoded JSON `{"title":"…","reason":"…"}`; the Cockpit sends it when an
480
+ operator rolls a record back). The gateway passes it to the App and the `runtime`
481
+ adapter passes it on with every request, so Baseline stores it with the history
482
+ entry of each write. It is descriptive only and never decides who is acting. A
483
+ note longer than 8192 bytes, or not one line of printable ASCII, is dropped and
484
+ the call proceeds. To describe a change the App makes on its own, pass
485
+ `auditNote` to the client (`createClient({ adapter: 'runtime', context, auditNote })`);
486
+ an empty string sends none. The `remote` adapter takes it as `auditNote` too.
487
+
385
488
  ## App settings
386
489
 
387
490
  An App declares the knobs a merchant may turn in `settings.json`; the Cockpit
package/dist/index.cjs CHANGED
@@ -396,11 +396,15 @@ function createRemoteAdapter(config) {
396
396
  }
397
397
  const base = String(config.endpoint ?? "").replace(/\/$/, "");
398
398
  if (!base) throw new Error("remote adapter: endpoint is required");
399
+ const audit = auditEnvelope(config.audit);
400
+ const note = auditNote(config.auditNote);
399
401
  const headers = (extra) => {
400
402
  const h = { "Content-Type": "application/json", Accept: "application/json", ...extra };
401
403
  if (config.token) h.Authorization = `Bearer ${config.token}`;
402
404
  if (config.tenant) h["X-Revenexx-Tenant"] = config.tenant;
403
405
  if (config.market) h["X-Revenexx-Market"] = config.market;
406
+ if (audit) h["X-Revenexx-Audit"] = audit;
407
+ if (note) h["X-Revenexx-Audit-Note"] = note;
404
408
  return h;
405
409
  };
406
410
  async function send(method, path, opts = {}) {
@@ -539,6 +543,12 @@ function createRemoteAdapter(config) {
539
543
  }
540
544
  };
541
545
  }
546
+ function auditEnvelope(value) {
547
+ return typeof value === "string" && /^[\x21-\x7e]{1,4096}$/.test(value) ? value : "";
548
+ }
549
+ function auditNote(value) {
550
+ return typeof value === "string" && /^[\x20-\x7e]{1,8192}$/.test(value) ? value : "";
551
+ }
542
552
 
543
553
  // src/adapters/runtime.ts
544
554
  var DEFAULT_DATA_ENDPOINT = "https://apps.api.revenexx.com";
@@ -555,7 +565,15 @@ function createRuntimeAdapter(config = {}) {
555
565
  // entities read the base table, so on the app path a list is unaffected by
556
566
  // it. See RemoteConfig.market; absent is a no-op on reads, not a narrower
557
567
  // default.
558
- market: get("x-revenexx-market") || env.REVENEXX_MARKET || ""
568
+ market: get("x-revenexx-market") || env.REVENEXX_MARKET || "",
569
+ // The record-history envelope of THIS request, passed through unchanged.
570
+ // Bound to the request's token and short-lived, so there is no env
571
+ // fallback: an App without one is attributed to the token's subject.
572
+ audit: get("x-revenexx-audit"),
573
+ // What the change is and why (the Cockpit sends it on a rollback). Like the
574
+ // envelope it belongs to THIS request, so there is no env fallback; unlike
575
+ // it, it names nobody, so an App may describe its own change instead.
576
+ auditNote: config.auditNote ?? get("x-revenexx-audit-note")
559
577
  });
560
578
  return { ...remote, kind: "runtime" };
561
579
  }