@encore.dev/sdk 0.0.0 → 2.0.0-beta.5

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.
Files changed (250) hide show
  1. package/LICENSE +362 -0
  2. package/README.md +122 -2
  3. package/app_meta.test.ts +134 -0
  4. package/app_meta.ts +186 -0
  5. package/config/config.test.ts +381 -0
  6. package/config/config.ts +178 -0
  7. package/config/mod.ts +14 -0
  8. package/config/secrets.ts +147 -0
  9. package/config/value.ts +243 -0
  10. package/cron/mod.ts +23 -0
  11. package/dist/app_meta.d.ts +93 -0
  12. package/dist/app_meta.js +65 -0
  13. package/dist/app_meta.js.map +1 -0
  14. package/dist/config/config.d.ts +105 -0
  15. package/dist/config/config.js +87 -0
  16. package/dist/config/config.js.map +1 -0
  17. package/dist/config/mod.d.ts +4 -0
  18. package/dist/config/mod.js +3 -0
  19. package/dist/config/mod.js.map +1 -0
  20. package/dist/config/secrets.d.ts +92 -0
  21. package/dist/config/secrets.js +80 -0
  22. package/dist/config/secrets.js.map +1 -0
  23. package/dist/config/value.d.ts +51 -0
  24. package/dist/config/value.js +178 -0
  25. package/dist/config/value.js.map +1 -0
  26. package/dist/cron/mod.d.ts +22 -0
  27. package/dist/cron/mod.js +9 -0
  28. package/dist/cron/mod.js.map +1 -0
  29. package/dist/internal/otel/backend.d.ts +50 -0
  30. package/dist/internal/otel/backend.js +2 -0
  31. package/dist/internal/otel/backend.js.map +1 -0
  32. package/dist/internal/otel/context.d.ts +10 -0
  33. package/dist/internal/otel/context.js +34 -0
  34. package/dist/internal/otel/context.js.map +1 -0
  35. package/dist/internal/otel/context_manager.d.ts +22 -0
  36. package/dist/internal/otel/context_manager.js +120 -0
  37. package/dist/internal/otel/context_manager.js.map +1 -0
  38. package/dist/internal/otel/encode.d.ts +112 -0
  39. package/dist/internal/otel/encode.js +290 -0
  40. package/dist/internal/otel/encode.js.map +1 -0
  41. package/dist/internal/otel/index.d.ts +9 -0
  42. package/dist/internal/otel/index.js +9 -0
  43. package/dist/internal/otel/index.js.map +1 -0
  44. package/dist/internal/otel/meter.d.ts +73 -0
  45. package/dist/internal/otel/meter.js +265 -0
  46. package/dist/internal/otel/meter.js.map +1 -0
  47. package/dist/internal/otel/propagator.d.ts +14 -0
  48. package/dist/internal/otel/propagator.js +61 -0
  49. package/dist/internal/otel/propagator.js.map +1 -0
  50. package/dist/internal/otel/provider.d.ts +9 -0
  51. package/dist/internal/otel/provider.js +19 -0
  52. package/dist/internal/otel/provider.js.map +1 -0
  53. package/dist/internal/otel/request_context.d.ts +11 -0
  54. package/dist/internal/otel/request_context.js +20 -0
  55. package/dist/internal/otel/request_context.js.map +1 -0
  56. package/dist/internal/otel/span.d.ts +61 -0
  57. package/dist/internal/otel/span.js +206 -0
  58. package/dist/internal/otel/span.js.map +1 -0
  59. package/dist/internal/otel/tracer.d.ts +15 -0
  60. package/dist/internal/otel/tracer.js +65 -0
  61. package/dist/internal/otel/tracer.js.map +1 -0
  62. package/dist/internal/reqtrack/mod.d.ts +6 -0
  63. package/dist/internal/reqtrack/mod.js +28 -0
  64. package/dist/internal/reqtrack/mod.js.map +1 -0
  65. package/dist/internal/runtime/meter.d.ts +11 -0
  66. package/dist/internal/runtime/meter.js +22 -0
  67. package/dist/internal/runtime/meter.js.map +1 -0
  68. package/dist/internal/runtime/mod.d.ts +12 -0
  69. package/dist/internal/runtime/mod.js +28 -0
  70. package/dist/internal/runtime/mod.js.map +1 -0
  71. package/dist/internal/runtime/napi/napi.cjs +122 -0
  72. package/dist/internal/runtime/napi/napi.d.cts +601 -0
  73. package/dist/internal/runtime/shutdown.d.ts +13 -0
  74. package/dist/internal/runtime/shutdown.js +56 -0
  75. package/dist/internal/runtime/shutdown.js.map +1 -0
  76. package/dist/internal/utils/constraints.d.ts +9 -0
  77. package/dist/internal/utils/constraints.js +2 -0
  78. package/dist/internal/utils/constraints.js.map +1 -0
  79. package/dist/log/index.d.ts +39 -0
  80. package/dist/log/index.js +44 -0
  81. package/dist/log/index.js.map +1 -0
  82. package/dist/log/logger.d.ts +123 -0
  83. package/dist/log/logger.js +203 -0
  84. package/dist/log/logger.js.map +1 -0
  85. package/dist/log/runtime.d.ts +19 -0
  86. package/dist/log/runtime.js +22 -0
  87. package/dist/log/runtime.js.map +1 -0
  88. package/dist/log/stderr.d.ts +9 -0
  89. package/dist/log/stderr.js +25 -0
  90. package/dist/log/stderr.js.map +1 -0
  91. package/dist/metrics/mod.d.ts +315 -0
  92. package/dist/metrics/mod.js +488 -0
  93. package/dist/metrics/mod.js.map +1 -0
  94. package/dist/mod.d.ts +6 -0
  95. package/dist/mod.js +4 -0
  96. package/dist/mod.js.map +1 -0
  97. package/dist/otel.d.ts +9 -0
  98. package/dist/otel.js +13 -0
  99. package/dist/otel.js.map +1 -0
  100. package/dist/pubsub/encoding.d.ts +3 -0
  101. package/dist/pubsub/encoding.js +10 -0
  102. package/dist/pubsub/encoding.js.map +1 -0
  103. package/dist/pubsub/mod.d.ts +6 -0
  104. package/dist/pubsub/mod.js +3 -0
  105. package/dist/pubsub/mod.js.map +1 -0
  106. package/dist/pubsub/refs.d.ts +12 -0
  107. package/dist/pubsub/refs.js +11 -0
  108. package/dist/pubsub/refs.js.map +1 -0
  109. package/dist/pubsub/subscription.d.ts +128 -0
  110. package/dist/pubsub/subscription.js +39 -0
  111. package/dist/pubsub/subscription.js.map +1 -0
  112. package/dist/pubsub/topic.d.ts +148 -0
  113. package/dist/pubsub/topic.js +164 -0
  114. package/dist/pubsub/topic.js.map +1 -0
  115. package/dist/req_meta.d.ts +47 -0
  116. package/dist/req_meta.js +26 -0
  117. package/dist/req_meta.js.map +1 -0
  118. package/dist/services/index.d.ts +12 -0
  119. package/dist/services/index.js +22 -0
  120. package/dist/services/index.js.map +1 -0
  121. package/dist/shutdown/mod.d.ts +23 -0
  122. package/dist/shutdown/mod.js +24 -0
  123. package/dist/shutdown/mod.js.map +1 -0
  124. package/dist/storage/objects/bucket.d.ts +216 -0
  125. package/dist/storage/objects/bucket.js +123 -0
  126. package/dist/storage/objects/bucket.js.map +1 -0
  127. package/dist/storage/objects/error.d.ts +14 -0
  128. package/dist/storage/objects/error.js +81 -0
  129. package/dist/storage/objects/error.js.map +1 -0
  130. package/dist/storage/objects/mod.d.ts +4 -0
  131. package/dist/storage/objects/mod.js +3 -0
  132. package/dist/storage/objects/mod.js.map +1 -0
  133. package/dist/storage/objects/refs.d.ts +31 -0
  134. package/dist/storage/objects/refs.js +20 -0
  135. package/dist/storage/objects/refs.js.map +1 -0
  136. package/dist/storage/postgres/database.d.ts +295 -0
  137. package/dist/storage/postgres/database.js +378 -0
  138. package/dist/storage/postgres/database.js.map +1 -0
  139. package/dist/storage/postgres/mod.d.ts +2 -0
  140. package/dist/storage/postgres/mod.js +2 -0
  141. package/dist/storage/postgres/mod.js.map +1 -0
  142. package/dist/storage/redis/commands.d.ts +573 -0
  143. package/dist/storage/redis/commands.js +637 -0
  144. package/dist/storage/redis/commands.js.map +1 -0
  145. package/dist/storage/redis/database.d.ts +302 -0
  146. package/dist/storage/redis/database.js +336 -0
  147. package/dist/storage/redis/database.js.map +1 -0
  148. package/dist/storage/redis/mod.d.ts +88 -0
  149. package/dist/storage/redis/mod.js +84 -0
  150. package/dist/storage/redis/mod.js.map +1 -0
  151. package/dist/storage/redis/native.d.ts +8 -0
  152. package/dist/storage/redis/native.js +11 -0
  153. package/dist/storage/redis/native.js.map +1 -0
  154. package/dist/storage/redis/options.d.ts +89 -0
  155. package/dist/storage/redis/options.js +53 -0
  156. package/dist/storage/redis/options.js.map +1 -0
  157. package/dist/storage/redis/pubsub.d.ts +53 -0
  158. package/dist/storage/redis/pubsub.js +88 -0
  159. package/dist/storage/redis/pubsub.js.map +1 -0
  160. package/dist/storage/redis/reply.d.ts +256 -0
  161. package/dist/storage/redis/reply.js +572 -0
  162. package/dist/storage/redis/reply.js.map +1 -0
  163. package/dist/storage/redis/scan.d.ts +11 -0
  164. package/dist/storage/redis/scan.js +76 -0
  165. package/dist/storage/redis/scan.js.map +1 -0
  166. package/dist/storage/redis/script.d.ts +91 -0
  167. package/dist/storage/redis/script.js +143 -0
  168. package/dist/storage/redis/script.js.map +1 -0
  169. package/dist/storage/redis/target.d.ts +47 -0
  170. package/dist/storage/redis/target.js +82 -0
  171. package/dist/storage/redis/target.js.map +1 -0
  172. package/dist/storage/redis/wire.d.ts +105 -0
  173. package/dist/storage/redis/wire.js +333 -0
  174. package/dist/storage/redis/wire.js.map +1 -0
  175. package/dist/tsconfig.build.tsbuildinfo +1 -0
  176. package/dist/types/mod.d.ts +42 -0
  177. package/dist/types/mod.js +65 -0
  178. package/dist/types/mod.js.map +1 -0
  179. package/internal/otel/backend.ts +60 -0
  180. package/internal/otel/context.test.ts +70 -0
  181. package/internal/otel/context.ts +48 -0
  182. package/internal/otel/context_manager.test.ts +154 -0
  183. package/internal/otel/context_manager.ts +141 -0
  184. package/internal/otel/encode.test.ts +266 -0
  185. package/internal/otel/encode.ts +408 -0
  186. package/internal/otel/index.ts +20 -0
  187. package/internal/otel/meter.test.ts +231 -0
  188. package/internal/otel/meter.ts +332 -0
  189. package/internal/otel/propagator.test.ts +105 -0
  190. package/internal/otel/propagator.ts +68 -0
  191. package/internal/otel/provider.ts +23 -0
  192. package/internal/otel/request_context.ts +32 -0
  193. package/internal/otel/span.ts +252 -0
  194. package/internal/otel/tracer.test.ts +352 -0
  195. package/internal/otel/tracer.ts +104 -0
  196. package/internal/reqtrack/mod.ts +39 -0
  197. package/internal/runtime/meter.ts +26 -0
  198. package/internal/runtime/mod.ts +41 -0
  199. package/internal/runtime/napi/napi.cjs +122 -0
  200. package/internal/runtime/napi/napi.d.cts +601 -0
  201. package/internal/runtime/shutdown.test.ts +248 -0
  202. package/internal/runtime/shutdown.ts +64 -0
  203. package/internal/utils/constraints.ts +12 -0
  204. package/log/index.ts +107 -0
  205. package/log/logger.test.ts +194 -0
  206. package/log/logger.ts +308 -0
  207. package/log/runtime.test.ts +65 -0
  208. package/log/runtime.ts +40 -0
  209. package/log/stderr.test.ts +23 -0
  210. package/log/stderr.ts +24 -0
  211. package/metrics/export.test.ts +337 -0
  212. package/metrics/mod.test.ts +180 -0
  213. package/metrics/mod.ts +619 -0
  214. package/mod.ts +22 -0
  215. package/otel.test.ts +84 -0
  216. package/otel.ts +17 -0
  217. package/package.json +121 -5
  218. package/pubsub/encoding.ts +8 -0
  219. package/pubsub/mod.ts +14 -0
  220. package/pubsub/pubsub.test.ts +186 -0
  221. package/pubsub/refs.ts +22 -0
  222. package/pubsub/subscription.ts +180 -0
  223. package/pubsub/topic.test.ts +121 -0
  224. package/pubsub/topic.ts +212 -0
  225. package/req_meta.ts +75 -0
  226. package/services/index.test.ts +30 -0
  227. package/services/index.ts +21 -0
  228. package/shutdown/mod.ts +24 -0
  229. package/storage/objects/bucket.ts +338 -0
  230. package/storage/objects/error.ts +94 -0
  231. package/storage/objects/mod.ts +35 -0
  232. package/storage/objects/refs.ts +69 -0
  233. package/storage/postgres/database.integration.test.ts +175 -0
  234. package/storage/postgres/database.test.ts +241 -0
  235. package/storage/postgres/database.ts +497 -0
  236. package/storage/postgres/mod.ts +15 -0
  237. package/storage/redis/commands.ts +1221 -0
  238. package/storage/redis/database.ts +466 -0
  239. package/storage/redis/mod.ts +135 -0
  240. package/storage/redis/native.ts +11 -0
  241. package/storage/redis/options.ts +119 -0
  242. package/storage/redis/pubsub.ts +92 -0
  243. package/storage/redis/redis.test.ts +706 -0
  244. package/storage/redis/reply.ts +705 -0
  245. package/storage/redis/runtime.test.ts +233 -0
  246. package/storage/redis/scan.ts +125 -0
  247. package/storage/redis/script.ts +162 -0
  248. package/storage/redis/target.ts +131 -0
  249. package/storage/redis/wire.ts +369 -0
  250. package/types/mod.ts +92 -0
@@ -0,0 +1,466 @@
1
+ import {activeCtxBytes} from '../../internal/otel/index';
2
+ import type * as runtime from '../../internal/runtime/mod';
3
+ import {StringLiteral} from '../../internal/utils/constraints';
4
+ import {
5
+ commandGroups,
6
+ queueGroups,
7
+ readCommandGroups,
8
+ type CommandGroups,
9
+ type QueueGroups,
10
+ type ReadCommandGroups,
11
+ } from './commands';
12
+ import {BatchError, Reply} from './reply';
13
+ import {Invocation, QueuedInvocation, Script} from './script';
14
+ import {ConnTarget, PoolTarget, type Target} from './target';
15
+ import {encodeList, type Cmd, type Value} from './wire';
16
+
17
+ /** What a database evicts when it runs out of memory. */
18
+ export type EvictionPolicy =
19
+ /** Evict nothing: a write that needs memory fails. */
20
+ | 'noeviction'
21
+ /** The least recently used key, of all keys. */
22
+ | 'allkeys-lru'
23
+ /** The least frequently used key, of all keys. */
24
+ | 'allkeys-lfu'
25
+ /** A random key, of all keys. */
26
+ | 'allkeys-random'
27
+ /** The least recently used key, of those with an expiry. */
28
+ | 'volatile-lru'
29
+ /** The least frequently used key, of those with an expiry. */
30
+ | 'volatile-lfu'
31
+ /** The key closest to expiring. */
32
+ | 'volatile-ttl'
33
+ /** A random key, of those with an expiry. */
34
+ | 'volatile-random';
35
+
36
+ /**
37
+ * A database's configuration. Encore reads it from the declaration, so its
38
+ * fields must be literals.
39
+ */
40
+ export interface DatabaseConfig {
41
+ /**
42
+ * The data must survive a restart, and is never evicted. Without it a
43
+ * database is a cache: what it holds may be lost or evicted.
44
+ */
45
+ persistent?: boolean;
46
+
47
+ /**
48
+ * What to evict when the database runs out of memory: the least recently
49
+ * used key, unless said otherwise. A persistent database evicts nothing and
50
+ * takes no policy.
51
+ */
52
+ evictionPolicy?: EvictionPolicy;
53
+ }
54
+
55
+ /** The replies of a batch, or the error some of its commands failed with. */
56
+ function batchReplies(values: Value[]): Reply[] {
57
+ const replies = values.map(v => new Reply(v));
58
+ const failed = replies.find(r => r.error);
59
+ if (failed) throw new BatchError(replies, failed.error!);
60
+ return replies;
61
+ }
62
+
63
+ /**
64
+ * A handle to a {@link Database} that can only read, made by
65
+ * {@link Database.read} or {@link Database.readPrimary}. Free to pass to other
66
+ * code.
67
+ *
68
+ * Its command groups hold the commands that read, and nothing else.
69
+ */
70
+ // The command groups are assigned in the constructor; this declares them.
71
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
72
+ export interface ReadOnlyDatabaseRef extends ReadCommandGroups {}
73
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
74
+ export class ReadOnlyDatabaseRef {
75
+ /** @internal */
76
+ constructor(
77
+ private readonly t: PoolTarget,
78
+ groups: ReadCommandGroups,
79
+ /**
80
+ * The runtime gives a database one pool for now, on the primary, which
81
+ * every handle shares.
82
+ */
83
+ readonly primary: boolean,
84
+ ) {
85
+ Object.assign(this, groups);
86
+ }
87
+
88
+ /** A call to `script`, which must be one made by {@link Script.readOnly}. */
89
+ script(script: Script): Invocation {
90
+ return new Invocation(this.t, script, true);
91
+ }
92
+ }
93
+
94
+ /**
95
+ * A handle to a {@link Database} that can read and write, made by
96
+ * {@link Database.write}. Free to pass to other code.
97
+ */
98
+ // The command groups are assigned in the constructor; this declares them.
99
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
100
+ export interface DatabaseRef extends CommandGroups {}
101
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
102
+ export class DatabaseRef {
103
+ /** @internal */
104
+ constructor(
105
+ /** @internal */
106
+ protected readonly t: PoolTarget,
107
+ /** @internal */
108
+ protected readonly groups: CommandGroups,
109
+ ) {
110
+ Object.assign(this, groups);
111
+ }
112
+
113
+ /**
114
+ * A batch of commands sent in one round trip. Not a transaction: other
115
+ * clients' commands may run between them, and one failing does not stop
116
+ * the rest.
117
+ *
118
+ * ```ts
119
+ * const pipe = SESSIONS.pipeline();
120
+ * pipe.string.get("name:1");
121
+ * pipe.string.get("name:2");
122
+ * const [first, second] = await pipe.exec();
123
+ * ```
124
+ */
125
+ pipeline(): Pipeline {
126
+ return new Pipeline(this.t);
127
+ }
128
+
129
+ /**
130
+ * A transaction (`MULTI`/`EXEC`): the commands queued on it run together,
131
+ * with no other client's in between.
132
+ *
133
+ * Nothing is sent until {@link Transaction.exec}, so a transaction is never
134
+ * left open while the code waits on something else.
135
+ *
136
+ * ```ts
137
+ * const tx = LEDGER.transaction();
138
+ * tx.string.incr("hits", 1);
139
+ * tx.hash.hset("user:1", "seen", Date.now());
140
+ * const [hits] = await tx.exec();
141
+ * ```
142
+ */
143
+ transaction(): Transaction {
144
+ return new Transaction(this.t);
145
+ }
146
+
147
+ /**
148
+ * Takes a connection out of the pool, for what must run on one connection:
149
+ * watching keys, then a transaction that depends on them. Return it with
150
+ * {@link Connection.close}, or declare it with `await using`.
151
+ */
152
+ async acquire(): Promise<Connection> {
153
+ const impl = await this.t.database().acquire(activeCtxBytes());
154
+ return new Connection(impl, this.t);
155
+ }
156
+
157
+ /**
158
+ * Runs `body` as an optimistic transaction on `keys`: `body` reads what it
159
+ * needs through the connection and queues its changes on the transaction,
160
+ * and the changes are applied only if none of `keys` changed in between. If
161
+ * one did, `body` runs again.
162
+ *
163
+ * ```ts
164
+ * const left = await LEDGER.watch(["balance"], async (conn, tx) => {
165
+ * const balance = (await conn.string.get("balance").number()) ?? 0;
166
+ * tx.string.set("balance", balance - 10);
167
+ * return balance - 10;
168
+ * });
169
+ * ```
170
+ */
171
+ async watch<T>(
172
+ keys: string[],
173
+ body: (conn: Connection, tx: WatchedTransaction) => Promise<T>,
174
+ ): Promise<T> {
175
+ // A key changing this many times in a row is not contention that another
176
+ // attempt will get past.
177
+ const attempts = 64;
178
+
179
+ const conn = await this.acquire();
180
+ try {
181
+ for (let i = 0; i < attempts; i++) {
182
+ await conn.watch(...keys);
183
+ const tx = conn.transaction();
184
+ const out = await body(conn, tx);
185
+ if ((await tx.exec()) !== null) return out;
186
+ }
187
+ throw new Error(
188
+ `redis: the watched keys kept changing: gave up after ${attempts} attempts`,
189
+ );
190
+ } finally {
191
+ await conn.close();
192
+ }
193
+ }
194
+
195
+ /** A call to `script`, to give its keys and arguments and then invoke. */
196
+ script(script: Script): Invocation {
197
+ return new Invocation(this.t, script, false);
198
+ }
199
+
200
+ /**
201
+ * The connection string to connect to this database with, for a client
202
+ * other than this SDK.
203
+ *
204
+ * It connects past the database's key prefix: what that client stores under
205
+ * a name is not what this SDK reads under it.
206
+ */
207
+ get connectionString(): string {
208
+ return this.t.database().connectionUrl();
209
+ }
210
+ }
211
+
212
+ /**
213
+ * A Redis database, backed by a connection pool built on first use.
214
+ *
215
+ * Declare it at module scope; its commands are in its command groups:
216
+ *
217
+ * ```ts
218
+ * import { Database } from "@encore.dev/sdk/storage/redis";
219
+ *
220
+ * const SESSIONS = new Database("sessions");
221
+ *
222
+ * await SESSIONS.string.incr("visits:1", 1);
223
+ * const name = await SESSIONS.string.get("name:1").text();
224
+ * ```
225
+ */
226
+ export class Database extends DatabaseRef {
227
+ private readGroups?: ReadCommandGroups;
228
+
229
+ /**
230
+ * Declares a Redis database.
231
+ *
232
+ * Encore reads the name and the configuration from the declaration, so both
233
+ * must be literals, and the database must be declared at module scope.
234
+ *
235
+ * The name must be unique within the Encore application, and be kebab-case.
236
+ * Once deployed, never change it: a new database would be created under the
237
+ * new name.
238
+ */
239
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
240
+ constructor(name: string, cfg?: DatabaseConfig) {
241
+ const t = new PoolTarget(name);
242
+ super(t, commandGroups(t));
243
+ }
244
+
245
+ /**
246
+ * References an existing database by name. To declare a new database, use
247
+ * `new Database(...)` instead.
248
+ *
249
+ * The name must be a string literal, so Encore can resolve it statically. A
250
+ * named database takes no configuration: it is configured where it is
251
+ * declared.
252
+ */
253
+ static named<Name extends string>(name: StringLiteral<Name>): Database {
254
+ return new Database(name);
255
+ }
256
+
257
+ /** A handle to the database that can read and write. */
258
+ write(): DatabaseRef {
259
+ return new DatabaseRef(this.t, this.groups);
260
+ }
261
+
262
+ /**
263
+ * A handle to the database that can only read, which may connect to a read
264
+ * replica. To always read from the primary server, use
265
+ * {@link Database.readPrimary}.
266
+ */
267
+ read(): ReadOnlyDatabaseRef {
268
+ return new ReadOnlyDatabaseRef(this.t, this.readOnlyGroups(), false);
269
+ }
270
+
271
+ /**
272
+ * A handle to the database that can only read, and connects to the primary
273
+ * server even if there are read replicas available.
274
+ */
275
+ readPrimary(): ReadOnlyDatabaseRef {
276
+ return new ReadOnlyDatabaseRef(this.t, this.readOnlyGroups(), true);
277
+ }
278
+
279
+ private readOnlyGroups(): ReadCommandGroups {
280
+ return (this.readGroups ??= readCommandGroups(this.t));
281
+ }
282
+ }
283
+
284
+ /**
285
+ * A batch of commands sent in one round trip, made by
286
+ * {@link DatabaseRef.pipeline}. Not a transaction. Its commands are queued
287
+ * through its command groups: `pipe.string.get(...)`.
288
+ */
289
+ // The command groups are assigned in the constructor; this declares them.
290
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
291
+ export interface Pipeline extends QueueGroups {}
292
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
293
+ export class Pipeline {
294
+ private readonly queued: Cmd[] = [];
295
+
296
+ /** @internal */
297
+ constructor(private readonly t: Target) {
298
+ Object.assign(this, queueGroups(this.queued));
299
+ }
300
+
301
+ /** How many commands are queued. */
302
+ get length(): number {
303
+ return this.queued.length;
304
+ }
305
+
306
+ /** Queues a call to `script`. Finish it with {@link QueuedInvocation.queue}. */
307
+ script(script: Script): QueuedInvocation {
308
+ return new QueuedInvocation(this.queued, script);
309
+ }
310
+
311
+ /**
312
+ * Sends the queued commands and returns their replies, in order. If the
313
+ * server rejected any, fails with a {@link BatchError} holding them all.
314
+ * The pipeline is empty afterwards.
315
+ */
316
+ async exec(): Promise<Reply[]> {
317
+ const values = await this.t.runAll(this.queued.splice(0), false);
318
+ return batchReplies(values ?? []);
319
+ }
320
+ }
321
+
322
+ /**
323
+ * A transaction, made by {@link DatabaseRef.transaction}: the commands queued
324
+ * on it, through its command groups, run together, with no other client's in
325
+ * between.
326
+ */
327
+ // The command groups are assigned in the constructor; this declares them.
328
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
329
+ export interface Transaction extends QueueGroups {}
330
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
331
+ export class Transaction {
332
+ private readonly queued: Cmd[] = [];
333
+
334
+ /** @internal */
335
+ constructor(private readonly t: Target) {
336
+ Object.assign(this, queueGroups(this.queued));
337
+ }
338
+
339
+ /** How many commands are queued. */
340
+ get length(): number {
341
+ return this.queued.length;
342
+ }
343
+
344
+ /** Queues a call to `script`. Finish it with {@link QueuedInvocation.queue}. */
345
+ script(script: Script): QueuedInvocation {
346
+ return new QueuedInvocation(this.queued, script);
347
+ }
348
+
349
+ /**
350
+ * Runs the queued commands as one transaction and returns their replies, as
351
+ * {@link Pipeline.exec} does. A command the server rejects when it runs does
352
+ * not stop the others: Redis has no rollback.
353
+ */
354
+ async exec(): Promise<Reply[]> {
355
+ const values = await this.t.runAll(this.queued.splice(0), true);
356
+ return batchReplies(values ?? []);
357
+ }
358
+
359
+ /**
360
+ * Abandons the transaction. Nothing was sent, so there is nothing to undo:
361
+ * this empties the queue.
362
+ */
363
+ discard(): void {
364
+ this.queued.splice(0);
365
+ }
366
+ }
367
+
368
+ /**
369
+ * A transaction on a {@link Connection}, made by {@link Connection.transaction}:
370
+ * it does nothing if a key the connection watches has changed.
371
+ */
372
+ // The command groups are assigned in the constructor; this declares them.
373
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
374
+ export interface WatchedTransaction extends QueueGroups {}
375
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
376
+ export class WatchedTransaction {
377
+ private readonly queued: Cmd[] = [];
378
+
379
+ /** @internal */
380
+ constructor(private readonly t: ConnTarget) {
381
+ Object.assign(this, queueGroups(this.queued));
382
+ }
383
+
384
+ /** How many commands are queued. */
385
+ get length(): number {
386
+ return this.queued.length;
387
+ }
388
+
389
+ /** Queues a call to `script`. Finish it with {@link QueuedInvocation.queue}. */
390
+ script(script: Script): QueuedInvocation {
391
+ return new QueuedInvocation(this.queued, script);
392
+ }
393
+
394
+ /**
395
+ * Runs the queued commands as one transaction and returns their replies, as
396
+ * {@link Transaction.exec} does, or `null` if a watched key changed, in
397
+ * which case none of them ran. Either way the connection watches nothing
398
+ * afterwards.
399
+ */
400
+ async exec(): Promise<Reply[] | null> {
401
+ const values = await this.t.runAll(this.queued.splice(0), true);
402
+ return values === null ? null : batchReplies(values);
403
+ }
404
+ }
405
+
406
+ /**
407
+ * A connection taken out of a database's pool, made by
408
+ * {@link DatabaseRef.acquire}. Its commands, in its command groups, run one at
409
+ * a time. Return it to the pool with {@link Connection.close}.
410
+ */
411
+ // The command groups are assigned in the constructor; this declares them.
412
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
413
+ export interface Connection extends CommandGroups {}
414
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
415
+ export class Connection implements AsyncDisposable {
416
+ private readonly t: ConnTarget;
417
+
418
+ /** @internal */
419
+ constructor(
420
+ private readonly impl: runtime.RedisConnection,
421
+ pool: PoolTarget,
422
+ ) {
423
+ this.t = new ConnTarget(impl, pool);
424
+ Object.assign(this, commandGroups(this.t));
425
+ }
426
+
427
+ /**
428
+ * Watches `keys`: a {@link Connection.transaction} then does nothing if any
429
+ * of them has changed by the time it is run.
430
+ */
431
+ async watch(...keys: string[]): Promise<void> {
432
+ await this.impl.watch(encodeList(keys), activeCtxBytes());
433
+ }
434
+
435
+ /** Stops watching every key. */
436
+ async unwatch(): Promise<void> {
437
+ await this.impl.unwatch(activeCtxBytes());
438
+ }
439
+
440
+ /** A transaction on this connection, which depends on the keys it watches. */
441
+ transaction(): WatchedTransaction {
442
+ return new WatchedTransaction(this.t);
443
+ }
444
+
445
+ /** A batch of commands sent in one round trip on this connection. */
446
+ pipeline(): Pipeline {
447
+ return new Pipeline(this.t);
448
+ }
449
+
450
+ /** A call to `script` on this connection. */
451
+ script(script: Script): Invocation {
452
+ return new Invocation(this.t, script, false);
453
+ }
454
+
455
+ /**
456
+ * Returns the connection to its pool. Keys it still watches are unwatched
457
+ * first.
458
+ */
459
+ async close(): Promise<void> {
460
+ await this.impl.release();
461
+ }
462
+
463
+ async [Symbol.asyncDispose](): Promise<void> {
464
+ await this.close();
465
+ }
466
+ }
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Redis databases. A database is declared at module scope; its connection pool
3
+ * is built on first use and reused thereafter.
4
+ *
5
+ * ```ts
6
+ * import { Database } from "@encore.dev/sdk/storage/redis";
7
+ *
8
+ * const SESSIONS = new Database("sessions");
9
+ *
10
+ * export async function touch(user: string): Promise<string | null> {
11
+ * await SESSIONS.string.incr(`visits:${user}`, 1);
12
+ * return SESSIONS.string.get(`name:${user}`).text();
13
+ * }
14
+ * ```
15
+ *
16
+ * A database is a resource of its own: there is no cluster to put it in, and
17
+ * no keyspaces to declare in it. Its keys are whatever the code passes.
18
+ *
19
+ * ## Commands
20
+ *
21
+ * Commands are grouped by the data type they work on, each group a property of
22
+ * the database: `string`, `hash`, `list`, `set`, `sortedSet`, `stream`, `geo`,
23
+ * `bitmap`, `pubsub`, and `generic` for the ones that work on any key. Within a
24
+ * group a command is named after the Redis command it runs — `get`, `hset`,
25
+ * `zadd`, `xadd` — with words of its own for its variants: `setEx`,
26
+ * `zrangeWithscores`.
27
+ *
28
+ * A command whose reply has one shape returns it: `strlen` a number,
29
+ * `sismember` a boolean. One whose reply is the caller's to read returns a
30
+ * {@link ReplyPromise}, read as what it holds:
31
+ *
32
+ * ```ts
33
+ * const name = await SESSIONS.string.get("name:1").text();
34
+ * const visits = await SESSIONS.string.get("visits:1").number();
35
+ * const fields = await SESSIONS.hash.hgetall("user:1").textMap();
36
+ * ```
37
+ *
38
+ * A missing key reads as `null`.
39
+ *
40
+ * A command is called in the same expression that names its group. That is
41
+ * what lets Encore grant each service exactly the access it uses: the command
42
+ * is visible at the call, so Encore's parser can read it. A group that is
43
+ * stored or passed on instead says nothing about what it will be used for, and
44
+ * is reported as an error — to do that, start from a handle.
45
+ *
46
+ * ## Handles
47
+ *
48
+ * A database cannot be passed around as a value. To hand it to other code,
49
+ * make a handle with the access that code needs — {@link Database.write},
50
+ * {@link Database.read} or {@link Database.readPrimary} — which the service is
51
+ * then granted in full:
52
+ *
53
+ * ```ts
54
+ * // Library code takes a handle, and can only do what the handle allows.
55
+ * function nameOf(db: ReadOnlyDatabaseRef, user: string) {
56
+ * return db.string.get(`name:${user}`).text();
57
+ * }
58
+ *
59
+ * export function greet(user: string) {
60
+ * return nameOf(SESSIONS.read(), user);
61
+ * }
62
+ * ```
63
+ *
64
+ * ## Keys
65
+ *
66
+ * Every key is stored under a prefix of the database's own, which is what
67
+ * keeps databases sharing a server apart. It is applied to every key a command
68
+ * takes and removed from every key a command returns, so code never sees it.
69
+ * Two things follow:
70
+ *
71
+ * - a {@link Script}'s `KEYS` are prefixed, but nothing else in it is: a key
72
+ * it names in its source or its `ARGV` is reached unprefixed, outside the
73
+ * database's isolation, so a script must take its keys through `KEYS`;
74
+ * - {@link DatabaseRef.connectionString} connects past the prefix, so a client
75
+ * using it does not see the keys this SDK writes under the same names.
76
+ *
77
+ * @module
78
+ */
79
+
80
+ export {
81
+ Database,
82
+ DatabaseRef,
83
+ ReadOnlyDatabaseRef,
84
+ Pipeline,
85
+ Transaction,
86
+ WatchedTransaction,
87
+ Connection,
88
+ } from './database';
89
+ export type {DatabaseConfig, EvictionPolicy} from './database';
90
+ export type {
91
+ BitmapCommands,
92
+ CommandGroups,
93
+ Commands,
94
+ GenericCommands,
95
+ GeoCommands,
96
+ HashCommands,
97
+ ListCommands,
98
+ PubsubCommands,
99
+ Queue,
100
+ QueueGroups,
101
+ ReadCommandGroups,
102
+ ReadCommands,
103
+ ScoreBound,
104
+ SetCommands,
105
+ SortedSetCommands,
106
+ StreamCommands,
107
+ StringCommands,
108
+ } from './commands';
109
+ export type {
110
+ Direction,
111
+ Expiry,
112
+ RadiusOptions,
113
+ ScanOptions,
114
+ SetExpiry,
115
+ SetOptions,
116
+ StreamMaxlen,
117
+ Unit,
118
+ } from './options';
119
+ export {BatchError, Reply, ReplyPromise} from './reply';
120
+ export type {
121
+ FieldValue,
122
+ GeoPosition,
123
+ GeoRadiusResult,
124
+ RedisValue,
125
+ ScoredMember,
126
+ Stream,
127
+ StreamAutoClaim,
128
+ StreamEntry,
129
+ StreamInfo,
130
+ StreamPending,
131
+ } from './reply';
132
+ export {Script, Invocation, QueuedInvocation} from './script';
133
+ export {Message, Subscription} from './pubsub';
134
+ export {ServerError} from './wire';
135
+ export type {Pairs, RedisArg} from './wire';
@@ -0,0 +1,11 @@
1
+ import * as runtime from '../../internal/runtime/mod';
2
+
3
+ /**
4
+ * The native handle of the database `name`: where the SDK meets the runtime,
5
+ * and what its tests stand in for.
6
+ *
7
+ * @internal
8
+ */
9
+ export function openDatabase(name: string): runtime.RedisDatabase {
10
+ return runtime.RT.redisDatabase(name);
11
+ }