@tinyshed/tinystore 0.1.0-rc.5 → 0.1.0-rc.7
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/README.md +37 -37
- package/bin/tinystore.js +12 -1
- package/dist/backup.d.ts +33 -0
- package/dist/backup.js +49 -0
- package/dist/blobs.d.ts +160 -79
- package/dist/blobs.js +510 -217
- package/dist/channels.d.ts +90 -0
- package/dist/channels.js +291 -0
- package/dist/clock.js +3 -3
- package/dist/config.d.ts +209 -86
- package/dist/config.js +581 -538
- package/dist/connection.d.ts +64 -2
- package/dist/connection.js +201 -16
- package/dist/console.d.ts +27 -3
- package/dist/console.js +165 -12
- package/dist/dotenv.d.ts +7 -0
- package/dist/dotenv.js +79 -0
- package/dist/errors.d.ts +61 -1
- package/dist/errors.js +81 -1
- package/dist/handles.d.ts +44 -2
- package/dist/handles.js +81 -2
- package/dist/index.d.ts +17 -11
- package/dist/index.js +5 -3
- package/dist/instruments.d.ts +177 -0
- package/dist/instruments.js +819 -0
- package/dist/jobs.d.ts +335 -239
- package/dist/jobs.js +716 -536
- package/dist/json.d.ts +2 -0
- package/dist/json.js +122 -0
- package/dist/kv.d.ts +130 -243
- package/dist/kv.js +273 -640
- package/dist/limits.d.ts +80 -0
- package/dist/limits.js +139 -0
- package/dist/locks.d.ts +62 -0
- package/dist/locks.js +237 -0
- package/dist/logger.d.ts +45 -9
- package/dist/logger.js +150 -38
- package/dist/metrics.d.ts +210 -209
- package/dist/metrics.js +319 -556
- package/dist/once.d.ts +19 -18
- package/dist/once.js +74 -63
- package/dist/query.d.ts +181 -0
- package/dist/query.js +788 -0
- package/dist/records.d.ts +241 -150
- package/dist/records.js +507 -291
- package/dist/runtime/addon.d.ts +14 -0
- package/dist/runtime/addon.js +69 -0
- package/dist/runtime/bun.js +5 -7
- package/dist/runtime/node.js +5 -7
- package/dist/runtime/pipe.d.ts +17 -0
- package/dist/runtime/pipe.js +133 -0
- package/dist/runtime/shared.d.ts +6 -0
- package/dist/runtime/shared.js +19 -0
- package/dist/runtime.d.ts +5 -2
- package/dist/search.d.ts +189 -0
- package/dist/search.js +281 -0
- package/dist/session.d.ts +31 -3
- package/dist/session.js +153 -41
- package/dist/sql.d.ts +228 -78
- package/dist/sql.js +745 -240
- package/dist/store.d.ts +244 -24
- package/dist/store.js +270 -67
- package/dist/time.d.ts +5 -1
- package/dist/time.js +22 -2
- package/dist/tx.d.ts +61 -0
- package/dist/tx.js +314 -0
- package/dist/wire/codec.d.ts +23 -7
- package/dist/wire/codec.js +56 -35
- package/dist/wire/frame.d.ts +2 -0
- package/dist/wire/frame.js +31 -14
- package/dist/wire/messages.d.ts +259 -0
- package/dist/wire/messages.js +22 -0
- package/dist/wire/msgpack.d.ts +49 -1
- package/dist/wire/msgpack.js +293 -56
- package/dist/wire/protocol.d.ts +2683 -0
- package/dist/wire/protocol.js +10846 -0
- package/package.json +39 -38
- package/src/backup.ts +81 -0
- package/src/blobs.ts +678 -301
- package/src/channels.ts +377 -0
- package/src/clock.ts +4 -4
- package/src/config.ts +902 -612
- package/src/connection.ts +279 -21
- package/src/console.ts +180 -12
- package/src/dotenv.ts +82 -0
- package/src/errors.ts +105 -0
- package/src/handles.ts +157 -8
- package/src/index.ts +158 -52
- package/src/instruments.ts +1042 -0
- package/src/jobs.ts +1017 -733
- package/src/json.ts +133 -0
- package/src/kv.ts +424 -847
- package/src/limits.ts +202 -0
- package/src/locks.ts +320 -0
- package/src/logger.ts +209 -40
- package/src/metrics.ts +557 -752
- package/src/once.ts +86 -83
- package/src/query.ts +1005 -0
- package/src/records.ts +795 -418
- package/src/runtime/addon.ts +99 -0
- package/src/runtime/bun.ts +5 -7
- package/src/runtime/node.ts +5 -7
- package/src/runtime/pipe.ts +178 -0
- package/src/runtime/shared.ts +20 -0
- package/src/runtime.ts +5 -2
- package/src/search.ts +480 -0
- package/src/session.ts +187 -41
- package/src/sql.ts +993 -306
- package/src/store.ts +473 -78
- package/src/time.ts +48 -3
- package/src/tx.ts +426 -0
- package/src/wire/codec.ts +78 -37
- package/src/wire/frame.ts +44 -14
- package/src/wire/messages.ts +25 -0
- package/src/wire/msgpack.ts +327 -56
- package/src/wire/protocol.ts +11709 -0
- package/dist/limiter.d.ts +0 -45
- package/dist/limiter.js +0 -68
- package/dist/quota.d.ts +0 -44
- package/dist/quota.js +0 -98
- package/src/limiter.ts +0 -99
- package/src/quota.ts +0 -137
package/dist/store.js
CHANGED
|
@@ -1,39 +1,224 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { backup } from './backup.js';
|
|
2
|
+
import { openFiles } from './blobs.js';
|
|
3
|
+
import { Channel } from './channels.js';
|
|
4
4
|
import { Clock } from './clock.js';
|
|
5
|
-
import {
|
|
5
|
+
import { Config } from './config.js';
|
|
6
|
+
import { asking, checkDurability, embedded, Link, privateChild, remote, sidecar, } from './connection.js';
|
|
6
7
|
import { ClosedError, InvalidError } from './errors.js';
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
8
|
+
import { Instruments } from './instruments.js';
|
|
9
|
+
import { openQueue, openSchedule, } from './jobs.js';
|
|
10
|
+
import { Bucket, bucketOpen, Counters, countersOpen, valuesOf, } from './kv.js';
|
|
11
|
+
import { Quota, quotaOpen, RateLimit, rateLimitOpen, } from './limits.js';
|
|
12
|
+
import { Lock, Semaphore } from './locks.js';
|
|
13
|
+
import { sayOwn } from './logger.js';
|
|
9
14
|
import { Metrics } from './metrics.js';
|
|
10
|
-
import {
|
|
15
|
+
import { Once, onceOpen } from './once.js';
|
|
16
|
+
import { AllEvents, openEvents, storeLogger, } from './records.js';
|
|
11
17
|
import { bunRuntime } from './runtime/bun.js';
|
|
12
18
|
import { nodeRuntime } from './runtime/node.js';
|
|
19
|
+
import { platformPackage } from './runtime/shared.js';
|
|
20
|
+
import { dropIndex, indexOpen, listIndexes, SearchIndex, } from './search.js';
|
|
13
21
|
import { openDatabase } from './sql.js';
|
|
14
22
|
import { ms, unixMs } from './time.js';
|
|
15
|
-
import {
|
|
23
|
+
import { runTx } from './tx.js';
|
|
16
24
|
/**
|
|
17
25
|
* The store in a directory, as another process serves it. Close it once, as
|
|
18
26
|
* a Go program closes its tinystore.Store: `await using store = await open(dir)`.
|
|
19
27
|
*/
|
|
20
28
|
export class Store {
|
|
21
|
-
kv;
|
|
22
|
-
jobs;
|
|
23
|
-
blobs;
|
|
24
|
-
records;
|
|
25
29
|
metrics;
|
|
26
30
|
/** The test's clock of a private store opened with `clock`; on any other, its calls are InvalidError. */
|
|
27
31
|
clock;
|
|
28
32
|
#link;
|
|
33
|
+
/** the configs open, by what opened them, so that the same open shares one stream */
|
|
34
|
+
#configs = new Map();
|
|
35
|
+
#workers = new Set();
|
|
36
|
+
#loggers = new Set();
|
|
37
|
+
#instruments;
|
|
38
|
+
#closing = false;
|
|
29
39
|
constructor(link) {
|
|
30
40
|
this.#link = link;
|
|
31
41
|
this.clock = new Clock(link);
|
|
32
|
-
this
|
|
33
|
-
this.
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
42
|
+
this.#instruments = new Instruments(link);
|
|
43
|
+
this.metrics = new Metrics(link, this.#instruments);
|
|
44
|
+
}
|
|
45
|
+
events(stream, options) {
|
|
46
|
+
return stream === undefined
|
|
47
|
+
? new AllEvents(this.#link)
|
|
48
|
+
: openEvents(this.#link, stream, options);
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* A logger of the stream: each line printed as it is logged and kept
|
|
52
|
+
* within a second, and a call never waits; what its buffer has no room
|
|
53
|
+
* for is dropped and counted. The store's close hands over what it holds.
|
|
54
|
+
* Its options are the config `log`'s, whose level a change of any process
|
|
55
|
+
* sets for every logger of the store once each has its config open:
|
|
56
|
+
*
|
|
57
|
+
* const log = store.logger('api', { redact: secrets })
|
|
58
|
+
* log.info('signed in', { user: 42 })
|
|
59
|
+
* const settings = await store.config('log', [{ level: live('info') }])
|
|
60
|
+
* await settings.update({ level: 'debug' })
|
|
61
|
+
*/
|
|
62
|
+
logger(stream, options) {
|
|
63
|
+
const [logger, log] = storeLogger(this.#link, stream, options);
|
|
64
|
+
this.#loggers.add(logger);
|
|
65
|
+
this.config('log', log.layers).then(config => void config.watch(value => log.take(value.level)), (err) => {
|
|
66
|
+
if (!this.#closing) {
|
|
67
|
+
saidUnfollowed(err);
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
return logger;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* A bucket of values by key, JSON unless `type` says otherwise:
|
|
74
|
+
*
|
|
75
|
+
* const sessions = store.bucket<Session>('sessions', { idle: '30d' })
|
|
76
|
+
* const codes = store.bucket<number>('login-codes', { ttl: '15m', type: 'int' })
|
|
77
|
+
* const seen = store.bucket('stripe-events', { ttl: '7d' }) // keys alone: a set
|
|
78
|
+
*/
|
|
79
|
+
bucket(name, options) {
|
|
80
|
+
const values = valuesOf(options?.type);
|
|
81
|
+
return new Bucket(this.#link, name, bucketOpen(name, options), values, []);
|
|
82
|
+
}
|
|
83
|
+
/** Numbers by key that only add up: `store.counters('login-attempts', { ttl: '15m' })`. */
|
|
84
|
+
counters(name, options) {
|
|
85
|
+
return new Counters(this.#link, name, countersOpen(name, options), []);
|
|
86
|
+
}
|
|
87
|
+
/** A smooth rate of requests a key: `store.rateLimit('api', { rate: '100/s', burst: 20 })`. */
|
|
88
|
+
rateLimit(name, options) {
|
|
89
|
+
return new RateLimit(this.#link, name, rateLimitOpen(name, options), []);
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Uses by key in named windows, each counted from a key's first use, all
|
|
93
|
+
* of them or none: `store.quota('ai', { daily: '100/1d', weekly: '300/7d' })`.
|
|
94
|
+
*/
|
|
95
|
+
quota(name, windows) {
|
|
96
|
+
return new Quota(this.#link, name, quotaOpen(name, windows), []);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Documents of one type set by id and found again by their words, by
|
|
100
|
+
* vectors the program's model gives them, or by both:
|
|
101
|
+
*
|
|
102
|
+
* const articles = store.index<Article>('articles', { fields: { title: 2, body: 1 } })
|
|
103
|
+
* const { hits } = await articles.search('как испечь хлеб')
|
|
104
|
+
*
|
|
105
|
+
* Opening an index with other settings than it holds changes it, and
|
|
106
|
+
* never waits for the work a change needs.
|
|
107
|
+
*/
|
|
108
|
+
index(name, options) {
|
|
109
|
+
return new SearchIndex(this.#link, name, indexOpen(name, options));
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Opens an index as `index` does and reads it again beside itself in the
|
|
113
|
+
* background: a change `rebuild: 'manual'` left waiting, or its documents
|
|
114
|
+
* numbered again. It answers once the rebuild began; `ready()` waits for it.
|
|
115
|
+
*/
|
|
116
|
+
async reindex(name, options) {
|
|
117
|
+
const index = new SearchIndex(this.#link, name, indexOpen(name, options, true));
|
|
118
|
+
await index.status();
|
|
119
|
+
return index;
|
|
120
|
+
}
|
|
121
|
+
/** Drops an index and every document it holds, in the background; says whether there was one. */
|
|
122
|
+
dropIndex(name) {
|
|
123
|
+
return dropIndex(this.#link, name);
|
|
124
|
+
}
|
|
125
|
+
/** Every index the store holds: its documents and vectors, when it was last opened, and a rebuild under way. */
|
|
126
|
+
indexes() {
|
|
127
|
+
return listIndexes(this.#link);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Messages of one type that every subscriber listening when one is
|
|
131
|
+
* published receives, in memory and at most once:
|
|
132
|
+
* `const chat = store.channel<Chat>('chat'); await chat.under(roomId).publish(message)`.
|
|
133
|
+
*/
|
|
134
|
+
channel(name) {
|
|
135
|
+
return new Channel(this.#link, name);
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Keys held one holder at a time, across every program of the store:
|
|
139
|
+
* `await store.lock('invoices').hold(invoice.id, lease => charge(invoice, lease.fence))`.
|
|
140
|
+
*/
|
|
141
|
+
lock(name, options) {
|
|
142
|
+
return new Lock(this.#link, name, options);
|
|
143
|
+
}
|
|
144
|
+
/** Keys held by up to `limit` at a time: `store.semaphore('uploads', { limit: 3 })`. */
|
|
145
|
+
semaphore(name, options) {
|
|
146
|
+
return new Semaphore(this.#link, name, options);
|
|
147
|
+
}
|
|
148
|
+
/** A function run once a key, its JSON answer kept a day unless `keep` says: `store.once<Receipt>('charges')`. */
|
|
149
|
+
once(name, options) {
|
|
150
|
+
return new Once(this.#link, name, onceOpen(name, options), []);
|
|
151
|
+
}
|
|
152
|
+
queue(name, options = {}) {
|
|
153
|
+
return openQueue(this.#link, this.#workers, name, options);
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* A repeat the code owns: one repeating job under name, and handler run at
|
|
157
|
+
* each of its times, started at once as a queue's work is. The code's
|
|
158
|
+
* repeat replaces the one kept each time the program opens it.
|
|
159
|
+
*
|
|
160
|
+
* store.schedule('cleanup', { cron: '10 3 * * *', timeZone: 'Europe/Berlin' }, async run => {
|
|
161
|
+
* await purgeDeletedBefore(daysBefore(run.at, 30))
|
|
162
|
+
* })
|
|
163
|
+
*/
|
|
164
|
+
schedule(name, when, handler, options) {
|
|
165
|
+
return openSchedule(this.#link, this.#workers, name, when, handler, options);
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Runs fn as one transaction over the handles it takes in with
|
|
169
|
+
* `tx.with(handle)`, and gives back what fn returns. Reads go at once;
|
|
170
|
+
* writes commit together when fn returns, after a check that nothing it
|
|
171
|
+
* read has changed, and fn runs again when something did, five times at
|
|
172
|
+
* most, so it does nothing else that must happen once.
|
|
173
|
+
*
|
|
174
|
+
* await store.tx(async tx => {
|
|
175
|
+
* const left = (await tx.with(stock).get(sku)) ?? 0
|
|
176
|
+
* if (left < 1) throw new SoldOut()
|
|
177
|
+
* await tx.with(stock).set(sku, left - 1)
|
|
178
|
+
* })
|
|
179
|
+
*/
|
|
180
|
+
tx(fn) {
|
|
181
|
+
return runTx(this.#link, fn);
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* A program's settings as one typed value: the declaration first, every
|
|
185
|
+
* setting with its default, then objects, files and the environment, each
|
|
186
|
+
* over the ones before it, and a live setting's change over them all.
|
|
187
|
+
*
|
|
188
|
+
* const config = await store.config('app', [
|
|
189
|
+
* { port: 8080, db: { url: secret(String) }, limits: { rps: live(100) } },
|
|
190
|
+
* file('app.yaml'),
|
|
191
|
+
* env('APP', { vars: { port: 'PORT' } }),
|
|
192
|
+
* ])
|
|
193
|
+
*
|
|
194
|
+
* It follows every change, whoever makes it, until the store closes; the
|
|
195
|
+
* same config opened again in the process shares its one stream.
|
|
196
|
+
*/
|
|
197
|
+
async config(name, layers, options = {}) {
|
|
198
|
+
const key = JSON.stringify([name, layers, options.strict === true]);
|
|
199
|
+
const found = this.#configs.get(key);
|
|
200
|
+
if (found !== undefined && found.validate === options.validate) {
|
|
201
|
+
return found.config;
|
|
202
|
+
}
|
|
203
|
+
const config = Config.open(this.#link, name, layers, options);
|
|
204
|
+
this.#configs.set(key, { config, validate: options.validate });
|
|
205
|
+
config.catch(() => this.#configs.delete(key));
|
|
206
|
+
return config;
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* A backup of every engine of the store as one zip, made while the store
|
|
210
|
+
* keeps working, written beside `path` and renamed once whole, so that a
|
|
211
|
+
* backup that fails leaves no zip. A file of the program's goes in only
|
|
212
|
+
* when `include` names it, and the store's encryption key only when
|
|
213
|
+
* `includeEncryptionKey` asks; `tinystore restore` puts it back into an empty
|
|
214
|
+
* directory, every byte checked. Through a server, it takes an admin's
|
|
215
|
+
* token.
|
|
216
|
+
*
|
|
217
|
+
* const backup = await store.backup('backup-2026-10-13.zip', { include: ['secret.key'] })
|
|
218
|
+
* if (backup.keyLeftOut) console.warn('keep encryption.key apart: the backup opens with it alone')
|
|
219
|
+
*/
|
|
220
|
+
backup(path, options = {}) {
|
|
221
|
+
return backup(this.#link, path, options);
|
|
37
222
|
}
|
|
38
223
|
/**
|
|
39
224
|
* What the server this store reaches is: its version, the protocol the
|
|
@@ -51,67 +236,54 @@ export class Store {
|
|
|
51
236
|
};
|
|
52
237
|
}
|
|
53
238
|
/**
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
* nothing.
|
|
239
|
+
* A named set of files by path, written whole and replaced whole:
|
|
240
|
+
*
|
|
241
|
+
* const avatars = store.files('avatars')
|
|
242
|
+
* const reports = store.files('reports', { ttl: '24h', maxFileSize: '2GiB' })
|
|
59
243
|
*/
|
|
60
|
-
|
|
61
|
-
return
|
|
244
|
+
files(name, options) {
|
|
245
|
+
return openFiles(this.#link, name, options);
|
|
62
246
|
}
|
|
63
247
|
/**
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
*
|
|
248
|
+
* The application's database name, sql/<name>.db, once its migrations
|
|
249
|
+
* are applied and checked: a migration that fails, or one changed after
|
|
250
|
+
* it was applied, is told here, at the start. Without migrations the file
|
|
251
|
+
* opens as it is, an empty one when there is none.
|
|
252
|
+
*
|
|
253
|
+
* const db = await store.database('app', { migrations: `${import.meta.dir}/migrations` })
|
|
69
254
|
*/
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
try {
|
|
73
|
-
await this.#link.run('read', async (connection) => {
|
|
74
|
-
const file = await openFile(part, 'w');
|
|
75
|
-
try {
|
|
76
|
-
const stream = await connection.session.open(methods['server.backup'], Empty.encode({}), true);
|
|
77
|
-
await stream.next(); // the RESPONSE that heads the zip
|
|
78
|
-
for (;;) {
|
|
79
|
-
const event = await stream.next();
|
|
80
|
-
stream.consumed(event.body.length);
|
|
81
|
-
await file.write(event.body);
|
|
82
|
-
if (event.end) {
|
|
83
|
-
break;
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
await file.sync();
|
|
87
|
-
}
|
|
88
|
-
finally {
|
|
89
|
-
await file.close();
|
|
90
|
-
}
|
|
91
|
-
});
|
|
92
|
-
await rename(part, path);
|
|
93
|
-
}
|
|
94
|
-
catch (err) {
|
|
95
|
-
await rm(part, { force: true });
|
|
96
|
-
throw err;
|
|
97
|
-
}
|
|
255
|
+
database(name, options) {
|
|
256
|
+
return openDatabase(this.#link, this.#workers, name, options);
|
|
98
257
|
}
|
|
99
258
|
/**
|
|
100
|
-
*
|
|
101
|
-
*
|
|
259
|
+
* Stops every worker, each once its handlers under way have answered,
|
|
260
|
+
* ingests the instruments' last values, hands over the loggers' lines and
|
|
261
|
+
* cancels every config's stream, then closes the connection. A private child is waited for until it has
|
|
102
262
|
* exited, so that the directory is free once this returns; the directory's
|
|
103
263
|
* sidecar goes once it has been idle.
|
|
104
264
|
*/
|
|
105
265
|
async close() {
|
|
106
|
-
|
|
107
|
-
await this.
|
|
108
|
-
this.
|
|
266
|
+
this.#closing = true;
|
|
267
|
+
await Promise.all([...this.#workers].map(worker => worker.stop()));
|
|
268
|
+
await this.#instruments.stop();
|
|
269
|
+
await Promise.all([...this.#loggers].map(logger => logger.stop()));
|
|
270
|
+
await Promise.all([...this.#configs.values()].map(({ config }) => config.then(opened => opened.stop(), () => { })));
|
|
109
271
|
await this.#link.close();
|
|
110
272
|
}
|
|
111
273
|
[Symbol.asyncDispose]() {
|
|
112
274
|
return this.close();
|
|
113
275
|
}
|
|
114
276
|
}
|
|
277
|
+
let unfollowed = false;
|
|
278
|
+
/** Says once in a process that a store's logger follows no config `log`, its level then the code's and the environment's. */
|
|
279
|
+
function saidUnfollowed(err) {
|
|
280
|
+
if (!unfollowed) {
|
|
281
|
+
unfollowed = true;
|
|
282
|
+
sayOwn('warn', 'a logger follows no config log', {
|
|
283
|
+
error: err instanceof Error ? err.message : String(err),
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
}
|
|
115
287
|
/** Bun's own runtime under Bun, and Node's under Node. */
|
|
116
288
|
const runtime = typeof Bun === 'undefined' ? nodeRuntime : bunRuntime;
|
|
117
289
|
/**
|
|
@@ -130,9 +302,20 @@ export async function openWith(runtime, dir, options = {}) {
|
|
|
130
302
|
throw new InvalidError("a clock is a private server's: a shared sidecar runs on the system's time");
|
|
131
303
|
}
|
|
132
304
|
const clock = options.clock === undefined ? undefined : new Date(unixMs(options.clock));
|
|
133
|
-
const
|
|
134
|
-
|
|
135
|
-
|
|
305
|
+
const durability = options.durability;
|
|
306
|
+
checkDurability(durability, 'open');
|
|
307
|
+
const started = {
|
|
308
|
+
durability,
|
|
309
|
+
encryptionKeyFile: options.encryptionKeyFile,
|
|
310
|
+
node: options.node,
|
|
311
|
+
selfMetrics: options.selfMetrics,
|
|
312
|
+
};
|
|
313
|
+
const dial = options.embedded === true
|
|
314
|
+
? embedded(runtime, dir, () => findLibrary(runtime, options.library), started)
|
|
315
|
+
: options.private === true
|
|
316
|
+
? privateChild(runtime, dir, binary, clock, started)
|
|
317
|
+
: sidecar(runtime, dir, binary, { idle, ...started });
|
|
318
|
+
const link = new Link(asking(dial, dir, durability));
|
|
136
319
|
await link.connection();
|
|
137
320
|
return new Store(link);
|
|
138
321
|
}
|
|
@@ -166,10 +349,30 @@ function checkDirectory(dir) {
|
|
|
166
349
|
}
|
|
167
350
|
}
|
|
168
351
|
function findBinary(runtime, given) {
|
|
169
|
-
const
|
|
352
|
+
const executable = runtime.windows ? 'tinystore.exe' : 'tinystore';
|
|
353
|
+
const found = given ??
|
|
354
|
+
process.env.TINYSTORE_BIN ??
|
|
355
|
+
runtime.packaged(`bin/${executable}`) ??
|
|
356
|
+
runtime.which('tinystore');
|
|
170
357
|
if (found === undefined || found === '') {
|
|
171
|
-
throw new ClosedError(`no tinystore binary:
|
|
358
|
+
throw new ClosedError(`no tinystore binary: ${platformPackage()} is not installed; ` +
|
|
172
359
|
'install it, put tinystore on PATH, or set TINYSTORE_BIN');
|
|
173
360
|
}
|
|
174
361
|
return found;
|
|
175
362
|
}
|
|
363
|
+
/**
|
|
364
|
+
* The core an embedded store loads: under Bun the C library, under Node its
|
|
365
|
+
* addon; the one given, the variable's, or this platform's package's.
|
|
366
|
+
*/
|
|
367
|
+
function findLibrary(runtime, library) {
|
|
368
|
+
const node = typeof Bun === 'undefined';
|
|
369
|
+
const variable = node ? 'TINYSTORE_ADDON' : 'TINYSTORE_LIBRARY';
|
|
370
|
+
const file = node
|
|
371
|
+
? 'tinystore.node'
|
|
372
|
+
: ({ win32: 'tinystore_ffi.dll', darwin: 'libtinystore_ffi.dylib' }[process.platform] ?? 'libtinystore_ffi.so');
|
|
373
|
+
const found = library ?? process.env[variable] ?? runtime.packaged(`lib/${file}`);
|
|
374
|
+
if (found === undefined || found === '') {
|
|
375
|
+
throw new InvalidError(`an embedded store needs the core: ${platformPackage()} is not installed; pass library or set ${variable}`);
|
|
376
|
+
}
|
|
377
|
+
return found;
|
|
378
|
+
}
|
package/dist/time.d.ts
CHANGED
|
@@ -12,13 +12,15 @@ type Spelled<U extends readonly string[]> = U extends readonly [
|
|
|
12
12
|
infer First extends string,
|
|
13
13
|
...infer Rest extends string[]
|
|
14
14
|
] ? `${number}${First}${Spelled<Rest> | ''}` | Spelled<Rest> : never;
|
|
15
|
+
/** The spans a program names most, which an editor offers as their text is typed. */
|
|
16
|
+
type Offered = '1s' | '5s' | '10s' | '15s' | '30s' | '1m' | '5m' | '10m' | '15m' | '30m' | '1h' | '6h' | '12h' | '24h' | '1d' | '7d' | '30d' | '90d';
|
|
15
17
|
/**
|
|
16
18
|
* A duration's text, '30d', '1h30m', '15m', '1s' or '250ms', which the type
|
|
17
19
|
* checks as it is written, so that '1hr' or '90mins' does not compile. Text
|
|
18
20
|
* from elsewhere, an environment's, is cast as Duration and checked when the
|
|
19
21
|
* call runs.
|
|
20
22
|
*/
|
|
21
|
-
export type DurationText = Spelled<Units
|
|
23
|
+
export type DurationText = Offered | (Spelled<Units> & Record<never, never>);
|
|
22
24
|
/** A length of time: milliseconds, or the text of one, such as '1h30m'. */
|
|
23
25
|
export type Duration = number | DurationText;
|
|
24
26
|
/** A moment: a Date, or unix milliseconds. */
|
|
@@ -28,6 +30,8 @@ export type Time = Date | number;
|
|
|
28
30
|
* 90m30m. It takes any text, since text cast as a Duration reaches it too.
|
|
29
31
|
*/
|
|
30
32
|
export declare function ms(d: Duration | string): number;
|
|
33
|
+
/** Milliseconds as a duration is written, largest units first: 5_400_000 is 1h30m, 0 is 0s. */
|
|
34
|
+
export declare function spelled(milliseconds: number): DurationText;
|
|
31
35
|
/** A moment's unix milliseconds. */
|
|
32
36
|
export declare function unixMs(t: Time): number;
|
|
33
37
|
/** A moment the server named in unix milliseconds, none for 0 or absent. */
|
package/dist/time.js
CHANGED
|
@@ -23,12 +23,32 @@ export function ms(d) {
|
|
|
23
23
|
throw new InvalidError(`the duration ${JSON.stringify(d)}; write it as 30d, 1h30m, 15m, 1s or 250ms`);
|
|
24
24
|
}
|
|
25
25
|
const [, w, days, h, m, s, milli] = parts;
|
|
26
|
-
|
|
26
|
+
const total = Number(w ?? 0) * units.w +
|
|
27
27
|
Number(days ?? 0) * units.d +
|
|
28
28
|
Number(h ?? 0) * units.h +
|
|
29
29
|
Number(m ?? 0) * units.m +
|
|
30
30
|
Number(s ?? 0) * units.s +
|
|
31
|
-
Number(milli ?? 0)
|
|
31
|
+
Number(milli ?? 0);
|
|
32
|
+
if (!Number.isSafeInteger(total)) {
|
|
33
|
+
throw new InvalidError(`the duration ${JSON.stringify(d)} is past the milliseconds a number holds`);
|
|
34
|
+
}
|
|
35
|
+
return total;
|
|
36
|
+
}
|
|
37
|
+
/** Milliseconds as a duration is written, largest units first: 5_400_000 is 1h30m, 0 is 0s. */
|
|
38
|
+
export function spelled(milliseconds) {
|
|
39
|
+
if (milliseconds === 0) {
|
|
40
|
+
return '0s';
|
|
41
|
+
}
|
|
42
|
+
let left = milliseconds;
|
|
43
|
+
let text = '';
|
|
44
|
+
for (const unit of ['w', 'd', 'h', 'm', 's', 'ms']) {
|
|
45
|
+
const size = units[unit];
|
|
46
|
+
if (left >= size) {
|
|
47
|
+
text += `${Math.floor(left / size)}${unit}`;
|
|
48
|
+
left %= size;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return text;
|
|
32
52
|
}
|
|
33
53
|
/** A moment's unix milliseconds. */
|
|
34
54
|
export function unixMs(t) {
|
package/dist/tx.d.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { type Channel, type TxChannel } from './channels.ts';
|
|
2
|
+
import type { Link } from './connection.ts';
|
|
3
|
+
import { type Queue, StoreTxQueue } from './jobs.ts';
|
|
4
|
+
import { type Bucket, type Counters, type Entry, type Parts, type Values, type WriteOptions } from './kv.ts';
|
|
5
|
+
import { type Duration } from './time.ts';
|
|
6
|
+
import type { Key, Written } from './wire/codec.ts';
|
|
7
|
+
import { KvCall, KvEntry, type Method } from './wire/protocol.ts';
|
|
8
|
+
/** Whether the caller runs inside the function of a store's transaction. */
|
|
9
|
+
export declare function insideStoreTx(): boolean;
|
|
10
|
+
/**
|
|
11
|
+
* Runs fn as one transaction and gives back what it returns: its writes all
|
|
12
|
+
* commit or none do. When a key fn read changed before the commit, fn runs
|
|
13
|
+
* again, five times at most, so it does nothing else that must happen once.
|
|
14
|
+
*/
|
|
15
|
+
export declare function runTx<T>(link: Link, fn: (tx: Tx) => T | Promise<T>): Promise<T>;
|
|
16
|
+
type Found = ReturnType<typeof KvEntry.decode>;
|
|
17
|
+
type CallFields = Omit<Written<typeof KvCall.fields>, 'handle' | 'under'>;
|
|
18
|
+
/** The calls of a transaction, each through `tx.with(handle)`. */
|
|
19
|
+
export declare class Tx {
|
|
20
|
+
#private;
|
|
21
|
+
constructor(link: Link);
|
|
22
|
+
with<T>(bucket: Bucket<T>): TxBucket<T>;
|
|
23
|
+
with(counters: Counters): TxCounters;
|
|
24
|
+
with<T>(queue: Queue<T>): StoreTxQueue<T>;
|
|
25
|
+
with<T>(channel: Channel<T>): TxChannel<T>;
|
|
26
|
+
/** What the key holds as this transaction sees it: its own writes over what the store held. */
|
|
27
|
+
read(parts: Parts, key: Key): Promise<Found>;
|
|
28
|
+
/** Keeps a write for the commit; found is what a read of its key answers after it. */
|
|
29
|
+
write(method: Method, parts: Parts, fields: CallFields, found?: Found): void;
|
|
30
|
+
clear(parts: Parts): void;
|
|
31
|
+
/** Sends the writes in one kv.tx, after a check of each key read: still at its version, or still absent. */
|
|
32
|
+
/** Commits the writes, then hands over the messages published inside. */
|
|
33
|
+
commit(): Promise<void>;
|
|
34
|
+
}
|
|
35
|
+
/** A bucket's calls inside a transaction: reads answer at once, writes wait for its commit. */
|
|
36
|
+
export declare class TxBucket<T> {
|
|
37
|
+
#private;
|
|
38
|
+
constructor(tx: Tx, parts: Parts, values: Values<unknown>);
|
|
39
|
+
under(...owners: Key[]): TxBucket<T>;
|
|
40
|
+
get(key: Key): Promise<T | undefined>;
|
|
41
|
+
entry(key: Key): Promise<Entry<T> | undefined>;
|
|
42
|
+
has(key: Key): Promise<boolean>;
|
|
43
|
+
set(key: Key, value: T, options?: WriteOptions): Promise<void>;
|
|
44
|
+
/** Writes the value only where no live key is, and says whether it will. */
|
|
45
|
+
create(key: Key, value: T, options?: Omit<WriteOptions, 'ifVersion'>): Promise<boolean>;
|
|
46
|
+
add(key: Key, options?: Omit<WriteOptions, 'ifVersion'>): Promise<boolean>;
|
|
47
|
+
take(key: Key, options?: Pick<WriteOptions, 'ifVersion'>): Promise<T | undefined>;
|
|
48
|
+
delete(key: Key, options?: Pick<WriteOptions, 'ifVersion'>): Promise<boolean>;
|
|
49
|
+
expire(key: Key, when: Duration | Date, options?: Pick<WriteOptions, 'ifVersion'>): Promise<boolean>;
|
|
50
|
+
/** Removes this branch's keys and every branch's under it, with the commit. */
|
|
51
|
+
clear(): Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
/** Counters inside a transaction: an add commits with its writes. */
|
|
54
|
+
export declare class TxCounters {
|
|
55
|
+
#private;
|
|
56
|
+
constructor(tx: Tx, parts: Parts);
|
|
57
|
+
under(...owners: Key[]): TxCounters;
|
|
58
|
+
/** Adds n, 1 unless given, with the commit; the count is known once it has. */
|
|
59
|
+
add(key: Key, n?: number | bigint): Promise<void>;
|
|
60
|
+
}
|
|
61
|
+
export {};
|