@tinyshed/tinystore 0.1.0-rc.4 → 0.1.0-rc.6
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/src/time.ts
CHANGED
|
@@ -19,13 +19,36 @@ type Spelled<U extends readonly string[]> = U extends readonly [
|
|
|
19
19
|
? `${number}${First}${Spelled<Rest> | ''}` | Spelled<Rest>
|
|
20
20
|
: never
|
|
21
21
|
|
|
22
|
+
/** The spans a program names most, which an editor offers as their text is typed. */
|
|
23
|
+
type Offered =
|
|
24
|
+
| '1s'
|
|
25
|
+
| '5s'
|
|
26
|
+
| '10s'
|
|
27
|
+
| '15s'
|
|
28
|
+
| '30s'
|
|
29
|
+
| '1m'
|
|
30
|
+
| '5m'
|
|
31
|
+
| '10m'
|
|
32
|
+
| '15m'
|
|
33
|
+
| '30m'
|
|
34
|
+
| '1h'
|
|
35
|
+
| '6h'
|
|
36
|
+
| '12h'
|
|
37
|
+
| '24h'
|
|
38
|
+
| '1d'
|
|
39
|
+
| '7d'
|
|
40
|
+
| '30d'
|
|
41
|
+
| '90d'
|
|
42
|
+
|
|
22
43
|
/**
|
|
23
44
|
* A duration's text, '30d', '1h30m', '15m', '1s' or '250ms', which the type
|
|
24
45
|
* checks as it is written, so that '1hr' or '90mins' does not compile. Text
|
|
25
46
|
* from elsewhere, an environment's, is cast as Duration and checked when the
|
|
26
47
|
* call runs.
|
|
27
48
|
*/
|
|
28
|
-
|
|
49
|
+
// a literal beside a template that takes it in is folded into it and no longer
|
|
50
|
+
// offered; the intersection keeps them apart, where `& {}` of a union does not
|
|
51
|
+
export type DurationText = Offered | (Spelled<Units> & Record<never, never>)
|
|
29
52
|
|
|
30
53
|
/** A length of time: milliseconds, or the text of one, such as '1h30m'. */
|
|
31
54
|
export type Duration = number | DurationText
|
|
@@ -62,14 +85,36 @@ export function ms(d: Duration | string): number {
|
|
|
62
85
|
)
|
|
63
86
|
}
|
|
64
87
|
const [, w, days, h, m, s, milli] = parts
|
|
65
|
-
|
|
88
|
+
const total =
|
|
66
89
|
Number(w ?? 0) * units.w! +
|
|
67
90
|
Number(days ?? 0) * units.d! +
|
|
68
91
|
Number(h ?? 0) * units.h! +
|
|
69
92
|
Number(m ?? 0) * units.m! +
|
|
70
93
|
Number(s ?? 0) * units.s! +
|
|
71
94
|
Number(milli ?? 0)
|
|
72
|
-
)
|
|
95
|
+
if (!Number.isSafeInteger(total)) {
|
|
96
|
+
throw new InvalidError(
|
|
97
|
+
`the duration ${JSON.stringify(d)} is past the milliseconds a number holds`,
|
|
98
|
+
)
|
|
99
|
+
}
|
|
100
|
+
return total
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Milliseconds as a duration is written, largest units first: 5_400_000 is 1h30m, 0 is 0s. */
|
|
104
|
+
export function spelled(milliseconds: number): DurationText {
|
|
105
|
+
if (milliseconds === 0) {
|
|
106
|
+
return '0s'
|
|
107
|
+
}
|
|
108
|
+
let left = milliseconds
|
|
109
|
+
let text = ''
|
|
110
|
+
for (const unit of ['w', 'd', 'h', 'm', 's', 'ms']) {
|
|
111
|
+
const size = units[unit]!
|
|
112
|
+
if (left >= size) {
|
|
113
|
+
text += `${Math.floor(left / size)}${unit}`
|
|
114
|
+
left %= size
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return text as DurationText
|
|
73
118
|
}
|
|
74
119
|
|
|
75
120
|
/** A moment's unix milliseconds. */
|
package/src/tx.ts
ADDED
|
@@ -0,0 +1,426 @@
|
|
|
1
|
+
// A transaction across the wire, which never holds the writer while the host
|
|
2
|
+
// awaits: a read goes at once and is kept with what it found; a write waits,
|
|
3
|
+
// and when the function returns the writes commit in one kv.tx, after a check
|
|
4
|
+
// that every key it read is still as it read it. A check that fails runs the
|
|
5
|
+
// function again.
|
|
6
|
+
|
|
7
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
8
|
+
|
|
9
|
+
import { type Channel, channelParts, type TxChannel, txChannel } from './channels.ts'
|
|
10
|
+
import type { Link } from './connection.ts'
|
|
11
|
+
import { ConflictError, InvalidError } from './errors.ts'
|
|
12
|
+
import { handleOn } from './handles.ts'
|
|
13
|
+
import { commitJobs, type JobOp, type Queue, queueParts, StoreTxQueue } from './jobs.ts'
|
|
14
|
+
import {
|
|
15
|
+
type Bucket,
|
|
16
|
+
type Counters,
|
|
17
|
+
type Entry,
|
|
18
|
+
entryOf,
|
|
19
|
+
keyText,
|
|
20
|
+
type Parts,
|
|
21
|
+
partsOf,
|
|
22
|
+
underField,
|
|
23
|
+
type Values,
|
|
24
|
+
type WriteOptions,
|
|
25
|
+
writeFields,
|
|
26
|
+
} from './kv.ts'
|
|
27
|
+
import { type Duration, ms, unixMs } from './time.ts'
|
|
28
|
+
import type { Key, Written } from './wire/codec.ts'
|
|
29
|
+
import { KvCall, KvEntry, KvTx, type Method, methods } from './wire/protocol.ts'
|
|
30
|
+
|
|
31
|
+
/** How many times tx runs its function before a key it read that keeps changing is ConflictError. */
|
|
32
|
+
const runs = 5
|
|
33
|
+
|
|
34
|
+
// Whether the caller runs inside a transaction's function, as its async
|
|
35
|
+
// context carries it: a lock's hold refuses to wait there.
|
|
36
|
+
const inside = new AsyncLocalStorage<boolean>()
|
|
37
|
+
|
|
38
|
+
/** Whether the caller runs inside the function of a store's transaction. */
|
|
39
|
+
export function insideStoreTx(): boolean {
|
|
40
|
+
return inside.getStore() === true
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Runs fn as one transaction and gives back what it returns: its writes all
|
|
45
|
+
* commit or none do. When a key fn read changed before the commit, fn runs
|
|
46
|
+
* again, five times at most, so it does nothing else that must happen once.
|
|
47
|
+
*/
|
|
48
|
+
export async function runTx<T>(link: Link, fn: (tx: Tx) => T | Promise<T>): Promise<T> {
|
|
49
|
+
for (let run = 1; ; run++) {
|
|
50
|
+
const tx = new Tx(link)
|
|
51
|
+
const returned = await inside.run(true, () => fn(tx))
|
|
52
|
+
try {
|
|
53
|
+
await tx.commit()
|
|
54
|
+
return returned
|
|
55
|
+
} catch (err) {
|
|
56
|
+
const changed = err instanceof ConflictError && err.what.check !== undefined
|
|
57
|
+
if (run >= runs || !changed) {
|
|
58
|
+
throw err
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
type Found = ReturnType<typeof KvEntry.decode>
|
|
65
|
+
type CallFields = Omit<Written<typeof KvCall.fields>, 'handle' | 'under'>
|
|
66
|
+
|
|
67
|
+
/** A key the transaction read from the store, which its commit checks. */
|
|
68
|
+
interface Read {
|
|
69
|
+
parts: Parts
|
|
70
|
+
key: string
|
|
71
|
+
found: Found
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A write the commit sends, in the order the function made it. */
|
|
75
|
+
interface Op {
|
|
76
|
+
method: Method
|
|
77
|
+
parts: Parts
|
|
78
|
+
fields: CallFields
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const absent: Found = { found: false }
|
|
82
|
+
|
|
83
|
+
/** The calls of a transaction, each through `tx.with(handle)`. */
|
|
84
|
+
export class Tx {
|
|
85
|
+
readonly #link: Link
|
|
86
|
+
readonly #reads = new Map<string, Promise<Read>>()
|
|
87
|
+
/** what the transaction wrote to a key, so that a read after it answers it */
|
|
88
|
+
readonly #written = new Map<string, { found: Found; at: number }>()
|
|
89
|
+
readonly #cleared: { handle: string; under: readonly string[]; at: number }[] = []
|
|
90
|
+
readonly #ops: Op[] = []
|
|
91
|
+
/** a queue's writes: a transaction takes the handles of one file, kv.db's or jobs.db's */
|
|
92
|
+
readonly #jobs: JobOp[] = []
|
|
93
|
+
/** messages published inside, handed over once the commit answered */
|
|
94
|
+
readonly #published: Uint8Array[] = []
|
|
95
|
+
#file: 'kv.db' | 'jobs.db' | undefined
|
|
96
|
+
#done = false
|
|
97
|
+
|
|
98
|
+
constructor(link: Link) {
|
|
99
|
+
this.#link = link
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
with<T>(bucket: Bucket<T>): TxBucket<T>
|
|
103
|
+
with(counters: Counters): TxCounters
|
|
104
|
+
with<T>(queue: Queue<T>): StoreTxQueue<T>
|
|
105
|
+
with<T>(channel: Channel<T>): TxChannel<T>
|
|
106
|
+
with(
|
|
107
|
+
handle: Bucket<unknown> | Counters | Queue<unknown> | Channel<unknown>,
|
|
108
|
+
): TxBucket<unknown> | TxCounters | StoreTxQueue<unknown> | TxChannel<unknown> {
|
|
109
|
+
const channel = channelParts(handle)
|
|
110
|
+
if (channel !== undefined) {
|
|
111
|
+
// a store's transaction commits in one kv.tx, which carries no message:
|
|
112
|
+
// its messages leave once its commit answered
|
|
113
|
+
return txChannel(channel.name, channel.branch, async body => {
|
|
114
|
+
this.#published.push(body)
|
|
115
|
+
})
|
|
116
|
+
}
|
|
117
|
+
const queue = queueParts(handle)
|
|
118
|
+
if (queue !== undefined) {
|
|
119
|
+
const what = `jobs queue ${queue.name}`
|
|
120
|
+
this.#takes(queue.source.link, queue.source.home?.describe, 'jobs.db', what)
|
|
121
|
+
return new StoreTxQueue(queue, op => {
|
|
122
|
+
this.#open()
|
|
123
|
+
this.#jobs.push(op)
|
|
124
|
+
})
|
|
125
|
+
}
|
|
126
|
+
const parts = partsOf(handle)
|
|
127
|
+
if (parts === undefined) {
|
|
128
|
+
throw new InvalidError('tx.with takes a bucket, counters or a queue')
|
|
129
|
+
}
|
|
130
|
+
this.#takes(parts.link, parts.home?.describe, 'kv.db', `kv ${parts.name}`)
|
|
131
|
+
if (parts.values === undefined) {
|
|
132
|
+
return new TxCounters(this, parts)
|
|
133
|
+
}
|
|
134
|
+
return new TxBucket(this, parts, parts.values)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** What the key holds as this transaction sees it: its own writes over what the store held. */
|
|
138
|
+
async read(parts: Parts, key: Key): Promise<Found> {
|
|
139
|
+
this.#open()
|
|
140
|
+
const text = keyText(key)
|
|
141
|
+
const own = this.#own(parts, text)
|
|
142
|
+
if (own !== undefined) {
|
|
143
|
+
return own
|
|
144
|
+
}
|
|
145
|
+
const place = placeOf(parts, text)
|
|
146
|
+
let reading = this.#reads.get(place)
|
|
147
|
+
if (reading === undefined) {
|
|
148
|
+
reading = this.#fetch(parts, text)
|
|
149
|
+
// a read the function never awaited still fails the commit, which awaits it
|
|
150
|
+
reading.catch(() => {})
|
|
151
|
+
this.#reads.set(place, reading)
|
|
152
|
+
}
|
|
153
|
+
return (await reading).found
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Keeps a write for the commit; found is what a read of its key answers after it. */
|
|
157
|
+
write(method: Method, parts: Parts, fields: CallFields, found?: Found): void {
|
|
158
|
+
this.#open()
|
|
159
|
+
this.#ops.push({ method, parts, fields })
|
|
160
|
+
if (found !== undefined && fields.key !== undefined) {
|
|
161
|
+
this.#written.set(placeOf(parts, keyText(fields.key)), { found, at: this.#ops.length })
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
clear(parts: Parts): void {
|
|
166
|
+
this.write('kv.clear', parts, {})
|
|
167
|
+
this.#cleared.push({ handle: handleOf(parts), under: parts.under, at: this.#ops.length })
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Refuses a handle of another store, one kept in a database's file, and
|
|
172
|
+
* one of the store's other file: a bucket and a queue of the store are two
|
|
173
|
+
* files, and no write is atomic across two.
|
|
174
|
+
*/
|
|
175
|
+
#takes(link: Link, home: string | undefined, file: 'kv.db' | 'jobs.db', what: string): void {
|
|
176
|
+
if (link !== this.#link) {
|
|
177
|
+
throw new InvalidError(`${what}: a handle of another store, in a transaction of this one`)
|
|
178
|
+
}
|
|
179
|
+
if (home !== undefined) {
|
|
180
|
+
throw new InvalidError(
|
|
181
|
+
`${home}: ${what}: kept in the database's file, outside this transaction of the store: take it in with db.tx`,
|
|
182
|
+
)
|
|
183
|
+
}
|
|
184
|
+
if (this.#file !== undefined && this.#file !== file) {
|
|
185
|
+
throw new InvalidError(
|
|
186
|
+
`${what}: kept in ${file}, outside this transaction of ${this.#file}: open both from a database to commit them together`,
|
|
187
|
+
)
|
|
188
|
+
}
|
|
189
|
+
this.#file = file
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Sends the writes in one kv.tx, after a check of each key read: still at its version, or still absent. */
|
|
193
|
+
/** Commits the writes, then hands over the messages published inside. */
|
|
194
|
+
async commit(): Promise<void> {
|
|
195
|
+
this.#done = true
|
|
196
|
+
await this.#commitWrites()
|
|
197
|
+
for (const body of this.#published) {
|
|
198
|
+
await this.#link.run('write', connection =>
|
|
199
|
+
connection.session.call(methods['channels.publish'], body),
|
|
200
|
+
)
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async #commitWrites(): Promise<void> {
|
|
205
|
+
if (this.#jobs.length > 0) {
|
|
206
|
+
return commitJobs(this.#link, this.#jobs)
|
|
207
|
+
}
|
|
208
|
+
const reads = await Promise.all(this.#reads.values())
|
|
209
|
+
if (reads.length === 0 && this.#ops.length === 0) {
|
|
210
|
+
return
|
|
211
|
+
}
|
|
212
|
+
await this.#link.run(this.#ops.length > 0 ? 'write' : 'read', async connection => {
|
|
213
|
+
const handle = (parts: Parts) => handleOn(connection, methods[parts.openMethod], parts.open)
|
|
214
|
+
const checks = []
|
|
215
|
+
for (const read of reads) {
|
|
216
|
+
const version = read.found.found === true ? read.found.version : undefined
|
|
217
|
+
checks.push({
|
|
218
|
+
handle: await handle(read.parts),
|
|
219
|
+
under: underField(read.parts.under),
|
|
220
|
+
key: read.key,
|
|
221
|
+
version,
|
|
222
|
+
})
|
|
223
|
+
}
|
|
224
|
+
const writes = []
|
|
225
|
+
for (const op of this.#ops) {
|
|
226
|
+
const call = {
|
|
227
|
+
...op.fields,
|
|
228
|
+
handle: await handle(op.parts),
|
|
229
|
+
under: underField(op.parts.under),
|
|
230
|
+
}
|
|
231
|
+
writes.push({ method: methods[op.method], call })
|
|
232
|
+
}
|
|
233
|
+
await connection.session.call(methods['kv.tx'], KvTx.encode({ checks, writes }))
|
|
234
|
+
})
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
#open(): void {
|
|
238
|
+
if (this.#done) {
|
|
239
|
+
throw new InvalidError(
|
|
240
|
+
'a transaction takes its calls while its function runs, before it commits',
|
|
241
|
+
)
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// the transaction's own word on a key: a write of it, or a clear of a branch above it, whichever came last
|
|
246
|
+
#own(parts: Parts, key: string): Found | undefined {
|
|
247
|
+
const written = this.#written.get(placeOf(parts, key))
|
|
248
|
+
let cleared = 0
|
|
249
|
+
for (const clear of this.#cleared) {
|
|
250
|
+
if (clear.handle === handleOf(parts) && startsWith(parts.under, clear.under)) {
|
|
251
|
+
cleared = Math.max(cleared, clear.at)
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
if (written !== undefined && written.at > cleared) {
|
|
255
|
+
return written.found
|
|
256
|
+
}
|
|
257
|
+
return cleared > 0 ? absent : undefined
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
async #fetch(parts: Parts, key: string): Promise<Read> {
|
|
261
|
+
const found = await this.#link.run('read', async connection => {
|
|
262
|
+
const handle = await handleOn(connection, methods[parts.openMethod], parts.open)
|
|
263
|
+
const call = KvCall.encode({ handle, under: underField(parts.under), key })
|
|
264
|
+
return KvEntry.decode(await connection.session.call(methods['kv.get'], call))
|
|
265
|
+
})
|
|
266
|
+
return { parts, key, found }
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** A bucket's calls inside a transaction: reads answer at once, writes wait for its commit. */
|
|
271
|
+
export class TxBucket<T> {
|
|
272
|
+
readonly #tx: Tx
|
|
273
|
+
readonly #parts: Parts
|
|
274
|
+
readonly #values: Values<T>
|
|
275
|
+
|
|
276
|
+
constructor(tx: Tx, parts: Parts, values: Values<unknown>) {
|
|
277
|
+
this.#tx = tx
|
|
278
|
+
this.#parts = parts
|
|
279
|
+
this.#values = values as Values<T>
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
under(...owners: Key[]): TxBucket<T> {
|
|
283
|
+
const parts = { ...this.#parts, under: [...this.#parts.under, ...owners.map(keyText)] }
|
|
284
|
+
return new TxBucket(this.#tx, parts, this.#values as Values<unknown>)
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
async get(key: Key): Promise<T | undefined> {
|
|
288
|
+
return (await this.entry(key))?.value
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
async entry(key: Key): Promise<Entry<T> | undefined> {
|
|
292
|
+
const found = await this.#tx.read(this.#parts, key)
|
|
293
|
+
return found.found === true ? entryOf(key, found, this.#values) : undefined
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
async has(key: Key): Promise<boolean> {
|
|
297
|
+
return (await this.#tx.read(this.#parts, key)).found === true
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
async set(key: Key, value: T, options?: WriteOptions): Promise<void> {
|
|
301
|
+
const raw = this.#values.encode(value)
|
|
302
|
+
this.#tx.write(
|
|
303
|
+
'kv.set',
|
|
304
|
+
this.#parts,
|
|
305
|
+
{ key, value: raw, ...writeFields(options) },
|
|
306
|
+
{ found: true, value: raw },
|
|
307
|
+
)
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** Writes the value only where no live key is, and says whether it will. */
|
|
311
|
+
async create(key: Key, value: T, options?: Omit<WriteOptions, 'ifVersion'>): Promise<boolean> {
|
|
312
|
+
if ((await this.#tx.read(this.#parts, key)).found === true) {
|
|
313
|
+
return false
|
|
314
|
+
}
|
|
315
|
+
const raw = this.#values.encode(value)
|
|
316
|
+
this.#tx.write(
|
|
317
|
+
'kv.create',
|
|
318
|
+
this.#parts,
|
|
319
|
+
{ key, value: raw, ...writeFields(options) },
|
|
320
|
+
{ found: true, value: raw },
|
|
321
|
+
)
|
|
322
|
+
return true
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
async add(key: Key, options?: Omit<WriteOptions, 'ifVersion'>): Promise<boolean> {
|
|
326
|
+
if ((await this.#tx.read(this.#parts, key)).found === true) {
|
|
327
|
+
return false
|
|
328
|
+
}
|
|
329
|
+
this.#tx.write(
|
|
330
|
+
'kv.create',
|
|
331
|
+
this.#parts,
|
|
332
|
+
{ key, ...writeFields(options) },
|
|
333
|
+
{ found: true, value: null },
|
|
334
|
+
)
|
|
335
|
+
return true
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
async take(key: Key, options?: Pick<WriteOptions, 'ifVersion'>): Promise<T | undefined> {
|
|
339
|
+
const found = await this.#remove('kv.take', key, options)
|
|
340
|
+
return found.found === true ? this.#values.decode(found.value ?? null) : undefined
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
async delete(key: Key, options?: Pick<WriteOptions, 'ifVersion'>): Promise<boolean> {
|
|
344
|
+
return (await this.#remove('kv.delete', key, options)).found === true
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
async expire(
|
|
348
|
+
key: Key,
|
|
349
|
+
when: Duration | Date,
|
|
350
|
+
options?: Pick<WriteOptions, 'ifVersion'>,
|
|
351
|
+
): Promise<boolean> {
|
|
352
|
+
const found = await this.#tx.read(this.#parts, key)
|
|
353
|
+
if (found.found !== true && options?.ifVersion === undefined) {
|
|
354
|
+
return false
|
|
355
|
+
}
|
|
356
|
+
const expiry = when instanceof Date ? { expiresAt: when } : { ttl: when }
|
|
357
|
+
const expiresAt = when instanceof Date ? unixMs(when) : Date.now() + ms(when)
|
|
358
|
+
const fields = { key, ...writeFields({ ...options, ...expiry }) }
|
|
359
|
+
this.#tx.write(
|
|
360
|
+
'kv.expire',
|
|
361
|
+
this.#parts,
|
|
362
|
+
fields,
|
|
363
|
+
found.found === true ? { ...found, expiresAt } : undefined,
|
|
364
|
+
)
|
|
365
|
+
return found.found === true
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** Removes this branch's keys and every branch's under it, with the commit. */
|
|
369
|
+
async clear(): Promise<void> {
|
|
370
|
+
this.#tx.clear(this.#parts)
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// a take or a delete: what the key held, and its removal, sent when the
|
|
374
|
+
// key was there or when the caller named the version it must be at
|
|
375
|
+
async #remove(
|
|
376
|
+
method: Method,
|
|
377
|
+
key: Key,
|
|
378
|
+
options?: Pick<WriteOptions, 'ifVersion'>,
|
|
379
|
+
): Promise<Found> {
|
|
380
|
+
const found = await this.#tx.read(this.#parts, key)
|
|
381
|
+
if (found.found === true || options?.ifVersion !== undefined) {
|
|
382
|
+
this.#tx.write(method, this.#parts, { key, ...writeFields(options) }, absent)
|
|
383
|
+
}
|
|
384
|
+
return found
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** Counters inside a transaction: an add commits with its writes. */
|
|
389
|
+
export class TxCounters {
|
|
390
|
+
readonly #tx: Tx
|
|
391
|
+
readonly #parts: Parts
|
|
392
|
+
|
|
393
|
+
constructor(tx: Tx, parts: Parts) {
|
|
394
|
+
this.#tx = tx
|
|
395
|
+
this.#parts = parts
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
under(...owners: Key[]): TxCounters {
|
|
399
|
+
return new TxCounters(this.#tx, {
|
|
400
|
+
...this.#parts,
|
|
401
|
+
under: [...this.#parts.under, ...owners.map(keyText)],
|
|
402
|
+
})
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** Adds n, 1 unless given, with the commit; the count is known once it has. */
|
|
406
|
+
async add(key: Key, n: number | bigint = 1): Promise<void> {
|
|
407
|
+
this.#tx.write('kv.counters.add', this.#parts, { key, n })
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** A key's place as one text, its handle and owners included, each kept apart. */
|
|
412
|
+
function placeOf(parts: Parts, key: string): string {
|
|
413
|
+
return JSON.stringify([handleOf(parts), parts.under, key])
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/** A handle's place as text: its open's bytes, which a store's own handle has. */
|
|
417
|
+
function handleOf(parts: Parts): string {
|
|
418
|
+
if (typeof parts.open === 'function') {
|
|
419
|
+
throw new InvalidError(`kv ${parts.name}: a handle of a database, in a transaction of kv.db`)
|
|
420
|
+
}
|
|
421
|
+
return `${parts.openMethod} ${Buffer.from(parts.open).toString('base64')}`
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
function startsWith(under: readonly string[], branch: readonly string[]): boolean {
|
|
425
|
+
return branch.length <= under.length && branch.every((owner, i) => under[i] === owner)
|
|
426
|
+
}
|