@midsummer-ai/sdk 0.1.0-staging.4456 → 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/apps.d.mts
CHANGED
|
@@ -17,6 +17,11 @@ interface AppEvent<Data extends Record<string, unknown> = Record<string, unknown
|
|
|
17
17
|
* so a request carries a signature from each, and either one passing is enough.
|
|
18
18
|
*/
|
|
19
19
|
declare function verifyEvent(headers: Headers | Readonly<Record<string, string | undefined>>, body: string, secret: string, now?: number): Promise<boolean>;
|
|
20
|
+
/**
|
|
21
|
+
* The `webhook-signature` entry Standard Webhooks gives a delivery: `v1,` and the base64 HMAC-SHA256, under the secret
|
|
22
|
+
* after its `whsec_`, of `<id>.<timestamp>.<body>`. What `verifyEvent` checks against, and what a Stand-in signs with.
|
|
23
|
+
*/
|
|
24
|
+
declare function signEvent(secret: string, id: string, timestamp: number, body: string): Promise<string>;
|
|
20
25
|
/**
|
|
21
26
|
* An app acting in the teams that installed it. Each installation's token is asked for with the
|
|
22
27
|
* app's id and secret, kept until a minute before it ends, and asked for again after; a team that
|
|
@@ -45,4 +50,4 @@ declare class InstalledApp {
|
|
|
45
50
|
}>;
|
|
46
51
|
}
|
|
47
52
|
//#endregion
|
|
48
|
-
export { AppEvent, InstalledApp, verifyEvent };
|
|
53
|
+
export { AppEvent, InstalledApp, signEvent, verifyEvent };
|
package/apps.mjs
CHANGED
|
@@ -29,17 +29,24 @@ async function verifyEvent(headers, body, secret, now = Date.now()) {
|
|
|
29
29
|
const id = read("webhook-id"), timestamp = read("webhook-timestamp"), signatures = read("webhook-signature");
|
|
30
30
|
if (!id || !timestamp || !signatures || !/^\d+$/.test(timestamp)) return false;
|
|
31
31
|
if (Math.abs(now / 1e3 - Number(timestamp)) > TOLERANCE_SECONDS) return false;
|
|
32
|
-
const
|
|
33
|
-
name: "HMAC",
|
|
34
|
-
hash: "SHA-256"
|
|
35
|
-
}, false, ["sign"]);
|
|
36
|
-
const expected = toBase64(new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${id}.${timestamp}.${body}`))));
|
|
32
|
+
const expected = (await signEvent(secret, id, Number(timestamp), body)).slice(3);
|
|
37
33
|
return signatures.split(" ").some((entry) => {
|
|
38
34
|
const [version, signature] = entry.split(",");
|
|
39
35
|
return version === "v1" && signature !== void 0 && same(signature, expected);
|
|
40
36
|
});
|
|
41
37
|
}
|
|
42
38
|
/**
|
|
39
|
+
* The `webhook-signature` entry Standard Webhooks gives a delivery: `v1,` and the base64 HMAC-SHA256, under the secret
|
|
40
|
+
* after its `whsec_`, of `<id>.<timestamp>.<body>`. What `verifyEvent` checks against, and what a Stand-in signs with.
|
|
41
|
+
*/
|
|
42
|
+
async function signEvent(secret, id, timestamp, body) {
|
|
43
|
+
const key = await crypto.subtle.importKey("raw", fromBase64(secret.replace(/^whsec_/, "")), {
|
|
44
|
+
name: "HMAC",
|
|
45
|
+
hash: "SHA-256"
|
|
46
|
+
}, false, ["sign"]);
|
|
47
|
+
return `v1,${toBase64(new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${id}.${timestamp}.${body}`))))}`;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
43
50
|
* An app acting in the teams that installed it. Each installation's token is asked for with the
|
|
44
51
|
* app's id and secret, kept until a minute before it ends, and asked for again after; a team that
|
|
45
52
|
* removes the app ends its tokens at once, and its calls answer 401.
|
|
@@ -122,4 +129,4 @@ function same(a, b) {
|
|
|
122
129
|
return differ === 0;
|
|
123
130
|
}
|
|
124
131
|
//#endregion
|
|
125
|
-
export { InstalledApp, verifyEvent };
|
|
132
|
+
export { InstalledApp, signEvent, verifyEvent };
|
package/here-C2jhTheQ.mjs
CHANGED
|
@@ -12,7 +12,7 @@ function processEnv() {
|
|
|
12
12
|
* This package's version: `0.0.0-dev` here, and in a published package the version it was published at, which the
|
|
13
13
|
* release writes in its place as it stages the package (`stampSdk` in `scripts/release/packages.ts`).
|
|
14
14
|
*/
|
|
15
|
-
const SDK_VERSION = "0.1.0-staging.
|
|
15
|
+
const SDK_VERSION = "0.1.0-staging.4462";
|
|
16
16
|
/**
|
|
17
17
|
* The header that tells Midsummer which client made each of this package's calls: `Midsummer-Client: sdk/<version>
|
|
18
18
|
* <part>`, `part` the product whose client it is (`database`, `storage`, `queues`, ...), so the platform counts which
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { KeyValue } from "./index.mjs";
|
|
2
|
+
//#region src/kv/contract.d.ts
|
|
3
|
+
interface KvCase {
|
|
4
|
+
/** A line of the specification. */
|
|
5
|
+
readonly name: string;
|
|
6
|
+
run(world: {
|
|
7
|
+
readonly kv: KeyValue;
|
|
8
|
+
advance(ms: number): void;
|
|
9
|
+
readonly at: number;
|
|
10
|
+
}): Promise<void>;
|
|
11
|
+
}
|
|
12
|
+
declare const kvContract: ReadonlyArray<KvCase>;
|
|
13
|
+
//#endregion
|
|
14
|
+
export { KvCase, kvContract };
|
package/kv/contract.mjs
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
import { KvError } from "./index.mjs";
|
|
2
|
+
//#region src/kv/contract.ts
|
|
3
|
+
/**
|
|
4
|
+
* The key-value store's contract: what every engine promises, as cases any test runner can run. The stand-in runs
|
|
5
|
+
* them in this package, through the wire too; the platform runs them against its store, and the engine's own check
|
|
6
|
+
* runs them against the engine.
|
|
7
|
+
*
|
|
8
|
+
* for (const c of kvContract) test(c.name, () => { const time = clockAt(T0); return c.run({ kv: kvStore(makeEngine(time.now)), advance: time.advance, at: T0 }) })
|
|
9
|
+
*
|
|
10
|
+
* Each case gets an empty store over an engine whose clock starts at `at` and moves with `advance`, and throws when
|
|
11
|
+
* the engine breaks the promise. Expected values are written out, never computed with the SDK's own code.
|
|
12
|
+
*/
|
|
13
|
+
const SECOND = 1e3;
|
|
14
|
+
const kvContract = [
|
|
15
|
+
{
|
|
16
|
+
name: "a value set is read back as it was set, and a key never set has none",
|
|
17
|
+
async run({ kv }) {
|
|
18
|
+
equal(await kv.set("session:42", {
|
|
19
|
+
user: "ada",
|
|
20
|
+
roles: ["admin"],
|
|
21
|
+
seen: 3
|
|
22
|
+
}), true, "what set returns");
|
|
23
|
+
equal(await kv.get("session:42"), {
|
|
24
|
+
user: "ada",
|
|
25
|
+
roles: ["admin"],
|
|
26
|
+
seen: 3
|
|
27
|
+
}, "the value read back");
|
|
28
|
+
equal(await kv.get("session:43"), void 0, "a key never set");
|
|
29
|
+
await kv.set("session:42", "replaced");
|
|
30
|
+
equal(await kv.get("session:42"), "replaced", "the value after a second set");
|
|
31
|
+
await kv.set("flag", null);
|
|
32
|
+
equal(await kv.get("flag"), null, "a null value");
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
name: "getMany reads up to 100 keys in the order asked",
|
|
37
|
+
async run({ kv }) {
|
|
38
|
+
await kv.set("a", 1);
|
|
39
|
+
await kv.set("c", 3);
|
|
40
|
+
equal(await kv.getMany([
|
|
41
|
+
"c",
|
|
42
|
+
"b",
|
|
43
|
+
"a"
|
|
44
|
+
]), [
|
|
45
|
+
3,
|
|
46
|
+
void 0,
|
|
47
|
+
1
|
|
48
|
+
], "the values in the order asked");
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
name: "a key set with ttlSeconds is read until that second and never after",
|
|
53
|
+
async run({ kv, advance }) {
|
|
54
|
+
await kv.set("otp:ada", "481516", { ttlSeconds: 60 });
|
|
55
|
+
advance(60 * SECOND - 1);
|
|
56
|
+
equal(await kv.get("otp:ada"), "481516", "a millisecond before it expires");
|
|
57
|
+
advance(1);
|
|
58
|
+
equal(await kv.get("otp:ada"), void 0, "once it expires");
|
|
59
|
+
equal((await kv.list()).keys, [], "the list once it expires");
|
|
60
|
+
equal(await kv.delete("otp:ada"), 0, "deleting it once it expired");
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
name: "a set with ifAbsent writes only when the key has no value, so a retried request runs once",
|
|
65
|
+
async run({ kv, advance }) {
|
|
66
|
+
equal(await kv.set("order:r-1", "first", {
|
|
67
|
+
ifAbsent: true,
|
|
68
|
+
ttlSeconds: 10
|
|
69
|
+
}), true, "the first set");
|
|
70
|
+
equal(await kv.set("order:r-1", "second", {
|
|
71
|
+
ifAbsent: true,
|
|
72
|
+
ttlSeconds: 10
|
|
73
|
+
}), false, "the second set");
|
|
74
|
+
equal(await kv.get("order:r-1"), "first", "the value kept");
|
|
75
|
+
advance(10 * SECOND);
|
|
76
|
+
equal(await kv.set("order:r-1", "third", { ifAbsent: true }), true, "a set once the first expired");
|
|
77
|
+
equal(await kv.get("order:r-1"), "third", "the value then");
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
name: "of many ifAbsent sets at once exactly one writes",
|
|
82
|
+
async run({ kv }) {
|
|
83
|
+
equal((await Promise.all(Array.from({ length: 50 }, (_, i) => kv.set("lock:report", i, { ifAbsent: true })))).filter(Boolean).length, 1, "the sets that wrote");
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
{
|
|
87
|
+
name: "incr counts from 0, adds by, and sets ttlSeconds only when it makes the key",
|
|
88
|
+
async run({ kv, advance }) {
|
|
89
|
+
equal(await kv.incr("views:home"), 1, "the first incr");
|
|
90
|
+
equal(await kv.incr("views:home", { by: 9 }), 10, "adding 9");
|
|
91
|
+
equal(await kv.incr("views:home", { by: -3 }), 7, "taking 3 away");
|
|
92
|
+
equal(await kv.get("views:home"), 7, "the value read back");
|
|
93
|
+
equal(await kv.incr("hits:minute", { ttlSeconds: 60 }), 1, "a counter with a window");
|
|
94
|
+
advance(30 * SECOND);
|
|
95
|
+
equal(await kv.incr("hits:minute", { ttlSeconds: 60 }), 2, "the second incr in the window");
|
|
96
|
+
advance(30 * SECOND);
|
|
97
|
+
equal(await kv.get("hits:minute"), void 0, "the counter once its first window ended");
|
|
98
|
+
equal(await kv.incr("hits:minute", { ttlSeconds: 60 }), 1, "the first incr of the next window");
|
|
99
|
+
}
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
name: "a thousand incrs at once each count once",
|
|
103
|
+
async run({ kv }) {
|
|
104
|
+
await Promise.all(Array.from({ length: 1e3 }, () => kv.incr("likes:post-7")));
|
|
105
|
+
equal(await kv.get("likes:post-7"), 1e3, "the count");
|
|
106
|
+
}
|
|
107
|
+
},
|
|
108
|
+
{
|
|
109
|
+
name: "incr on a value that isn't a whole number is refused and changes nothing",
|
|
110
|
+
async run({ kv }) {
|
|
111
|
+
await kv.set("name", "ada");
|
|
112
|
+
await refuses(() => kv.incr("name"), "invalid", "incr on text");
|
|
113
|
+
equal(await kv.get("name"), "ada", "the value after the refusal");
|
|
114
|
+
await kv.set("big", 9007199254740991);
|
|
115
|
+
await refuses(() => kv.incr("big"), "invalid", "incr past the largest safe whole number");
|
|
116
|
+
equal(await kv.get("big"), 9007199254740991, "the value after that refusal");
|
|
117
|
+
}
|
|
118
|
+
},
|
|
119
|
+
{
|
|
120
|
+
name: "delete removes keys and returns how many had a value",
|
|
121
|
+
async run({ kv }) {
|
|
122
|
+
await kv.set("a", 1);
|
|
123
|
+
await kv.set("b", 2);
|
|
124
|
+
equal(await kv.delete("a", "b", "c"), 2, "the keys deleted");
|
|
125
|
+
equal(await kv.getMany(["a", "b"]), [void 0, void 0], "the values after");
|
|
126
|
+
}
|
|
127
|
+
},
|
|
128
|
+
{
|
|
129
|
+
name: "expire sets when a key goes, or keeps it forever with null, and says whether the key has a value",
|
|
130
|
+
async run({ kv, advance }) {
|
|
131
|
+
await kv.set("cart:9", ["tea"]);
|
|
132
|
+
equal(await kv.expire("cart:9", 5), true, "expire on a key with a value");
|
|
133
|
+
equal(await kv.expire("cart:10", 5), false, "expire on a key with none");
|
|
134
|
+
advance(4 * SECOND);
|
|
135
|
+
equal(await kv.expire("cart:9", null), true, "keeping it forever");
|
|
136
|
+
advance(10 * SECOND);
|
|
137
|
+
equal(await kv.get("cart:9"), ["tea"], "the value long after its old expiry");
|
|
138
|
+
}
|
|
139
|
+
},
|
|
140
|
+
{
|
|
141
|
+
name: "list returns keys by prefix in byte order, a page at a time, with each one's size and expiry",
|
|
142
|
+
async run({ kv, at }) {
|
|
143
|
+
await kv.set("session:b", "xy", { ttlSeconds: 100 });
|
|
144
|
+
await kv.set("session:a", 1);
|
|
145
|
+
await kv.set("session:c", true);
|
|
146
|
+
await kv.set("user:a", 1);
|
|
147
|
+
const first = await kv.list({
|
|
148
|
+
prefix: "session:",
|
|
149
|
+
limit: 2
|
|
150
|
+
});
|
|
151
|
+
equal(first, {
|
|
152
|
+
keys: [{
|
|
153
|
+
key: "session:a",
|
|
154
|
+
bytes: 10
|
|
155
|
+
}, {
|
|
156
|
+
key: "session:b",
|
|
157
|
+
bytes: 13,
|
|
158
|
+
expiresAt: at + 100 * SECOND
|
|
159
|
+
}],
|
|
160
|
+
next: "session:b"
|
|
161
|
+
}, "the first page");
|
|
162
|
+
equal(await kv.list({
|
|
163
|
+
prefix: "session:",
|
|
164
|
+
limit: 2,
|
|
165
|
+
after: first.next
|
|
166
|
+
}), { keys: [{
|
|
167
|
+
key: "session:c",
|
|
168
|
+
bytes: 13
|
|
169
|
+
}] }, "the second page");
|
|
170
|
+
equal((await kv.list()).keys.map((k) => k.key), [
|
|
171
|
+
"session:a",
|
|
172
|
+
"session:b",
|
|
173
|
+
"session:c",
|
|
174
|
+
"user:a"
|
|
175
|
+
], "every key");
|
|
176
|
+
}
|
|
177
|
+
},
|
|
178
|
+
{
|
|
179
|
+
name: "a limit admits max calls in any window, refuses the next with when to retry, and slides",
|
|
180
|
+
async run({ kv, advance, at }) {
|
|
181
|
+
const limit = () => kv.limit("ip:203.0.113.9", {
|
|
182
|
+
max: 2,
|
|
183
|
+
perSeconds: 10
|
|
184
|
+
});
|
|
185
|
+
equal(await limit(), {
|
|
186
|
+
success: true,
|
|
187
|
+
limit: 2,
|
|
188
|
+
remaining: 1,
|
|
189
|
+
reset: at + 10 * SECOND
|
|
190
|
+
}, "the first call");
|
|
191
|
+
advance(6 * SECOND);
|
|
192
|
+
equal(await limit(), {
|
|
193
|
+
success: true,
|
|
194
|
+
limit: 2,
|
|
195
|
+
remaining: 0,
|
|
196
|
+
reset: at + 10 * SECOND
|
|
197
|
+
}, "the second call, at 6 s");
|
|
198
|
+
advance(1 * SECOND);
|
|
199
|
+
equal(await limit(), {
|
|
200
|
+
success: false,
|
|
201
|
+
limit: 2,
|
|
202
|
+
remaining: 0,
|
|
203
|
+
reset: at + 10 * SECOND,
|
|
204
|
+
retryAfter: 3
|
|
205
|
+
}, "the third call, at 7 s");
|
|
206
|
+
advance(3 * SECOND);
|
|
207
|
+
equal(await limit(), {
|
|
208
|
+
success: true,
|
|
209
|
+
limit: 2,
|
|
210
|
+
remaining: 0,
|
|
211
|
+
reset: at + 16 * SECOND
|
|
212
|
+
}, "a call at 10 s, once the first left the window");
|
|
213
|
+
advance(1 * SECOND);
|
|
214
|
+
equal(await limit(), {
|
|
215
|
+
success: false,
|
|
216
|
+
limit: 2,
|
|
217
|
+
remaining: 0,
|
|
218
|
+
reset: at + 16 * SECOND,
|
|
219
|
+
retryAfter: 5
|
|
220
|
+
}, "a call at 11 s, though a new fixed window would have begun");
|
|
221
|
+
}
|
|
222
|
+
},
|
|
223
|
+
{
|
|
224
|
+
name: "of a thousand limit calls at once exactly max are admitted",
|
|
225
|
+
async run({ kv }) {
|
|
226
|
+
equal((await Promise.all(Array.from({ length: 1e3 }, () => kv.limit("signup", {
|
|
227
|
+
max: 10,
|
|
228
|
+
perSeconds: 60
|
|
229
|
+
})))).filter((d) => d.success).length, 10, "the calls admitted");
|
|
230
|
+
}
|
|
231
|
+
},
|
|
232
|
+
{
|
|
233
|
+
name: "a call's cost counts that many against its limit",
|
|
234
|
+
async run({ kv }) {
|
|
235
|
+
equal((await kv.limit("tokens:ada", {
|
|
236
|
+
max: 100,
|
|
237
|
+
perSeconds: 60,
|
|
238
|
+
cost: 70
|
|
239
|
+
})).remaining, 30, "remaining after a cost of 70");
|
|
240
|
+
equal((await kv.limit("tokens:ada", {
|
|
241
|
+
max: 100,
|
|
242
|
+
perSeconds: 60,
|
|
243
|
+
cost: 40
|
|
244
|
+
})).success, false, "a cost of 40 then");
|
|
245
|
+
equal((await kv.limit("tokens:ada", {
|
|
246
|
+
max: 100,
|
|
247
|
+
perSeconds: 60,
|
|
248
|
+
cost: 30
|
|
249
|
+
})).remaining, 0, "a cost of 30 then");
|
|
250
|
+
}
|
|
251
|
+
},
|
|
252
|
+
{
|
|
253
|
+
name: "a limit is kept apart from the keys, and resetLimit empties its window",
|
|
254
|
+
async run({ kv }) {
|
|
255
|
+
await kv.limit("ip:1", {
|
|
256
|
+
max: 1,
|
|
257
|
+
perSeconds: 60
|
|
258
|
+
});
|
|
259
|
+
equal(await kv.get("ip:1"), void 0, "get on the limit's key");
|
|
260
|
+
equal((await kv.list()).keys, [], "the list");
|
|
261
|
+
await kv.set("ip:1", "a value");
|
|
262
|
+
equal((await kv.limit("ip:1", {
|
|
263
|
+
max: 1,
|
|
264
|
+
perSeconds: 60
|
|
265
|
+
})).success, false, "the limit after a set of the same key");
|
|
266
|
+
await kv.resetLimit("ip:1");
|
|
267
|
+
equal((await kv.limit("ip:1", {
|
|
268
|
+
max: 1,
|
|
269
|
+
perSeconds: 60
|
|
270
|
+
})).success, true, "the limit after its reset");
|
|
271
|
+
equal(await kv.get("ip:1"), "a value", "the key after the reset");
|
|
272
|
+
}
|
|
273
|
+
},
|
|
274
|
+
{
|
|
275
|
+
name: "keys, values and options past their limits are refused, and write nothing",
|
|
276
|
+
async run({ kv }) {
|
|
277
|
+
await refuses(() => kv.set("k".repeat(513), 1), "too-large", "a 513-byte key");
|
|
278
|
+
await refuses(() => kv.set("big", "x".repeat(1048576)), "too-large", "a value of 1 MiB and its quotes");
|
|
279
|
+
await refuses(() => kv.set("line\nbreak", 1), "invalid", "a key with a line break");
|
|
280
|
+
await refuses(() => kv.set("ttl", 1, { ttlSeconds: 0 }), "invalid", "a ttl of 0");
|
|
281
|
+
await refuses(() => kv.set("ttl", 1, { ttlSeconds: 1.5 }), "invalid", "a ttl of 1.5 seconds");
|
|
282
|
+
await refuses(() => kv.limit("l", {
|
|
283
|
+
max: 0,
|
|
284
|
+
perSeconds: 60
|
|
285
|
+
}), "invalid", "a max of 0");
|
|
286
|
+
await refuses(() => kv.limit("l", {
|
|
287
|
+
max: 5,
|
|
288
|
+
perSeconds: 60,
|
|
289
|
+
cost: 6
|
|
290
|
+
}), "invalid", "a cost past max");
|
|
291
|
+
equal((await kv.list()).keys, [], "the keys after the refusals");
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
];
|
|
295
|
+
function equal(actual, expected, what) {
|
|
296
|
+
const a = JSON.stringify(actual), e = JSON.stringify(expected);
|
|
297
|
+
if (a !== e) throw new Error(`${what}: expected ${e}, got ${a}`);
|
|
298
|
+
}
|
|
299
|
+
async function refuses(call, code, what) {
|
|
300
|
+
try {
|
|
301
|
+
await call();
|
|
302
|
+
} catch (error) {
|
|
303
|
+
if (error instanceof KvError && error.code === code) return;
|
|
304
|
+
throw new Error(`${what}: expected a KvError ${code}, got ${error instanceof Error ? `${error.name} ${error.code ?? ""}: ${error.message}` : String(error)}`);
|
|
305
|
+
}
|
|
306
|
+
throw new Error(`${what}: expected a KvError ${code}, but it succeeded`);
|
|
307
|
+
}
|
|
308
|
+
//#endregion
|
|
309
|
+
export { kvContract };
|
package/kv/index.d.mts
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
//#region src/kv/index.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* The key-value store: each environment's store of keys, there before the first call, for sessions, counters, caches,
|
|
4
|
+
* idempotency keys and rate limits. Every read sees the last write, and every limit is exact.
|
|
5
|
+
*
|
|
6
|
+
* import { kv } from "@midsummer-ai/sdk/kv"
|
|
7
|
+
*
|
|
8
|
+
* await kv.set("session:42", { user: "ada" }, { ttlSeconds: 3600 })
|
|
9
|
+
* const session = await kv.get<{ user: string }>("session:42")
|
|
10
|
+
* const views = await kv.incr("views:home")
|
|
11
|
+
* const first = await kv.set(`order:${requestId}`, true, { ifAbsent: true, ttlSeconds: 86_400 })
|
|
12
|
+
* const { success, remaining, retryAfter } = await kv.limit(`ip:${ip}`, { max: 10, perSeconds: 60 })
|
|
13
|
+
*
|
|
14
|
+
* In a deployment, in any framework, `kv` reaches its environment's store with nothing to create or bind: a
|
|
15
|
+
* preview's store is its own and starts empty, so it never holds production's keys. Under `midsummer dev` it
|
|
16
|
+
* reaches that run's store on your computer. In tests, give it the stand-in:
|
|
17
|
+
*
|
|
18
|
+
* import { kvStore } from "@midsummer-ai/sdk/kv"
|
|
19
|
+
* import { standIn } from "@midsummer-ai/sdk/kv/stand-in"
|
|
20
|
+
*
|
|
21
|
+
* const store = kvStore(standIn({ clock: Date.now }))
|
|
22
|
+
*
|
|
23
|
+
* A key is 1 to 512 bytes of text with no line breaks; group keys with a prefix (`session:`), which `list` reads
|
|
24
|
+
* by. A value is any JSON value up to 1 MiB, returned as it was set. A key with `ttlSeconds` is gone once that
|
|
25
|
+
* many seconds pass, to the second: nothing reads it after, whether or not it has been cleared away yet.
|
|
26
|
+
*
|
|
27
|
+
* `limit` admits a call when fewer than `max` were admitted in the last `perSeconds` (a sliding window, exact
|
|
28
|
+
* however many calls arrive at once) and records it in the same step. A limit is kept apart from the keys, so
|
|
29
|
+
* `get` and `list` never see it; `resetLimit` forgets what it admitted. When a limit can't be checked, `limit`
|
|
30
|
+
* throws `unavailable` and never lets the call through on its own: catch it to choose.
|
|
31
|
+
*
|
|
32
|
+
* Each engine is held to the cases in `@midsummer-ai/sdk/kv/contract`; a behaviour that is not a case there is not
|
|
33
|
+
* promised. Every key, value and option is checked here, before anything leaves the caller. Every failure is a
|
|
34
|
+
* `KvError`, whose `code` is the one the wire carries.
|
|
35
|
+
*/
|
|
36
|
+
/** Why a call failed: what was sent (`invalid`, `too-large`), who sent it (`forbidden`), spending (`quota`), or reaching the store (`unavailable`, worth trying again). */
|
|
37
|
+
type KvErrorCode = "invalid" | "too-large" | "forbidden" | "quota" | "unavailable";
|
|
38
|
+
declare const kvErrorCodes: ReadonlyArray<KvErrorCode>;
|
|
39
|
+
declare class KvError extends Error {
|
|
40
|
+
readonly code: KvErrorCode;
|
|
41
|
+
constructor(code: KvErrorCode, why: string);
|
|
42
|
+
}
|
|
43
|
+
/** Any value JSON can carry. */
|
|
44
|
+
type Json = string | number | boolean | null | ReadonlyArray<Json> | {
|
|
45
|
+
readonly [key: string]: Json;
|
|
46
|
+
};
|
|
47
|
+
interface SetOptions {
|
|
48
|
+
/** Seconds until the key is gone: 1 to 31,536,000 (365 days). Left out, it stays until it is deleted. */
|
|
49
|
+
readonly ttlSeconds?: number;
|
|
50
|
+
/** Write only when the key has no value now, and return whether it wrote: an idempotency key or a lock. */
|
|
51
|
+
readonly ifAbsent?: boolean;
|
|
52
|
+
}
|
|
53
|
+
interface IncrOptions {
|
|
54
|
+
/** How much to add: a whole number, negative to take away. 1 when left out. */
|
|
55
|
+
readonly by?: number;
|
|
56
|
+
/** Seconds until the key is gone, set only when this call makes the key, so a counter of a window ends with it. */
|
|
57
|
+
readonly ttlSeconds?: number;
|
|
58
|
+
}
|
|
59
|
+
interface LimitOptions {
|
|
60
|
+
/** At most this many calls in any `perSeconds`: 1 to 10,000. */
|
|
61
|
+
readonly max: number;
|
|
62
|
+
/** The window, in seconds: 1 to 86,400 (a day). */
|
|
63
|
+
readonly perSeconds: number;
|
|
64
|
+
/** How much this call counts for: 1 to `max`, 1 when left out. */
|
|
65
|
+
readonly cost?: number;
|
|
66
|
+
}
|
|
67
|
+
/** What a limit decided for one call. */
|
|
68
|
+
interface LimitResult {
|
|
69
|
+
/** Whether the call is admitted. Admitted, it counts against the limit from now. */
|
|
70
|
+
readonly success: boolean;
|
|
71
|
+
/** The limit's `max`. */
|
|
72
|
+
readonly limit: number;
|
|
73
|
+
/** How many more calls the window admits now. */
|
|
74
|
+
readonly remaining: number;
|
|
75
|
+
/** When the oldest call admitted in the window leaves it, in milliseconds since the epoch. */
|
|
76
|
+
readonly reset: number;
|
|
77
|
+
/** When refused, whole seconds until this call would be admitted: what a `Retry-After` header says. */
|
|
78
|
+
readonly retryAfter?: number;
|
|
79
|
+
}
|
|
80
|
+
/** One key as `list` returns it: its size and when it expires, without its value. */
|
|
81
|
+
interface KeyInfo {
|
|
82
|
+
readonly key: string;
|
|
83
|
+
/** The key and its value as JSON, in bytes. */
|
|
84
|
+
readonly bytes: number;
|
|
85
|
+
/** When it is gone, in milliseconds since the epoch; absent when it stays until deleted. */
|
|
86
|
+
readonly expiresAt?: number;
|
|
87
|
+
}
|
|
88
|
+
interface ListOptions {
|
|
89
|
+
/** Only keys that start with this, such as `session:`. Every key when left out. */
|
|
90
|
+
readonly prefix?: string;
|
|
91
|
+
/** The `next` of the page before. */
|
|
92
|
+
readonly after?: string;
|
|
93
|
+
/** At most this many keys: 1 to 1,000, 100 when left out. */
|
|
94
|
+
readonly limit?: number;
|
|
95
|
+
}
|
|
96
|
+
/** One environment's keys. */
|
|
97
|
+
interface KeyValue {
|
|
98
|
+
/** The key's value, or undefined when it has none or it has expired. */
|
|
99
|
+
get<Value = Json>(key: string): Promise<Value | undefined>;
|
|
100
|
+
/** Up to 100 keys' values, in the order asked, undefined for each that has none. */
|
|
101
|
+
getMany<Value = Json>(keys: ReadonlyArray<string>): Promise<ReadonlyArray<Value | undefined>>;
|
|
102
|
+
/** Sets a key's value. Returns true when it wrote: always, unless `ifAbsent` found a value there. */
|
|
103
|
+
set(key: string, value: Json, options?: SetOptions): Promise<boolean>;
|
|
104
|
+
/** Adds to a key's whole number, starting from 0, and returns the new value. A value that isn't a whole number is `invalid`. */
|
|
105
|
+
incr(key: string, options?: IncrOptions): Promise<number>;
|
|
106
|
+
/** Deletes up to 100 keys; returns how many had a value. */
|
|
107
|
+
delete(...keys: ReadonlyArray<string>): Promise<number>;
|
|
108
|
+
/** Sets when a key is gone, `ttlSeconds` from now, or never with `null`. Returns whether the key has a value. */
|
|
109
|
+
expire(key: string, ttlSeconds: number | null): Promise<boolean>;
|
|
110
|
+
/** A page of keys in order, with each one's size and expiry, and `next` when there are more. */
|
|
111
|
+
list(options?: ListOptions): Promise<{
|
|
112
|
+
readonly keys: ReadonlyArray<KeyInfo>;
|
|
113
|
+
readonly next?: string;
|
|
114
|
+
}>;
|
|
115
|
+
/** Admits or refuses one call under a sliding-window limit named by `key`, such as `ip:203.0.113.9`. */
|
|
116
|
+
limit(key: string, options: LimitOptions): Promise<LimitResult>;
|
|
117
|
+
/** Forgets every call a limit admitted, so its window starts empty. */
|
|
118
|
+
resetLimit(key: string): Promise<void>;
|
|
119
|
+
}
|
|
120
|
+
/** A value as an engine is given it: JSON text, and when it expires. */
|
|
121
|
+
interface EngineEntry {
|
|
122
|
+
readonly value: string;
|
|
123
|
+
readonly expiresAt?: number;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Where keys live: the seam under `kvStore()`. The stand-in and the real store are its Adapters. Calls arrive
|
|
127
|
+
* checked: keys are valid, values are JSON text, times are milliseconds and defaults are filled in.
|
|
128
|
+
*/
|
|
129
|
+
interface KvEngine {
|
|
130
|
+
get(keys: ReadonlyArray<string>): Promise<ReadonlyArray<EngineEntry | null>>;
|
|
131
|
+
set(key: string, value: string, options: {
|
|
132
|
+
readonly ttlMs?: number;
|
|
133
|
+
readonly ifAbsent?: boolean;
|
|
134
|
+
}): Promise<boolean>;
|
|
135
|
+
incr(key: string, by: number, ttlMs?: number): Promise<number>;
|
|
136
|
+
delete(keys: ReadonlyArray<string>): Promise<number>;
|
|
137
|
+
expire(key: string, ttlMs: number | null): Promise<boolean>;
|
|
138
|
+
list(options: {
|
|
139
|
+
readonly prefix: string;
|
|
140
|
+
readonly after?: string;
|
|
141
|
+
readonly limit: number;
|
|
142
|
+
}): Promise<{
|
|
143
|
+
readonly keys: ReadonlyArray<KeyInfo>;
|
|
144
|
+
readonly next?: string;
|
|
145
|
+
}>;
|
|
146
|
+
limit(key: string, options: {
|
|
147
|
+
readonly max: number;
|
|
148
|
+
readonly windowMs: number;
|
|
149
|
+
readonly cost: number;
|
|
150
|
+
}): Promise<{
|
|
151
|
+
readonly ok: boolean;
|
|
152
|
+
readonly limit: number;
|
|
153
|
+
readonly remaining: number;
|
|
154
|
+
readonly resetAt: number;
|
|
155
|
+
readonly retryAfterMs?: number;
|
|
156
|
+
}>;
|
|
157
|
+
/** Forgets what a limit admitted; whether it had admitted anything in its window. */
|
|
158
|
+
resetLimit(key: string): Promise<boolean>;
|
|
159
|
+
}
|
|
160
|
+
/** Where a run's key-value frames go with its Workload token (`workloadTransport`). */
|
|
161
|
+
declare const WORKLOAD_PATH = "/kv/workload";
|
|
162
|
+
/** Keys are at most this many bytes of UTF-8. */
|
|
163
|
+
declare const MAX_KEY = 512;
|
|
164
|
+
/** Values are at most this many bytes of JSON. */
|
|
165
|
+
declare const MAX_VALUE: number;
|
|
166
|
+
/** The longest a key may be kept by `ttlSeconds`: 365 days. */
|
|
167
|
+
declare const MAX_TTL_SECONDS: number;
|
|
168
|
+
/** The most keys one `getMany` or `delete` takes. */
|
|
169
|
+
declare const MAX_KEYS = 100;
|
|
170
|
+
/** The most keys one `list` returns. */
|
|
171
|
+
declare const MAX_LIST = 1000;
|
|
172
|
+
/** The largest `max` a limit takes. */
|
|
173
|
+
declare const MAX_LIMIT = 10000;
|
|
174
|
+
/** The longest window a limit takes, in seconds: a day. */
|
|
175
|
+
declare const MAX_WINDOW_SECONDS = 86400;
|
|
176
|
+
declare function invalid(why: string): never;
|
|
177
|
+
/** A key: 1 to 512 bytes of UTF-8 text, with no line breaks or other control characters. */
|
|
178
|
+
declare function checkKey(key: unknown): asserts key is string;
|
|
179
|
+
/** A prefix to list by: a key's start, empty for every key. */
|
|
180
|
+
declare function checkPrefix(prefix: unknown): asserts prefix is string;
|
|
181
|
+
/** The JSON text of `value`, which must be a JSON value of at most 1 MiB. */
|
|
182
|
+
declare function valueText(value: unknown): string;
|
|
183
|
+
/** JSON text as an engine is given it: at most 1 MiB. */
|
|
184
|
+
declare function checkValueText(text: string): void;
|
|
185
|
+
declare function checkTtlMs(ms: unknown): asserts ms is number;
|
|
186
|
+
declare function checkBy(by: unknown): asserts by is number;
|
|
187
|
+
declare function checkLimit(options: {
|
|
188
|
+
readonly max: unknown;
|
|
189
|
+
readonly windowMs: unknown;
|
|
190
|
+
readonly cost: unknown;
|
|
191
|
+
}): void;
|
|
192
|
+
declare function checkKeys(keys: ReadonlyArray<unknown>): void;
|
|
193
|
+
declare function checkListLimit(limit: unknown): asserts limit is number;
|
|
194
|
+
/**
|
|
195
|
+
* The store of the environment this code runs in: the request's own in a deployment, a run's through its Workload
|
|
196
|
+
* session (a CI run, an agent's dev server), or `midsummer dev`'s on this computer. Every call goes to the one
|
|
197
|
+
* current when it is made.
|
|
198
|
+
*/
|
|
199
|
+
declare function hereEngine(): KvEngine;
|
|
200
|
+
/** The key-value store over `engine`: the stand-in's in tests, or `hereEngine()`. */
|
|
201
|
+
declare function kvStore(engine: KvEngine): KeyValue;
|
|
202
|
+
/** The environment's key-value store, from code in a deployment in any framework, or `midsummer dev`'s. */
|
|
203
|
+
declare const kv: KeyValue;
|
|
204
|
+
//#endregion
|
|
205
|
+
export { EngineEntry, IncrOptions, Json, KeyInfo, KeyValue, KvEngine, KvError, KvErrorCode, LimitOptions, LimitResult, ListOptions, MAX_KEY, MAX_KEYS, MAX_LIMIT, MAX_LIST, MAX_TTL_SECONDS, MAX_VALUE, MAX_WINDOW_SECONDS, SetOptions, WORKLOAD_PATH, checkBy, checkKey, checkKeys, checkLimit, checkListLimit, checkPrefix, checkTtlMs, checkValueText, hereEngine, invalid, kv, kvErrorCodes, kvStore, valueText };
|