@holz/idb-backend 0.0.0-stage → 0.11.2-rc.10.sha-159a74e
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 +21 -0
- package/README.md +153 -2
- package/dist/database.d.ts +6 -0
- package/dist/database.js +6 -0
- package/dist/define-database-B2tYqa5-.d.ts +48 -0
- package/dist/holz-idb-backend.d.ts +47 -0
- package/dist/holz-idb-backend.js +83 -0
- package/dist/open-gzb3NeIz.js +44 -0
- package/package.json +59 -4
- package/src/database/connect.ts +87 -0
- package/src/database/define-database.ts +37 -0
- package/src/database/delete-database.ts +6 -0
- package/src/database/external.ts +2 -0
- package/src/database/insert.ts +69 -0
- package/src/database/internal.ts +8 -0
- package/src/database/migrations.ts +41 -0
- package/src/database/open.ts +76 -0
- package/src/database/promise.ts +36 -0
- package/src/idb-backend.ts +134 -0
- package/src/index.ts +8 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Jesse Gibson
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,154 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@holz/idb-backend`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Stream logs into [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/Window/indexedDB). Many instances can write to the same database, including [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) and [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API).
|
|
4
|
+
|
|
5
|
+
> [!CAUTION]
|
|
6
|
+
> This package is experimental and unstable. It is not ready for production.
|
|
7
|
+
|
|
8
|
+
## Examples
|
|
9
|
+
|
|
10
|
+
- **Multi-process o11y:** Aggregate events across tabs, processes, and PWAs without coordinating.
|
|
11
|
+
- **Offline cache:** Persist logs and retry upload until it's successful.
|
|
12
|
+
- **Error context:** Query recent logs as breadcrumbs in a bug report.
|
|
13
|
+
- **Crash debugging:** See what happened before a tab crashed or reloaded.
|
|
14
|
+
- **Local-first apps:** Stream to storage as though it's a log file in a desktop app.
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
```typescript
|
|
19
|
+
import { createLogger } from '@holz/core';
|
|
20
|
+
import { createIdbBackend, defineDatabase } from '@holz/idb-backend';
|
|
21
|
+
|
|
22
|
+
const { close, flush, processor } = createIdbBackend({
|
|
23
|
+
batch: { size: 50 },
|
|
24
|
+
retain: 10_000,
|
|
25
|
+
onError: console.error,
|
|
26
|
+
|
|
27
|
+
// OPTIONAL: Configure where logs are stored along with custom indexes.
|
|
28
|
+
db: defineDatabase('@holz', 'logs', (migrations) => migrations),
|
|
29
|
+
|
|
30
|
+
// OPTIONAL: Limit how many logs queue while waiting for the DB to open.
|
|
31
|
+
buffer: { capacity: 1_000 },
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
const logger = createLogger(processor);
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Options
|
|
38
|
+
|
|
39
|
+
- `batch.size`: How many logs make a full batch.
|
|
40
|
+
- `retain`: Max number of logs to keep. See [Retention](#retention).
|
|
41
|
+
- `onError`: Receives errors, such as a database that fails to open or a log that can't be serialized.
|
|
42
|
+
- `buffer.capacity` (optional): How many logs to hold while the database opens. Unbounded by default. Once full, new logs overwrite the oldest.
|
|
43
|
+
- `db` (optional): Where logs are persisted. See [Customizing the Database](#customizing-the-database). Defaults to the `logs` table in the `@holz` database.
|
|
44
|
+
|
|
45
|
+
## Batching and Close Events
|
|
46
|
+
|
|
47
|
+
Logs persist in batches. If the process or tab closes before a batch is filled, **pending logs will be lost**.
|
|
48
|
+
|
|
49
|
+
Guard the case by detecting a closing page and explicitly flushing the queue:
|
|
50
|
+
|
|
51
|
+
```typescript
|
|
52
|
+
document.addEventListener('visibilitychange', () => {
|
|
53
|
+
if (document.visibilityState === 'hidden') flush();
|
|
54
|
+
});
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Flushing only writes the pending batch. Logs still waiting for the database to open are lost if the page closes first.
|
|
58
|
+
|
|
59
|
+
This only works for the main thread. Web Workers have no close signal and need to be messaged.
|
|
60
|
+
|
|
61
|
+
Service Workers are harder: they can terminate at any time. Consider setting batch size to `1` (write immediately) or accept the potential data loss.
|
|
62
|
+
|
|
63
|
+
## Retention
|
|
64
|
+
|
|
65
|
+
`retain` controls the maximum number of stored logs. When the count hits the limit, the oldest logs are pruned. Pruning follows write order, which may not match timestamp order.
|
|
66
|
+
|
|
67
|
+
Choose `Infinity` to manage pruning behavior manually.
|
|
68
|
+
|
|
69
|
+
## Customizing the Database
|
|
70
|
+
|
|
71
|
+
Use `defineDatabase(name, table)` to choose where logs go:
|
|
72
|
+
|
|
73
|
+
```typescript
|
|
74
|
+
import { createIdbBackend, defineDatabase } from '@holz/idb-backend';
|
|
75
|
+
|
|
76
|
+
const backend = createIdbBackend({
|
|
77
|
+
db: defineDatabase('my-app', 'logs'),
|
|
78
|
+
// ...
|
|
79
|
+
});
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Multiple backends may share one database, as long as they agree on its definition.
|
|
83
|
+
|
|
84
|
+
### Migrations
|
|
85
|
+
|
|
86
|
+
This plugin only persists logs. It makes no assumptions about how they're queried.
|
|
87
|
+
|
|
88
|
+
To create a custom index, extend the list of default migrations.
|
|
89
|
+
|
|
90
|
+
> [!WARNING]
|
|
91
|
+
> Be careful: this can break the database.
|
|
92
|
+
>
|
|
93
|
+
> - Never reorder or remove migrations that shipped to clients.
|
|
94
|
+
> - Always anchor custom migrations against `name` so future migrations apply in the correct order.
|
|
95
|
+
|
|
96
|
+
```typescript
|
|
97
|
+
const descriptor = defineDatabase('@holz', 'logs', (migrations) => {
|
|
98
|
+
return migrations.flatMap((migration) => {
|
|
99
|
+
if (migration.name !== 'init') return migration;
|
|
100
|
+
|
|
101
|
+
return [
|
|
102
|
+
migration,
|
|
103
|
+
{
|
|
104
|
+
name: 'index-by-timestamp',
|
|
105
|
+
run: (tx) => {
|
|
106
|
+
tx.objectStore('logs').createIndex('by-timestamp', 'timestamp');
|
|
107
|
+
},
|
|
108
|
+
},
|
|
109
|
+
];
|
|
110
|
+
});
|
|
111
|
+
});
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
The primary object store is owned by this plugin. Anything else (indexes, other object stores) is fair game.
|
|
115
|
+
|
|
116
|
+
> [!NOTE]
|
|
117
|
+
> Tabs still running an older release reconnect after an upgrade and use the new schema as-is. That means writes **must be compatible across versions**.
|
|
118
|
+
|
|
119
|
+
## Reading Logs
|
|
120
|
+
|
|
121
|
+
Logs are stored as structured clones of `Log` objects with auto-incrementing keys, so standard IndexedDB APIs work.
|
|
122
|
+
|
|
123
|
+
A helper opens the database at its current version, applying any missing migrations, or accepting a newer schema from another tab:
|
|
124
|
+
|
|
125
|
+
```typescript
|
|
126
|
+
import { openDatabase } from '@holz/idb-backend/database';
|
|
127
|
+
|
|
128
|
+
const db = await openDatabase(descriptor);
|
|
129
|
+
const logs = await new Promise((resolve, reject) => {
|
|
130
|
+
const request = db.transaction('logs').objectStore('logs').getAll();
|
|
131
|
+
|
|
132
|
+
request.onsuccess = () => resolve(request.result);
|
|
133
|
+
request.onerror = () => reject(request.error);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
db.close();
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Close the connection promptly. While open, it blocks other tabs from upgrading or deleting the database.
|
|
140
|
+
|
|
141
|
+
For complex work, the [`wrap(...)` from idb](https://www.npmjs.com/package/idb#wrap) provides a better API.
|
|
142
|
+
|
|
143
|
+
## Wiping the Database
|
|
144
|
+
|
|
145
|
+
Helpful in browser tests. This helper is effectively a thin promise wrapper over [indexedDB.deleteDatabase](https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory/deleteDatabase).
|
|
146
|
+
|
|
147
|
+
```typescript
|
|
148
|
+
import { deleteDatabase } from '@holz/idb-backend/database';
|
|
149
|
+
|
|
150
|
+
// Delete the logs database.
|
|
151
|
+
await deleteDatabase('@holz');
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
Note: a live backend reconnects as soon as the database is deleted, which recreates it empty. Call `close()` first to stop it.
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { n as DatabaseDefinition } from "./define-database-B2tYqa5-.js";
|
|
2
|
+
/** A thin promise wrapper over `indexedDB.deleteDatabase`. */
|
|
3
|
+
export declare const deleteDatabase: (name: string) => Promise<void>;
|
|
4
|
+
/** Open at the version `migrations` implies, or any newer one a peer left. */
|
|
5
|
+
declare const openCurrent: (db: DatabaseDefinition) => Promise<IDBDatabase>;
|
|
6
|
+
export { openCurrent as openDatabase };
|
package/dist/database.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The list of migrations can be extended by package consumers. They must have
|
|
3
|
+
* a stable position, otherwise schemas become corrupted. The version would no
|
|
4
|
+
* longer reflect applied migrations.
|
|
5
|
+
*
|
|
6
|
+
* Names provide a stable identifier to anchor custom steps. For example: add
|
|
7
|
+
* index for a custom field, positioned after `init`. If this library ships
|
|
8
|
+
* a new migration, the anchor preserves the correct version and order.
|
|
9
|
+
*
|
|
10
|
+
* So, names are important. Depending on how consumers insert, a type error on
|
|
11
|
+
* a misspelled name could be the difference between a simple fix and database
|
|
12
|
+
* corruption.
|
|
13
|
+
*/
|
|
14
|
+
type MigrationNames = "init";
|
|
15
|
+
/** One step in the schema's history. */
|
|
16
|
+
interface Migration<Name extends string = string> {
|
|
17
|
+
/** Stable identifier consumers can use to position their own migrations. */
|
|
18
|
+
name: Name;
|
|
19
|
+
/**
|
|
20
|
+
* Moves the schema forward by one version. The transaction is shared by all
|
|
21
|
+
* migrations via the `upgradeneeded` event.
|
|
22
|
+
*
|
|
23
|
+
* Note: for safety, thrown errors abort the upgrade, including uncommitted
|
|
24
|
+
* migrations applied earlier in the transaction.
|
|
25
|
+
*/
|
|
26
|
+
run: (transaction: IDBTransaction) => void;
|
|
27
|
+
}
|
|
28
|
+
/** Where logs are persisted, and how that database's schema evolves. */
|
|
29
|
+
interface DatabaseDefinition {
|
|
30
|
+
/** Database name. */
|
|
31
|
+
name: string;
|
|
32
|
+
/** Object store logs land in. */
|
|
33
|
+
table: string;
|
|
34
|
+
/** Every migration, oldest first. A migration's position is its version. */
|
|
35
|
+
migrations: Migration[];
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Customize the schema's migrations, e.g. to add your own. Receives the
|
|
39
|
+
* defaults, oldest first, and returns the full list. A migration's position is
|
|
40
|
+
* its version, so never reorder or remove one that has shipped.
|
|
41
|
+
*/
|
|
42
|
+
type CustomizeMigrations = (defaults: Migration<MigrationNames>[]) => Migration[];
|
|
43
|
+
/**
|
|
44
|
+
* Define a log database: its name, the object store logs land in, and,
|
|
45
|
+
* optionally, changes to its default migrations.
|
|
46
|
+
*/
|
|
47
|
+
declare const defineDatabase: (name: string, table: string, customize?: CustomizeMigrations) => DatabaseDefinition;
|
|
48
|
+
export { Migration as i, DatabaseDefinition as n, defineDatabase as r, CustomizeMigrations as t };
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { i as Migration, n as DatabaseDefinition, r as defineDatabase, t as CustomizeMigrations } from "./define-database-B2tYqa5-.js";
|
|
2
|
+
import { LogBatcherOptions, LogBufferOptions } from "@holz/core/functions";
|
|
3
|
+
import { LogProcessor } from "@holz/core";
|
|
4
|
+
/** Options for {@link createIdbBackend}. */
|
|
5
|
+
interface IdbBackendConfig {
|
|
6
|
+
/**
|
|
7
|
+
* Where logs are persisted, from {@link defineDatabase}. Defaults to the
|
|
8
|
+
* `logs` table in the `@holz` database.
|
|
9
|
+
*/
|
|
10
|
+
db?: DatabaseDefinition;
|
|
11
|
+
/** Holds logs while the database opens. Unlimited by default. */
|
|
12
|
+
buffer?: LogBufferOptions;
|
|
13
|
+
/** Groups logs into batches, each written in a single transaction. */
|
|
14
|
+
batch: Pick<LogBatcherOptions, "size">;
|
|
15
|
+
/**
|
|
16
|
+
* Max number of logs to retain. Discards the earliest written first, which
|
|
17
|
+
* may not be the earliest timestamp.
|
|
18
|
+
*/
|
|
19
|
+
retain: number;
|
|
20
|
+
/**
|
|
21
|
+
* Receives errors from the backend, such as a database that fails to open.
|
|
22
|
+
* Report them however suits your app. For example, pass `console.error`.
|
|
23
|
+
*/
|
|
24
|
+
onError: (error: unknown) => void;
|
|
25
|
+
}
|
|
26
|
+
/** A backend created by {@link createIdbBackend}. */
|
|
27
|
+
interface IdbBackend {
|
|
28
|
+
/** Install this in your logging pipeline. */
|
|
29
|
+
processor: LogProcessor;
|
|
30
|
+
/**
|
|
31
|
+
* Write the pending batch now, without waiting for it to fill. Call this
|
|
32
|
+
* when the app may stop soon, such as when the page is hidden. Logs still
|
|
33
|
+
* waiting on the database to open aren't written.
|
|
34
|
+
*/
|
|
35
|
+
flush: () => void;
|
|
36
|
+
/**
|
|
37
|
+
* Write any pending batch, then disconnect from the database and discard all
|
|
38
|
+
* logs from then on.
|
|
39
|
+
*/
|
|
40
|
+
close: () => void;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Create the holz backend. Holds logs until the database opens, and discards
|
|
44
|
+
* them if it can't.
|
|
45
|
+
*/
|
|
46
|
+
export declare const createIdbBackend: ({ db, batch: batchOptions, buffer: bufferOptions, retain, onError }: IdbBackendConfig) => IdbBackend;
|
|
47
|
+
export { type CustomizeMigrations, type DatabaseDefinition, type IdbBackend, type IdbBackendConfig, type Migration, defineDatabase };
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { r as e, t } from "./open-gzb3NeIz.js";
|
|
2
|
+
import { createBatcher as n, createBuffer as r, createRouter as i } from "@holz/core/functions";
|
|
3
|
+
// src/database/connect.ts
|
|
4
|
+
var a = (e) => {
|
|
5
|
+
let n = !1, r = null, i = () => {
|
|
6
|
+
n || t(e.db).then((t) => {
|
|
7
|
+
if (n) return t.close();
|
|
8
|
+
t.onclose = t.onversionchange = o, e.onChange(r = t);
|
|
9
|
+
}).catch((t) => {
|
|
10
|
+
n || (s(), e.onError(t));
|
|
11
|
+
});
|
|
12
|
+
}, a = () => {
|
|
13
|
+
r && (r.onclose = r.onversionchange = null, r.close(), e.onChange(r = null));
|
|
14
|
+
}, o = () => {
|
|
15
|
+
a(), i();
|
|
16
|
+
}, s = () => {
|
|
17
|
+
n = !0, a();
|
|
18
|
+
};
|
|
19
|
+
return i(), s;
|
|
20
|
+
}, o = async (t, n, { db: { table: r }, retain: i }) => {
|
|
21
|
+
let a = t.transaction(r, "readwrite", { durability: "relaxed" }), o = a.objectStore(r), s = [], c = n.flatMap((e) => {
|
|
22
|
+
try {
|
|
23
|
+
return [o.add(e)];
|
|
24
|
+
} catch (e) {
|
|
25
|
+
return s.push(e), [];
|
|
26
|
+
}
|
|
27
|
+
}).at(-1);
|
|
28
|
+
c && (c.onsuccess = () => {
|
|
29
|
+
let e = c.result;
|
|
30
|
+
o.delete(IDBKeyRange.upperBound(e - i));
|
|
31
|
+
});
|
|
32
|
+
try {
|
|
33
|
+
await e(a);
|
|
34
|
+
} catch (e) {
|
|
35
|
+
s.push(e);
|
|
36
|
+
}
|
|
37
|
+
if (s.length === 1) throw s[0];
|
|
38
|
+
if (s.length > 1) throw AggregateError(s, "Some logs could not be saved.");
|
|
39
|
+
}, s = (e) => [{
|
|
40
|
+
name: "init",
|
|
41
|
+
run: (t) => void t.db.createObjectStore(e, { autoIncrement: !0 })
|
|
42
|
+
}], c = (e, t, n = (e) => e) => ({
|
|
43
|
+
name: e,
|
|
44
|
+
table: t,
|
|
45
|
+
migrations: n(s(t))
|
|
46
|
+
}), l = ({ db: e = c("@holz", "logs"), batch: t, buffer: s, retain: l, onError: u }) => {
|
|
47
|
+
let d = null, f = (t) => {
|
|
48
|
+
o(d, t, {
|
|
49
|
+
db: e,
|
|
50
|
+
retain: l
|
|
51
|
+
}).catch(u);
|
|
52
|
+
}, p = n({
|
|
53
|
+
...t,
|
|
54
|
+
sink: f
|
|
55
|
+
}), { clear: m, processor: h } = r(s), { select: g, processor: _ } = i("buffer", {
|
|
56
|
+
buffer: h,
|
|
57
|
+
db: p.processor,
|
|
58
|
+
noop: () => {}
|
|
59
|
+
}), v = () => {
|
|
60
|
+
g("noop"), p.clear(), m();
|
|
61
|
+
}, y = a({
|
|
62
|
+
db: e,
|
|
63
|
+
onChange: (e) => {
|
|
64
|
+
if (d = e, g(d ? "db" : "buffer"), d) {
|
|
65
|
+
let e = m();
|
|
66
|
+
e.length && f(e);
|
|
67
|
+
} else p.clear().forEach(h);
|
|
68
|
+
},
|
|
69
|
+
onError: (e) => {
|
|
70
|
+
v(), u(e);
|
|
71
|
+
}
|
|
72
|
+
}), b = () => {
|
|
73
|
+
d && p.flush();
|
|
74
|
+
};
|
|
75
|
+
return {
|
|
76
|
+
processor: _,
|
|
77
|
+
flush: b,
|
|
78
|
+
close: () => {
|
|
79
|
+
b(), y(), v();
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
};
|
|
83
|
+
export { l as createIdbBackend, c as defineDatabase };
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// src/database/promise.ts
|
|
2
|
+
var e = (e) => {
|
|
3
|
+
let { promise: t, resolve: n, reject: r } = Promise.withResolvers();
|
|
4
|
+
return e.onsuccess = () => n(e.result), e.onerror = () => {
|
|
5
|
+
let t = e.error ?? Error("IndexedDB request failed.", { cause: e });
|
|
6
|
+
r(t);
|
|
7
|
+
}, t;
|
|
8
|
+
}, t = (e) => {
|
|
9
|
+
let { promise: t, resolve: n, reject: r } = Promise.withResolvers();
|
|
10
|
+
return e.oncomplete = () => n(), e.onabort = () => {
|
|
11
|
+
let t = e.error ?? Error("IndexedDB transaction aborted.", { cause: e });
|
|
12
|
+
r(t);
|
|
13
|
+
}, t;
|
|
14
|
+
}, n = async ({ name: t, migrations: n }) => {
|
|
15
|
+
let r = indexedDB.open(t, n.length), i;
|
|
16
|
+
r.onupgradeneeded = (e) => {
|
|
17
|
+
try {
|
|
18
|
+
n.slice(e.oldVersion).forEach((e) => e.run(r.transaction));
|
|
19
|
+
} catch (e) {
|
|
20
|
+
i = e, r.transaction?.abort();
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
try {
|
|
24
|
+
return await e(r);
|
|
25
|
+
} catch (e) {
|
|
26
|
+
throw i ?? e;
|
|
27
|
+
}
|
|
28
|
+
}, r = ({ name: t }) => {
|
|
29
|
+
let n = indexedDB.open(t);
|
|
30
|
+
return n.onupgradeneeded = () => n.transaction?.abort(), e(n);
|
|
31
|
+
}, i = async (e) => {
|
|
32
|
+
try {
|
|
33
|
+
return await n(e);
|
|
34
|
+
} catch (e) {
|
|
35
|
+
if (!a(e, "VersionError")) throw e;
|
|
36
|
+
}
|
|
37
|
+
try {
|
|
38
|
+
return await r(e);
|
|
39
|
+
} catch (e) {
|
|
40
|
+
if (!a(e, "AbortError")) throw e;
|
|
41
|
+
}
|
|
42
|
+
return i(e);
|
|
43
|
+
}, a = (e, t) => e instanceof DOMException && e.name === t;
|
|
44
|
+
export { e as n, t as r, i as t };
|
package/package.json
CHANGED
|
@@ -1,6 +1,61 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@holz/idb-backend",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.11.2-rc.10.sha-159a74e",
|
|
4
|
+
"description": "Persist logs to IndexedDB.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/PsychoLlama/holz",
|
|
9
|
+
"directory": "packages/holz-idb-backend"
|
|
10
|
+
},
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"source": "./src/index.ts",
|
|
14
|
+
"types": "./dist/holz-idb-backend.d.ts",
|
|
15
|
+
"default": "./dist/holz-idb-backend.js"
|
|
16
|
+
},
|
|
17
|
+
"./database": {
|
|
18
|
+
"source": "./src/database/external.ts",
|
|
19
|
+
"types": "./dist/database.d.ts",
|
|
20
|
+
"default": "./dist/database.js"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public",
|
|
25
|
+
"timeout": 60000
|
|
26
|
+
},
|
|
27
|
+
"author": "Jesse Gibson",
|
|
28
|
+
"license": "MIT",
|
|
29
|
+
"sideEffects": false,
|
|
30
|
+
"files": [
|
|
31
|
+
"dist",
|
|
32
|
+
"src",
|
|
33
|
+
"!src/**/__tests__"
|
|
34
|
+
],
|
|
35
|
+
"keywords": [
|
|
36
|
+
"holz-backend",
|
|
37
|
+
"indexeddb",
|
|
38
|
+
"structured",
|
|
39
|
+
"logging"
|
|
40
|
+
],
|
|
41
|
+
"scripts": {
|
|
42
|
+
"prepack": "vite build",
|
|
43
|
+
"test:unit": "vitest run --color --passWithNoTests",
|
|
44
|
+
"test:coverage": "vitest run --coverage --color --passWithNoTests",
|
|
45
|
+
"test:types": "tsc"
|
|
46
|
+
},
|
|
47
|
+
"peerDependencies": {
|
|
48
|
+
"@holz/core": "^0.11.0"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@holz/core": "^0.11.2-rc.10.sha-159a74e",
|
|
52
|
+
"@vitest/browser-playwright": "^5.0.0",
|
|
53
|
+
"@vitest/coverage-v8": "^5.0.0",
|
|
54
|
+
"playwright": "^1.65.0",
|
|
55
|
+
"rolldown-plugin-dts": "^0.30.0",
|
|
56
|
+
"typescript": "^6.0.0",
|
|
57
|
+
"vite": "^8.0.0",
|
|
58
|
+
"vitest": "^5.0.0"
|
|
59
|
+
},
|
|
60
|
+
"gitHead": "159a74e011f8b2eaa6b809fe19f3ce5142b11516"
|
|
61
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type { DatabaseDefinition } from './define-database';
|
|
2
|
+
import { openCurrent } from './open';
|
|
3
|
+
|
|
4
|
+
/** Options for {@link connect}. */
|
|
5
|
+
export interface ConnectConfig {
|
|
6
|
+
/**
|
|
7
|
+
* Database to stay connected to. Its migrations apply whenever a connection
|
|
8
|
+
* finds it behind.
|
|
9
|
+
*/
|
|
10
|
+
db: DatabaseDefinition;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Receives each new connection, then `null` when it goes away. Start no
|
|
14
|
+
* transactions after `null`, and leave closing to {@link connect}.
|
|
15
|
+
*/
|
|
16
|
+
onChange: (database: IDBDatabase | null) => void;
|
|
17
|
+
|
|
18
|
+
/** Receives whatever stops the connection for good. Nothing retries after. */
|
|
19
|
+
onError: (error: unknown) => void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Stay connected to a database for as long as possible. Gives up the connection
|
|
24
|
+
* when another context needs to upgrade or delete the database, or when the
|
|
25
|
+
* browser closes it. A new connection follows unless reopening fails.
|
|
26
|
+
*
|
|
27
|
+
* A database already past its migrations is used as it stands, on the assumption
|
|
28
|
+
* that newer versions stay compatible.
|
|
29
|
+
*
|
|
30
|
+
* Returns a function that closes the connection for good. An open already
|
|
31
|
+
* underway still applies its migrations, but its outcome is ignored.
|
|
32
|
+
*/
|
|
33
|
+
export const connect = (config: ConnectConfig): (() => void) => {
|
|
34
|
+
let terminated = false;
|
|
35
|
+
let current: IDBDatabase | null = null;
|
|
36
|
+
|
|
37
|
+
const attach = () => {
|
|
38
|
+
if (terminated) return;
|
|
39
|
+
|
|
40
|
+
openCurrent(config.db)
|
|
41
|
+
.then((db) => {
|
|
42
|
+
// Request canceled while opening.
|
|
43
|
+
if (terminated) return db.close();
|
|
44
|
+
|
|
45
|
+
// Release and reconnect if:
|
|
46
|
+
// - We're blocking a new migration (assumes version is compatible)
|
|
47
|
+
// - The DB was deleted or closed unexpectedly.
|
|
48
|
+
//
|
|
49
|
+
// Note: `close()` waits for in-flight transactions.
|
|
50
|
+
db.onclose = db.onversionchange = reconnect;
|
|
51
|
+
|
|
52
|
+
// Successfully connected.
|
|
53
|
+
config.onChange((current = db));
|
|
54
|
+
})
|
|
55
|
+
.catch((error: unknown) => {
|
|
56
|
+
if (terminated) return;
|
|
57
|
+
|
|
58
|
+
// A throwing `onChange` leaves a live connection behind.
|
|
59
|
+
terminate();
|
|
60
|
+
config.onError(error);
|
|
61
|
+
});
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const disconnect = () => {
|
|
65
|
+
// Already closed.
|
|
66
|
+
if (!current) return;
|
|
67
|
+
|
|
68
|
+
// Late events from a released connection must not disturb the next one.
|
|
69
|
+
current.onclose = current.onversionchange = null;
|
|
70
|
+
current.close();
|
|
71
|
+
config.onChange((current = null));
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const reconnect = () => {
|
|
75
|
+
disconnect();
|
|
76
|
+
attach();
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const terminate = () => {
|
|
80
|
+
terminated = true;
|
|
81
|
+
disconnect();
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
attach();
|
|
85
|
+
|
|
86
|
+
return terminate;
|
|
87
|
+
};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { getMigrations } from './migrations';
|
|
2
|
+
import type { Migration, MigrationNames } from './migrations';
|
|
3
|
+
|
|
4
|
+
/** Where logs are persisted, and how that database's schema evolves. */
|
|
5
|
+
export interface DatabaseDefinition {
|
|
6
|
+
/** Database name. */
|
|
7
|
+
name: string;
|
|
8
|
+
|
|
9
|
+
/** Object store logs land in. */
|
|
10
|
+
table: string;
|
|
11
|
+
|
|
12
|
+
/** Every migration, oldest first. A migration's position is its version. */
|
|
13
|
+
migrations: Migration[];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Customize the schema's migrations, e.g. to add your own. Receives the
|
|
18
|
+
* defaults, oldest first, and returns the full list. A migration's position is
|
|
19
|
+
* its version, so never reorder or remove one that has shipped.
|
|
20
|
+
*/
|
|
21
|
+
export type CustomizeMigrations = (
|
|
22
|
+
defaults: Migration<MigrationNames>[],
|
|
23
|
+
) => Migration[];
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Define a log database: its name, the object store logs land in, and,
|
|
27
|
+
* optionally, changes to its default migrations.
|
|
28
|
+
*/
|
|
29
|
+
export const defineDatabase = (
|
|
30
|
+
name: string,
|
|
31
|
+
table: string,
|
|
32
|
+
customize: CustomizeMigrations = (defaults) => defaults,
|
|
33
|
+
): DatabaseDefinition => ({
|
|
34
|
+
name,
|
|
35
|
+
table,
|
|
36
|
+
migrations: customize(getMigrations(table)),
|
|
37
|
+
});
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import type { Log } from '@holz/core';
|
|
2
|
+
|
|
3
|
+
import type { DatabaseDefinition } from './define-database';
|
|
4
|
+
import { promisifyTransaction } from './promise';
|
|
5
|
+
|
|
6
|
+
/** Options for {@link insert}. */
|
|
7
|
+
export interface InsertOptions {
|
|
8
|
+
/** Database whose object store to write to. */
|
|
9
|
+
db: DatabaseDefinition;
|
|
10
|
+
|
|
11
|
+
/** Max number of logs to keep. Discards the earliest written first. */
|
|
12
|
+
retain: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Write a batch of logs in a single transaction, then discard the oldest
|
|
17
|
+
* until at most `retain` remain. Saves every log it can. Resolves once the
|
|
18
|
+
* transaction commits, or rejects with every failure: the error itself if
|
|
19
|
+
* there's one, or an `AggregateError` if there are more.
|
|
20
|
+
*/
|
|
21
|
+
export const insert = async (
|
|
22
|
+
database: IDBDatabase,
|
|
23
|
+
logs: Log[],
|
|
24
|
+
{ db: { table }, retain }: InsertOptions,
|
|
25
|
+
): Promise<void> => {
|
|
26
|
+
const transaction = database.transaction(table, 'readwrite', {
|
|
27
|
+
// Minor perf: flush on the OS's schedule. Don't force fsync.
|
|
28
|
+
durability: 'relaxed',
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
const store = transaction.objectStore(table);
|
|
32
|
+
const errors: unknown[] = [];
|
|
33
|
+
|
|
34
|
+
// `add` throws on logs it can't save (e.g. uncloneable). Skip them so the
|
|
35
|
+
// rest still land. Best-effort persistence assumes well-structured logs.
|
|
36
|
+
const requests = logs.flatMap((log) => {
|
|
37
|
+
try {
|
|
38
|
+
return [store.add(log)];
|
|
39
|
+
} catch (error) {
|
|
40
|
+
errors.push(error);
|
|
41
|
+
return [];
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
// Keys auto-increment, so the newest `retain` logs sit at or above
|
|
46
|
+
// `lastKey - retain + 1`. Gaps in the keys (e.g. rows deleted by hand) only
|
|
47
|
+
// ever leave fewer than `retain`, never more.
|
|
48
|
+
const last = requests.at(-1);
|
|
49
|
+
|
|
50
|
+
// Undefined if every log failed to serialize. Nothing was added, so there's
|
|
51
|
+
// nothing to prune.
|
|
52
|
+
if (last) {
|
|
53
|
+
last.onsuccess = () => {
|
|
54
|
+
const lastKey = last.result as number;
|
|
55
|
+
store.delete(IDBKeyRange.upperBound(lastKey - retain));
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
try {
|
|
60
|
+
await promisifyTransaction(transaction);
|
|
61
|
+
} catch (error) {
|
|
62
|
+
errors.push(error);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (errors.length === 1) throw errors[0];
|
|
66
|
+
if (errors.length > 1) {
|
|
67
|
+
throw new AggregateError(errors, 'Some logs could not be saved.');
|
|
68
|
+
}
|
|
69
|
+
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { connect } from './connect';
|
|
2
|
+
export { insert } from './insert';
|
|
3
|
+
export { defineDatabase } from './define-database';
|
|
4
|
+
export type {
|
|
5
|
+
CustomizeMigrations,
|
|
6
|
+
DatabaseDefinition,
|
|
7
|
+
} from './define-database';
|
|
8
|
+
export type { Migration } from './migrations';
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The list of migrations can be extended by package consumers. They must have
|
|
3
|
+
* a stable position, otherwise schemas become corrupted. The version would no
|
|
4
|
+
* longer reflect applied migrations.
|
|
5
|
+
*
|
|
6
|
+
* Names provide a stable identifier to anchor custom steps. For example: add
|
|
7
|
+
* index for a custom field, positioned after `init`. If this library ships
|
|
8
|
+
* a new migration, the anchor preserves the correct version and order.
|
|
9
|
+
*
|
|
10
|
+
* So, names are important. Depending on how consumers insert, a type error on
|
|
11
|
+
* a misspelled name could be the difference between a simple fix and database
|
|
12
|
+
* corruption.
|
|
13
|
+
*/
|
|
14
|
+
export type MigrationNames = 'init';
|
|
15
|
+
|
|
16
|
+
/** One step in the schema's history. */
|
|
17
|
+
export interface Migration<Name extends string = string> {
|
|
18
|
+
/** Stable identifier consumers can use to position their own migrations. */
|
|
19
|
+
name: Name;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Moves the schema forward by one version. The transaction is shared by all
|
|
23
|
+
* migrations via the `upgradeneeded` event.
|
|
24
|
+
*
|
|
25
|
+
* Note: for safety, thrown errors abort the upgrade, including uncommitted
|
|
26
|
+
* migrations applied earlier in the transaction.
|
|
27
|
+
*/
|
|
28
|
+
run: (transaction: IDBTransaction) => void;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Every schema migration, oldest first. A migration's position determines its
|
|
33
|
+
* version: index 0 upgrades to v1. Append only.
|
|
34
|
+
*/
|
|
35
|
+
export const getMigrations = (table: string): Migration<MigrationNames>[] => [
|
|
36
|
+
{
|
|
37
|
+
name: 'init',
|
|
38
|
+
run: (transaction) =>
|
|
39
|
+
void transaction.db.createObjectStore(table, { autoIncrement: true }),
|
|
40
|
+
},
|
|
41
|
+
];
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { DatabaseDefinition } from './define-database';
|
|
2
|
+
import { promisifyRequest } from './promise';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Open a database at the version implied by `migrations`, applying any it
|
|
6
|
+
* hasn't seen. Rejects if the open fails or the database is already past that
|
|
7
|
+
* version. If a migration throws, rejects with its error and rolls back every
|
|
8
|
+
* migration in the upgrade.
|
|
9
|
+
*/
|
|
10
|
+
export const openOrUpgrade = async ({
|
|
11
|
+
name,
|
|
12
|
+
migrations,
|
|
13
|
+
}: DatabaseDefinition): Promise<IDBDatabase> => {
|
|
14
|
+
const request = indexedDB.open(name, migrations.length);
|
|
15
|
+
let migrationError: unknown;
|
|
16
|
+
|
|
17
|
+
request.onupgradeneeded = (event) => {
|
|
18
|
+
try {
|
|
19
|
+
migrations
|
|
20
|
+
.slice(event.oldVersion)
|
|
21
|
+
.forEach((migration) => migration.run(request.transaction!));
|
|
22
|
+
} catch (error) {
|
|
23
|
+
// Left uncaught, the browser still aborts the upgrade, but the error
|
|
24
|
+
// escapes to the global scope and the request fails with `AbortError`.
|
|
25
|
+
migrationError = error;
|
|
26
|
+
request.transaction?.abort();
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
try {
|
|
31
|
+
return await promisifyRequest(request);
|
|
32
|
+
} catch (error) {
|
|
33
|
+
// Wait for the request to fail so the rollback is done before rejecting.
|
|
34
|
+
throw migrationError ?? error;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Open a database at its current version, without migrating it. Rejects with an
|
|
40
|
+
* `AbortError` and creates nothing if the database doesn't exist.
|
|
41
|
+
*/
|
|
42
|
+
export const openExisting = ({
|
|
43
|
+
name,
|
|
44
|
+
}: DatabaseDefinition): Promise<IDBDatabase> => {
|
|
45
|
+
const request = indexedDB.open(name);
|
|
46
|
+
|
|
47
|
+
// Only fires when there's no database, and this would leave an empty one.
|
|
48
|
+
request.onupgradeneeded = () => request.transaction?.abort();
|
|
49
|
+
|
|
50
|
+
return promisifyRequest(request);
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
/** Open at the version `migrations` implies, or any newer one a peer left. */
|
|
54
|
+
export const openCurrent = async (
|
|
55
|
+
db: DatabaseDefinition,
|
|
56
|
+
): Promise<IDBDatabase> => {
|
|
57
|
+
try {
|
|
58
|
+
// Init, migrate, or open existing at current version.
|
|
59
|
+
return await openOrUpgrade(db);
|
|
60
|
+
} catch (error) {
|
|
61
|
+
if (!hasErrorName(error, 'VersionError')) throw error;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
try {
|
|
65
|
+
// Open at a version beyond what our code knows about.
|
|
66
|
+
return await openExisting(db);
|
|
67
|
+
} catch (error) {
|
|
68
|
+
if (!hasErrorName(error, 'AbortError')) throw error;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Extreme edge case: future version deleted before we could open it.
|
|
72
|
+
return openCurrent(db);
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const hasErrorName = (error: unknown, name: string): boolean =>
|
|
76
|
+
error instanceof DOMException && error.name === name;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** Resolves with the request's result, or rejects with its error. */
|
|
2
|
+
export const promisifyRequest = <T>(request: IDBRequest<T>): Promise<T> => {
|
|
3
|
+
const { promise, resolve, reject } = Promise.withResolvers<T>();
|
|
4
|
+
|
|
5
|
+
request.onsuccess = () => resolve(request.result);
|
|
6
|
+
request.onerror = () => {
|
|
7
|
+
const error =
|
|
8
|
+
request.error ??
|
|
9
|
+
new Error('IndexedDB request failed.', { cause: request });
|
|
10
|
+
|
|
11
|
+
reject(error);
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
return promise;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
/** Resolves once the transaction commits, or rejects if it aborts. */
|
|
18
|
+
export const promisifyTransaction = (
|
|
19
|
+
transaction: IDBTransaction,
|
|
20
|
+
): Promise<void> => {
|
|
21
|
+
const { promise, resolve, reject } = Promise.withResolvers<void>();
|
|
22
|
+
|
|
23
|
+
transaction.oncomplete = () => resolve();
|
|
24
|
+
|
|
25
|
+
// Every failure ends here, including requests that fail and writes that
|
|
26
|
+
// exceed the storage quota at commit.
|
|
27
|
+
transaction.onabort = () => {
|
|
28
|
+
const error =
|
|
29
|
+
transaction.error ??
|
|
30
|
+
new Error('IndexedDB transaction aborted.', { cause: transaction });
|
|
31
|
+
|
|
32
|
+
reject(error);
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
return promise;
|
|
36
|
+
};
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import type { Log, LogProcessor } from '@holz/core';
|
|
2
|
+
import {
|
|
3
|
+
createBatcher,
|
|
4
|
+
createBuffer,
|
|
5
|
+
createRouter,
|
|
6
|
+
} from '@holz/core/functions';
|
|
7
|
+
import type { LogBatcherOptions, LogBufferOptions } from '@holz/core/functions';
|
|
8
|
+
|
|
9
|
+
import { connect, defineDatabase, insert } from './database/internal';
|
|
10
|
+
import type { DatabaseDefinition } from './database/internal';
|
|
11
|
+
|
|
12
|
+
/** Options for {@link createIdbBackend}. */
|
|
13
|
+
export interface IdbBackendConfig {
|
|
14
|
+
/**
|
|
15
|
+
* Where logs are persisted, from {@link defineDatabase}. Defaults to the
|
|
16
|
+
* `logs` table in the `@holz` database.
|
|
17
|
+
*/
|
|
18
|
+
db?: DatabaseDefinition;
|
|
19
|
+
|
|
20
|
+
/** Holds logs while the database opens. Unlimited by default. */
|
|
21
|
+
buffer?: LogBufferOptions;
|
|
22
|
+
|
|
23
|
+
/** Groups logs into batches, each written in a single transaction. */
|
|
24
|
+
batch: Pick<LogBatcherOptions, 'size'>;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Max number of logs to retain. Discards the earliest written first, which
|
|
28
|
+
* may not be the earliest timestamp.
|
|
29
|
+
*/
|
|
30
|
+
retain: number;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Receives errors from the backend, such as a database that fails to open.
|
|
34
|
+
* Report them however suits your app. For example, pass `console.error`.
|
|
35
|
+
*/
|
|
36
|
+
onError: (error: unknown) => void;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** A backend created by {@link createIdbBackend}. */
|
|
40
|
+
export interface IdbBackend {
|
|
41
|
+
/** Install this in your logging pipeline. */
|
|
42
|
+
processor: LogProcessor;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Write the pending batch now, without waiting for it to fill. Call this
|
|
46
|
+
* when the app may stop soon, such as when the page is hidden. Logs still
|
|
47
|
+
* waiting on the database to open aren't written.
|
|
48
|
+
*/
|
|
49
|
+
flush: () => void;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Write any pending batch, then disconnect from the database and discard all
|
|
53
|
+
* logs from then on.
|
|
54
|
+
*/
|
|
55
|
+
close: () => void;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Create the holz backend. Holds logs until the database opens, and discards
|
|
60
|
+
* them if it can't.
|
|
61
|
+
*/
|
|
62
|
+
export const createIdbBackend = ({
|
|
63
|
+
db = defineDatabase('@holz', 'logs'),
|
|
64
|
+
batch: batchOptions,
|
|
65
|
+
buffer: bufferOptions,
|
|
66
|
+
retain,
|
|
67
|
+
onError,
|
|
68
|
+
}: IdbBackendConfig): IdbBackend => {
|
|
69
|
+
let connection: IDBDatabase | null = null;
|
|
70
|
+
|
|
71
|
+
// Called when:
|
|
72
|
+
// - DB (re)connects with buffered logs.
|
|
73
|
+
// - Batch size is met.
|
|
74
|
+
// - Explicitly flushed or closed.
|
|
75
|
+
//
|
|
76
|
+
// Caller responsible for ensuring a live connection before invocation.
|
|
77
|
+
const write = (logs: Log[]) => {
|
|
78
|
+
insert(connection!, logs, { db, retain }).catch(onError);
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
const batch = createBatcher({ ...batchOptions, sink: write });
|
|
82
|
+
|
|
83
|
+
const { clear: clearBuffer, processor: buffer } = createBuffer(bufferOptions);
|
|
84
|
+
const { select, processor: router } = createRouter('buffer', {
|
|
85
|
+
buffer, // Queue while connecting.
|
|
86
|
+
db: batch.processor, // Persist to IndexedDB.
|
|
87
|
+
noop: () => {}, // Terminal state. Drops logs.
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
const discardAndYield = () => {
|
|
91
|
+
select('noop'); // Ignore future logs.
|
|
92
|
+
batch.clear(); // Clear pending batch.
|
|
93
|
+
clearBuffer(); // Clear queued logs.
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const disconnect = connect({
|
|
97
|
+
db,
|
|
98
|
+
|
|
99
|
+
// May invoke multiple times. Handle is released and re-acquired if new
|
|
100
|
+
// tabs/processes have new migrations, if the DB is deleted, or if the
|
|
101
|
+
// browser closes it (e.g. storage was cleared).
|
|
102
|
+
onChange: (next) => {
|
|
103
|
+
connection = next;
|
|
104
|
+
select(connection ? 'db' : 'buffer');
|
|
105
|
+
|
|
106
|
+
if (connection) {
|
|
107
|
+
const buffered = clearBuffer();
|
|
108
|
+
if (buffered.length) write(buffered);
|
|
109
|
+
} else {
|
|
110
|
+
// Move uncommitted logs to the buffer.
|
|
111
|
+
batch.clear().forEach(buffer);
|
|
112
|
+
}
|
|
113
|
+
},
|
|
114
|
+
|
|
115
|
+
// Unrecoverable error. Give up and sinkhole future logs.
|
|
116
|
+
onError: (error) => {
|
|
117
|
+
discardAndYield();
|
|
118
|
+
onError(error);
|
|
119
|
+
},
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
// Batches only fill while connected, so there's nothing to write otherwise.
|
|
123
|
+
const flush = () => {
|
|
124
|
+
if (connection) batch.flush();
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
const close = () => {
|
|
128
|
+
flush();
|
|
129
|
+
disconnect();
|
|
130
|
+
discardAndYield();
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
return { processor: router, flush, close };
|
|
134
|
+
};
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { createIdbBackend } from './idb-backend';
|
|
2
|
+
export type { IdbBackend, IdbBackendConfig } from './idb-backend';
|
|
3
|
+
export { defineDatabase } from './database/internal';
|
|
4
|
+
export type {
|
|
5
|
+
CustomizeMigrations,
|
|
6
|
+
DatabaseDefinition,
|
|
7
|
+
Migration,
|
|
8
|
+
} from './database/internal';
|