@revenexx/app-sdk 1.1.0 → 1.2.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,36 @@ 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
+
385
478
  ## App settings
386
479
 
387
480
  An App declares the knobs a merchant may turn in `settings.json`; the Cockpit
package/dist/index.cjs CHANGED
@@ -396,11 +396,13 @@ 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);
399
400
  const headers = (extra) => {
400
401
  const h = { "Content-Type": "application/json", Accept: "application/json", ...extra };
401
402
  if (config.token) h.Authorization = `Bearer ${config.token}`;
402
403
  if (config.tenant) h["X-Revenexx-Tenant"] = config.tenant;
403
404
  if (config.market) h["X-Revenexx-Market"] = config.market;
405
+ if (audit) h["X-Revenexx-Audit"] = audit;
404
406
  return h;
405
407
  };
406
408
  async function send(method, path, opts = {}) {
@@ -539,6 +541,9 @@ function createRemoteAdapter(config) {
539
541
  }
540
542
  };
541
543
  }
544
+ function auditEnvelope(value) {
545
+ return typeof value === "string" && /^[\x21-\x7e]{1,4096}$/.test(value) ? value : "";
546
+ }
542
547
 
543
548
  // src/adapters/runtime.ts
544
549
  var DEFAULT_DATA_ENDPOINT = "https://apps.api.revenexx.com";
@@ -555,7 +560,11 @@ function createRuntimeAdapter(config = {}) {
555
560
  // entities read the base table, so on the app path a list is unaffected by
556
561
  // it. See RemoteConfig.market; absent is a no-op on reads, not a narrower
557
562
  // default.
558
- market: get("x-revenexx-market") || env.REVENEXX_MARKET || ""
563
+ market: get("x-revenexx-market") || env.REVENEXX_MARKET || "",
564
+ // The record-history envelope of THIS request, passed through unchanged.
565
+ // Bound to the request's token and short-lived, so there is no env
566
+ // fallback: an App without one is attributed to the token's subject.
567
+ audit: get("x-revenexx-audit")
559
568
  });
560
569
  return { ...remote, kind: "runtime" };
561
570
  }