@midsummer-ai/sdk 0.1.0-staging.4459 → 0.1.0-staging.4462
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/apps.d.mts +6 -1
- package/apps.mjs +13 -6
- package/here-C2jhTheQ.mjs +1 -1
- package/kv/contract.d.mts +14 -0
- package/kv/contract.mjs +309 -0
- package/kv/index.d.mts +205 -0
- package/kv/index.mjs +232 -0
- package/kv/stand-in.d.mts +14 -0
- package/kv/stand-in.mjs +148 -0
- package/kv/wire.d.mts +24 -0
- package/kv/wire.mjs +277 -0
- package/package.json +50 -1
- package/webhooks/contract.d.mts +17 -0
- package/webhooks/contract.mjs +163 -0
- package/webhooks/index.d.mts +224 -0
- package/webhooks/index.mjs +355 -0
- package/webhooks/stand-in.d.mts +12 -0
- package/webhooks/stand-in.mjs +305 -0
package/kv/index.mjs
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { a as processEnv, n as here, o as workloadTransport, r as late } from "../here-C2jhTheQ.mjs";
|
|
2
|
+
//#region src/kv/index.ts
|
|
3
|
+
/**
|
|
4
|
+
* The key-value store: each environment's store of keys, there before the first call, for sessions, counters, caches,
|
|
5
|
+
* idempotency keys and rate limits. Every read sees the last write, and every limit is exact.
|
|
6
|
+
*
|
|
7
|
+
* import { kv } from "@midsummer-ai/sdk/kv"
|
|
8
|
+
*
|
|
9
|
+
* await kv.set("session:42", { user: "ada" }, { ttlSeconds: 3600 })
|
|
10
|
+
* const session = await kv.get<{ user: string }>("session:42")
|
|
11
|
+
* const views = await kv.incr("views:home")
|
|
12
|
+
* const first = await kv.set(`order:${requestId}`, true, { ifAbsent: true, ttlSeconds: 86_400 })
|
|
13
|
+
* const { success, remaining, retryAfter } = await kv.limit(`ip:${ip}`, { max: 10, perSeconds: 60 })
|
|
14
|
+
*
|
|
15
|
+
* In a deployment, in any framework, `kv` reaches its environment's store with nothing to create or bind: a
|
|
16
|
+
* preview's store is its own and starts empty, so it never holds production's keys. Under `midsummer dev` it
|
|
17
|
+
* reaches that run's store on your computer. In tests, give it the stand-in:
|
|
18
|
+
*
|
|
19
|
+
* import { kvStore } from "@midsummer-ai/sdk/kv"
|
|
20
|
+
* import { standIn } from "@midsummer-ai/sdk/kv/stand-in"
|
|
21
|
+
*
|
|
22
|
+
* const store = kvStore(standIn({ clock: Date.now }))
|
|
23
|
+
*
|
|
24
|
+
* A key is 1 to 512 bytes of text with no line breaks; group keys with a prefix (`session:`), which `list` reads
|
|
25
|
+
* by. A value is any JSON value up to 1 MiB, returned as it was set. A key with `ttlSeconds` is gone once that
|
|
26
|
+
* many seconds pass, to the second: nothing reads it after, whether or not it has been cleared away yet.
|
|
27
|
+
*
|
|
28
|
+
* `limit` admits a call when fewer than `max` were admitted in the last `perSeconds` (a sliding window, exact
|
|
29
|
+
* however many calls arrive at once) and records it in the same step. A limit is kept apart from the keys, so
|
|
30
|
+
* `get` and `list` never see it; `resetLimit` forgets what it admitted. When a limit can't be checked, `limit`
|
|
31
|
+
* throws `unavailable` and never lets the call through on its own: catch it to choose.
|
|
32
|
+
*
|
|
33
|
+
* Each engine is held to the cases in `@midsummer-ai/sdk/kv/contract`; a behaviour that is not a case there is not
|
|
34
|
+
* promised. Every key, value and option is checked here, before anything leaves the caller. Every failure is a
|
|
35
|
+
* `KvError`, whose `code` is the one the wire carries.
|
|
36
|
+
*/
|
|
37
|
+
/** The wire, loaded on the first call: it reads this module's names as it loads, so it can't load with it. */
|
|
38
|
+
let wire;
|
|
39
|
+
const remoteOver = (transport) => (wire ??= import("./wire.mjs")).then(({ remote }) => remote(transport));
|
|
40
|
+
const kvErrorCodes = [
|
|
41
|
+
"invalid",
|
|
42
|
+
"too-large",
|
|
43
|
+
"forbidden",
|
|
44
|
+
"quota",
|
|
45
|
+
"unavailable"
|
|
46
|
+
];
|
|
47
|
+
var KvError = class extends Error {
|
|
48
|
+
code;
|
|
49
|
+
constructor(code, why) {
|
|
50
|
+
super(why);
|
|
51
|
+
this.code = code;
|
|
52
|
+
this.name = "KvError";
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
/** Where a run's key-value frames go with its Workload token (`workloadTransport`). */
|
|
56
|
+
const WORKLOAD_PATH = "/kv/workload";
|
|
57
|
+
/** Keys are at most this many bytes of UTF-8. */
|
|
58
|
+
const MAX_KEY = 512;
|
|
59
|
+
/** Values are at most this many bytes of JSON. */
|
|
60
|
+
const MAX_VALUE = 1048576;
|
|
61
|
+
/** The longest a key may be kept by `ttlSeconds`: 365 days. */
|
|
62
|
+
const MAX_TTL_SECONDS = 31536e3;
|
|
63
|
+
/** The most keys one `getMany` or `delete` takes. */
|
|
64
|
+
const MAX_KEYS = 100;
|
|
65
|
+
/** The most keys one `list` returns. */
|
|
66
|
+
const MAX_LIST = 1e3;
|
|
67
|
+
/** The largest `max` a limit takes. */
|
|
68
|
+
const MAX_LIMIT = 1e4;
|
|
69
|
+
/** The longest window a limit takes, in seconds: a day. */
|
|
70
|
+
const MAX_WINDOW_SECONDS = 86400;
|
|
71
|
+
function invalid(why) {
|
|
72
|
+
throw new KvError("invalid", why);
|
|
73
|
+
}
|
|
74
|
+
const whole = (n, low, high) => typeof n === "number" && Number.isSafeInteger(n) && n >= low && n <= high;
|
|
75
|
+
const encoder = new TextEncoder();
|
|
76
|
+
/** A key: 1 to 512 bytes of UTF-8 text, with no line breaks or other control characters. */
|
|
77
|
+
function checkKey(key) {
|
|
78
|
+
if (typeof key !== "string" || key.length === 0) invalid("a key is text of 1 to 512 bytes");
|
|
79
|
+
if (/[\x00-\x1f\x7f]/u.test(key)) invalid(`the key "${key.slice(0, 40)}" has a line break or another control character`);
|
|
80
|
+
const bytes = encoder.encode(key).length;
|
|
81
|
+
if (bytes > 512) throw new KvError("too-large", `a key is at most 512 bytes; this one is ${bytes}`);
|
|
82
|
+
}
|
|
83
|
+
/** A prefix to list by: a key's start, empty for every key. */
|
|
84
|
+
function checkPrefix(prefix) {
|
|
85
|
+
if (typeof prefix !== "string") invalid("a prefix is text");
|
|
86
|
+
if (prefix !== "") checkKey(prefix);
|
|
87
|
+
}
|
|
88
|
+
/** The JSON text of `value`, which must be a JSON value of at most 1 MiB. */
|
|
89
|
+
function valueText(value) {
|
|
90
|
+
let text;
|
|
91
|
+
try {
|
|
92
|
+
text = JSON.stringify(value);
|
|
93
|
+
} catch {
|
|
94
|
+
invalid("the value is not a JSON value");
|
|
95
|
+
}
|
|
96
|
+
if (text === void 0) invalid("the value is not a JSON value: use delete to remove a key");
|
|
97
|
+
checkValueText(text);
|
|
98
|
+
return text;
|
|
99
|
+
}
|
|
100
|
+
/** JSON text as an engine is given it: at most 1 MiB. */
|
|
101
|
+
function checkValueText(text) {
|
|
102
|
+
const bytes = encoder.encode(text).length;
|
|
103
|
+
if (bytes > 1048576) throw new KvError("too-large", `a value is at most 1 MiB (1,048,576 bytes) of JSON; this one is ${bytes}`);
|
|
104
|
+
}
|
|
105
|
+
function checkTtlMs(ms) {
|
|
106
|
+
if (!whole(ms, 1e3, 31536e6) || ms % 1e3 !== 0) invalid("ttlSeconds is a whole number of seconds, 1 to 31,536,000 (365 days)");
|
|
107
|
+
}
|
|
108
|
+
function checkBy(by) {
|
|
109
|
+
if (!whole(by, -Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER)) invalid("by is a whole number");
|
|
110
|
+
}
|
|
111
|
+
function checkLimit(options) {
|
|
112
|
+
if (!whole(options.max, 1, 1e4)) invalid("a limit's max is a whole number, 1 to 10,000");
|
|
113
|
+
if (!whole(options.windowMs, 1e3, 864e5) || options.windowMs % 1e3 !== 0) invalid("a limit's perSeconds is a whole number of seconds, 1 to 86,400 (a day)");
|
|
114
|
+
if (!whole(options.cost, 1, options.max)) invalid("a call's cost is a whole number, 1 to the limit's max");
|
|
115
|
+
}
|
|
116
|
+
function checkKeys(keys) {
|
|
117
|
+
if (!Array.isArray(keys) || keys.length < 1 || keys.length > 100) invalid("give 1 to 100 keys");
|
|
118
|
+
for (const key of keys) checkKey(key);
|
|
119
|
+
}
|
|
120
|
+
function checkListLimit(limit) {
|
|
121
|
+
if (!whole(limit, 1, 1e3)) invalid("a list's limit is 1 to 1,000");
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* The store of the environment this code runs in: the request's own in a deployment, a run's through its Workload
|
|
125
|
+
* session (a CI run, an agent's dev server), or `midsummer dev`'s on this computer. Every call goes to the one
|
|
126
|
+
* current when it is made.
|
|
127
|
+
*/
|
|
128
|
+
function hereEngine() {
|
|
129
|
+
return late(() => {
|
|
130
|
+
const handle = here()?.kv;
|
|
131
|
+
if (handle) return remoteOver(handle);
|
|
132
|
+
const env = {
|
|
133
|
+
...processEnv(),
|
|
134
|
+
...here()?.env
|
|
135
|
+
}, url = env.MIDSUMMER_KV_URL, token = env.MIDSUMMER_KV_TOKEN;
|
|
136
|
+
if (url && token) return remoteOver({ async send(frame) {
|
|
137
|
+
const response = await fetch(url, {
|
|
138
|
+
method: "POST",
|
|
139
|
+
headers: {
|
|
140
|
+
authorization: `Bearer ${token}`,
|
|
141
|
+
"content-type": "application/octet-stream"
|
|
142
|
+
},
|
|
143
|
+
body: frame
|
|
144
|
+
}).catch(() => void 0);
|
|
145
|
+
if (!response || response.status !== 200) throw new KvError("unavailable", "The key-value store could not be reached. Is midsummer dev still running?");
|
|
146
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
147
|
+
} });
|
|
148
|
+
const transport = workloadTransport(WORKLOAD_PATH, "kv", (code, why) => new KvError(code, why));
|
|
149
|
+
if (transport) return remoteOver(transport);
|
|
150
|
+
throw new KvError("forbidden", "This code runs outside Midsummer, so it has no key-value store. In tests, use kvStore(standIn()) from @midsummer-ai/sdk/kv/stand-in.");
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
/** The key-value store over `engine`: the stand-in's in tests, or `hereEngine()`. */
|
|
154
|
+
function kvStore(engine) {
|
|
155
|
+
const parsed = (entry) => entry ? JSON.parse(entry.value) : void 0;
|
|
156
|
+
return {
|
|
157
|
+
async get(key) {
|
|
158
|
+
checkKey(key);
|
|
159
|
+
const [entry] = await engine.get([key]);
|
|
160
|
+
return parsed(entry ?? null);
|
|
161
|
+
},
|
|
162
|
+
async getMany(keys) {
|
|
163
|
+
checkKeys(keys);
|
|
164
|
+
return (await engine.get(keys)).map((entry) => parsed(entry));
|
|
165
|
+
},
|
|
166
|
+
async set(key, value, options = {}) {
|
|
167
|
+
checkKey(key);
|
|
168
|
+
const text = valueText(value);
|
|
169
|
+
const ttlMs = options.ttlSeconds === void 0 ? void 0 : options.ttlSeconds * 1e3;
|
|
170
|
+
if (ttlMs !== void 0) checkTtlMs(ttlMs);
|
|
171
|
+
return engine.set(key, text, {
|
|
172
|
+
...ttlMs === void 0 ? {} : { ttlMs },
|
|
173
|
+
...options.ifAbsent ? { ifAbsent: true } : {}
|
|
174
|
+
});
|
|
175
|
+
},
|
|
176
|
+
async incr(key, options = {}) {
|
|
177
|
+
checkKey(key);
|
|
178
|
+
const by = options.by ?? 1;
|
|
179
|
+
checkBy(by);
|
|
180
|
+
const ttlMs = options.ttlSeconds === void 0 ? void 0 : options.ttlSeconds * 1e3;
|
|
181
|
+
if (ttlMs !== void 0) checkTtlMs(ttlMs);
|
|
182
|
+
return engine.incr(key, by, ttlMs);
|
|
183
|
+
},
|
|
184
|
+
async delete(...keys) {
|
|
185
|
+
checkKeys(keys);
|
|
186
|
+
return engine.delete(keys);
|
|
187
|
+
},
|
|
188
|
+
async expire(key, ttlSeconds) {
|
|
189
|
+
checkKey(key);
|
|
190
|
+
const ttlMs = ttlSeconds === null ? null : ttlSeconds * 1e3;
|
|
191
|
+
if (ttlMs !== null) checkTtlMs(ttlMs);
|
|
192
|
+
return engine.expire(key, ttlMs);
|
|
193
|
+
},
|
|
194
|
+
async list(options = {}) {
|
|
195
|
+
const prefix = options.prefix ?? "";
|
|
196
|
+
checkPrefix(prefix);
|
|
197
|
+
if (options.after !== void 0) checkKey(options.after);
|
|
198
|
+
const limit = options.limit ?? 100;
|
|
199
|
+
checkListLimit(limit);
|
|
200
|
+
return engine.list({
|
|
201
|
+
prefix,
|
|
202
|
+
limit,
|
|
203
|
+
...options.after === void 0 ? {} : { after: options.after }
|
|
204
|
+
});
|
|
205
|
+
},
|
|
206
|
+
async limit(key, options) {
|
|
207
|
+
checkKey(key);
|
|
208
|
+
const call = {
|
|
209
|
+
max: options.max,
|
|
210
|
+
windowMs: options.perSeconds * 1e3,
|
|
211
|
+
cost: options.cost ?? 1
|
|
212
|
+
};
|
|
213
|
+
checkLimit(call);
|
|
214
|
+
const decided = await engine.limit(key, call);
|
|
215
|
+
return {
|
|
216
|
+
success: decided.ok,
|
|
217
|
+
limit: decided.limit,
|
|
218
|
+
remaining: decided.remaining,
|
|
219
|
+
reset: decided.resetAt,
|
|
220
|
+
...decided.retryAfterMs === void 0 ? {} : { retryAfter: Math.ceil(decided.retryAfterMs / 1e3) }
|
|
221
|
+
};
|
|
222
|
+
},
|
|
223
|
+
async resetLimit(key) {
|
|
224
|
+
checkKey(key);
|
|
225
|
+
await engine.resetLimit(key);
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
/** The environment's key-value store, from code in a deployment in any framework, or `midsummer dev`'s. */
|
|
230
|
+
const kv = kvStore(hereEngine());
|
|
231
|
+
//#endregion
|
|
232
|
+
export { KvError, MAX_KEY, MAX_KEYS, MAX_LIMIT, MAX_LIST, MAX_TTL_SECONDS, MAX_VALUE, MAX_WINDOW_SECONDS, WORKLOAD_PATH, checkBy, checkKey, checkKeys, checkLimit, checkListLimit, checkPrefix, checkTtlMs, checkValueText, hereEngine, invalid, kv, kvErrorCodes, kvStore, valueText };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { KvEngine } from "./index.mjs";
|
|
2
|
+
//#region src/kv/stand-in.d.ts
|
|
3
|
+
interface StandIn extends KvEngine {
|
|
4
|
+
/** The live keys and their bytes (each key and its value's JSON). */
|
|
5
|
+
stats(): Promise<{
|
|
6
|
+
readonly keys: number;
|
|
7
|
+
readonly bytes: number;
|
|
8
|
+
}>;
|
|
9
|
+
}
|
|
10
|
+
declare function standIn(options: {
|
|
11
|
+
readonly clock: () => number;
|
|
12
|
+
}): StandIn;
|
|
13
|
+
//#endregion
|
|
14
|
+
export { StandIn, standIn };
|
package/kv/stand-in.mjs
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { KvError, MAX_WINDOW_SECONDS } from "./index.mjs";
|
|
2
|
+
//#region src/kv/stand-in.ts
|
|
3
|
+
/**
|
|
4
|
+
* The key-value store's stand-in: its behaviour in memory, for `midsummer dev` and tests. It holds no engine code
|
|
5
|
+
* and passes the contract (`@midsummer-ai/sdk/kv/contract`) except durability and scale.
|
|
6
|
+
*
|
|
7
|
+
* const store = kvStore(standIn({ clock: Date.now }))
|
|
8
|
+
*
|
|
9
|
+
* Its clock decides expiry and limits, so a test moves time instead of waiting. `stats` counts the live keys and
|
|
10
|
+
* their bytes, as a store's page shows them. Everything is lost when the process ends.
|
|
11
|
+
*/
|
|
12
|
+
const encoder = new TextEncoder();
|
|
13
|
+
const size = (text) => encoder.encode(text).length;
|
|
14
|
+
/** Byte order of two keys' UTF-8, the order `list` returns them in. */
|
|
15
|
+
function byteOrder(a, b) {
|
|
16
|
+
const x = encoder.encode(a), y = encoder.encode(b);
|
|
17
|
+
for (let i = 0; i < Math.min(x.length, y.length); i++) if (x[i] !== y[i]) return x[i] - y[i];
|
|
18
|
+
return x.length - y.length;
|
|
19
|
+
}
|
|
20
|
+
function standIn(options) {
|
|
21
|
+
const { clock } = options;
|
|
22
|
+
const keys = /* @__PURE__ */ new Map();
|
|
23
|
+
/** Each limit's admissions in its window, oldest first. */
|
|
24
|
+
const limits = /* @__PURE__ */ new Map();
|
|
25
|
+
const live = (key) => {
|
|
26
|
+
const entry = keys.get(key);
|
|
27
|
+
if (entry && entry.expiresAt !== void 0 && entry.expiresAt <= clock()) {
|
|
28
|
+
keys.delete(key);
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
return entry;
|
|
32
|
+
};
|
|
33
|
+
const until = (ttlMs) => ttlMs === void 0 ? {} : { expiresAt: clock() + ttlMs };
|
|
34
|
+
return {
|
|
35
|
+
async get(asked) {
|
|
36
|
+
return asked.map((key) => live(key) ?? null);
|
|
37
|
+
},
|
|
38
|
+
async set(key, value, { ttlMs, ifAbsent }) {
|
|
39
|
+
if (ifAbsent && live(key)) return false;
|
|
40
|
+
keys.set(key, {
|
|
41
|
+
value,
|
|
42
|
+
...until(ttlMs)
|
|
43
|
+
});
|
|
44
|
+
return true;
|
|
45
|
+
},
|
|
46
|
+
async incr(key, by, ttlMs) {
|
|
47
|
+
const had = live(key);
|
|
48
|
+
let now = 0;
|
|
49
|
+
if (had) {
|
|
50
|
+
const parsed = JSON.parse(had.value);
|
|
51
|
+
if (typeof parsed !== "number" || !Number.isSafeInteger(parsed)) throw new KvError("invalid", `${key} holds a value that isn't a whole number, so it can't be added to`);
|
|
52
|
+
now = parsed;
|
|
53
|
+
}
|
|
54
|
+
const next = now + by;
|
|
55
|
+
if (!Number.isSafeInteger(next)) throw new KvError("invalid", `${key} would pass 9,007,199,254,740,991, the largest whole number a value keeps exactly`);
|
|
56
|
+
keys.set(key, {
|
|
57
|
+
value: JSON.stringify(next),
|
|
58
|
+
...had ? had.expiresAt === void 0 ? {} : { expiresAt: had.expiresAt } : until(ttlMs)
|
|
59
|
+
});
|
|
60
|
+
return next;
|
|
61
|
+
},
|
|
62
|
+
async delete(asked) {
|
|
63
|
+
let deleted = 0;
|
|
64
|
+
for (const key of new Set(asked)) if (live(key)) {
|
|
65
|
+
keys.delete(key);
|
|
66
|
+
deleted += 1;
|
|
67
|
+
}
|
|
68
|
+
return deleted;
|
|
69
|
+
},
|
|
70
|
+
async expire(key, ttlMs) {
|
|
71
|
+
const had = live(key);
|
|
72
|
+
if (!had) return false;
|
|
73
|
+
keys.set(key, {
|
|
74
|
+
value: had.value,
|
|
75
|
+
...ttlMs === null ? {} : until(ttlMs)
|
|
76
|
+
});
|
|
77
|
+
return true;
|
|
78
|
+
},
|
|
79
|
+
async list({ prefix, after, limit }) {
|
|
80
|
+
const found = [...keys.keys()].filter((key) => key.startsWith(prefix) && (after === void 0 || byteOrder(key, after) > 0) && live(key)).sort(byteOrder);
|
|
81
|
+
const page = found.slice(0, limit).map((key) => {
|
|
82
|
+
const entry = keys.get(key);
|
|
83
|
+
return {
|
|
84
|
+
key,
|
|
85
|
+
bytes: size(key) + size(entry.value),
|
|
86
|
+
...entry.expiresAt === void 0 ? {} : { expiresAt: entry.expiresAt }
|
|
87
|
+
};
|
|
88
|
+
});
|
|
89
|
+
return {
|
|
90
|
+
keys: page,
|
|
91
|
+
...found.length > limit ? { next: page[page.length - 1].key } : {}
|
|
92
|
+
};
|
|
93
|
+
},
|
|
94
|
+
async limit(key, { max, windowMs, cost }) {
|
|
95
|
+
if (max > 1e4) throw new KvError("invalid", "a limit's max is at most 10,000");
|
|
96
|
+
const now = clock();
|
|
97
|
+
const kept = (limits.get(key) ?? []).filter((admitted) => admitted.at > now - windowMs);
|
|
98
|
+
const used = kept.reduce((sum, admitted) => sum + admitted.cost, 0);
|
|
99
|
+
const ok = used + cost <= max;
|
|
100
|
+
if (ok) kept.push({
|
|
101
|
+
at: now,
|
|
102
|
+
cost
|
|
103
|
+
});
|
|
104
|
+
if (kept.length) limits.set(key, kept);
|
|
105
|
+
else limits.delete(key);
|
|
106
|
+
const resetAt = kept.length ? kept[0].at + windowMs : now;
|
|
107
|
+
if (ok) return {
|
|
108
|
+
ok,
|
|
109
|
+
limit: max,
|
|
110
|
+
remaining: max - used - cost,
|
|
111
|
+
resetAt
|
|
112
|
+
};
|
|
113
|
+
let freed = max - used, at = now;
|
|
114
|
+
for (const admitted of kept) {
|
|
115
|
+
if (freed >= cost) break;
|
|
116
|
+
freed += admitted.cost;
|
|
117
|
+
at = admitted.at + windowMs;
|
|
118
|
+
}
|
|
119
|
+
return {
|
|
120
|
+
ok,
|
|
121
|
+
limit: max,
|
|
122
|
+
remaining: Math.max(0, max - used),
|
|
123
|
+
resetAt,
|
|
124
|
+
retryAfterMs: Math.max(0, at - now)
|
|
125
|
+
};
|
|
126
|
+
},
|
|
127
|
+
async resetLimit(key) {
|
|
128
|
+
const kept = (limits.get(key) ?? []).some((admitted) => admitted.at > clock() - MAX_WINDOW_SECONDS * 1e3);
|
|
129
|
+
limits.delete(key);
|
|
130
|
+
return kept;
|
|
131
|
+
},
|
|
132
|
+
async stats() {
|
|
133
|
+
let count = 0, bytes = 0;
|
|
134
|
+
for (const key of [...keys.keys()]) {
|
|
135
|
+
const entry = live(key);
|
|
136
|
+
if (!entry) continue;
|
|
137
|
+
count += 1;
|
|
138
|
+
bytes += size(key) + size(entry.value);
|
|
139
|
+
}
|
|
140
|
+
return {
|
|
141
|
+
keys: count,
|
|
142
|
+
bytes
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
//#endregion
|
|
148
|
+
export { standIn };
|
package/kv/wire.d.mts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { Transport } from "../wire.mjs";
|
|
2
|
+
import { KvEngine } from "./index.mjs";
|
|
3
|
+
//#region src/kv/wire.d.ts
|
|
4
|
+
/** An engine that also shows how many live keys it keeps and their bytes, as a store's page and its meter read. */
|
|
5
|
+
interface CountedEngine extends KvEngine {
|
|
6
|
+
stats(): Promise<{
|
|
7
|
+
readonly keys: number;
|
|
8
|
+
readonly bytes: number;
|
|
9
|
+
}>;
|
|
10
|
+
}
|
|
11
|
+
/** The engine on the far side of `transport`. */
|
|
12
|
+
declare function remote(transport: Transport): CountedEngine;
|
|
13
|
+
/**
|
|
14
|
+
* Replies to one request frame from `engine`. Every frame is checked again here, since it comes from the network,
|
|
15
|
+
* and a failure becomes an error frame with its code. `kv.stats` is returned only by an engine that counts.
|
|
16
|
+
*/
|
|
17
|
+
declare function serve(engine: KvEngine & {
|
|
18
|
+
stats?(): Promise<{
|
|
19
|
+
readonly keys: number;
|
|
20
|
+
readonly bytes: number;
|
|
21
|
+
}>;
|
|
22
|
+
}): (frame: Uint8Array) => Promise<Uint8Array>;
|
|
23
|
+
//#endregion
|
|
24
|
+
export { CountedEngine, type Transport, remote, serve };
|
package/kv/wire.mjs
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import { decodeFrame, encodeFrame } from "../wire.mjs";
|
|
2
|
+
import { KvError, checkKey, checkKeys, checkLimit, checkListLimit, checkPrefix, checkTtlMs, checkValueText, kvErrorCodes } from "./index.mjs";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
//#region src/kv/wire.ts
|
|
5
|
+
/**
|
|
6
|
+
* The key-value store's wire: how a call crosses a network. `remote(transport)` is the engine a client uses;
|
|
7
|
+
* `serve(engine)` replies on the other side. A server implements `serve` over its own engine and nothing else, so
|
|
8
|
+
* the contract run through the wire holds for it too.
|
|
9
|
+
*
|
|
10
|
+
* const store = kvStore(remote({ send: (frame) => env.KV.send(frame) })) // in a site
|
|
11
|
+
* handle.onFrame(serve(engine)) // on the platform
|
|
12
|
+
*
|
|
13
|
+
* Frames are Storage's (`@midsummer-ai/sdk/wire`): a 4-byte little-endian length and that many bytes of JSON
|
|
14
|
+
* header, with no body after it. One request frame gets one reply frame. Changing a frame changes the contract
|
|
15
|
+
* with every server.
|
|
16
|
+
*/
|
|
17
|
+
const request = z.discriminatedUnion("op", [
|
|
18
|
+
z.object({
|
|
19
|
+
op: z.literal("kv.get"),
|
|
20
|
+
keys: z.array(z.string())
|
|
21
|
+
}).strict(),
|
|
22
|
+
z.object({
|
|
23
|
+
op: z.literal("kv.set"),
|
|
24
|
+
key: z.string(),
|
|
25
|
+
value: z.string(),
|
|
26
|
+
ttlMs: z.number().optional(),
|
|
27
|
+
ifAbsent: z.literal(true).optional()
|
|
28
|
+
}).strict(),
|
|
29
|
+
z.object({
|
|
30
|
+
op: z.literal("kv.incr"),
|
|
31
|
+
key: z.string(),
|
|
32
|
+
by: z.number(),
|
|
33
|
+
ttlMs: z.number().optional()
|
|
34
|
+
}).strict(),
|
|
35
|
+
z.object({
|
|
36
|
+
op: z.literal("kv.delete"),
|
|
37
|
+
keys: z.array(z.string())
|
|
38
|
+
}).strict(),
|
|
39
|
+
z.object({
|
|
40
|
+
op: z.literal("kv.expire"),
|
|
41
|
+
key: z.string(),
|
|
42
|
+
ttlMs: z.number().nullable()
|
|
43
|
+
}).strict(),
|
|
44
|
+
z.object({
|
|
45
|
+
op: z.literal("kv.list"),
|
|
46
|
+
prefix: z.string(),
|
|
47
|
+
after: z.string().optional(),
|
|
48
|
+
limit: z.number()
|
|
49
|
+
}).strict(),
|
|
50
|
+
z.object({
|
|
51
|
+
op: z.literal("kv.limit"),
|
|
52
|
+
key: z.string(),
|
|
53
|
+
max: z.number(),
|
|
54
|
+
windowMs: z.number(),
|
|
55
|
+
cost: z.number()
|
|
56
|
+
}).strict(),
|
|
57
|
+
z.object({
|
|
58
|
+
op: z.literal("kv.limit.reset"),
|
|
59
|
+
key: z.string()
|
|
60
|
+
}).strict(),
|
|
61
|
+
z.object({ op: z.literal("kv.stats") }).strict()
|
|
62
|
+
]);
|
|
63
|
+
const entry = z.object({
|
|
64
|
+
value: z.string(),
|
|
65
|
+
expiresAt: z.number().optional()
|
|
66
|
+
}).strict();
|
|
67
|
+
const info = z.object({
|
|
68
|
+
key: z.string(),
|
|
69
|
+
bytes: z.number(),
|
|
70
|
+
expiresAt: z.number().optional()
|
|
71
|
+
}).strict();
|
|
72
|
+
const decided = z.object({
|
|
73
|
+
ok: z.boolean(),
|
|
74
|
+
limit: z.number(),
|
|
75
|
+
remaining: z.number(),
|
|
76
|
+
resetAt: z.number(),
|
|
77
|
+
retryAfterMs: z.number().optional()
|
|
78
|
+
}).strict();
|
|
79
|
+
const answer = z.union([
|
|
80
|
+
z.object({
|
|
81
|
+
error: z.enum(kvErrorCodes),
|
|
82
|
+
why: z.string()
|
|
83
|
+
}).strict(),
|
|
84
|
+
z.object({ entries: z.array(entry.nullable()) }).strict(),
|
|
85
|
+
z.object({ written: z.boolean() }).strict(),
|
|
86
|
+
z.object({ value: z.number() }).strict(),
|
|
87
|
+
z.object({ deleted: z.number() }).strict(),
|
|
88
|
+
z.object({ found: z.boolean() }).strict(),
|
|
89
|
+
z.object({
|
|
90
|
+
keys: z.array(info),
|
|
91
|
+
next: z.string().optional()
|
|
92
|
+
}).strict(),
|
|
93
|
+
z.object({ decided }).strict(),
|
|
94
|
+
z.object({ reset: z.boolean() }).strict(),
|
|
95
|
+
z.object({ stats: z.object({
|
|
96
|
+
keys: z.number(),
|
|
97
|
+
bytes: z.number()
|
|
98
|
+
}).strict() }).strict()
|
|
99
|
+
]);
|
|
100
|
+
/** Drops the keys whose value is undefined, as JSON would, so a frame's object reads the same on both sides. */
|
|
101
|
+
const present = (value) => Object.fromEntries(Object.entries(value).filter(([, v]) => v !== void 0));
|
|
102
|
+
/** The engine on the far side of `transport`. */
|
|
103
|
+
function remote(transport) {
|
|
104
|
+
const call = async (header) => {
|
|
105
|
+
let frame;
|
|
106
|
+
try {
|
|
107
|
+
frame = await transport.send(encodeFrame(header));
|
|
108
|
+
} catch (error) {
|
|
109
|
+
if (error instanceof KvError) throw error;
|
|
110
|
+
if (error instanceof Error && "code" in error && (error.code === "forbidden" || error.code === "unavailable")) throw new KvError(error.code, "The key-value store could not be reached");
|
|
111
|
+
throw new KvError("unavailable", "The key-value store could not be reached");
|
|
112
|
+
}
|
|
113
|
+
let parsed;
|
|
114
|
+
try {
|
|
115
|
+
parsed = answer.parse(decodeFrame(frame).header);
|
|
116
|
+
} catch {
|
|
117
|
+
throw new KvError("unavailable", "The key-value store answered something that is not one of its answers");
|
|
118
|
+
}
|
|
119
|
+
if ("error" in parsed) throw new KvError(parsed.error, parsed.why);
|
|
120
|
+
return parsed;
|
|
121
|
+
};
|
|
122
|
+
const expect = (answered, key) => {
|
|
123
|
+
if (!(key in answered)) throw new KvError("unavailable", "The key-value store answered another call");
|
|
124
|
+
return answered[key];
|
|
125
|
+
};
|
|
126
|
+
return {
|
|
127
|
+
async get(keys) {
|
|
128
|
+
return expect(await call({
|
|
129
|
+
op: "kv.get",
|
|
130
|
+
keys: [...keys]
|
|
131
|
+
}), "entries").map((found) => found ? present(found) : null);
|
|
132
|
+
},
|
|
133
|
+
async set(key, value, options) {
|
|
134
|
+
return expect(await call(present({
|
|
135
|
+
op: "kv.set",
|
|
136
|
+
key,
|
|
137
|
+
value,
|
|
138
|
+
ttlMs: options.ttlMs,
|
|
139
|
+
ifAbsent: options.ifAbsent ? true : void 0
|
|
140
|
+
})), "written");
|
|
141
|
+
},
|
|
142
|
+
async incr(key, by, ttlMs) {
|
|
143
|
+
return expect(await call(present({
|
|
144
|
+
op: "kv.incr",
|
|
145
|
+
key,
|
|
146
|
+
by,
|
|
147
|
+
ttlMs
|
|
148
|
+
})), "value");
|
|
149
|
+
},
|
|
150
|
+
async delete(keys) {
|
|
151
|
+
return expect(await call({
|
|
152
|
+
op: "kv.delete",
|
|
153
|
+
keys: [...keys]
|
|
154
|
+
}), "deleted");
|
|
155
|
+
},
|
|
156
|
+
async expire(key, ttlMs) {
|
|
157
|
+
return expect(await call({
|
|
158
|
+
op: "kv.expire",
|
|
159
|
+
key,
|
|
160
|
+
ttlMs
|
|
161
|
+
}), "found");
|
|
162
|
+
},
|
|
163
|
+
async list(options) {
|
|
164
|
+
const listed = await call(present({
|
|
165
|
+
op: "kv.list",
|
|
166
|
+
prefix: options.prefix,
|
|
167
|
+
after: options.after,
|
|
168
|
+
limit: options.limit
|
|
169
|
+
}));
|
|
170
|
+
const keys = expect(listed, "keys").map((found) => present(found));
|
|
171
|
+
const next = listed.next;
|
|
172
|
+
return {
|
|
173
|
+
keys,
|
|
174
|
+
...next === void 0 ? {} : { next }
|
|
175
|
+
};
|
|
176
|
+
},
|
|
177
|
+
async limit(key, options) {
|
|
178
|
+
return present(expect(await call({
|
|
179
|
+
op: "kv.limit",
|
|
180
|
+
key,
|
|
181
|
+
...options
|
|
182
|
+
}), "decided"));
|
|
183
|
+
},
|
|
184
|
+
async resetLimit(key) {
|
|
185
|
+
return expect(await call({
|
|
186
|
+
op: "kv.limit.reset",
|
|
187
|
+
key
|
|
188
|
+
}), "reset");
|
|
189
|
+
},
|
|
190
|
+
async stats() {
|
|
191
|
+
return expect(await call({ op: "kv.stats" }), "stats");
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Replies to one request frame from `engine`. Every frame is checked again here, since it comes from the network,
|
|
197
|
+
* and a failure becomes an error frame with its code. `kv.stats` is returned only by an engine that counts.
|
|
198
|
+
*/
|
|
199
|
+
function serve(engine) {
|
|
200
|
+
return async (frame) => {
|
|
201
|
+
try {
|
|
202
|
+
let header;
|
|
203
|
+
try {
|
|
204
|
+
header = decodeFrame(frame).header;
|
|
205
|
+
} catch {
|
|
206
|
+
throw new KvError("invalid", "the frame is not a frame");
|
|
207
|
+
}
|
|
208
|
+
const parsed = request.safeParse(header);
|
|
209
|
+
if (!parsed.success) throw new KvError("invalid", "the request frame is not a key-value call");
|
|
210
|
+
const call = parsed.data;
|
|
211
|
+
switch (call.op) {
|
|
212
|
+
case "kv.get":
|
|
213
|
+
checkKeys(call.keys);
|
|
214
|
+
return encodeFrame({ entries: await engine.get(call.keys) });
|
|
215
|
+
case "kv.set":
|
|
216
|
+
checkKey(call.key);
|
|
217
|
+
checkValueText(call.value);
|
|
218
|
+
try {
|
|
219
|
+
JSON.parse(call.value);
|
|
220
|
+
} catch {
|
|
221
|
+
throw new KvError("invalid", "the value is not JSON text");
|
|
222
|
+
}
|
|
223
|
+
if (call.ttlMs !== void 0) checkTtlMs(call.ttlMs);
|
|
224
|
+
return encodeFrame({ written: await engine.set(call.key, call.value, {
|
|
225
|
+
...call.ttlMs === void 0 ? {} : { ttlMs: call.ttlMs },
|
|
226
|
+
...call.ifAbsent ? { ifAbsent: true } : {}
|
|
227
|
+
}) });
|
|
228
|
+
case "kv.incr":
|
|
229
|
+
checkKey(call.key);
|
|
230
|
+
if (!Number.isSafeInteger(call.by)) throw new KvError("invalid", "by is a whole number");
|
|
231
|
+
if (call.ttlMs !== void 0) checkTtlMs(call.ttlMs);
|
|
232
|
+
return encodeFrame({ value: await engine.incr(call.key, call.by, call.ttlMs) });
|
|
233
|
+
case "kv.delete":
|
|
234
|
+
checkKeys(call.keys);
|
|
235
|
+
return encodeFrame({ deleted: await engine.delete(call.keys) });
|
|
236
|
+
case "kv.expire":
|
|
237
|
+
checkKey(call.key);
|
|
238
|
+
if (call.ttlMs !== null) checkTtlMs(call.ttlMs);
|
|
239
|
+
return encodeFrame({ found: await engine.expire(call.key, call.ttlMs) });
|
|
240
|
+
case "kv.list":
|
|
241
|
+
checkPrefix(call.prefix);
|
|
242
|
+
if (call.after !== void 0) checkKey(call.after);
|
|
243
|
+
checkListLimit(call.limit);
|
|
244
|
+
return encodeFrame(await engine.list({
|
|
245
|
+
prefix: call.prefix,
|
|
246
|
+
limit: call.limit,
|
|
247
|
+
...call.after === void 0 ? {} : { after: call.after }
|
|
248
|
+
}));
|
|
249
|
+
case "kv.limit":
|
|
250
|
+
checkKey(call.key);
|
|
251
|
+
checkLimit(call);
|
|
252
|
+
return encodeFrame({ decided: await engine.limit(call.key, {
|
|
253
|
+
max: call.max,
|
|
254
|
+
windowMs: call.windowMs,
|
|
255
|
+
cost: call.cost
|
|
256
|
+
}) });
|
|
257
|
+
case "kv.limit.reset":
|
|
258
|
+
checkKey(call.key);
|
|
259
|
+
return encodeFrame({ reset: await engine.resetLimit(call.key) });
|
|
260
|
+
case "kv.stats":
|
|
261
|
+
if (!engine.stats) throw new KvError("invalid", "this store doesn't count its keys");
|
|
262
|
+
return encodeFrame({ stats: await engine.stats() });
|
|
263
|
+
}
|
|
264
|
+
} catch (error) {
|
|
265
|
+
if (error instanceof KvError) return encodeFrame({
|
|
266
|
+
error: error.code,
|
|
267
|
+
why: error.message
|
|
268
|
+
});
|
|
269
|
+
return encodeFrame({
|
|
270
|
+
error: "unavailable",
|
|
271
|
+
why: "The key-value store failed to answer"
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
//#endregion
|
|
277
|
+
export { remote, serve };
|