tero 0.0.6 → 0.0.8
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 +242 -224
- package/dist/acid-engine.d.ts +229 -13
- package/dist/acid-engine.js +772 -293
- package/dist/backup.d.ts +31 -0
- package/dist/backup.js +137 -15
- package/dist/index.d.ts +189 -2
- package/dist/index.js +517 -52
- package/dist/recovery.d.ts +14 -0
- package/dist/recovery.js +107 -20
- package/package.json +6 -2
package/README.md
CHANGED
|
@@ -1,347 +1,365 @@
|
|
|
1
1
|
# Tero
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
[
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
- **
|
|
18
|
-
- **
|
|
19
|
-
- **
|
|
20
|
-
- **
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
-
|
|
26
|
-
-
|
|
27
|
-
-
|
|
28
|
-
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
## Installation
|
|
3
|
+
An embedded ACID JSON database for the edge. Single-node durability via fsync-on-commit; cloud durability via S3/R2/GCS storage.
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
[edge Tero node] --WAL+snapshot--> [S3/R2/GCS bucket]
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Tero is a **library**, not a service. You embed it in a worker, container, or edge runtime. There is no clustering, no Raft, no distributed consensus — by design. Durability and scale come from cheap object storage, the same pattern Litestream pioneered for SQLite.
|
|
10
|
+
|
|
11
|
+
## What it is
|
|
12
|
+
|
|
13
|
+
- **Embedded JSON document DB** with key/value + batch operations
|
|
14
|
+
- **Real ACID**: WAL with fsync barriers on COMMIT/ROLLBACK, atomic data-file writes (temp → rename → fsync), in-memory pending-writes index so transaction reads never re-scan the WAL
|
|
15
|
+
- **WAL rotation** into archive segments — backs up WAL segments and snapshots to object storage
|
|
16
|
+
- **Schema validation** with strict mode (string/number/boolean/object/array/date/any, formats, enums, defaults, custom validators)
|
|
17
|
+
- **Cloud backup** to AWS S3 or Cloudflare R2 (cron-scheduled), archive or individual-file format
|
|
18
|
+
- **Cloud recovery** — full, single-file, or archive restore
|
|
19
|
+
- **v2: hydrate on startup** — pull missing or all files from object storage before the ACID engine initializes to reconstruct node state
|
|
20
|
+
- **v2: bucket backup** — one-shot snapshot of all data files + retained WAL segments + a manifest that hydrate-on-startup can discover
|
|
21
|
+
- **Per-instance cloud credentials** — each Tero instance manages its own storage credentials directly
|
|
22
|
+
|
|
23
|
+
## What it is not
|
|
24
|
+
|
|
25
|
+
- Not a server. No HTTP layer, no wire protocol. You embed it.
|
|
26
|
+
- Not distributed. No multi-node consensus. Global durability is the bucket's job.
|
|
27
|
+
- Not a query engine. Key/value + batch. No SQL, no indexes beyond the in-memory cache.
|
|
28
|
+
- Not horizontally scalable beyond one node's filesystem. One file per document puts a practical ceiling around 10⁵–10⁶ docs per node; the bucket is what scales.
|
|
29
|
+
|
|
30
|
+
These are deliberate design choices to keep Tero lightweight and fast inside edge worker runtimes while using object storage for global durability.
|
|
31
|
+
|
|
32
|
+
## Install
|
|
34
33
|
|
|
35
34
|
```bash
|
|
36
35
|
npm install tero
|
|
37
36
|
```
|
|
38
37
|
|
|
39
|
-
##
|
|
38
|
+
## Quick start
|
|
40
39
|
|
|
41
40
|
```javascript
|
|
42
41
|
import { Tero } from 'tero';
|
|
43
42
|
|
|
44
|
-
// Initialize database
|
|
45
43
|
const db = new Tero({
|
|
46
44
|
directory: './mydata',
|
|
47
|
-
cacheSize: 1000
|
|
45
|
+
cacheSize: 1000,
|
|
48
46
|
});
|
|
49
47
|
|
|
50
|
-
// Basic operations
|
|
51
48
|
await db.create('user1', { name: 'Alice', email: 'alice@example.com' });
|
|
52
49
|
const user = await db.get('user1');
|
|
53
50
|
await db.update('user1', { age: 30 });
|
|
54
51
|
await db.remove('user1');
|
|
55
52
|
```
|
|
56
53
|
|
|
57
|
-
## ACID
|
|
58
|
-
|
|
59
|
-
### Automatic Transactions
|
|
60
|
-
All basic operations are automatically wrapped in ACID transactions:
|
|
61
|
-
|
|
62
|
-
```javascript
|
|
63
|
-
// These operations are automatically ACID-compliant
|
|
64
|
-
await db.create('account', { balance: 1000 });
|
|
65
|
-
await db.update('account', { balance: 1500 });
|
|
66
|
-
```
|
|
54
|
+
## ACID transactions
|
|
67
55
|
|
|
68
|
-
|
|
69
|
-
For complex operations requiring multiple steps:
|
|
56
|
+
Every convenience method (`create`, `get`, `update`, `remove`) is auto-wrapped in a transaction. For multi-step operations, use explicit transactions:
|
|
70
57
|
|
|
71
58
|
```javascript
|
|
72
|
-
const
|
|
59
|
+
const tx = db.beginTransaction();
|
|
73
60
|
|
|
74
61
|
try {
|
|
75
|
-
await db.write(
|
|
76
|
-
await db.write(
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
const account1 = await db.read(txId, 'account1');
|
|
80
|
-
|
|
81
|
-
await db.commit(txId);
|
|
62
|
+
await db.write(tx, 'account1', { balance: 900 });
|
|
63
|
+
await db.write(tx, 'account2', { balance: 1100 });
|
|
64
|
+
const a = await db.read(tx, 'account1'); // reads pending state within the tx
|
|
65
|
+
await db.commit(tx);
|
|
82
66
|
} catch (error) {
|
|
83
|
-
await db.rollback(
|
|
67
|
+
await db.rollback(tx);
|
|
84
68
|
throw error;
|
|
85
69
|
}
|
|
86
70
|
```
|
|
87
71
|
|
|
88
|
-
|
|
89
|
-
Demonstrates ACID properties with business logic:
|
|
72
|
+
The money-transfer example demonstrates atomicity: `db.transferMoney('savings', 'checking', 500)` — both balances update or neither does, with the writer held to a durable commit before control returns.
|
|
90
73
|
|
|
91
|
-
|
|
92
|
-
// Atomic money transfer with validation
|
|
93
|
-
await db.transferMoney('savings', 'checking', 500);
|
|
94
|
-
```
|
|
74
|
+
### Durability guarantee
|
|
95
75
|
|
|
96
|
-
|
|
76
|
+
A `commit()` returns only after the WAL `COMMIT` record and all pending writes have been fsynced to disk. A crash after `commit()` returns cannot lose the transaction. A crash mid-`commit()` leaves either the old or new state on disk, never a partial of either — data files are written via temp-file → fsync → atomic rename.
|
|
97
77
|
|
|
98
|
-
|
|
78
|
+
## Schema validation
|
|
99
79
|
|
|
100
80
|
```javascript
|
|
101
|
-
// Set schema
|
|
102
81
|
db.setSchema('users', {
|
|
103
|
-
name:
|
|
82
|
+
name: { type: 'string', required: true, min: 2, max: 50 },
|
|
104
83
|
email: { type: 'string', required: true, format: 'email' },
|
|
105
|
-
age:
|
|
84
|
+
age: { type: 'number', min: 0, max: 150 },
|
|
106
85
|
profile: {
|
|
107
86
|
type: 'object',
|
|
108
87
|
properties: {
|
|
109
|
-
bio:
|
|
110
|
-
website: { type: 'string', format: 'url' }
|
|
111
|
-
}
|
|
112
|
-
}
|
|
88
|
+
bio: { type: 'string', max: 500 },
|
|
89
|
+
website: { type: 'string', format: 'url' },
|
|
90
|
+
},
|
|
91
|
+
},
|
|
113
92
|
});
|
|
114
93
|
|
|
115
|
-
|
|
116
|
-
await db.create('user1', userData, {
|
|
117
|
-
validate: true,
|
|
118
|
-
schemaName: 'users',
|
|
119
|
-
strict: true
|
|
120
|
-
});
|
|
94
|
+
await db.create('user1', userData, { validate: true, schemaName: 'users', strict: true });
|
|
121
95
|
```
|
|
122
96
|
|
|
123
|
-
|
|
97
|
+
Field types: `string`, `number`, `boolean`, `object`, `array`, `date`, `any`.
|
|
98
|
+
Validation options: `required`, `min`, `max`, `format` (email/url/uuid/date/time/datetime/phone/ip), `pattern`, `enum`, `default`, `custom`.
|
|
124
99
|
|
|
125
|
-
|
|
100
|
+
## Batch operations
|
|
126
101
|
|
|
127
102
|
```javascript
|
|
128
|
-
// Batch write
|
|
129
103
|
await db.batchWrite([
|
|
130
|
-
{ key: 'product1', data: { name: 'Laptop',
|
|
131
|
-
{ key: 'product2', data: { name: 'Mouse',
|
|
132
|
-
{ key: 'product3', data: { name: 'Keyboard', price: 79.99 } }
|
|
104
|
+
{ key: 'product1', data: { name: 'Laptop', price: 999.99 } },
|
|
105
|
+
{ key: 'product2', data: { name: 'Mouse', price: 29.99 } },
|
|
106
|
+
{ key: 'product3', data: { name: 'Keyboard', price: 79.99 } },
|
|
133
107
|
]);
|
|
134
108
|
|
|
135
|
-
// Batch read
|
|
136
109
|
const products = await db.batchRead(['product1', 'product2', 'product3']);
|
|
137
110
|
```
|
|
138
111
|
|
|
139
|
-
##
|
|
140
|
-
|
|
141
|
-
Configure automatic cloud backups:
|
|
112
|
+
## Cloud backup
|
|
142
113
|
|
|
143
114
|
```javascript
|
|
144
115
|
db.configureBackup({
|
|
145
|
-
format: 'archive',
|
|
116
|
+
format: 'archive', // or 'individual' for per-file backups
|
|
146
117
|
cloudStorage: {
|
|
147
118
|
provider: 'aws-s3',
|
|
148
119
|
region: 'us-east-1',
|
|
149
120
|
bucket: 'my-backup-bucket',
|
|
150
121
|
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
|
|
151
|
-
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
|
|
122
|
+
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
|
|
152
123
|
},
|
|
153
|
-
retention: '30d'
|
|
124
|
+
retention: '30d',
|
|
154
125
|
});
|
|
155
126
|
|
|
156
|
-
// Perform backup
|
|
157
127
|
const result = await db.performBackup();
|
|
128
|
+
const scheduleId = db.scheduleBackup({ interval: '6h', retention: '7d' });
|
|
129
|
+
db.cancelScheduledBackup(scheduleId);
|
|
158
130
|
```
|
|
159
131
|
|
|
160
|
-
|
|
132
|
+
Tero interacts directly with object storage from each instance, keeping credentials local and isolated.
|
|
133
|
+
|
|
134
|
+
📊 **Cost comparison:** see [BUCKET_COST_DATA.md](./BUCKET_COST_DATA.md) for AWS S3 vs Cloudflare R2 pricing (verified 2026-08-28), how backup operations map to billed requests, and monthly cost scenarios.
|
|
161
135
|
|
|
162
|
-
|
|
136
|
+
## Cloud recovery
|
|
163
137
|
|
|
164
138
|
```javascript
|
|
165
|
-
// Configure data recovery
|
|
166
139
|
db.configureDataRecovery({
|
|
167
140
|
cloudStorage: cloudConfig,
|
|
168
|
-
localPath: './mydata'
|
|
141
|
+
localPath: './mydata',
|
|
142
|
+
autoRecover: true,
|
|
169
143
|
});
|
|
170
144
|
|
|
171
|
-
//
|
|
172
|
-
await db.
|
|
173
|
-
|
|
174
|
-
//
|
|
175
|
-
const result = await db.recoverAllFromCloud();
|
|
145
|
+
await db.recoverFromCloud('important-data'); // one file
|
|
146
|
+
const result = await db.recoverAllFromCloud(); // all files
|
|
147
|
+
const archives = await db.listAvailableArchives(); // discover tar.gz backups
|
|
148
|
+
const info = await db.getRecoveryInfo(); // local vs cloud diff
|
|
176
149
|
```
|
|
177
150
|
|
|
178
|
-
##
|
|
151
|
+
## v2: hydrate on startup
|
|
179
152
|
|
|
180
|
-
|
|
153
|
+
`Tero.create()` is the async factory that pulls missing/all files from object storage **before** the ACID engine runs crash recovery — so a fresh node boots with the latest durable state.
|
|
181
154
|
|
|
182
155
|
```javascript
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
//
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
email: 'alice@example.com',
|
|
192
|
-
createdAt: new Date()
|
|
156
|
+
const db = await Tero.create({
|
|
157
|
+
directory: './mydata',
|
|
158
|
+
hydrateOnStartup: {
|
|
159
|
+
cloudStorage: cloudConfig,
|
|
160
|
+
mode: 'missing', // 'all' overwrites local; 'missing' only pulls absent files
|
|
161
|
+
continueOnError: true, // don't block boot on a single failed download
|
|
162
|
+
timeout: 30000,
|
|
163
|
+
},
|
|
193
164
|
});
|
|
194
165
|
|
|
195
|
-
//
|
|
196
|
-
|
|
197
|
-
await db.
|
|
198
|
-
level: 'info',
|
|
199
|
-
message: 'User created',
|
|
200
|
-
userId: userId
|
|
201
|
-
});
|
|
166
|
+
// Or run hydration any time after construction:
|
|
167
|
+
db.configureDataRecovery({ cloudStorage: cloudConfig, localPath: './mydata' });
|
|
168
|
+
await db.hydrate({ mode: 'missing' });
|
|
202
169
|
```
|
|
203
170
|
|
|
204
|
-
|
|
171
|
+
Hydration is non-fatal by design: an unreachable or misconfigured bucket will not block engine startup. The local filesystem remains the source of truth.
|
|
205
172
|
|
|
206
|
-
|
|
173
|
+
## v2: bucket backup with WAL segments
|
|
174
|
+
|
|
175
|
+
`backupToBucket()` snapshots every data JSON file plus any retained WAL archive segments and writes a manifest the hydrate path can discover:
|
|
176
|
+
|
|
177
|
+
```javascript
|
|
178
|
+
const result = await db.backupToBucket({ tag: 'hourly-snapshot' });
|
|
179
|
+
// result: { success, uploadedDataFiles, uploadedWALSegments, duration, errors }
|
|
180
|
+
|
|
181
|
+
// Force a fresh WAL archive segment first, then back it up:
|
|
182
|
+
await db.checkpointAndBackupToBucket({ tag: 'post-burst' });
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
This enables point-in-time recovery: rotate the WAL into a new immutable segment, push it to object storage, and a rehydrated node can replay from that segment forward.
|
|
186
|
+
|
|
187
|
+
## v2: read with cloud fallback
|
|
207
188
|
|
|
208
189
|
```javascript
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
190
|
+
const data = await db.getWithRecovery('maybe-missing');
|
|
191
|
+
// returns the document from local or, if absent locally, fetches from the bucket.
|
|
192
|
+
// returns false if absent on both sides. does not throw on cloud failure —
|
|
193
|
+
// use recoverFromCloud() if you need to see those errors.
|
|
213
194
|
|
|
214
|
-
|
|
195
|
+
const probe = await db.existsWithCloudCheck('user1');
|
|
196
|
+
// { local: true, cloud: true, canRecover: false }
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
## Unique ID generation
|
|
200
|
+
|
|
201
|
+
MongoDB ObjectId-style identifiers, unique across processes and time:
|
|
202
|
+
|
|
203
|
+
```javascript
|
|
204
|
+
const userId = db.getNewId('user'); // user-507f1f77bcf86cd799439011
|
|
205
|
+
const orderId = db.getNewId('order'); // order-507f1f77bcf86cd799439012
|
|
206
|
+
await db.create(userId, { name: 'Alice' });
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
Composition: 4-byte timestamp + 5-byte process-unique random + 3-byte incrementing counter.
|
|
210
|
+
|
|
211
|
+
## Monitoring
|
|
212
|
+
|
|
213
|
+
```javascript
|
|
214
|
+
const cache = db.getCacheStats(); // { size, maxSize, hitRate }
|
|
215
|
+
const tx = db.getTransactionStats(); // { active, committed, rolledBack, total }
|
|
215
216
|
const integrity = await db.verifyDataIntegrity();
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
217
|
+
// { totalFiles, corruptedFiles, missingFiles, healthy }
|
|
218
|
+
const active = db.getActiveTransactions();
|
|
219
|
+
db.forceCheckpoint(); // flush a CHECKPOINT into the WAL
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
## Architecture
|
|
219
223
|
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
224
|
+
```
|
|
225
|
+
Tero instance (one per process)
|
|
226
|
+
├── ACIDStorageEngine
|
|
227
|
+
│ ├── WriteAheadLog ─── append-only, fsync on barriers, rotates to archive segments
|
|
228
|
+
│ ├── LockManager ─── per-key shared/exclusive locks with wait queue
|
|
229
|
+
│ └── pendingWrites ─── in-memory per-transaction op index (O(1) reads within a tx)
|
|
230
|
+
├── SchemaValidator
|
|
231
|
+
├── BackupManager ─── cron-scheduled snapshot + WAL segment upload to object storage
|
|
232
|
+
└── DataRecovery ─── hydrate-on-startup + runtime getWithRecovery
|
|
223
233
|
```
|
|
224
234
|
|
|
225
|
-
## Error Handling
|
|
226
235
|
|
|
227
|
-
|
|
236
|
+
## Error handling
|
|
228
237
|
|
|
229
238
|
```javascript
|
|
230
239
|
try {
|
|
231
240
|
await db.create('user', invalidData, { validate: true, strict: true });
|
|
232
241
|
} catch (error) {
|
|
233
|
-
if (error.message.includes('Schema validation failed')) {
|
|
234
|
-
|
|
235
|
-
} else if (error.message.includes('already exists')) {
|
|
236
|
-
// Handle duplicate key error
|
|
237
|
-
}
|
|
242
|
+
if (error.message.includes('Schema validation failed')) { /* validation error */ }
|
|
243
|
+
else if (error.message.includes('already exists')) { /* duplicate key */ }
|
|
238
244
|
}
|
|
239
245
|
```
|
|
240
246
|
|
|
241
|
-
|
|
247
|
+
Keys are validated to prevent path traversal (`..`, `/`, `\` are rejected).
|
|
248
|
+
|
|
249
|
+
## Configuration
|
|
242
250
|
|
|
243
|
-
### Database Options
|
|
244
251
|
```javascript
|
|
245
252
|
const db = new Tero({
|
|
246
|
-
directory: './data', //
|
|
247
|
-
cacheSize: 1000
|
|
253
|
+
directory: './data', // default: 'TeroDB'
|
|
254
|
+
cacheSize: 1000, // default: 100, capped at 1000
|
|
255
|
+
backup: { ... }, // optional: install a BackupConfig at construction
|
|
256
|
+
hydrateOnStartup: { ... }, // optional: v2 hydration before engine init
|
|
248
257
|
});
|
|
249
258
|
```
|
|
250
259
|
|
|
251
|
-
### Schema Field Types
|
|
252
|
-
- `string`: Text data with length and format validation
|
|
253
|
-
- `number`: Numeric data with range validation
|
|
254
|
-
- `boolean`: True/false values
|
|
255
|
-
- `object`: Nested objects with property schemas
|
|
256
|
-
- `array`: Arrays with item type validation
|
|
257
|
-
- `date`: Date/time values
|
|
258
|
-
- `any`: Any data type (no validation)
|
|
259
|
-
|
|
260
|
-
### Schema Validation Options
|
|
261
|
-
- `required`: Field is mandatory
|
|
262
|
-
- `min/max`: Length/value constraints
|
|
263
|
-
- `format`: Built-in formats (email, url, uuid, etc.)
|
|
264
|
-
- `pattern`: Regular expression validation
|
|
265
|
-
- `enum`: Allowed values list
|
|
266
|
-
- `default`: Default value if not provided
|
|
267
|
-
- `custom`: Custom validation function
|
|
268
|
-
|
|
269
|
-
### Optimization Tips
|
|
270
|
-
1. Use batch operations for multiple documents
|
|
271
|
-
2. Enable caching for frequently accessed data
|
|
272
|
-
3. Use schema validation to catch errors early
|
|
273
|
-
4. Monitor cache hit rates and adjust cache size
|
|
274
|
-
5. Use transactions for related operations
|
|
275
|
-
|
|
276
|
-
## Security
|
|
277
|
-
|
|
278
|
-
- **Path Traversal Protection**: Automatic key sanitization
|
|
279
|
-
- **Input Validation**: Comprehensive data validation
|
|
280
|
-
- **Error Handling**: No sensitive data in error messages
|
|
281
|
-
- **Access Control**: File system permissions respected
|
|
282
|
-
|
|
283
|
-
## API Reference
|
|
284
|
-
|
|
285
|
-
### Core Methods
|
|
286
|
-
- `create(key, data, options?)`: Create new document
|
|
287
|
-
- `get(key)`: Read document
|
|
288
|
-
- `update(key, data, options?)`: Update document
|
|
289
|
-
- `remove(key)`: Delete document
|
|
290
|
-
- `exists(key)`: Check if document exists
|
|
291
|
-
|
|
292
|
-
### Transaction Methods
|
|
293
|
-
- `beginTransaction()`: Start new transaction
|
|
294
|
-
- `write(txId, key, data, options?)`: Write in transaction
|
|
295
|
-
- `read(txId, key)`: Read in transaction
|
|
296
|
-
- `delete(txId, key)`: Delete in transaction
|
|
297
|
-
- `commit(txId)`: Commit transaction
|
|
298
|
-
- `rollback(txId)`: Rollback transaction
|
|
299
|
-
|
|
300
|
-
### Batch Methods
|
|
301
|
-
- `batchWrite(operations, options?)`: Batch write operations
|
|
302
|
-
- `batchRead(keys)`: Batch read operations
|
|
303
|
-
|
|
304
|
-
### Schema Methods
|
|
305
|
-
- `setSchema(name, schema)`: Define schema
|
|
306
|
-
- `getSchema(name)`: Get schema definition
|
|
307
|
-
- `removeSchema(name)`: Remove schema
|
|
308
|
-
- `validateData(name, data)`: Validate against schema
|
|
309
|
-
|
|
310
|
-
### Utility Methods
|
|
311
|
-
- `getCacheStats()`: Cache performance metrics
|
|
312
|
-
- `verifyDataIntegrity()`: Check data health
|
|
313
|
-
- `getActiveTransactions()`: List active transactions
|
|
314
|
-
- `forceCheckpoint()`: Force WAL flush
|
|
315
|
-
- `clearCache()`: Clear memory cache
|
|
316
|
-
- `getNewId(prefix)`: Generate unique identifiers with custom prefix
|
|
317
|
-
- `destroy()`: Cleanup and shutdown
|
|
318
|
-
|
|
319
260
|
## Testing
|
|
320
261
|
|
|
321
|
-
|
|
262
|
+
```bash
|
|
263
|
+
npm run build # tsc + full test suite
|
|
264
|
+
npm run test # full suite (includes the ~60s benchmark)
|
|
265
|
+
npm run test:production # ACID + schema + transactions + perf
|
|
266
|
+
npm run test:backup # backup + scheduling + retention
|
|
267
|
+
npm run test:schema # schema validation
|
|
268
|
+
npm run test:legacy # legacy suite
|
|
269
|
+
node local_tests/v2-test.js # v2: hydrate + bucket backup surface
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
### Testing S3 live backup locally (MinIO)
|
|
273
|
+
|
|
274
|
+
`npm run test:s3` round-trips the live backup API against a real S3-compatible
|
|
275
|
+
endpoint: live writes → `backupToBucket()` → `checkpointAndBackupToBucket()` →
|
|
276
|
+
raw bucket verification → hydrate-on-startup into a fresh node. Without
|
|
277
|
+
credentials it skips, so plain `npm test` stays green.
|
|
278
|
+
|
|
279
|
+
The cheapest way to exercise it is MinIO in Docker:
|
|
280
|
+
|
|
281
|
+
```bash
|
|
282
|
+
# 1. Start a local S3-compatible server
|
|
283
|
+
docker run -d --name tero-minio-test -p 9000:9000 -p 9001:9001 \
|
|
284
|
+
-v /tmp/tero-minio-data:/data \
|
|
285
|
+
minio/minio server /data --console-address ":9001"
|
|
286
|
+
|
|
287
|
+
# 2. Run the round-trip test (bucket is created if missing)
|
|
288
|
+
S3_ENDPOINT=http://127.0.0.1:9000 \
|
|
289
|
+
S3_BUCKET=tero-live-backup-test \
|
|
290
|
+
AWS_ACCESS_KEY_ID=minioadmin \
|
|
291
|
+
AWS_SECRET_ACCESS_KEY=minioadmin \
|
|
292
|
+
npm run test:s3
|
|
293
|
+
|
|
294
|
+
# 3. Inspect what Tero wrote (console at http://localhost:9001)
|
|
295
|
+
# s3://tero-live-backup-test/tero-backups/<dbName>/
|
|
296
|
+
# ├── <key>.json # data snapshots
|
|
297
|
+
# ├── wal/.wal.<ts> # archived WAL segments
|
|
298
|
+
# └── MANIFEST.json # hydration entry point
|
|
299
|
+
|
|
300
|
+
# 4. Clean up
|
|
301
|
+
docker rm -f tero-minio-test && rm -rf /tmp/tero-minio-data
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
Against real AWS, omit `S3_ENDPOINT` and pass an IAM user with
|
|
305
|
+
`s3:PutObject/GetObject/ListBucket/CreateBucket` on the test bucket:
|
|
322
306
|
|
|
323
307
|
```bash
|
|
324
|
-
|
|
308
|
+
S3_BUCKET=my-test-bucket \
|
|
309
|
+
AWS_ACCESS_KEY_ID=... \
|
|
310
|
+
AWS_SECRET_ACCESS_KEY=... \
|
|
311
|
+
npm run test:s3
|
|
325
312
|
```
|
|
326
313
|
|
|
314
|
+
## Performance characteristics
|
|
315
|
+
|
|
316
|
+
```
|
|
317
|
+
normal mode (recommended production — group commit 10ms + deferred data flush):
|
|
318
|
+
Single create: ~10,000–14,000 ops/s
|
|
319
|
+
Update (same key): ~51,000 ops/s
|
|
320
|
+
Batch (100 docs/tx): ~47,000 docs/s
|
|
321
|
+
Hot read (cached): ~1,000,000 ops/s
|
|
322
|
+
exists(): ~1,000,000 ops/s
|
|
323
|
+
|
|
324
|
+
full mode (fsync per commit — max durability):
|
|
325
|
+
Single create: ~45 ops/s
|
|
326
|
+
Batch (100 docs/tx): ~4,000 docs/s
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
- **synchronous: 'full'** (default) — fsync per commit. Max durability. Use when every commit must survive power loss.
|
|
330
|
+
- **synchronous: 'normal'** — group commit + deferred data flush. WAL is fsynced every 10ms (configurable via `commitIntervalMs`); data files checkpoint every 50ms (configurable via `dataFlushIntervalMs`). 200x+ throughput vs full mode. WAL sync window is up to 10ms of writes. This is the SQLite `PRAGMA synchronous=NORMAL` equivalent.
|
|
331
|
+
- **synchronous: 'off'** — never fsync. Testing/benchmark only.
|
|
332
|
+
|
|
333
|
+
Architecture:
|
|
334
|
+
- In-memory WAL write buffer — one `appendFileSync` per flush, not per entry
|
|
335
|
+
- FNV-1a hash for WAL integrity (100x faster than SHA-256 for small entries)
|
|
336
|
+
- Deferred data-file writes via `committedBuffer` + background timer (SQLite WAL-mode pattern)
|
|
337
|
+
- Transaction-free `get()` fast path: LRU cache → committedBuffer → disk (zero syscalls on cache hit)
|
|
338
|
+
- `knownKeys` Set replaces `existsSync()` on the hot path
|
|
339
|
+
- Per-tx `heldLocks` Set for O(1) lock release (was O(allLocks))
|
|
340
|
+
- Per-tx `txTouchedKeys` Set for O(touched) cache promotion (was O(cacheSize))
|
|
341
|
+
- Sync `commitTransaction()` / `rollbackTransaction()` — no async overhead on the happy path
|
|
342
|
+
- Lock manager returns `true` (sync) instead of `Promise` on the uncontended fast path
|
|
343
|
+
- WAL rotation at 1 MB or every 500 commits, keeping recovery replays bounded
|
|
344
|
+
|
|
345
|
+
This is single-node throughput, not cluster throughput. For higher write rates, run multiple Tero instances behind a sharding layer; each owns its own bucket and directory.
|
|
346
|
+
|
|
327
347
|
## License
|
|
328
348
|
|
|
329
|
-
MIT
|
|
349
|
+
MIT — see [LICENSE](./LICENSE).
|
|
330
350
|
|
|
331
|
-
##
|
|
351
|
+
## Contributing
|
|
332
352
|
|
|
333
|
-
1. Fork the
|
|
353
|
+
1. Fork the repo
|
|
334
354
|
2. Create a feature branch
|
|
335
|
-
3. Add tests for new functionality
|
|
336
|
-
4. Ensure
|
|
337
|
-
5.
|
|
355
|
+
3. Add tests in `local_tests/` for new functionality
|
|
356
|
+
4. Ensure `npm run build` is green
|
|
357
|
+
5. Open a pull request
|
|
338
358
|
|
|
339
|
-
##
|
|
359
|
+
## Support
|
|
340
360
|
|
|
341
|
-
|
|
342
|
-
- GitHub Issues: [Report bugs and request features](https://github.com/codedynasty-dev/tero/issues)
|
|
343
|
-
- Documentation: [Full API documentation](https://github.com/codedynasty-dev/tero/wiki)
|
|
361
|
+
- GitHub Issues: https://github.com/codedynasty-dev/tero/issues
|
|
344
362
|
|
|
345
363
|
---
|
|
346
364
|
|
|
347
|
-
**Tero**
|
|
365
|
+
**Tero** — embedded ACID JSON for the edge.
|