@tinyshed/tinystore 0.1.0-rc.1
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 +202 -0
- package/README.md +262 -0
- package/bin/tinystore.js +50 -0
- package/dist/background.d.ts +30 -0
- package/dist/background.js +93 -0
- package/dist/blobs.d.ts +98 -0
- package/dist/blobs.js +299 -0
- package/dist/cancel.d.ts +14 -0
- package/dist/cancel.js +22 -0
- package/dist/clock.d.ts +21 -0
- package/dist/clock.js +35 -0
- package/dist/config.d.ts +60 -0
- package/dist/config.js +417 -0
- package/dist/connection.d.ts +78 -0
- package/dist/connection.js +405 -0
- package/dist/console.d.ts +48 -0
- package/dist/console.js +195 -0
- package/dist/errors.d.ts +103 -0
- package/dist/errors.js +158 -0
- package/dist/handles.d.ts +28 -0
- package/dist/handles.js +37 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.js +7 -0
- package/dist/jobs.d.ts +304 -0
- package/dist/jobs.js +684 -0
- package/dist/kv.d.ts +283 -0
- package/dist/kv.js +815 -0
- package/dist/limiter.d.ts +45 -0
- package/dist/limiter.js +68 -0
- package/dist/logger.d.ts +96 -0
- package/dist/logger.js +243 -0
- package/dist/metrics.d.ts +249 -0
- package/dist/metrics.js +610 -0
- package/dist/once.d.ts +31 -0
- package/dist/once.js +116 -0
- package/dist/quota.d.ts +44 -0
- package/dist/quota.js +98 -0
- package/dist/records.d.ts +182 -0
- package/dist/records.js +346 -0
- package/dist/runtime/bun.d.ts +2 -0
- package/dist/runtime/bun.js +164 -0
- package/dist/runtime/node.d.ts +2 -0
- package/dist/runtime/node.js +157 -0
- package/dist/runtime/shared.d.ts +25 -0
- package/dist/runtime/shared.js +45 -0
- package/dist/runtime.d.ts +48 -0
- package/dist/runtime.js +4 -0
- package/dist/schema.d.ts +39 -0
- package/dist/schema.js +21 -0
- package/dist/session.d.ts +120 -0
- package/dist/session.js +546 -0
- package/dist/sql.d.ts +121 -0
- package/dist/sql.js +342 -0
- package/dist/store.d.ts +103 -0
- package/dist/store.js +153 -0
- package/dist/time.d.ts +35 -0
- package/dist/time.js +44 -0
- package/dist/trace.d.ts +18 -0
- package/dist/trace.js +22 -0
- package/dist/wire/codec.d.ts +90 -0
- package/dist/wire/codec.js +383 -0
- package/dist/wire/frame.d.ts +41 -0
- package/dist/wire/frame.js +102 -0
- package/dist/wire/messages.d.ts +1403 -0
- package/dist/wire/messages.js +472 -0
- package/dist/wire/msgpack.d.ts +93 -0
- package/dist/wire/msgpack.js +680 -0
- package/package.json +40 -0
- package/src/background.ts +108 -0
- package/src/blobs.ts +437 -0
- package/src/cancel.ts +26 -0
- package/src/clock.ts +45 -0
- package/src/config.ts +501 -0
- package/src/connection.ts +512 -0
- package/src/console.ts +228 -0
- package/src/errors.ts +211 -0
- package/src/handles.ts +68 -0
- package/src/index.ts +92 -0
- package/src/jobs.ts +963 -0
- package/src/kv.ts +1093 -0
- package/src/limiter.ts +99 -0
- package/src/logger.ts +326 -0
- package/src/metrics.ts +896 -0
- package/src/once.ts +142 -0
- package/src/quota.ts +137 -0
- package/src/records.ts +537 -0
- package/src/runtime/bun.ts +190 -0
- package/src/runtime/node.ts +177 -0
- package/src/runtime/shared.ts +61 -0
- package/src/runtime.ts +57 -0
- package/src/schema.ts +69 -0
- package/src/session.ts +665 -0
- package/src/sql.ts +478 -0
- package/src/store.ts +219 -0
- package/src/time.ts +87 -0
- package/src/trace.ts +32 -0
- package/src/wire/codec.ts +445 -0
- package/src/wire/frame.ts +139 -0
- package/src/wire/messages.ts +562 -0
- package/src/wire/msgpack.ts +712 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
# TinyStore for Bun and Node
|
|
2
|
+
|
|
3
|
+
kv, jobs, blobs, SQL, records and metrics in one directory, served by a
|
|
4
|
+
sidecar the SDK starts. A Go program embeds the same engines;
|
|
5
|
+
[the guides](../../docs/README.md) show the three languages side by side.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
bun add @tinyshed/tinystore
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
The package for this platform, an optional dependency, carries the
|
|
12
|
+
`tinystore` binary. `TINYSTORE_BIN`, `open`'s `binary` or `PATH` name another.
|
|
13
|
+
Bun 1.4 or later, or Node 22 or later, with one API: Bun runs the package's
|
|
14
|
+
TypeScript, and Node the JavaScript it carries.
|
|
15
|
+
|
|
16
|
+
From a checkout, `bun add ../tinystore/sdk/js` installs the package as its
|
|
17
|
+
source. The declarations `types` names are built by a release, so TypeScript
|
|
18
|
+
checks that source in their place with `"customConditions": ["bun"]` and
|
|
19
|
+
`"allowImportingTsExtensions": true`.
|
|
20
|
+
|
|
21
|
+
The binary is the `tinystore` command too: `bunx @tinyshed/tinystore status ./data`,
|
|
22
|
+
`bunx @tinyshed/tinystore logs ./data -f`, and for an AI agent
|
|
23
|
+
`claude mcp add tinystore -- bunx @tinyshed/tinystore mcp ./data`.
|
|
24
|
+
|
|
25
|
+
## Open
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { connect, open } from '@tinyshed/tinystore'
|
|
29
|
+
|
|
30
|
+
await using store = await open('./data') // the directory's sidecar, started when none runs
|
|
31
|
+
await using alone = await open(dir, { private: true }) // a child of this process, for tests and scripts
|
|
32
|
+
await using remote = await connect('tls://db.internal:7070', { token })
|
|
33
|
+
|
|
34
|
+
await using test = await open(dir, { private: true, clock: new Date('2026-10-03T09:00:00Z') })
|
|
35
|
+
await test.clock.advance('1h') // keys expire and jobs come due without a wait
|
|
36
|
+
|
|
37
|
+
await store.backup('backup.zip') // every engine in one checked zip; tinystore restore takes it back
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
`open` returns once the server has answered, so a directory that cannot be
|
|
41
|
+
served fails there. Closing hands over the loggers' lines and the instruments'
|
|
42
|
+
last values; a sidecar leaves once its last connection has been idle 30 s.
|
|
43
|
+
|
|
44
|
+
## kv
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
const sessions = store.kv.bucket<Session>('sessions', { sliding: '30d' })
|
|
48
|
+
await sessions.of(user.id).set(token, session)
|
|
49
|
+
const found = await sessions.of(user.id).get(token) // undefined when absent or expired
|
|
50
|
+
const { created, entry } = await sessions.of(user.id).setEntryIfAbsent(token, session) // this one, or the one there
|
|
51
|
+
|
|
52
|
+
const views = store.kv.counters('views')
|
|
53
|
+
await views.add('/home')
|
|
54
|
+
|
|
55
|
+
const page = await sessions.scan({ limit: 100 }) // { items, next }; next goes back as after
|
|
56
|
+
for await (const entry of sessions.all()) { … }
|
|
57
|
+
|
|
58
|
+
const userId = await store.kv.tx(async tx => { // reads, decides, writes; runs again if a key it read changed
|
|
59
|
+
const userId = await codes.withTx(tx).take(digest(code))
|
|
60
|
+
if (userId === undefined) throw new InvalidCodeError()
|
|
61
|
+
sessions.withTx(tx).of(userId).set(digest(token), session)
|
|
62
|
+
return userId
|
|
63
|
+
})
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
A bucket's type is given once, where it opens: JSON of `T`, a kind
|
|
67
|
+
(`'string'`, `'bytes'`, `'bigint'`, …) or a Standard Schema such as zod's,
|
|
68
|
+
which checks every read. `setIfAbsent` and `setEntryIfAbsent` write only
|
|
69
|
+
where no live key is, in one write: two processes making the same key, a
|
|
70
|
+
day's salt or a claim, keep one, where a `get` and then a `set` keep both.
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
import file from './config.yaml'
|
|
74
|
+
|
|
75
|
+
const cfg = await store.kv.config('app', { port: 8080, dbUrl: '', origins: ['localhost'] }, { file })
|
|
76
|
+
cfg.value.port // PORT=3000 in .env makes it 3000
|
|
77
|
+
await cfg.update({ port: 4000 }) // kept: 4000 after a restart too, at once in every process
|
|
78
|
+
await cfg.reset('port') // back to .env's 3000
|
|
79
|
+
cfg.watch(c => server.setPort(c.port))
|
|
80
|
+
|
|
81
|
+
const limit = store.kv.limiter('api', { rate: '100/s', burst: 20 })
|
|
82
|
+
const { ok, retryAfter } = await limit.of(tenant).allow(userId)
|
|
83
|
+
|
|
84
|
+
const ai = store.kv.quota('ai', { session: '100/5h', weekly: '300/7d' })
|
|
85
|
+
const usage = await ai.allow(user.id) // one of each window, or none: usage.windows.weekly.left
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
A config is shaped and typed by its defaults: a file's values, then the
|
|
89
|
+
environment, then what `update` kept go over them, a variable named by its
|
|
90
|
+
field, `dbUrl` as `DB_URL`, after `prefix` when given. A number, `true`, a
|
|
91
|
+
list `a.com,b.com` or JSON read as the default's kind, and one that does not
|
|
92
|
+
is `InvalidError` at open, naming it. `env: { dbUrl: 'DATABASE_URL' }` names a
|
|
93
|
+
variable itself; `secret` fields are never kept; `schema` checks each change.
|
|
94
|
+
A quota's windows count a use together or not at all, each from a key's first
|
|
95
|
+
use; `get` reads them without using any, `refund` gives uses back.
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
const charges = store.kv.once<Receipt>('charges') // answers kept a day
|
|
99
|
+
const receipt = await charges.run(requestId, () => pay.charge(order, requestId))
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
`run` returns the answer kept under a key, or runs the function and keeps
|
|
103
|
+
its answer: a call of the key meanwhile, from any client, waits for it and
|
|
104
|
+
gets the same answer, and a throw keeps nothing, so the next call runs again.
|
|
105
|
+
The function runs once a key while its call lives; an effect outside the
|
|
106
|
+
store, a charge, carries the key too.
|
|
107
|
+
|
|
108
|
+
## jobs
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
const reminders = store.jobs.queue<{ note: number }>('reminders')
|
|
112
|
+
await reminders.enqueue({ note: 1 }, { after: '1h', key: 'note/1' })
|
|
113
|
+
|
|
114
|
+
await reminders.work(async job => {
|
|
115
|
+
await remind(job.value.note, { signal: job.signal })
|
|
116
|
+
}, { workers: 4, signal })
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
A handler's return acknowledges its job and a throw retries it, waiting longer
|
|
120
|
+
each time; `job.retry`, `job.fail` and `job.snooze` say otherwise. `work` runs
|
|
121
|
+
until its signal aborts; the jobs in hand finish first.
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
const videos = store.jobs.queue<Video>('videos', { maxRunning: 2 })
|
|
125
|
+
await videos.enqueue(video, { key: video.id })
|
|
126
|
+
for await (const s of videos.watch(video.id)) send(s.state, s.ahead, s.progress) // waiting 3 … running 0.4 … done
|
|
127
|
+
|
|
128
|
+
await videos.work(async job => {
|
|
129
|
+
await transcode(job.value, { signal: job.signal, onProgress: p => job.progress(p) })
|
|
130
|
+
})
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
`get` says where a job is: `waiting`, with how many jobs run `ahead` of it,
|
|
134
|
+
`running`, with the `progress` its handler last reported, `failed`, or `done`
|
|
135
|
+
while `keepDone` keeps its key; `watch` yields it again at each change until
|
|
136
|
+
it ends, `cancelled` included, and `ran` and `took` say when the last run a
|
|
137
|
+
handler finished began and how many milliseconds it took: a schedule's last
|
|
138
|
+
run beside its next, `at`. `job.progress` takes any JSON within 4 KiB and
|
|
139
|
+
sends the latest at most ten times a second. `cancel` takes a running job too:
|
|
140
|
+
its `job.signal` aborts with a `CancelledError`, and what the handler returns
|
|
141
|
+
settles nothing. `maxRunning` bounds the jobs running at once across every
|
|
142
|
+
worker of the store.
|
|
143
|
+
|
|
144
|
+
A step of a job's run keeps its answer, so that the attempt after a failure
|
|
145
|
+
does not run it again: `const hits = await job.step('search', () => search(q))`.
|
|
146
|
+
|
|
147
|
+
## blobs
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
const files = store.blobs.bucket('files')
|
|
151
|
+
await files.put('avatars/42.png', Bun.file('avatar.png'))
|
|
152
|
+
const avatar = await files.get('avatars/42.png') // undefined when absent
|
|
153
|
+
const bytes = await avatar?.bytes() // a whole read checks every byte
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
## SQL
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
const app = await store.sql('app', { migrations: './migrations' })
|
|
160
|
+
await app.exec`insert into notes (body) values (${body})`
|
|
161
|
+
const notes = await app.all<Note>`select id, body from notes where author = ${author}`
|
|
162
|
+
await app.batch(tx => { // one transaction, all or none
|
|
163
|
+
tx.exec`update notes set body = ${body} where id = ${id}`
|
|
164
|
+
tx.exec`insert into edits (note) values (${id})`
|
|
165
|
+
})
|
|
166
|
+
const [page, total] = await app.view(tx => [tx.all`select * from notes limit 20`, tx.scalar`select count(*) from notes`])
|
|
167
|
+
|
|
168
|
+
const index = store.jobs.queue<{ id: number }>('index', { in: app }) // the queue lives in sql/app.db
|
|
169
|
+
await app.batch(tx => {
|
|
170
|
+
tx.exec`update notes set body = ${body} where id = ${id}`
|
|
171
|
+
index.withTx(tx).enqueue({ id }) // commits with the update, or not at all
|
|
172
|
+
})
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
A value comes back as SQLite keeps it; a template's values are arguments,
|
|
176
|
+
never SQL.
|
|
177
|
+
|
|
178
|
+
## records
|
|
179
|
+
|
|
180
|
+
```ts
|
|
181
|
+
const log = store.records.logger('api', { redact: ['password'] }) // never waits for the server
|
|
182
|
+
log.with({ requestId }).warn('slow request', { ms: 1200 })
|
|
183
|
+
log.event('user.created', { userId: 42 })
|
|
184
|
+
await withTrace({ traceId, spanId }, async () => log.info('charged')) // the record carries the trace
|
|
185
|
+
|
|
186
|
+
const page = await store.records.scan({ since: '1h', minLevel: 'warn', limit: 100 })
|
|
187
|
+
const resets = await store.records.scan({ since: '1h', search: 'connection reset' }) // case ignored
|
|
188
|
+
const more = await store.records.scan({ since: '1h', minLevel: 'warn', limit: 100, after: page.next })
|
|
189
|
+
for await (const record of store.records.all({ since: '24h', traceId })) { … }
|
|
190
|
+
const { ms } = fields(page.items[0].attrs) // a record's [key, json] pairs, as JSON.parse reads them
|
|
191
|
+
|
|
192
|
+
const worker = store.records.lines('worker') // another program's output, cut anywhere
|
|
193
|
+
for await (const chunk of child.stdout) worker.write(chunk)
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
A logger holds 1024 lines and hands them over every second or once half of
|
|
197
|
+
them wait; what does not fit is dropped, counted in `log.dropped` and said on
|
|
198
|
+
stderr. A logger is for lines a burst may cost: what must all be kept goes
|
|
199
|
+
through `records.append`, which answers once it is, and a larger `buffer`
|
|
200
|
+
holds a longer burst.
|
|
201
|
+
|
|
202
|
+
Each line also goes to stderr as it is logged: pretty on a terminal, one JSON
|
|
203
|
+
object a line otherwise, the bytes Go's and Python's loggers write.
|
|
204
|
+
`console: 'pretty' | 'json' | 'off'` and `stdout: true` choose, and a logger
|
|
205
|
+
of events, a view a request, takes `'off'` or fills the program's log; `redact`
|
|
206
|
+
hides the values of fields of those names, at any depth, the case ignored, in
|
|
207
|
+
the store and on the console. A program that wants the logger and not the
|
|
208
|
+
records takes one without a store, and passes it, or a child, to what needs
|
|
209
|
+
it:
|
|
210
|
+
|
|
211
|
+
```ts
|
|
212
|
+
import { logger } from '@tinyshed/tinystore'
|
|
213
|
+
|
|
214
|
+
const log = logger('app', { redact: ['password'] }) // the console alone, nothing kept
|
|
215
|
+
const db = log.with({ module: 'db' })
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
## metrics
|
|
219
|
+
|
|
220
|
+
```ts
|
|
221
|
+
store.metrics.counter('http_requests_total').with({ route: '/users' }).inc()
|
|
222
|
+
store.metrics.gauge('queue_depth').set(12)
|
|
223
|
+
const latency = store.metrics.timer('http_request_ms')
|
|
224
|
+
const user = await latency.with({ route: '/users' }).measure(() => users.get(id))
|
|
225
|
+
|
|
226
|
+
await store.metrics.ingest({ name: 'cpu', kind: 'gauge', labels: { host: 'web-1' }, samples: [[new Date(), 0.42]] })
|
|
227
|
+
const series = await store.metrics.read({ name: 'cpu', match: { host: 'web-1' }, since: '1h' }) // columns: times, values
|
|
228
|
+
const failing = await store.metrics.read({ name: 'http_requests_total', since: '1h', where: { status: oneOf('500', '502') } })
|
|
229
|
+
const buckets = await store.metrics.aggregate({ name: 'http_requests_total', since: '24h', width: '1h', op: 'increase' })
|
|
230
|
+
const routes = await store.metrics.aggregate({ name: 'http_requests_total', since: '24h', width: '1h', op: 'rate', by: ['route'] })
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
A read answers each series as columns, `times` in unix milliseconds and
|
|
234
|
+
`values` a `Float64Array`, as `ingest` takes them too beside `[time, value]`
|
|
235
|
+
pairs. A sample comes back bit for bit, `-0` and a NaN's payload included; a
|
|
236
|
+
range is `since`, or `from` and `to` in unix milliseconds.
|
|
237
|
+
`metrics.explain(range)` says what a read or an aggregate would spend of its
|
|
238
|
+
limits before it runs.
|
|
239
|
+
|
|
240
|
+
A timer's `measure(fn)` answers what `fn` answered and throws what it threw,
|
|
241
|
+
recording the time either way; `record(ms)` adds a duration of its own. Every
|
|
242
|
+
flush writes `http_request_ms_count` and `http_request_ms_sum`, counters, and
|
|
243
|
+
the longest since the flush before, `http_request_ms_max`, so that a range's
|
|
244
|
+
mean is the increase of its sum over the increase of its count. A series the
|
|
245
|
+
store refuses, a label it cannot keep, is left out from then on and said
|
|
246
|
+
once, and the other instruments go on being written.
|
|
247
|
+
|
|
248
|
+
## Errors and cancellation
|
|
249
|
+
|
|
250
|
+
Every error is its code's class, a `TinystoreError`: `InvalidError`,
|
|
251
|
+
`ConflictError`, `LimitError`, `TooOldError` and the rest, each carrying what it
|
|
252
|
+
names; a `LimitError` names the bound, what the call wanted and the bound.
|
|
253
|
+
Every call inside `withSignal(signal, fn)` ends when the signal aborts, one
|
|
254
|
+
`CANCEL` on the wire; `work`, `put` and `get` of blobs also take a signal of
|
|
255
|
+
their own. `await store.status()` says what the server is: its version, its
|
|
256
|
+
protocol, its engines.
|
|
257
|
+
|
|
258
|
+
What fails where no call waits is said on stderr, as a logger of stream
|
|
259
|
+
`tinystore` writes a line: an instrument's flush or a logger's write that
|
|
260
|
+
failed, and its recovery; a gauge's function that threw; a refused
|
|
261
|
+
instrument; the lines a full logger dropped. A failure repeated is said again
|
|
262
|
+
ten minutes on, or when it changes, as Go's store logs its own.
|
package/bin/tinystore.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The tinystore command, as this package installs it: the binary its platform's
|
|
3
|
+
// package carries, run with these arguments on this console, its exit code
|
|
4
|
+
// this process's. `bunx @tinyshed/tinystore status ./data` and `npx @tinyshed/tinystore` need
|
|
5
|
+
// nothing else installed. Plain JavaScript, so that Node and Bun both run it.
|
|
6
|
+
|
|
7
|
+
import { spawn } from 'node:child_process'
|
|
8
|
+
import { createRequire } from 'node:module'
|
|
9
|
+
import { constants } from 'node:os'
|
|
10
|
+
|
|
11
|
+
const executable = process.platform === 'win32' ? 'tinystore.exe' : 'tinystore'
|
|
12
|
+
const platform = `@tinyshed/tinystore-${process.platform}-${process.arch}`
|
|
13
|
+
|
|
14
|
+
function packagedBinary() {
|
|
15
|
+
try {
|
|
16
|
+
return createRequire(import.meta.url).resolve(`${platform}/bin/${executable}`)
|
|
17
|
+
} catch {
|
|
18
|
+
return undefined
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Not PATH's tinystore: that may be this very command, which would run itself.
|
|
23
|
+
const binary = process.env.TINYSTORE_BIN || packagedBinary()
|
|
24
|
+
if (binary === undefined) {
|
|
25
|
+
process.stderr.write(
|
|
26
|
+
`tinystore: ${platform}, which carries the binary, was not installed; ` +
|
|
27
|
+
'install tinystore again without --no-optional, or set TINYSTORE_BIN\n',
|
|
28
|
+
)
|
|
29
|
+
process.exit(1)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const child = spawn(binary, process.argv.slice(2), { stdio: 'inherit' })
|
|
33
|
+
// A Ctrl+C reaches the binary as it reaches this process, and the binary ends
|
|
34
|
+
// on its own, letting its SERVE and its lock go, while this one waits. A signal
|
|
35
|
+
// sent to this process alone is passed on, but not on Windows, where passing
|
|
36
|
+
// one on ends the binary outright.
|
|
37
|
+
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
|
|
38
|
+
process.on(signal, () => {
|
|
39
|
+
if (process.platform !== 'win32') {
|
|
40
|
+
child.kill(signal)
|
|
41
|
+
}
|
|
42
|
+
})
|
|
43
|
+
}
|
|
44
|
+
child.on('error', err => {
|
|
45
|
+
process.stderr.write(`tinystore: ${binary}: ${err.message}\n`)
|
|
46
|
+
process.exit(1)
|
|
47
|
+
})
|
|
48
|
+
child.on('exit', (code, signal) => {
|
|
49
|
+
process.exit(code ?? 128 + (constants.signals[signal] ?? 0))
|
|
50
|
+
})
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Fields } from './records.ts';
|
|
2
|
+
/** Where TinyStore's own lines go: the console of a logger of stream tinystore, or a test's. */
|
|
3
|
+
export type Say = (level: 'info' | 'warn', message: string, fields: Fields) => void;
|
|
4
|
+
/**
|
|
5
|
+
* A background work's failures, said as Go's failureLog logs them:
|
|
6
|
+
*
|
|
7
|
+
* 00:00 disk full → warn "background work failed" failures=1
|
|
8
|
+
* 00:01…00:09 the same → counted
|
|
9
|
+
* 00:10 disk full → warn failures=11
|
|
10
|
+
* 00:11 success → info "background work recovered" failures=11
|
|
11
|
+
*/
|
|
12
|
+
export declare class FailureLog {
|
|
13
|
+
#private;
|
|
14
|
+
constructor(work: string, say: Say, now?: () => number);
|
|
15
|
+
failed(err: unknown): void;
|
|
16
|
+
succeeded(): void;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* The lines a logger dropped for want of room, said at a flush and at most
|
|
20
|
+
* once in a quiet period: a burst is one line, and a logger that keeps
|
|
21
|
+
* dropping says how many every ten minutes rather than every second.
|
|
22
|
+
*/
|
|
23
|
+
export declare class DropNotice {
|
|
24
|
+
#private;
|
|
25
|
+
constructor(stream: string, buffer: number, say: Say, now?: () => number);
|
|
26
|
+
dropped(): void;
|
|
27
|
+
sayIfDue(): void;
|
|
28
|
+
}
|
|
29
|
+
/** An error's message, as Go's err.Error() reads, without the class JavaScript puts first. */
|
|
30
|
+
export declare function messageOf(err: unknown): string;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// What the SDK does in the background, an instrument's flush or a logger's
|
|
2
|
+
// write, has no caller to tell when it fails. It says so as Go's
|
|
3
|
+
// tinystore.Store does, in TinyStore's own lines: once, again when the
|
|
4
|
+
// failure changes or ten minutes on, and once more when the work recovers.
|
|
5
|
+
/** A failure repeated within this long is counted rather than said again. */
|
|
6
|
+
const quiet = 10 * 60_000;
|
|
7
|
+
/**
|
|
8
|
+
* A background work's failures, said as Go's failureLog logs them:
|
|
9
|
+
*
|
|
10
|
+
* 00:00 disk full → warn "background work failed" failures=1
|
|
11
|
+
* 00:01…00:09 the same → counted
|
|
12
|
+
* 00:10 disk full → warn failures=11
|
|
13
|
+
* 00:11 success → info "background work recovered" failures=11
|
|
14
|
+
*/
|
|
15
|
+
export class FailureLog {
|
|
16
|
+
#work;
|
|
17
|
+
#say;
|
|
18
|
+
#now;
|
|
19
|
+
#last = '';
|
|
20
|
+
#saidAt = 0;
|
|
21
|
+
#failures = 0;
|
|
22
|
+
constructor(work, say, now = Date.now) {
|
|
23
|
+
this.#work = work;
|
|
24
|
+
this.#say = say;
|
|
25
|
+
this.#now = now;
|
|
26
|
+
}
|
|
27
|
+
failed(err) {
|
|
28
|
+
this.#failures++;
|
|
29
|
+
const error = messageOf(err);
|
|
30
|
+
if (error === this.#last && this.#now() - this.#saidAt < quiet) {
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
this.#say('warn', 'background work failed', {
|
|
34
|
+
work: this.#work,
|
|
35
|
+
error,
|
|
36
|
+
failures: this.#failures,
|
|
37
|
+
});
|
|
38
|
+
this.#last = error;
|
|
39
|
+
this.#saidAt = this.#now();
|
|
40
|
+
}
|
|
41
|
+
succeeded() {
|
|
42
|
+
if (this.#failures > 0) {
|
|
43
|
+
this.#say('info', 'background work recovered', {
|
|
44
|
+
work: this.#work,
|
|
45
|
+
failures: this.#failures,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
this.#last = '';
|
|
49
|
+
this.#failures = 0;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The lines a logger dropped for want of room, said at a flush and at most
|
|
54
|
+
* once in a quiet period: a burst is one line, and a logger that keeps
|
|
55
|
+
* dropping says how many every ten minutes rather than every second.
|
|
56
|
+
*/
|
|
57
|
+
export class DropNotice {
|
|
58
|
+
#stream;
|
|
59
|
+
#buffer;
|
|
60
|
+
#say;
|
|
61
|
+
#now;
|
|
62
|
+
#unsaid = 0;
|
|
63
|
+
#saidAt;
|
|
64
|
+
constructor(stream, buffer, say, now = Date.now) {
|
|
65
|
+
this.#stream = stream;
|
|
66
|
+
this.#buffer = buffer;
|
|
67
|
+
this.#say = say;
|
|
68
|
+
this.#now = now;
|
|
69
|
+
}
|
|
70
|
+
dropped() {
|
|
71
|
+
this.#unsaid++;
|
|
72
|
+
}
|
|
73
|
+
sayIfDue() {
|
|
74
|
+
if (this.#unsaid === 0) {
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (this.#saidAt !== undefined && this.#now() - this.#saidAt < quiet) {
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
// logger, since a console line's own stream is tinystore's
|
|
81
|
+
this.#say('warn', 'log lines dropped', {
|
|
82
|
+
logger: this.#stream,
|
|
83
|
+
dropped: this.#unsaid,
|
|
84
|
+
buffer: this.#buffer,
|
|
85
|
+
});
|
|
86
|
+
this.#unsaid = 0;
|
|
87
|
+
this.#saidAt = this.#now();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** An error's message, as Go's err.Error() reads, without the class JavaScript puts first. */
|
|
91
|
+
export function messageOf(err) {
|
|
92
|
+
return err instanceof Error ? err.message : String(err);
|
|
93
|
+
}
|