@encore.dev/sdk 0.0.0 → 2.0.0-beta.4
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/LICENSE +362 -0
- package/README.md +122 -2
- package/app_meta.test.ts +134 -0
- package/app_meta.ts +186 -0
- package/config/config.test.ts +381 -0
- package/config/config.ts +178 -0
- package/config/mod.ts +14 -0
- package/config/secrets.ts +147 -0
- package/config/value.ts +243 -0
- package/cron/mod.ts +23 -0
- package/dist/app_meta.d.ts +93 -0
- package/dist/app_meta.js +65 -0
- package/dist/app_meta.js.map +1 -0
- package/dist/config/config.d.ts +105 -0
- package/dist/config/config.js +87 -0
- package/dist/config/config.js.map +1 -0
- package/dist/config/mod.d.ts +4 -0
- package/dist/config/mod.js +3 -0
- package/dist/config/mod.js.map +1 -0
- package/dist/config/secrets.d.ts +92 -0
- package/dist/config/secrets.js +80 -0
- package/dist/config/secrets.js.map +1 -0
- package/dist/config/value.d.ts +51 -0
- package/dist/config/value.js +178 -0
- package/dist/config/value.js.map +1 -0
- package/dist/cron/mod.d.ts +22 -0
- package/dist/cron/mod.js +9 -0
- package/dist/cron/mod.js.map +1 -0
- package/dist/internal/otel/backend.d.ts +50 -0
- package/dist/internal/otel/backend.js +2 -0
- package/dist/internal/otel/backend.js.map +1 -0
- package/dist/internal/otel/context.d.ts +10 -0
- package/dist/internal/otel/context.js +34 -0
- package/dist/internal/otel/context.js.map +1 -0
- package/dist/internal/otel/context_manager.d.ts +22 -0
- package/dist/internal/otel/context_manager.js +120 -0
- package/dist/internal/otel/context_manager.js.map +1 -0
- package/dist/internal/otel/encode.d.ts +112 -0
- package/dist/internal/otel/encode.js +290 -0
- package/dist/internal/otel/encode.js.map +1 -0
- package/dist/internal/otel/index.d.ts +9 -0
- package/dist/internal/otel/index.js +9 -0
- package/dist/internal/otel/index.js.map +1 -0
- package/dist/internal/otel/meter.d.ts +73 -0
- package/dist/internal/otel/meter.js +265 -0
- package/dist/internal/otel/meter.js.map +1 -0
- package/dist/internal/otel/propagator.d.ts +14 -0
- package/dist/internal/otel/propagator.js +61 -0
- package/dist/internal/otel/propagator.js.map +1 -0
- package/dist/internal/otel/provider.d.ts +9 -0
- package/dist/internal/otel/provider.js +19 -0
- package/dist/internal/otel/provider.js.map +1 -0
- package/dist/internal/otel/request_context.d.ts +11 -0
- package/dist/internal/otel/request_context.js +20 -0
- package/dist/internal/otel/request_context.js.map +1 -0
- package/dist/internal/otel/span.d.ts +61 -0
- package/dist/internal/otel/span.js +206 -0
- package/dist/internal/otel/span.js.map +1 -0
- package/dist/internal/otel/tracer.d.ts +15 -0
- package/dist/internal/otel/tracer.js +65 -0
- package/dist/internal/otel/tracer.js.map +1 -0
- package/dist/internal/reqtrack/mod.d.ts +6 -0
- package/dist/internal/reqtrack/mod.js +28 -0
- package/dist/internal/reqtrack/mod.js.map +1 -0
- package/dist/internal/runtime/meter.d.ts +11 -0
- package/dist/internal/runtime/meter.js +22 -0
- package/dist/internal/runtime/meter.js.map +1 -0
- package/dist/internal/runtime/mod.d.ts +12 -0
- package/dist/internal/runtime/mod.js +28 -0
- package/dist/internal/runtime/mod.js.map +1 -0
- package/dist/internal/runtime/napi/napi.cjs +122 -0
- package/dist/internal/runtime/napi/napi.d.cts +601 -0
- package/dist/internal/runtime/shutdown.d.ts +13 -0
- package/dist/internal/runtime/shutdown.js +56 -0
- package/dist/internal/runtime/shutdown.js.map +1 -0
- package/dist/internal/utils/constraints.d.ts +9 -0
- package/dist/internal/utils/constraints.js +2 -0
- package/dist/internal/utils/constraints.js.map +1 -0
- package/dist/log/index.d.ts +39 -0
- package/dist/log/index.js +44 -0
- package/dist/log/index.js.map +1 -0
- package/dist/log/logger.d.ts +123 -0
- package/dist/log/logger.js +203 -0
- package/dist/log/logger.js.map +1 -0
- package/dist/log/runtime.d.ts +19 -0
- package/dist/log/runtime.js +22 -0
- package/dist/log/runtime.js.map +1 -0
- package/dist/log/stderr.d.ts +9 -0
- package/dist/log/stderr.js +25 -0
- package/dist/log/stderr.js.map +1 -0
- package/dist/metrics/mod.d.ts +315 -0
- package/dist/metrics/mod.js +488 -0
- package/dist/metrics/mod.js.map +1 -0
- package/dist/mod.d.ts +6 -0
- package/dist/mod.js +4 -0
- package/dist/mod.js.map +1 -0
- package/dist/otel.d.ts +9 -0
- package/dist/otel.js +13 -0
- package/dist/otel.js.map +1 -0
- package/dist/pubsub/encoding.d.ts +3 -0
- package/dist/pubsub/encoding.js +10 -0
- package/dist/pubsub/encoding.js.map +1 -0
- package/dist/pubsub/mod.d.ts +6 -0
- package/dist/pubsub/mod.js +3 -0
- package/dist/pubsub/mod.js.map +1 -0
- package/dist/pubsub/refs.d.ts +12 -0
- package/dist/pubsub/refs.js +11 -0
- package/dist/pubsub/refs.js.map +1 -0
- package/dist/pubsub/subscription.d.ts +128 -0
- package/dist/pubsub/subscription.js +39 -0
- package/dist/pubsub/subscription.js.map +1 -0
- package/dist/pubsub/topic.d.ts +148 -0
- package/dist/pubsub/topic.js +164 -0
- package/dist/pubsub/topic.js.map +1 -0
- package/dist/req_meta.d.ts +47 -0
- package/dist/req_meta.js +26 -0
- package/dist/req_meta.js.map +1 -0
- package/dist/services/index.d.ts +7 -0
- package/dist/services/index.js +17 -0
- package/dist/services/index.js.map +1 -0
- package/dist/shutdown/mod.d.ts +23 -0
- package/dist/shutdown/mod.js +24 -0
- package/dist/shutdown/mod.js.map +1 -0
- package/dist/storage/objects/bucket.d.ts +216 -0
- package/dist/storage/objects/bucket.js +123 -0
- package/dist/storage/objects/bucket.js.map +1 -0
- package/dist/storage/objects/error.d.ts +14 -0
- package/dist/storage/objects/error.js +81 -0
- package/dist/storage/objects/error.js.map +1 -0
- package/dist/storage/objects/mod.d.ts +4 -0
- package/dist/storage/objects/mod.js +3 -0
- package/dist/storage/objects/mod.js.map +1 -0
- package/dist/storage/objects/refs.d.ts +31 -0
- package/dist/storage/objects/refs.js +20 -0
- package/dist/storage/objects/refs.js.map +1 -0
- package/dist/storage/postgres/database.d.ts +295 -0
- package/dist/storage/postgres/database.js +378 -0
- package/dist/storage/postgres/database.js.map +1 -0
- package/dist/storage/postgres/mod.d.ts +2 -0
- package/dist/storage/postgres/mod.js +2 -0
- package/dist/storage/postgres/mod.js.map +1 -0
- package/dist/storage/redis/commands.d.ts +573 -0
- package/dist/storage/redis/commands.js +637 -0
- package/dist/storage/redis/commands.js.map +1 -0
- package/dist/storage/redis/database.d.ts +302 -0
- package/dist/storage/redis/database.js +336 -0
- package/dist/storage/redis/database.js.map +1 -0
- package/dist/storage/redis/mod.d.ts +88 -0
- package/dist/storage/redis/mod.js +84 -0
- package/dist/storage/redis/mod.js.map +1 -0
- package/dist/storage/redis/native.d.ts +8 -0
- package/dist/storage/redis/native.js +11 -0
- package/dist/storage/redis/native.js.map +1 -0
- package/dist/storage/redis/options.d.ts +89 -0
- package/dist/storage/redis/options.js +53 -0
- package/dist/storage/redis/options.js.map +1 -0
- package/dist/storage/redis/pubsub.d.ts +53 -0
- package/dist/storage/redis/pubsub.js +88 -0
- package/dist/storage/redis/pubsub.js.map +1 -0
- package/dist/storage/redis/reply.d.ts +256 -0
- package/dist/storage/redis/reply.js +572 -0
- package/dist/storage/redis/reply.js.map +1 -0
- package/dist/storage/redis/scan.d.ts +11 -0
- package/dist/storage/redis/scan.js +76 -0
- package/dist/storage/redis/scan.js.map +1 -0
- package/dist/storage/redis/script.d.ts +91 -0
- package/dist/storage/redis/script.js +143 -0
- package/dist/storage/redis/script.js.map +1 -0
- package/dist/storage/redis/target.d.ts +47 -0
- package/dist/storage/redis/target.js +82 -0
- package/dist/storage/redis/target.js.map +1 -0
- package/dist/storage/redis/wire.d.ts +105 -0
- package/dist/storage/redis/wire.js +333 -0
- package/dist/storage/redis/wire.js.map +1 -0
- package/dist/tsconfig.build.tsbuildinfo +1 -0
- package/dist/types/mod.d.ts +42 -0
- package/dist/types/mod.js +65 -0
- package/dist/types/mod.js.map +1 -0
- package/internal/otel/backend.ts +60 -0
- package/internal/otel/context.test.ts +70 -0
- package/internal/otel/context.ts +48 -0
- package/internal/otel/context_manager.test.ts +154 -0
- package/internal/otel/context_manager.ts +141 -0
- package/internal/otel/encode.test.ts +266 -0
- package/internal/otel/encode.ts +408 -0
- package/internal/otel/index.ts +20 -0
- package/internal/otel/meter.test.ts +231 -0
- package/internal/otel/meter.ts +332 -0
- package/internal/otel/propagator.test.ts +105 -0
- package/internal/otel/propagator.ts +68 -0
- package/internal/otel/provider.ts +23 -0
- package/internal/otel/request_context.ts +32 -0
- package/internal/otel/span.ts +252 -0
- package/internal/otel/tracer.test.ts +352 -0
- package/internal/otel/tracer.ts +104 -0
- package/internal/reqtrack/mod.ts +39 -0
- package/internal/runtime/meter.ts +26 -0
- package/internal/runtime/mod.ts +41 -0
- package/internal/runtime/napi/napi.cjs +122 -0
- package/internal/runtime/napi/napi.d.cts +601 -0
- package/internal/runtime/shutdown.test.ts +248 -0
- package/internal/runtime/shutdown.ts +64 -0
- package/internal/utils/constraints.ts +12 -0
- package/log/index.ts +107 -0
- package/log/logger.test.ts +194 -0
- package/log/logger.ts +308 -0
- package/log/runtime.test.ts +65 -0
- package/log/runtime.ts +40 -0
- package/log/stderr.test.ts +23 -0
- package/log/stderr.ts +24 -0
- package/metrics/export.test.ts +337 -0
- package/metrics/mod.test.ts +180 -0
- package/metrics/mod.ts +619 -0
- package/mod.ts +22 -0
- package/otel.test.ts +84 -0
- package/otel.ts +17 -0
- package/package.json +121 -5
- package/pubsub/encoding.ts +8 -0
- package/pubsub/mod.ts +14 -0
- package/pubsub/pubsub.test.ts +186 -0
- package/pubsub/refs.ts +22 -0
- package/pubsub/subscription.ts +180 -0
- package/pubsub/topic.test.ts +121 -0
- package/pubsub/topic.ts +212 -0
- package/req_meta.ts +75 -0
- package/services/index.test.ts +30 -0
- package/services/index.ts +16 -0
- package/shutdown/mod.ts +24 -0
- package/storage/objects/bucket.ts +338 -0
- package/storage/objects/error.ts +94 -0
- package/storage/objects/mod.ts +35 -0
- package/storage/objects/refs.ts +69 -0
- package/storage/postgres/database.integration.test.ts +175 -0
- package/storage/postgres/database.test.ts +241 -0
- package/storage/postgres/database.ts +497 -0
- package/storage/postgres/mod.ts +15 -0
- package/storage/redis/commands.ts +1221 -0
- package/storage/redis/database.ts +466 -0
- package/storage/redis/mod.ts +135 -0
- package/storage/redis/native.ts +11 -0
- package/storage/redis/options.ts +119 -0
- package/storage/redis/pubsub.ts +92 -0
- package/storage/redis/redis.test.ts +706 -0
- package/storage/redis/reply.ts +705 -0
- package/storage/redis/runtime.test.ts +233 -0
- package/storage/redis/scan.ts +125 -0
- package/storage/redis/script.ts +162 -0
- package/storage/redis/target.ts +131 -0
- package/storage/redis/wire.ts +369 -0
- package/types/mod.ts +92 -0
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import {afterAll, describe, expect, test} from 'bun:test';
|
|
2
|
+
import {createServer, type Socket} from 'node:net';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The SDK on the native runtime, against a server that is no Redis: it
|
|
6
|
+
* records the commands the core sends and answers each from a script, so that
|
|
7
|
+
* this checks what crosses napi and the core, both ways, and nothing of how a
|
|
8
|
+
* server behaves, which the core's own tests check against miniredis.
|
|
9
|
+
*
|
|
10
|
+
* The runtime reads its config from the environment it starts with, which Bun
|
|
11
|
+
* does not let a test change for the process it runs in (see
|
|
12
|
+
* `app_meta.test.ts`), so the SDK runs in a child process given the server's
|
|
13
|
+
* address.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** Commands received, as their arguments joined by spaces. */
|
|
17
|
+
const received: string[] = [];
|
|
18
|
+
|
|
19
|
+
/** Replies by command name, in RESP; `+OK` for the rest. */
|
|
20
|
+
const replies: Record<string, string> = {
|
|
21
|
+
GET: '$3\r\nada\r\n',
|
|
22
|
+
MGET: '*2\r\n$3\r\nada\r\n$-1\r\n',
|
|
23
|
+
INCRBY: ':2\r\n',
|
|
24
|
+
HGETALL: '*2\r\n$1\r\nf\r\n$1\r\nv\r\n',
|
|
25
|
+
LPUSH:
|
|
26
|
+
'-WRONGTYPE Operation against a key holding the wrong kind of value\r\n',
|
|
27
|
+
XREAD:
|
|
28
|
+
'*1\r\n*2\r\n$6\r\np/jobs\r\n*1\r\n*2\r\n$3\r\n1-0\r\n*2\r\n$1\r\nf\r\n$1\r\nv\r\n',
|
|
29
|
+
SCAN: '*2\r\n$1\r\n0\r\n*1\r\n$6\r\np/name\r\n',
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const bulk = (s: string) => `$${Buffer.byteLength(s)}\r\n${s}\r\n`;
|
|
33
|
+
|
|
34
|
+
/** Reads the commands, each an array of bulk strings, from a connection. */
|
|
35
|
+
function serve(socket: Socket) {
|
|
36
|
+
let buf = Buffer.alloc(0);
|
|
37
|
+
socket.on('data', chunk => {
|
|
38
|
+
buf = Buffer.concat([buf, chunk]);
|
|
39
|
+
for (;;) {
|
|
40
|
+
const parsed = parseCommand(buf);
|
|
41
|
+
if (!parsed) return;
|
|
42
|
+
const [args, rest] = parsed;
|
|
43
|
+
buf = rest;
|
|
44
|
+
const name = args[0].toUpperCase();
|
|
45
|
+
if (name === 'CLIENT' || name === 'HELLO') {
|
|
46
|
+
socket.write('+OK\r\n');
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (name === 'PING') {
|
|
50
|
+
socket.write('+PONG\r\n');
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
received.push(args.join(' '));
|
|
54
|
+
if (name === 'SUBSCRIBE') {
|
|
55
|
+
const channel = args[1];
|
|
56
|
+
socket.write(`*3\r\n${bulk('subscribe')}${bulk(channel)}:1\r\n`);
|
|
57
|
+
// Published as soon as it is subscribed to, so that the child has one
|
|
58
|
+
// message to read.
|
|
59
|
+
socket.write(
|
|
60
|
+
`*3\r\n${bulk('message')}${bulk(channel)}${bulk('hello')}`,
|
|
61
|
+
);
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (name === 'MULTI') {
|
|
65
|
+
socket.write('+OK\r\n');
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (name === 'EXEC') {
|
|
69
|
+
socket.write('*2\r\n+OK\r\n:2\r\n');
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
// Inside MULTI each command is queued.
|
|
73
|
+
const inMulti = received.includes('MULTI') && !received.includes('EXEC');
|
|
74
|
+
socket.write(inMulti ? '+QUEUED\r\n' : (replies[name] ?? '+OK\r\n'));
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function parseCommand(buf: Buffer): [string[], Buffer] | null {
|
|
80
|
+
let at = 0;
|
|
81
|
+
const line = () => {
|
|
82
|
+
const end = buf.indexOf('\r\n', at);
|
|
83
|
+
if (end < 0) return null;
|
|
84
|
+
const out = buf.subarray(at, end).toString();
|
|
85
|
+
at = end + 2;
|
|
86
|
+
return out;
|
|
87
|
+
};
|
|
88
|
+
const head = line();
|
|
89
|
+
if (head === null) return null;
|
|
90
|
+
const n = Number(head.slice(1));
|
|
91
|
+
const args: string[] = [];
|
|
92
|
+
for (let i = 0; i < n; i++) {
|
|
93
|
+
const size = line();
|
|
94
|
+
if (size === null) return null;
|
|
95
|
+
const len = Number(size.slice(1));
|
|
96
|
+
if (buf.length < at + len + 2) return null;
|
|
97
|
+
const arg = buf.subarray(at, at + len);
|
|
98
|
+
args.push(
|
|
99
|
+
arg.every(c => c >= 0x20 && c < 0x7f)
|
|
100
|
+
? arg.toString()
|
|
101
|
+
: `0x${arg.toString('hex')}`,
|
|
102
|
+
);
|
|
103
|
+
at += len + 2;
|
|
104
|
+
}
|
|
105
|
+
return [args, buf.subarray(at)];
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const server = createServer(serve);
|
|
109
|
+
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
|
|
110
|
+
afterAll(() => server.close());
|
|
111
|
+
const address = server.address();
|
|
112
|
+
if (!address || typeof address === 'string') throw new Error('no address');
|
|
113
|
+
|
|
114
|
+
/** A runtime config, as JSON (`crates/encore_runtimecfg/src/encoding.rs`). */
|
|
115
|
+
const runtimeConfig = JSON.stringify({
|
|
116
|
+
environment: {
|
|
117
|
+
app_id: 'test-app',
|
|
118
|
+
app_slug: 'test-app',
|
|
119
|
+
env_id: 'test-env',
|
|
120
|
+
env_name: 'test',
|
|
121
|
+
env_type: 'development',
|
|
122
|
+
cloud: 'local',
|
|
123
|
+
},
|
|
124
|
+
infra: {
|
|
125
|
+
resources: {
|
|
126
|
+
redis_clusters: [
|
|
127
|
+
{
|
|
128
|
+
rid: 'redis',
|
|
129
|
+
servers: [
|
|
130
|
+
{
|
|
131
|
+
rid: 'redis-server',
|
|
132
|
+
host: `127.0.0.1:${address.port}`,
|
|
133
|
+
kind: 'primary',
|
|
134
|
+
},
|
|
135
|
+
],
|
|
136
|
+
databases: [
|
|
137
|
+
{
|
|
138
|
+
rid: 'redis-db',
|
|
139
|
+
encore_name: 'test-db',
|
|
140
|
+
key_prefix: 'p/',
|
|
141
|
+
conn_pools: [{role_rid: 'redis-role', max_connections: 4}],
|
|
142
|
+
},
|
|
143
|
+
],
|
|
144
|
+
},
|
|
145
|
+
],
|
|
146
|
+
},
|
|
147
|
+
credentials: {redis_roles: [{rid: 'redis-role'}]},
|
|
148
|
+
},
|
|
149
|
+
deployment: {deploy_id: 'test-deploy', hosted_services: [{name: 'svc'}]},
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
/** What the child does, and prints as JSON on its last line. */
|
|
153
|
+
const probe = `
|
|
154
|
+
import { Database, ServerError } from ${JSON.stringify(`${import.meta.dir}/mod`)};
|
|
155
|
+
const DB = new Database("test-db");
|
|
156
|
+
const out = {};
|
|
157
|
+
await DB.string.set("name", Buffer.from([0, 0xff]));
|
|
158
|
+
out.get = await DB.string.get("name").text();
|
|
159
|
+
out.mget = await DB.string.mget("name", "nobody").optionalTexts();
|
|
160
|
+
out.incr = await DB.string.incr("visits", 2);
|
|
161
|
+
out.hgetall = await DB.hash.hgetall("user").textMap();
|
|
162
|
+
try {
|
|
163
|
+
await DB.list.lpush("name", "x");
|
|
164
|
+
} catch (err) {
|
|
165
|
+
out.error = err instanceof ServerError ? err.code : String(err);
|
|
166
|
+
}
|
|
167
|
+
out.streams = await DB.stream.xread(["jobs"], ["0"]).streams();
|
|
168
|
+
out.keys = [];
|
|
169
|
+
for await (const key of DB.generic.scan()) out.keys.push(key);
|
|
170
|
+
const tx = DB.transaction();
|
|
171
|
+
tx.string.set("a", 1);
|
|
172
|
+
tx.string.incr("a", 1);
|
|
173
|
+
out.tx = (await tx.exec()).map((r) => r.value());
|
|
174
|
+
const sub = await DB.pubsub.subscribe("events");
|
|
175
|
+
const message = await sub.next();
|
|
176
|
+
out.message = [message.channel, message.text()];
|
|
177
|
+
await sub.close();
|
|
178
|
+
console.log(JSON.stringify(out));
|
|
179
|
+
process.exit(0);
|
|
180
|
+
`;
|
|
181
|
+
|
|
182
|
+
describe('the native runtime', () => {
|
|
183
|
+
test('prefixes the keys, runs the commands and decodes their replies', async () => {
|
|
184
|
+
const env: Record<string, string | undefined> = {
|
|
185
|
+
...process.env,
|
|
186
|
+
ENCORE_RUNTIME_CONFIG: runtimeConfig,
|
|
187
|
+
};
|
|
188
|
+
const proc = Bun.spawn({
|
|
189
|
+
cmd: [process.execPath, '-e', probe],
|
|
190
|
+
cwd: import.meta.dir,
|
|
191
|
+
env,
|
|
192
|
+
stdout: 'pipe',
|
|
193
|
+
stderr: 'pipe',
|
|
194
|
+
});
|
|
195
|
+
const [stdout, stderr, code] = await Promise.all([
|
|
196
|
+
new Response(proc.stdout).text(),
|
|
197
|
+
new Response(proc.stderr).text(),
|
|
198
|
+
proc.exited,
|
|
199
|
+
]);
|
|
200
|
+
if (code !== 0)
|
|
201
|
+
throw new Error(`the probe failed (exit ${code}):\n${stdout}\n${stderr}`);
|
|
202
|
+
// The core logs to stdout as it initializes; the probe's JSON is the last line.
|
|
203
|
+
const lines = stdout.trim().split('\n');
|
|
204
|
+
const out = JSON.parse(lines[lines.length - 1]);
|
|
205
|
+
|
|
206
|
+
expect(out).toEqual({
|
|
207
|
+
get: 'ada',
|
|
208
|
+
mget: ['ada', null],
|
|
209
|
+
incr: 2,
|
|
210
|
+
hgetall: {f: 'v'},
|
|
211
|
+
error: 'WRONGTYPE',
|
|
212
|
+
streams: [{key: 'jobs', entries: [{id: '1-0', fields: {f: 'v'}}]}],
|
|
213
|
+
keys: ['name'],
|
|
214
|
+
tx: ['OK', 2],
|
|
215
|
+
message: ['events', 'hello'],
|
|
216
|
+
});
|
|
217
|
+
expect(received).toEqual([
|
|
218
|
+
'SET p/name 0x00ff',
|
|
219
|
+
'GET p/name',
|
|
220
|
+
'MGET p/name p/nobody',
|
|
221
|
+
'INCRBY p/visits 2',
|
|
222
|
+
'HGETALL p/user',
|
|
223
|
+
'LPUSH p/name x',
|
|
224
|
+
'XREAD STREAMS p/jobs 0',
|
|
225
|
+
'SCAN 0 MATCH p/*',
|
|
226
|
+
'MULTI',
|
|
227
|
+
'SET p/a 1',
|
|
228
|
+
'INCRBY p/a 1',
|
|
229
|
+
'EXEC',
|
|
230
|
+
'SUBSCRIBE p/events',
|
|
231
|
+
]);
|
|
232
|
+
});
|
|
233
|
+
});
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import type {ScanOptions} from './options';
|
|
2
|
+
import {
|
|
3
|
+
arrayOf,
|
|
4
|
+
scoredMembersOf,
|
|
5
|
+
textOf,
|
|
6
|
+
type FieldValue,
|
|
7
|
+
type ScoredMember,
|
|
8
|
+
} from './reply';
|
|
9
|
+
import type {Target} from './target';
|
|
10
|
+
import {Cmd, type Value} from './wire';
|
|
11
|
+
|
|
12
|
+
// The scans: they return an iteration, not a reply.
|
|
13
|
+
//
|
|
14
|
+
// As with Redis's own SCAN, an element present for the whole iteration is
|
|
15
|
+
// returned at least once — possibly more — and one added or removed during it
|
|
16
|
+
// may or may not be.
|
|
17
|
+
|
|
18
|
+
/** Iterates over the database's keys. */
|
|
19
|
+
export async function* scanKeys(
|
|
20
|
+
t: Target,
|
|
21
|
+
options: ScanOptions = {},
|
|
22
|
+
): AsyncGenerator<string> {
|
|
23
|
+
const prefix = t.prefix() ?? '';
|
|
24
|
+
// Keys are scanned across the whole server, so the pattern has to select
|
|
25
|
+
// this database's: its prefix, then what was asked for.
|
|
26
|
+
const pattern = prefix
|
|
27
|
+
? escapeGlob(prefix) + (options.pattern ?? '*')
|
|
28
|
+
: options.pattern;
|
|
29
|
+
const base = new Cmd('scan', 'SCAN', false);
|
|
30
|
+
for await (const batch of scanBatches(t, base, pattern, options.count)) {
|
|
31
|
+
for (const item of batch) {
|
|
32
|
+
const key = textOf(item);
|
|
33
|
+
yield key.startsWith(prefix) ? key.slice(prefix.length) : key;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Iterates over a set's members. */
|
|
39
|
+
export async function* scanMembers(
|
|
40
|
+
t: Target,
|
|
41
|
+
key: string,
|
|
42
|
+
options: ScanOptions = {},
|
|
43
|
+
): AsyncGenerator<string> {
|
|
44
|
+
const base = new Cmd('sscan', 'SSCAN', false).key(key);
|
|
45
|
+
for await (const batch of scanBatches(
|
|
46
|
+
t,
|
|
47
|
+
base,
|
|
48
|
+
options.pattern,
|
|
49
|
+
options.count,
|
|
50
|
+
)) {
|
|
51
|
+
for (const item of batch) yield textOf(item);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Iterates over a hash's fields, each with its value. */
|
|
56
|
+
export async function* scanFields(
|
|
57
|
+
t: Target,
|
|
58
|
+
key: string,
|
|
59
|
+
options: ScanOptions = {},
|
|
60
|
+
): AsyncGenerator<FieldValue> {
|
|
61
|
+
const base = new Cmd('hscan', 'HSCAN', false).key(key);
|
|
62
|
+
for await (const batch of scanBatches(
|
|
63
|
+
t,
|
|
64
|
+
base,
|
|
65
|
+
options.pattern,
|
|
66
|
+
options.count,
|
|
67
|
+
)) {
|
|
68
|
+
if (batch.length % 2 !== 0) {
|
|
69
|
+
throw new TypeError(
|
|
70
|
+
"redis: the scan's reply does not divide into fields and values",
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
for (let i = 0; i < batch.length; i += 2) {
|
|
74
|
+
yield {field: textOf(batch[i]), value: textOf(batch[i + 1])};
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Iterates over a sorted set's members, each with its score. */
|
|
80
|
+
export async function* scanScored(
|
|
81
|
+
t: Target,
|
|
82
|
+
key: string,
|
|
83
|
+
options: ScanOptions = {},
|
|
84
|
+
): AsyncGenerator<ScoredMember> {
|
|
85
|
+
const base = new Cmd('zscan', 'ZSCAN', false).key(key);
|
|
86
|
+
for await (const batch of scanBatches(
|
|
87
|
+
t,
|
|
88
|
+
base,
|
|
89
|
+
options.pattern,
|
|
90
|
+
options.count,
|
|
91
|
+
)) {
|
|
92
|
+
for (const member of scoredMembersOf(batch)) yield member;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Runs `base` — a scan command, up to its cursor — from cursor 0 until the
|
|
98
|
+
* server says there is no more, yielding each batch it returns.
|
|
99
|
+
*/
|
|
100
|
+
async function* scanBatches(
|
|
101
|
+
t: Target,
|
|
102
|
+
base: Cmd,
|
|
103
|
+
pattern: string | undefined,
|
|
104
|
+
count: number | undefined,
|
|
105
|
+
): AsyncGenerator<Value[]> {
|
|
106
|
+
let cursor = '0';
|
|
107
|
+
do {
|
|
108
|
+
const cmd = base.clone().arg(cursor);
|
|
109
|
+
if (pattern !== undefined) cmd.arg('MATCH').arg(pattern);
|
|
110
|
+
if (count) cmd.arg('COUNT').arg(count);
|
|
111
|
+
const parts = arrayOf(await t.run(cmd));
|
|
112
|
+
if (parts.length !== 2) {
|
|
113
|
+
throw new TypeError(
|
|
114
|
+
'redis: a scan replied something other than a cursor and a batch',
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
cursor = textOf(parts[0]);
|
|
118
|
+
yield arrayOf(parts[1]);
|
|
119
|
+
} while (cursor !== '0');
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** `text` with the characters a glob pattern gives meaning to escaped. */
|
|
123
|
+
function escapeGlob(text: string): string {
|
|
124
|
+
return text.replace(/[*?[\]\\]/g, c => `\\${c}`);
|
|
125
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
import {Reply, ReplyPromise} from './reply';
|
|
4
|
+
import type {Target} from './target';
|
|
5
|
+
import {Cmd, ServerError, type RedisArg} from './wire';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A Lua script the database runs, declared at module scope.
|
|
9
|
+
*
|
|
10
|
+
* ```ts
|
|
11
|
+
* import { Database, Script } from "@encore.dev/sdk/storage/redis";
|
|
12
|
+
*
|
|
13
|
+
* const LOCKS = new Database("locks");
|
|
14
|
+
*
|
|
15
|
+
* const RELEASE = new Script(`
|
|
16
|
+
* if redis.call("get", KEYS[1]) == ARGV[1] then
|
|
17
|
+
* return redis.call("del", KEYS[1])
|
|
18
|
+
* end
|
|
19
|
+
* return 0
|
|
20
|
+
* `);
|
|
21
|
+
*
|
|
22
|
+
* async function release(job: string, token: string): Promise<boolean> {
|
|
23
|
+
* const released = await LOCKS.script(RELEASE).key(`lock:${job}`).arg(token).invoke().bool();
|
|
24
|
+
* return released === true;
|
|
25
|
+
* }
|
|
26
|
+
* ```
|
|
27
|
+
*
|
|
28
|
+
* Only the keys passed through `KEYS`, with {@link Invocation.key}, get the
|
|
29
|
+
* database's key prefix. The script's source and its `ARGV` are sent as they
|
|
30
|
+
* are, and Redis cannot hold a script to `KEYS`: a key it names any other way
|
|
31
|
+
* is the server's key of that name, unprefixed, outside this database's
|
|
32
|
+
* isolation, which can be another database's on the same server. So a script
|
|
33
|
+
* must take every key it touches through `KEYS`.
|
|
34
|
+
*/
|
|
35
|
+
export class Script {
|
|
36
|
+
/** The script's source. */
|
|
37
|
+
readonly source: string;
|
|
38
|
+
/** Whether it only reads: see {@link Script.readOnly}. */
|
|
39
|
+
readonly isReadOnly: boolean = false;
|
|
40
|
+
/** The source's SHA-1, which the server caches the script under. */
|
|
41
|
+
private readonly hash: string;
|
|
42
|
+
|
|
43
|
+
/** Declares a script. */
|
|
44
|
+
constructor(source: string) {
|
|
45
|
+
this.source = source;
|
|
46
|
+
this.hash = createHash('sha1').update(source).digest('hex');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Declares a script that only reads. The server refuses to let it write,
|
|
51
|
+
* which is what lets it run on a handle that can only read.
|
|
52
|
+
*/
|
|
53
|
+
static readOnly(source: string): Script {
|
|
54
|
+
const script = new Script(source);
|
|
55
|
+
(script as {isReadOnly: boolean}).isReadOnly = true;
|
|
56
|
+
return script;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The command that runs the script: by its hash, which the server has if
|
|
61
|
+
* it has run it before, or by its source.
|
|
62
|
+
*
|
|
63
|
+
* @internal
|
|
64
|
+
*/
|
|
65
|
+
command(
|
|
66
|
+
byHash: boolean,
|
|
67
|
+
keys: readonly string[],
|
|
68
|
+
args: readonly RedisArg[],
|
|
69
|
+
): Cmd {
|
|
70
|
+
const name = (byHash ? 'EVALSHA' : 'EVAL') + (this.isReadOnly ? '_RO' : '');
|
|
71
|
+
return new Cmd('script', name, !this.isReadOnly)
|
|
72
|
+
.arg(byHash ? this.hash : this.source)
|
|
73
|
+
.arg(keys.length)
|
|
74
|
+
.keys(keys)
|
|
75
|
+
.argsOf(args);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** A call to a {@link Script}, to give its keys and arguments and then invoke. */
|
|
80
|
+
export class Invocation {
|
|
81
|
+
private readonly keys: string[] = [];
|
|
82
|
+
private readonly args: RedisArg[] = [];
|
|
83
|
+
|
|
84
|
+
/** @internal */
|
|
85
|
+
constructor(
|
|
86
|
+
private readonly t: Target,
|
|
87
|
+
private readonly script: Script,
|
|
88
|
+
/** Whether the handle it was made from can only read. */
|
|
89
|
+
private readonly readOnly: boolean,
|
|
90
|
+
) {}
|
|
91
|
+
|
|
92
|
+
/** A key the script works on: the next of its `KEYS`. */
|
|
93
|
+
key(key: string): this {
|
|
94
|
+
this.keys.push(key);
|
|
95
|
+
return this;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** An argument: the next of the script's `ARGV`. */
|
|
99
|
+
arg(arg: RedisArg): this {
|
|
100
|
+
this.args.push(arg);
|
|
101
|
+
return this;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Runs the script, replying what it returns. */
|
|
105
|
+
invoke(): ReplyPromise {
|
|
106
|
+
return new ReplyPromise(this.run());
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
private async run(): Promise<Reply> {
|
|
110
|
+
try {
|
|
111
|
+
if (this.readOnly && !this.script.isReadOnly) {
|
|
112
|
+
throw new Error(
|
|
113
|
+
'redis: a handle that can only read runs only scripts declared with Script.readOnly',
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
const reply = await this.t.run(
|
|
117
|
+
this.script.command(true, this.keys, this.args),
|
|
118
|
+
);
|
|
119
|
+
// The server has not seen the script: send it, which also caches it.
|
|
120
|
+
if (reply instanceof ServerError && reply.code === 'NOSCRIPT') {
|
|
121
|
+
return new Reply(
|
|
122
|
+
await this.t.run(this.script.command(false, this.keys, this.args)),
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
return new Reply(reply);
|
|
126
|
+
} catch (err) {
|
|
127
|
+
return Reply.failed(err);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** A call to a {@link Script} being queued on a pipeline or a transaction. */
|
|
133
|
+
export class QueuedInvocation {
|
|
134
|
+
private readonly keys: string[] = [];
|
|
135
|
+
private readonly args: RedisArg[] = [];
|
|
136
|
+
|
|
137
|
+
/** @internal */
|
|
138
|
+
constructor(
|
|
139
|
+
private readonly queued: Cmd[],
|
|
140
|
+
private readonly script: Script,
|
|
141
|
+
) {}
|
|
142
|
+
|
|
143
|
+
/** A key the script works on: the next of its `KEYS`. */
|
|
144
|
+
key(key: string): this {
|
|
145
|
+
this.keys.push(key);
|
|
146
|
+
return this;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** An argument: the next of the script's `ARGV`. */
|
|
150
|
+
arg(arg: RedisArg): this {
|
|
151
|
+
this.args.push(arg);
|
|
152
|
+
return this;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Queues the call. It is sent by source rather than by hash: a batch cannot
|
|
157
|
+
* stop halfway to send a script the server turns out not to have.
|
|
158
|
+
*/
|
|
159
|
+
queue(): void {
|
|
160
|
+
this.queued.push(this.script.command(false, this.keys, this.args));
|
|
161
|
+
}
|
|
162
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import {activeCtxBytes} from '../../internal/otel/index';
|
|
2
|
+
import type * as runtime from '../../internal/runtime/mod';
|
|
3
|
+
import {openDatabase} from './native';
|
|
4
|
+
import {
|
|
5
|
+
Cmd,
|
|
6
|
+
decodeReply,
|
|
7
|
+
encodeBatch,
|
|
8
|
+
encodeCommand,
|
|
9
|
+
stripReplyKeys,
|
|
10
|
+
type Value,
|
|
11
|
+
} from './wire';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Where a command runs: on a connection from the database's pool, or on one
|
|
15
|
+
* taken out of it.
|
|
16
|
+
*
|
|
17
|
+
* @internal
|
|
18
|
+
*/
|
|
19
|
+
export interface Target {
|
|
20
|
+
/**
|
|
21
|
+
* Runs `cmd`, resolving to its reply: the error the server rejected it
|
|
22
|
+
* with, if it did. Rejects if it could not be sent.
|
|
23
|
+
*/
|
|
24
|
+
run(cmd: Cmd): Promise<Value>;
|
|
25
|
+
/**
|
|
26
|
+
* Runs `cmds` in one round trip — as a transaction, if `atomic` — resolving
|
|
27
|
+
* to each one's reply. A command the server rejects fails alone. `null` for
|
|
28
|
+
* a transaction that did not run because a watched key changed.
|
|
29
|
+
*/
|
|
30
|
+
runAll(cmds: readonly Cmd[], atomic: boolean): Promise<Value[] | null>;
|
|
31
|
+
/** The prefix every key of the database is stored under. */
|
|
32
|
+
prefix(): string | undefined;
|
|
33
|
+
/** The database's native handle. */
|
|
34
|
+
database(): runtime.RedisDatabase;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The replies of a batch, one per command.
|
|
39
|
+
*/
|
|
40
|
+
function replies(
|
|
41
|
+
out: Buffer,
|
|
42
|
+
cmds: readonly Cmd[],
|
|
43
|
+
prefix: () => string | undefined,
|
|
44
|
+
): Value[] {
|
|
45
|
+
const v = decodeReply(out);
|
|
46
|
+
if (!Array.isArray(v) || v.length !== cmds.length) {
|
|
47
|
+
// The batch as a whole was rejected, as a transaction is for a command
|
|
48
|
+
// that could not be queued.
|
|
49
|
+
if (v instanceof Error) throw v;
|
|
50
|
+
throw new Error(
|
|
51
|
+
`redis: ${cmds.length} commands got a reply of another shape`,
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
cmds.forEach((cmd, i) => {
|
|
55
|
+
if (cmd.replyKeys) stripReplyKeys(v[i], prefix());
|
|
56
|
+
});
|
|
57
|
+
return v;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A database's pool, its native handle made on first use. */
|
|
61
|
+
export class PoolTarget implements Target {
|
|
62
|
+
private impl?: runtime.RedisDatabase;
|
|
63
|
+
/** `null` once known to have none. */
|
|
64
|
+
private keyPrefix?: string | null;
|
|
65
|
+
|
|
66
|
+
constructor(readonly name: string) {}
|
|
67
|
+
|
|
68
|
+
database(): runtime.RedisDatabase {
|
|
69
|
+
return (this.impl ??= openDatabase(this.name));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
prefix(): string | undefined {
|
|
73
|
+
if (this.keyPrefix === undefined) {
|
|
74
|
+
this.keyPrefix = this.database().keyPrefix() ?? null;
|
|
75
|
+
}
|
|
76
|
+
return this.keyPrefix ?? undefined;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async run(cmd: Cmd): Promise<Value> {
|
|
80
|
+
const out = await this.database().execute(
|
|
81
|
+
encodeCommand(cmd),
|
|
82
|
+
activeCtxBytes(),
|
|
83
|
+
);
|
|
84
|
+
const v = decodeReply(out);
|
|
85
|
+
if (cmd.replyKeys) stripReplyKeys(v, this.prefix());
|
|
86
|
+
return v;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async runAll(cmds: readonly Cmd[], atomic: boolean): Promise<Value[]> {
|
|
90
|
+
if (cmds.length === 0) return [];
|
|
91
|
+
const out = await this.database().executeEach(
|
|
92
|
+
encodeBatch(cmds),
|
|
93
|
+
atomic,
|
|
94
|
+
activeCtxBytes(),
|
|
95
|
+
);
|
|
96
|
+
return replies(out, cmds, () => this.prefix());
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** A connection taken out of a database's pool. */
|
|
101
|
+
export class ConnTarget implements Target {
|
|
102
|
+
constructor(
|
|
103
|
+
readonly conn: runtime.RedisConnection,
|
|
104
|
+
private readonly pool: PoolTarget,
|
|
105
|
+
) {}
|
|
106
|
+
|
|
107
|
+
database(): runtime.RedisDatabase {
|
|
108
|
+
return this.pool.database();
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
prefix(): string | undefined {
|
|
112
|
+
return this.pool.prefix();
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async run(cmd: Cmd): Promise<Value> {
|
|
116
|
+
const out = await this.conn.execute(encodeCommand(cmd), activeCtxBytes());
|
|
117
|
+
const v = decodeReply(out);
|
|
118
|
+
if (cmd.replyKeys) stripReplyKeys(v, this.prefix());
|
|
119
|
+
return v;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async runAll(cmds: readonly Cmd[], atomic: boolean): Promise<Value[] | null> {
|
|
123
|
+
const out = await this.conn.executeEach(
|
|
124
|
+
encodeBatch(cmds),
|
|
125
|
+
atomic,
|
|
126
|
+
activeCtxBytes(),
|
|
127
|
+
);
|
|
128
|
+
if (out === null) return null;
|
|
129
|
+
return replies(out, cmds, () => this.prefix());
|
|
130
|
+
}
|
|
131
|
+
}
|