Lifecycle Events
Hook into store lifecycle events for logging, monitoring, and custom side effects.
Overview
Persist emits lifecycle events at key points during store operations. You can subscribe to these events for logging, monitoring, metrics, or triggering side effects.
Subscribing to events
import { createStore } from "@cuitty/persist";
const store = await createStore("my-app", {
adapter: "sqlite",
path: "./data/my-app.db",
});
store.on("record:put", (event) => {
console.log(`Record written: ${event.key}`);
});
store.on("sync:complete", (event) => {
console.log(`Sync finished: pushed ${event.pushed}, pulled ${event.pulled}`);
});
Record events
| Event | Payload | Fired when |
|---|---|---|
record:put | { key, value, version } | A record is written |
record:delete | { key } | A record is deleted |
record:conflict | { key, local, remote } | A sync conflict is detected |
record:resolve | { key, resolution } | A conflict is resolved |
Event stream events
| Event | Payload | Fired when |
|---|---|---|
event:append | { stream, payload, id } | An event is appended |
event:prune | { stream, count } | Events are pruned by retention policy |
Blob events
| Event | Payload | Fired when |
|---|---|---|
blob:put | { key, size } | A blob is written |
blob:delete | { key } | A blob is deleted |
blob:upload:progress | { key, loaded, total } | Multipart upload progress |
Sync events
| Event | Payload | Fired when |
|---|---|---|
sync:start | { remote } | A sync cycle begins |
sync:complete | { pushed, pulled, conflicts } | A sync cycle finishes |
sync:error | { error, remote } | A sync cycle fails |
sync:offline | {} | Connectivity is lost |
sync:online | {} | Connectivity is restored |
Key management events
| Event | Payload | Fired when |
|---|---|---|
key:rotation:due | { daysUntilExpiry } | KEK is approaching rotation threshold |
key:rotated | { algorithm } | KEK rotation completed |
Unsubscribing
The on method returns an unsubscribe function:
const off = store.on("record:put", handler);
// Later, stop listening
off();
Wildcard listeners
Subscribe to all events from a category using a wildcard:
store.on("record:*", (event) => {
console.log(`Record event: ${event.type}`, event);
});
store.on("sync:*", (event) => {
// Log all sync events to an external service
telemetry.track(event.type, event);
});
Error handling in handlers
Event handlers are called synchronously. If a handler throws, the error is caught and emitted as an error event. Store operations are never interrupted by handler failures.
store.on("error", (err) => {
console.error("Event handler error:", err);
});