@inferencebureau/apps-sdk 0.16.7 → 0.16.9
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/dist/index.d.ts +119 -2
- package/dist/index.js +100 -2
- package/dist/test.js +93 -17
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -72,6 +72,12 @@ export interface FieldDef {
|
|
|
72
72
|
parent?: {
|
|
73
73
|
model: string;
|
|
74
74
|
};
|
|
75
|
+
/**
|
|
76
|
+
* A belongsTo's: what happens to this record when the record it points at is deleted. `"cascade"` deletes it too,
|
|
77
|
+
* `"setNull"` empties the field, `"restrict"` refuses the delete while a record still points at it. Unset, the field
|
|
78
|
+
* keeps the id of a record that's gone. Applied in the delete's own transaction, without running the model's delete action.
|
|
79
|
+
*/
|
|
80
|
+
onDelete?: "cascade" | "setNull" | "restrict";
|
|
75
81
|
child?: {
|
|
76
82
|
model: string;
|
|
77
83
|
belongsToField?: string;
|
|
@@ -113,7 +119,8 @@ export type ComputedAggregate = ({
|
|
|
113
119
|
* save or deploy (nothing blocks on it). `{ fields: ["shop", "createdAt"] }` serves equality on its first field with
|
|
114
120
|
* ranges and sorting on the rest; `unique: true` makes the fields' values unique together, checked by the database;
|
|
115
121
|
* `search: true` with fields serves `startsWith` and `contains` on each of them, and alone serves the model's text
|
|
116
|
-
* search
|
|
122
|
+
* search; one vector field on its own (`{ fields: ["embedding"] }`) serves nearest searches on it, given its
|
|
123
|
+
* `dimensions`. Fields are string, email, url, color, enum (one option), number, boolean, dateTime, belongsTo, or `id`,
|
|
117
124
|
* `createdAt`, `updatedAt`; `search` takes the text types (and rich text).
|
|
118
125
|
*/
|
|
119
126
|
export interface IndexDef {
|
|
@@ -625,8 +632,19 @@ export interface SaveOptions {
|
|
|
625
632
|
/** A number field's value written as an increment: `{ hits: increment(1) }` adds to the stored value under the record's lock, so two at once both count. */
|
|
626
633
|
export interface Increment {
|
|
627
634
|
_increment: number;
|
|
635
|
+
min?: number;
|
|
636
|
+
max?: number;
|
|
628
637
|
}
|
|
629
|
-
|
|
638
|
+
/**
|
|
639
|
+
* `increment(-1, { min: 0 })` takes one only while there's one to take: with a `min` or `max`, the write is made
|
|
640
|
+
* only if the value stays within it, checked on the stored value under the record's lock, so two at once can't both
|
|
641
|
+
* take the last one. One that would cross it throws a 409 `out_of_bounds` ApiError (`problems` names the field) and
|
|
642
|
+
* nothing is written.
|
|
643
|
+
*/
|
|
644
|
+
export declare const increment: (by?: number, o?: {
|
|
645
|
+
min?: number;
|
|
646
|
+
max?: number;
|
|
647
|
+
}) => Increment;
|
|
630
648
|
/** Marks a plain object as a record `save` can write: the action's own (the runtime does this before `run`), or one its `api` read or built. */
|
|
631
649
|
export declare function trackRecord<T extends object>(record: T, model?: string | null, isNew?: boolean): T;
|
|
632
650
|
/** Copies the action's params onto the record: `params.<model>` when the caller nested them, else params themselves. */
|
|
@@ -873,6 +891,31 @@ export type Api = ModelClients & {
|
|
|
873
891
|
* Held to the client's store and role as reads are: a store's client hears only of its records.
|
|
874
892
|
*/
|
|
875
893
|
$changes(o: ChangesOptions): Promise<Changes>;
|
|
894
|
+
/**
|
|
895
|
+
* Reads, then writes that depend on what was read, made together or not at all:
|
|
896
|
+
*
|
|
897
|
+
* await api.$transaction(async (tx) => {
|
|
898
|
+
* const slot = await tx.slot.findOne(slotId);
|
|
899
|
+
* if (!slot || slot.taken >= slot.capacity) throw new Error("That class is full.");
|
|
900
|
+
* tx.slot.update(slot.id, { taken: slot.taken + 1 });
|
|
901
|
+
* tx.booking.create({ slot: slot.id, user: userId });
|
|
902
|
+
* });
|
|
903
|
+
*
|
|
904
|
+
* `tx` reads like the API and collects writes instead of sending them. When the function returns, the writes are
|
|
905
|
+
* sent in one call and made in one database transaction, only if every record it read (by id, or in a page a find
|
|
906
|
+
* answered) still has the `updatedAt` it was read with. If one changed meanwhile, nothing is written and the
|
|
907
|
+
* function runs again from the top with fresh reads, up to `retries` more times (3 unless given), then the 409
|
|
908
|
+
* `version_conflict` ApiError is thrown. So the function may run several times: keep anything that mustn't repeat
|
|
909
|
+
* (an email, a charge) outside it. If it throws, nothing is written. It answers what the function returned.
|
|
910
|
+
*
|
|
911
|
+
* What it doesn't do: reads inside it see the records as stored, not its own writes so far; which records a
|
|
912
|
+
* `findMany` matched isn't checked again (one created since, or changed to match, goes unseen), so read the record
|
|
913
|
+
* that holds the count or the stock; related records read through `select` aren't checked; and the writes are made
|
|
914
|
+
* directly, as `save()` on another record in an action is: a model's own create, update or delete action doesn't
|
|
915
|
+
* run. At most 250 writes. Not through a role-held `api` (`asRole`); a store's (`forShop`) writes that store's
|
|
916
|
+
* records. In an action it stands apart from the run: it commits at once, whether or not the run goes on to succeed.
|
|
917
|
+
*/
|
|
918
|
+
$transaction<T>(run: (tx: Transaction) => Promise<T>, o?: TransactionOptions): Promise<T>;
|
|
876
919
|
/** Runs a global action (`api/actions/<name>.ts`). With an `idempotencyKey`, a retried call answers the first run. */
|
|
877
920
|
$global<A extends GlobalName>(action: A, params?: GlobalOf<A>["params"], o?: IdempotentOptions): Promise<{
|
|
878
921
|
result?: GlobalOf<A>["result"];
|
|
@@ -905,6 +948,28 @@ export type Api = ModelClients & {
|
|
|
905
948
|
* request's `api` already are.
|
|
906
949
|
*/
|
|
907
950
|
asRole(role: string | string[], session?: CallerSession): Api;
|
|
951
|
+
/**
|
|
952
|
+
* The same API with its calls counted against one caller's own limit (20 a second, bursts of 300), so one caller
|
|
953
|
+
* can't use up the app's: `key` is whatever tells callers apart, an API customer's id or a device. Calls for a
|
|
954
|
+
* signed-in user or a customer (`asRole(role, { userId })`) are already counted per person, and the app's records
|
|
955
|
+
* route (`serveRecords`) counts signed-out visitors by IP; name a key where neither fits. Past the limit a call
|
|
956
|
+
* throws ApiError 429 `rate_limit_exceeded`.
|
|
957
|
+
*/
|
|
958
|
+
asCaller(key: string): Api;
|
|
959
|
+
/**
|
|
960
|
+
* A limit of the app's own: counts one call against `key` and answers whether it's within `limit` per
|
|
961
|
+
* `windowSeconds` (up to a day). For what the app decides to limit, in a page, a route or an action:
|
|
962
|
+
*
|
|
963
|
+
* const gate = await api.rateLimit(`contact:${ip}`, { limit: 5, windowSeconds: 3600 });
|
|
964
|
+
* if (!gate.allowed) return { error: `Too many messages. Try again in ${Math.ceil(gate.resetAfter / 60)} minutes.` };
|
|
965
|
+
*
|
|
966
|
+
* The call is counted either way, before it answers, so calls sent at once can't all pass. Keys are the
|
|
967
|
+
* environment's own; put what the limit is for in the key (`"contact:"`), so two limits never share a count.
|
|
968
|
+
*/
|
|
969
|
+
rateLimit(key: string, o: {
|
|
970
|
+
limit: number;
|
|
971
|
+
windowSeconds: number;
|
|
972
|
+
}): Promise<RateLimit>;
|
|
908
973
|
/** Shopify sync on demand: one store, some or all of its synced models, everything or what changed since a date. */
|
|
909
974
|
shopifySync: ShopifySync;
|
|
910
975
|
/**
|
|
@@ -914,6 +979,54 @@ export type Api = ModelClients & {
|
|
|
914
979
|
*/
|
|
915
980
|
files: FilesClient;
|
|
916
981
|
};
|
|
982
|
+
/** A model inside `api.$transaction`: reads go to the API and are remembered; writes are collected for the commit. */
|
|
983
|
+
export interface TransactionModel<M extends ModelTypes = UntypedModel> {
|
|
984
|
+
findOne<S extends SelectOf<M> | undefined = undefined>(id: string, o?: {
|
|
985
|
+
select?: S;
|
|
986
|
+
}): Promise<ReadOf<M, S> | null>;
|
|
987
|
+
findMany<S extends SelectOf<M> | undefined = undefined>(o?: FindManyOptions<M, S>): Promise<RecordPage<ReadOf<M, S>>>;
|
|
988
|
+
findFirst<S extends SelectOf<M> | undefined = undefined>(o?: Omit<FindManyOptions<M, S>, "first" | "after" | "last" | "before">): Promise<ReadOf<M, S> | null>;
|
|
989
|
+
/** A new record, made when the transaction commits. Its id is known now, so other writes can point at it. */
|
|
990
|
+
create(values: M["input"]): {
|
|
991
|
+
id: string;
|
|
992
|
+
};
|
|
993
|
+
/** Changes the given fields when the transaction commits; a number field takes `increment(n)`. */
|
|
994
|
+
update(id: string, values: M["input"]): void;
|
|
995
|
+
delete(id: string): void;
|
|
996
|
+
}
|
|
997
|
+
/** What `api.$transaction` hands its function: each model by name, as `api` has them. */
|
|
998
|
+
export type Transaction = (Typed<AppModels> extends true ? {
|
|
999
|
+
[K in keyof AppModels]: TransactionModel<AppModels[K] extends ModelTypes ? AppModels[K] : UntypedModel>;
|
|
1000
|
+
} : {
|
|
1001
|
+
[model: string]: TransactionModel;
|
|
1002
|
+
}) & {
|
|
1003
|
+
$model<N extends string>(name: N): TransactionModel<ModelOf<N>>;
|
|
1004
|
+
};
|
|
1005
|
+
export interface TransactionOptions {
|
|
1006
|
+
/** How many more times the function runs when a record it read changed before the commit: 3 unless given, 0 to 10. */
|
|
1007
|
+
retries?: number;
|
|
1008
|
+
}
|
|
1009
|
+
/** What a transaction sends when its function returns: the records it read, as read, and its writes in order. */
|
|
1010
|
+
export interface TransactionCommit {
|
|
1011
|
+
reads: {
|
|
1012
|
+
model: string;
|
|
1013
|
+
id: string;
|
|
1014
|
+
updatedAt: string;
|
|
1015
|
+
}[];
|
|
1016
|
+
writes: StagedWrite[];
|
|
1017
|
+
}
|
|
1018
|
+
/**
|
|
1019
|
+
* Runs a transaction's function over `api`'s reads and sends what it collected to `commit`, again when the commit
|
|
1020
|
+
* answers that a read changed (409 `version_conflict`). Shared by the API client and the test app.
|
|
1021
|
+
*/
|
|
1022
|
+
export declare function runTransaction<T>(api: Api, commit: (c: TransactionCommit) => Promise<unknown>, run: (tx: Transaction) => Promise<T>, o?: TransactionOptions): Promise<T>;
|
|
1023
|
+
/** What `api.rateLimit` answers: whether the call is within the limit, how many are left in the window, and the seconds until it ends. */
|
|
1024
|
+
export interface RateLimit {
|
|
1025
|
+
allowed: boolean;
|
|
1026
|
+
limit: number;
|
|
1027
|
+
remaining: number;
|
|
1028
|
+
resetAfter: number;
|
|
1029
|
+
}
|
|
917
1030
|
/** A file in the app's storage. `url` is the CDN's for a public file and signed for an hour for a private one. */
|
|
918
1031
|
export interface StorageFile {
|
|
919
1032
|
path: string;
|
|
@@ -1082,6 +1195,10 @@ export interface ClientOptions {
|
|
|
1082
1195
|
/** Holds every call to a role in permissions.ib.ts, or to several roles' grants together (see `Api.asRole`). */
|
|
1083
1196
|
role?: string | string[];
|
|
1084
1197
|
session?: CallerSession;
|
|
1198
|
+
/** Counts every call against this caller's own limit (see `Api.asCaller`). */
|
|
1199
|
+
caller?: string;
|
|
1200
|
+
/** The visitor's IP, which calls are counted by when they're for no user, customer or named caller (`serveRecords` sets it). */
|
|
1201
|
+
callerIp?: string;
|
|
1085
1202
|
}
|
|
1086
1203
|
/** The app's API. In an app's deployment every option comes from its environment variables. */
|
|
1087
1204
|
export declare function createClient(o?: ClientOptions): Api;
|
package/dist/index.js
CHANGED
|
@@ -35,7 +35,13 @@ export function describeSchema(name, schema) {
|
|
|
35
35
|
],
|
|
36
36
|
};
|
|
37
37
|
}
|
|
38
|
-
|
|
38
|
+
/**
|
|
39
|
+
* `increment(-1, { min: 0 })` takes one only while there's one to take: with a `min` or `max`, the write is made
|
|
40
|
+
* only if the value stays within it, checked on the stored value under the record's lock, so two at once can't both
|
|
41
|
+
* take the last one. One that would cross it throws a 409 `out_of_bounds` ApiError (`problems` names the field) and
|
|
42
|
+
* nothing is written.
|
|
43
|
+
*/
|
|
44
|
+
export const increment = (by = 1, o = {}) => ({ _increment: by, ...(o.min !== undefined ? { min: o.min } : {}), ...(o.max !== undefined ? { max: o.max } : {}) });
|
|
39
45
|
/** Shared by every copy of this module that loads, so `save` works whichever copy an action imported. */
|
|
40
46
|
const STATE = Symbol.for("inferencebureau.apps.record");
|
|
41
47
|
/** The order records were saved in, across copies too: they're written in that order. */
|
|
@@ -134,6 +140,76 @@ export class ApiError extends Error {
|
|
|
134
140
|
}
|
|
135
141
|
/** The most records one bulk call takes. */
|
|
136
142
|
export const MAX_BULK = 250;
|
|
143
|
+
const TRANSACTION_RETRIES = 3;
|
|
144
|
+
/**
|
|
145
|
+
* Runs a transaction's function over `api`'s reads and sends what it collected to `commit`, again when the commit
|
|
146
|
+
* answers that a read changed (409 `version_conflict`). Shared by the API client and the test app.
|
|
147
|
+
*/
|
|
148
|
+
export async function runTransaction(api, commit, run, o = {}) {
|
|
149
|
+
const retries = o.retries ?? TRANSACTION_RETRIES;
|
|
150
|
+
if (!Number.isInteger(retries) || retries < 0 || retries > 10)
|
|
151
|
+
throw new Error("A transaction's retries is a whole number from 0 to 10.");
|
|
152
|
+
for (let tries = 0;; tries++) {
|
|
153
|
+
const reads = new Map();
|
|
154
|
+
const writes = [];
|
|
155
|
+
let open = true;
|
|
156
|
+
const stage = (w) => {
|
|
157
|
+
if (!open)
|
|
158
|
+
throw new Error("This transaction has finished: its function returned before this write. Await the work inside it.");
|
|
159
|
+
if (writes.length >= MAX_BULK)
|
|
160
|
+
throw new Error(`A transaction makes at most ${MAX_BULK} writes. Queue the rest as jobs.`);
|
|
161
|
+
writes.push(w);
|
|
162
|
+
};
|
|
163
|
+
// The first read of a record is the one checked: a later read that differs means it changed mid-way, a conflict.
|
|
164
|
+
const see = (model, r) => {
|
|
165
|
+
if (!r)
|
|
166
|
+
return r;
|
|
167
|
+
if (typeof r.id !== "string" || typeof r.updatedAt !== "string")
|
|
168
|
+
throw new Error(`A transaction checks what it read by id and updatedAt; keep both in the select of ${model}.`);
|
|
169
|
+
if (!reads.has(r.id))
|
|
170
|
+
reads.set(r.id, { model, id: r.id, updatedAt: r.updatedAt });
|
|
171
|
+
return r;
|
|
172
|
+
};
|
|
173
|
+
const values = (v) => Object.fromEntries(Object.entries(v ?? {}).filter(([k, x]) => k !== "id" && k !== "createdAt" && k !== "updatedAt" && x !== undefined));
|
|
174
|
+
const models = new Map();
|
|
175
|
+
const model = (name) => {
|
|
176
|
+
if (!models.has(name)) {
|
|
177
|
+
const m = api.$model(name);
|
|
178
|
+
models.set(name, {
|
|
179
|
+
findOne: async (id, q) => see(name, await m.findOne(id, q)),
|
|
180
|
+
findFirst: async (q) => see(name, await m.findFirst(q)),
|
|
181
|
+
findMany: async (q) => { const page = await m.findMany(q); for (const r of page.records)
|
|
182
|
+
see(name, r); return page; },
|
|
183
|
+
create(v) { const id = newRecordId(); stage({ model: name, op: "create", id, values: values(v) }); return { id }; },
|
|
184
|
+
update(id, v) { stage({ model: name, op: "update", id, values: values(v) }); },
|
|
185
|
+
delete(id) { stage({ model: name, op: "delete", id }); },
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
return models.get(name);
|
|
189
|
+
};
|
|
190
|
+
const tx = new Proxy({}, { get: (_t, prop) => (prop === "$model" ? model : typeof prop !== "string" || prop === "then" ? undefined : model(prop)) });
|
|
191
|
+
let result;
|
|
192
|
+
try {
|
|
193
|
+
result = await run(tx);
|
|
194
|
+
}
|
|
195
|
+
finally {
|
|
196
|
+
open = false;
|
|
197
|
+
}
|
|
198
|
+
// Nothing to write: the reads were ordinary reads, and there's nothing for them to hold up.
|
|
199
|
+
if (!writes.length)
|
|
200
|
+
return result;
|
|
201
|
+
try {
|
|
202
|
+
await commit({ reads: [...reads.values()], writes });
|
|
203
|
+
return result;
|
|
204
|
+
}
|
|
205
|
+
catch (e) {
|
|
206
|
+
if (!(e instanceof ApiError && e.status === 409 && e.code === "version_conflict") || tries >= retries)
|
|
207
|
+
throw e;
|
|
208
|
+
// A short, growing, jittered wait, so the writers that collided don't all come back at once.
|
|
209
|
+
await new Promise((done) => setTimeout(done, Math.min(1000, 20 * 2 ** tries) * (0.5 + Math.random())));
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
137
213
|
/** The most bytes `files.put` sends in the request itself; a bigger file goes straight to storage. */
|
|
138
214
|
export const STORAGE_INLINE_BYTES = 4 * 1024 * 1024;
|
|
139
215
|
const envVar = (name) => globalThis.process?.env?.[name];
|
|
@@ -150,6 +226,8 @@ export function createClient(o = {}) {
|
|
|
150
226
|
const scope = {
|
|
151
227
|
...(o.shop ? { "x-ib-shop": o.shop } : {}), ...(role ? { "x-ib-role": role } : {}),
|
|
152
228
|
...(role && o.session ? { "x-ib-session": JSON.stringify({ userId: o.session.userId ?? null, customerId: o.session.customerId ?? null, ...(o.session.customerRecordId ? { customerRecordId: o.session.customerRecordId } : {}), ...(o.session.accountId ? { accountId: o.session.accountId } : {}) }) } : {}),
|
|
229
|
+
// Who the calls are for, so they count against that caller's own limit (#285).
|
|
230
|
+
...(o.caller ? { "x-ib-caller": o.caller } : {}), ...(o.callerIp ? { "x-ib-caller-ip": o.callerIp } : {}),
|
|
153
231
|
};
|
|
154
232
|
/**
|
|
155
233
|
* A call with a JSON body (or none); `raw` sends bytes as they are, with their type when known. A call turned away
|
|
@@ -296,8 +374,19 @@ export function createClient(o = {}) {
|
|
|
296
374
|
};
|
|
297
375
|
const forShop = (shop) => createClient({ ...o, url, token, app, environment, fetch: f, shop });
|
|
298
376
|
const asRole = (role, session) => createClient({ ...o, url, token, app, environment, fetch: f, role, ...(session ? { session } : {}) });
|
|
299
|
-
|
|
377
|
+
const asCaller = (caller) => createClient({ ...o, url, token, app, environment, fetch: f, caller });
|
|
378
|
+
const rateLimit = (key, q) => call("POST", "/rate-limit", { key, limit: q.limit, windowSeconds: q.windowSeconds });
|
|
379
|
+
const $transaction = (run, q) => runTransaction(self, (commit) => call("POST", "/transactions", commit), run, q);
|
|
380
|
+
const self = new Proxy({}, {
|
|
300
381
|
get(_t, prop) {
|
|
382
|
+
if (prop === "$transaction")
|
|
383
|
+
return $transaction;
|
|
384
|
+
if (prop === "asCaller")
|
|
385
|
+
return asCaller;
|
|
386
|
+
if (prop === "rateLimit")
|
|
387
|
+
return rateLimit;
|
|
388
|
+
if (prop === CALLER_IP)
|
|
389
|
+
return (ip) => (o.callerIp === ip ? undefined : createClient({ ...o, url, token, app, environment, fetch: f, callerIp: ip }));
|
|
301
390
|
if (prop === "$global")
|
|
302
391
|
return $global;
|
|
303
392
|
if (prop === "$changes")
|
|
@@ -321,7 +410,11 @@ export function createClient(o = {}) {
|
|
|
321
410
|
return modelNamed(prop);
|
|
322
411
|
},
|
|
323
412
|
});
|
|
413
|
+
return self;
|
|
324
414
|
}
|
|
415
|
+
// ---- the records route ----
|
|
416
|
+
/** How serveRecords hands a client the visitor's IP; not part of the Api's surface. */
|
|
417
|
+
const CALLER_IP = Symbol.for("ib.callerIp");
|
|
325
418
|
const errorBody = (status, code, message, problems = []) => Response.json({ error: { code, message, ...(problems.length ? { problems } : {}) } }, { status });
|
|
326
419
|
/**
|
|
327
420
|
* The app's records route, for its pages' own scripts: the hooks and AutoTable/AutoForm in
|
|
@@ -340,6 +433,11 @@ export async function serveRecords(request, api, o = {}) {
|
|
|
340
433
|
return errorBody(401, "unauthorized", "Sign in to see this.");
|
|
341
434
|
if (request.method !== "POST")
|
|
342
435
|
return errorBody(405, "method_not_allowed", "The records route takes POST.");
|
|
436
|
+
// The visitor's IP, as Inference Bureau's router sets it, so a signed-out visitor's calls count against their own
|
|
437
|
+
// limit and not only the app's (#285). Not on a Shopify proxy request: that one comes from Shopify's servers.
|
|
438
|
+
const ip = request.headers.get("x-ib-proxy-signature") ? null : request.headers.get("x-ib-client-ip");
|
|
439
|
+
if (ip)
|
|
440
|
+
api = api[CALLER_IP]?.(ip) ?? api;
|
|
343
441
|
let body;
|
|
344
442
|
try {
|
|
345
443
|
body = (await request.json());
|
package/dist/test.js
CHANGED
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
* fetched, size 0), and `upload`/`createUpload` tokens as the upload (a `createUpload` needs no PUT here). The app's
|
|
20
20
|
* storage (`api.files`) is in memory too: a file reads back as a `data:` URL, and `reset()` empties it.
|
|
21
21
|
*/
|
|
22
|
-
import { ApiError, MAX_BULK, ShopifyError, createAiClient, describeSchema, newRecordId } from "./index.js";
|
|
22
|
+
import { ApiError, MAX_BULK, ShopifyError, createAiClient, describeSchema, newRecordId, runTransaction } from "./index.js";
|
|
23
23
|
import { runAction as runPhase } from "./runtime.js";
|
|
24
24
|
/** Kept in `data`; the rest are a vector, the other side of a relationship, or worked out (computed). */
|
|
25
25
|
const STORED = new Set(["string", "richText", "email", "url", "color", "number", "dateTime", "enum", "boolean", "roleList", "json", "belongsTo", "password", "encryptedString", "file"]);
|
|
@@ -89,7 +89,16 @@ const ifUpdatedAtOf = (v) => {
|
|
|
89
89
|
return v;
|
|
90
90
|
};
|
|
91
91
|
/** A number field written as `{ _increment: n }` (the SDK's `increment`): added to the stored value. */
|
|
92
|
-
const incrementOf = (v) => (
|
|
92
|
+
const incrementOf = (v) => incrementSpec(v)?.by ?? null;
|
|
93
|
+
/** With an optional `min` and `max` the result must stay within (`increment(n, { min, max })`), else 409 `out_of_bounds`. */
|
|
94
|
+
function incrementSpec(v) {
|
|
95
|
+
if (!isObj(v) || typeof v._increment !== "number" || !Number.isFinite(v._increment))
|
|
96
|
+
return null;
|
|
97
|
+
const bound = (b) => b === undefined || (typeof b === "number" && Number.isFinite(b));
|
|
98
|
+
if (Object.keys(v).some((k) => k !== "_increment" && k !== "min" && k !== "max") || !bound(v.min) || !bound(v.max))
|
|
99
|
+
return null;
|
|
100
|
+
return { by: v._increment, ...(v.min !== undefined ? { min: v.min } : {}), ...(v.max !== undefined ? { max: v.max } : {}) };
|
|
101
|
+
}
|
|
93
102
|
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
94
103
|
/** What crosses the wire between Inference Bureau and the app: JSON (a Date arrives as its ISO string). */
|
|
95
104
|
const wire = (v) => (v === undefined ? v : JSON.parse(JSON.stringify(v)));
|
|
@@ -1484,6 +1493,7 @@ class Records {
|
|
|
1484
1493
|
if (!isObj(params))
|
|
1485
1494
|
throw invalid([{ field: "record", message: "must be an object of field values" }]);
|
|
1486
1495
|
const problems = [];
|
|
1496
|
+
const bounds = [];
|
|
1487
1497
|
const data = { ...(current?.data ?? {}) };
|
|
1488
1498
|
const vectors = new Map();
|
|
1489
1499
|
const changed = new Set();
|
|
@@ -1511,7 +1521,17 @@ class Records {
|
|
|
1511
1521
|
continue;
|
|
1512
1522
|
}
|
|
1513
1523
|
const stored = current ? current.data[f.key] : defaultOf(f);
|
|
1514
|
-
const
|
|
1524
|
+
const next = by === null ? value : (typeof stored === "number" ? stored : Number(stored) || 0) + by;
|
|
1525
|
+
const inc = incrementSpec(value);
|
|
1526
|
+
if (inc?.min !== undefined && next < inc.min) {
|
|
1527
|
+
bounds.push({ field: name, message: `would go below ${inc.min} (it would be ${next})` });
|
|
1528
|
+
continue;
|
|
1529
|
+
}
|
|
1530
|
+
if (inc?.max !== undefined && next > inc.max) {
|
|
1531
|
+
bounds.push({ field: name, message: `would go above ${inc.max} (it would be ${next})` });
|
|
1532
|
+
continue;
|
|
1533
|
+
}
|
|
1534
|
+
const c = convert(f, next, "write");
|
|
1515
1535
|
if (!c.ok) {
|
|
1516
1536
|
problems.push({ field: name, message: c.message });
|
|
1517
1537
|
continue;
|
|
@@ -1594,6 +1614,8 @@ class Records {
|
|
|
1594
1614
|
}
|
|
1595
1615
|
if (problems.length)
|
|
1596
1616
|
throw invalid(problems);
|
|
1617
|
+
if (bounds.length)
|
|
1618
|
+
throw new ApiError(bounds.map((p) => `${p.field}: ${p.message}`).join("; "), 409, "out_of_bounds", bounds);
|
|
1597
1619
|
if (JSON.stringify(data).length > MAX_RECORD_BYTES)
|
|
1598
1620
|
throw invalid([{ field: "record", message: `is larger than ${MAX_RECORD_BYTES / 1024} KiB` }]);
|
|
1599
1621
|
return { data, vectors, changed };
|
|
@@ -2526,20 +2548,7 @@ export function createTestApp(o = {}) {
|
|
|
2526
2548
|
else
|
|
2527
2549
|
saved = type === "create" ? await store.create(model, reply.write.values, String(record.id)) : await store.update(model, input.id, reply.write.values, { ifUpdatedAt: ifUpdatedAtOf(reply.write.ifUpdatedAt ?? input.ifUpdatedAt) });
|
|
2528
2550
|
}
|
|
2529
|
-
|
|
2530
|
-
const m = store.model(w.model);
|
|
2531
|
-
// A run about one store writes that store's records of a store-owned model, as through the API.
|
|
2532
|
-
const f = shop ? storeField(m) : null;
|
|
2533
|
-
const own = { shop, role: null, session: { userId: null, customerId: null, customerRecordId: null, accountId: null } };
|
|
2534
|
-
if (w.op !== "create" && f && !(await findVisible(m.name, w.id, { [f]: { equals: shop } })))
|
|
2535
|
-
throw notFound(`There's no ${m.name} with id ${w.id}.`);
|
|
2536
|
-
if (w.op === "delete")
|
|
2537
|
-
store.delete(m.name, w.id);
|
|
2538
|
-
else if (w.op === "update")
|
|
2539
|
-
await store.update(m.name, w.id, f ? scopedUpdate(own, m, wire(w.values)) : wire(w.values), { ifUpdatedAt: ifUpdatedAtOf(w.ifUpdatedAt) });
|
|
2540
|
-
else
|
|
2541
|
-
await store.create(m.name, f ? scopedValues(own, m, wire(w.values)) : wire(w.values), w.id);
|
|
2542
|
-
}
|
|
2551
|
+
await applyStaged(shop, others);
|
|
2543
2552
|
}
|
|
2544
2553
|
catch (e) {
|
|
2545
2554
|
store.restore(before);
|
|
@@ -2559,6 +2568,50 @@ export function createTestApp(o = {}) {
|
|
|
2559
2568
|
const otherStore = (shop) => denied(`This call is for ${shop}; it can't reach another store's records.`);
|
|
2560
2569
|
/** The record by id when the filter lets the call see it (undefined: no narrowing), else null. */
|
|
2561
2570
|
const findVisible = async (model, id, filter, select, readable) => (filter ? (await store.findMany(model, { filter: { AND: [{ id: { equals: id } }, filter] }, first: 1, select, readable })).records[0] ?? null : store.findOne(model, id, { select, readable }));
|
|
2571
|
+
/** Writes sent to be made together (a run's other records, a transaction's), in order; the caller restores the store when one is refused. */
|
|
2572
|
+
const applyStaged = async (shop, writes) => {
|
|
2573
|
+
for (const w of writes) {
|
|
2574
|
+
const m = store.model(w.model);
|
|
2575
|
+
// A run about one store writes that store's records of a store-owned model, as through the API.
|
|
2576
|
+
const f = shop ? storeField(m) : null;
|
|
2577
|
+
const own = { shop, role: null, session: { userId: null, customerId: null, customerRecordId: null, accountId: null } };
|
|
2578
|
+
if (w.op !== "create" && f && !(await findVisible(m.name, w.id, { [f]: { equals: shop } })))
|
|
2579
|
+
throw notFound(`There's no ${m.name} with id ${w.id}.`);
|
|
2580
|
+
if (w.op === "delete")
|
|
2581
|
+
store.delete(m.name, w.id);
|
|
2582
|
+
else if (w.op === "update")
|
|
2583
|
+
await store.update(m.name, w.id, f ? scopedUpdate(own, m, wire(w.values)) : wire(w.values), { ifUpdatedAt: ifUpdatedAtOf(w.ifUpdatedAt) });
|
|
2584
|
+
else
|
|
2585
|
+
await store.create(m.name, f ? scopedValues(own, m, wire(w.values)) : wire(w.values), w.id);
|
|
2586
|
+
}
|
|
2587
|
+
};
|
|
2588
|
+
/**
|
|
2589
|
+
* A transaction's commit (`api.$transaction`), as the API makes it: every record read must stand as it was read
|
|
2590
|
+
* (409 `version_conflict` otherwise), then the writes are made, all or none.
|
|
2591
|
+
*/
|
|
2592
|
+
const commitTransaction = async (scope, c) => {
|
|
2593
|
+
if (scope.role)
|
|
2594
|
+
throw denied("A transaction writes records directly, past a role's grants and the models' actions; commit it from the app's server code, without a role.");
|
|
2595
|
+
const sent = wire(c);
|
|
2596
|
+
if (sent.writes.length > MAX_BULK)
|
|
2597
|
+
throw new ApiError(`A transaction makes at most ${MAX_BULK} writes; this one has ${sent.writes.length}. Queue the rest as jobs.`, 400, "invalid_request");
|
|
2598
|
+
for (const r of sent.reads) {
|
|
2599
|
+
const m = store.model(r.model);
|
|
2600
|
+
const now = store.findOne(m.name, r.id);
|
|
2601
|
+
if (!now)
|
|
2602
|
+
throw new ApiError(`${m.name} ${r.id} was deleted after it was read. Read again and retry.`, 409, "version_conflict");
|
|
2603
|
+
if (!sameInstant(now.updatedAt, r.updatedAt))
|
|
2604
|
+
throw new ConflictError(m.name, r.id, now.updatedAt);
|
|
2605
|
+
}
|
|
2606
|
+
const before = store.snapshot();
|
|
2607
|
+
try {
|
|
2608
|
+
await applyStaged(scope.shop, sent.writes);
|
|
2609
|
+
}
|
|
2610
|
+
catch (e) {
|
|
2611
|
+
store.restore(before);
|
|
2612
|
+
throw e;
|
|
2613
|
+
}
|
|
2614
|
+
};
|
|
2562
2615
|
/** Refuses a run the scope doesn't allow; a record its store or grant doesn't reach is answered as missing. */
|
|
2563
2616
|
async function canRun(scope, model, action, id) {
|
|
2564
2617
|
if (!isScoped(scope))
|
|
@@ -2808,6 +2861,22 @@ export function createTestApp(o = {}) {
|
|
|
2808
2861
|
};
|
|
2809
2862
|
const syncRuns = [];
|
|
2810
2863
|
const apis = new Map();
|
|
2864
|
+
// The app's own rate limits, counted as the API does: per key, in fixed windows from the epoch on the harness's clock.
|
|
2865
|
+
const limitCounts = new Map();
|
|
2866
|
+
const rateLimit = async (key, q) => {
|
|
2867
|
+
const whole = (n, max) => typeof n === "number" && Number.isInteger(n) && n >= 1 && n <= max;
|
|
2868
|
+
if (typeof key !== "string" || !key.trim() || key.length > 200)
|
|
2869
|
+
throw new ApiError("key is text of 1 to 200 characters", 400, "invalid_request");
|
|
2870
|
+
if (!whole(q?.limit, 1_000_000))
|
|
2871
|
+
throw new ApiError("limit is a whole number from 1 to 1,000,000", 400, "invalid_request");
|
|
2872
|
+
if (!whole(q?.windowSeconds, 86_400))
|
|
2873
|
+
throw new ApiError("windowSeconds is a whole number from 1 to 86,400 (a day)", 400, "invalid_request");
|
|
2874
|
+
const now = (o.now ?? Date.now)(), span = q.windowSeconds * 1000, window = Math.floor(now / span);
|
|
2875
|
+
const at = `${key}\n${q.windowSeconds}\n${window}`;
|
|
2876
|
+
const n = (limitCounts.get(at) ?? 0) + 1;
|
|
2877
|
+
limitCounts.set(at, n);
|
|
2878
|
+
return { allowed: n <= q.limit, limit: q.limit, remaining: Math.max(0, q.limit - n), resetAfter: Math.max(1, Math.ceil(((window + 1) * span - now) / 1000)) };
|
|
2879
|
+
};
|
|
2811
2880
|
/** A role's name as the API takes it; a malformed one is refused, never ignored (ignoring it would widen the call). */
|
|
2812
2881
|
const roleOf = (role) => {
|
|
2813
2882
|
const names = [...new Set((Array.isArray(role) ? role : role.split(",")).map((r) => r.trim()).filter(Boolean))];
|
|
@@ -2881,6 +2950,8 @@ export function createTestApp(o = {}) {
|
|
|
2881
2950
|
return $global;
|
|
2882
2951
|
if (prop === "$changes")
|
|
2883
2952
|
return $changes;
|
|
2953
|
+
if (prop === "$transaction")
|
|
2954
|
+
return (run, q) => runTransaction(made, (c) => commitTransaction(scope, c), run, q);
|
|
2884
2955
|
if (prop === "$model")
|
|
2885
2956
|
return (name) => made[name];
|
|
2886
2957
|
if (prop === "enqueue")
|
|
@@ -2891,6 +2962,11 @@ export function createTestApp(o = {}) {
|
|
|
2891
2962
|
return (s) => apiFor({ ...scope, shop: s });
|
|
2892
2963
|
if (prop === "asRole")
|
|
2893
2964
|
return (role, session) => apiFor({ ...scope, role: roleOf(role), session: session ? sessionOf(session) : scope.session });
|
|
2965
|
+
// A caller's own limit is the API's to keep; under test the calls go through as they are.
|
|
2966
|
+
if (prop === "asCaller")
|
|
2967
|
+
return () => made;
|
|
2968
|
+
if (prop === "rateLimit")
|
|
2969
|
+
return rateLimit;
|
|
2894
2970
|
if (prop === "shopifySync")
|
|
2895
2971
|
return shopifySync(scope);
|
|
2896
2972
|
if (prop === "files")
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inferencebureau/apps-sdk",
|
|
3
|
-
"version": "0.16.
|
|
3
|
+
"version": "0.16.9",
|
|
4
4
|
"description": "The SDK an Inference Bureau app's code imports: action helpers, metadata types, the records API client, React hooks with AutoTable and AutoForm, and a test harness for its actions.",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"keywords": [
|