@hozon/store-log 0.0.0-stage → 0.1.0

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Paul Le Cam
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,17 @@
1
- # Temporary Holding Version
1
+ # @hozon/store-log
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Persistent structured log store with chronological queries, trace lookup, and retention.
4
+
5
+ ```sh
6
+ pnpm add @hozon/store-log @hozon/db
7
+ ```
8
+
9
+ ```ts
10
+ import { getLogStore, logStoreDefinition } from '@hozon/store-log'
11
+
12
+ db.register(logStoreDefinition)
13
+ const logs = await getLogStore(db)
14
+ await logs.addLogs([])
15
+ ```
16
+
17
+ See the [store reference](../../docs/reference/stores.md).
package/lib/api.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import type { Adapter } from '@hozon/adapter';
2
+ import type { Kysely } from 'kysely';
3
+ import type { LogTables } from './tables.js';
4
+ import type { LogStore } from './types.js';
5
+ export declare function createLogStoreAPI(db: Kysely<LogTables>, adapter: Adapter): LogStore;
package/lib/api.js ADDED
@@ -0,0 +1,124 @@
1
+ import { chunk, withKeepSet, withStoreTransaction } from '@hozon/db';
2
+ import { categoryRange, encodeCategory } from './category.js';
3
+ function encodeCursor(timestamp, seq) {
4
+ return btoa(JSON.stringify([
5
+ timestamp,
6
+ seq
7
+ ])).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
8
+ }
9
+ function decodeCursor(cursor) {
10
+ try {
11
+ const value = JSON.parse(atob(cursor.replaceAll('-', '+').replaceAll('_', '/')));
12
+ if (!Array.isArray(value) || value.length !== 2 || !value.every((item)=>typeof item === 'number' && Number.isFinite(item)) || !Number.isInteger(value[1])) {
13
+ throw new TypeError('Invalid log cursor');
14
+ }
15
+ return value;
16
+ } catch (cause) {
17
+ throw new TypeError('Invalid log cursor', {
18
+ cause
19
+ });
20
+ }
21
+ }
22
+ export function createLogStoreAPI(db, adapter) {
23
+ return {
24
+ async addLogs (logs) {
25
+ if (logs.length === 0) return;
26
+ // Validate and encode the whole input before writing any batch.
27
+ const rows = logs.map((log, index)=>{
28
+ if (log.traceID === undefined !== (log.spanID === undefined)) {
29
+ throw new TypeError(`Unpaired trace/span IDs at index ${index}`);
30
+ }
31
+ return {
32
+ timestamp: log.timestamp,
33
+ level: log.level,
34
+ category: encodeCategory(log.category),
35
+ trace_id: log.traceID ?? null,
36
+ span_id: log.spanID ?? null,
37
+ data: adapter.encodeJSON(log)
38
+ };
39
+ });
40
+ await withStoreTransaction(db, async (trx)=>{
41
+ for (const batch of chunk(rows, 71)){
42
+ await trx.insertInto('hozon_logs').values(batch).execute();
43
+ }
44
+ });
45
+ },
46
+ async queryLogs (params) {
47
+ if (!Number.isInteger(params.limit) || params.limit <= 0) throw new RangeError('Log limit must be a positive integer');
48
+ const limit = Math.min(params.limit, 1000);
49
+ let query = db.selectFrom('hozon_logs').select([
50
+ 'timestamp',
51
+ 'seq',
52
+ 'data'
53
+ ]);
54
+ if (params.from !== undefined) query = query.where('timestamp', '>=', params.from);
55
+ if (params.to !== undefined) query = query.where('timestamp', '<=', params.to);
56
+ if (params.levels !== undefined) {
57
+ if (params.levels.length === 0) return {
58
+ logs: []
59
+ };
60
+ query = query.where('level', 'in', [
61
+ ...new Set(params.levels)
62
+ ]);
63
+ }
64
+ if (params.categoryPrefix !== undefined && params.categoryPrefix.length > 0) {
65
+ const { gte, lt } = categoryRange(params.categoryPrefix);
66
+ query = query.where('category', '>=', gte).where('category', '<', lt);
67
+ }
68
+ if (params.traceID !== undefined) query = query.where('trace_id', '=', params.traceID);
69
+ if (params.cursor !== undefined) {
70
+ const [timestamp, seq] = decodeCursor(params.cursor);
71
+ query = query.where((eb)=>eb.or([
72
+ eb('timestamp', '>', timestamp),
73
+ eb.and([
74
+ eb('timestamp', '=', timestamp),
75
+ eb('seq', '>', seq)
76
+ ])
77
+ ]));
78
+ }
79
+ const rows = await query.orderBy('timestamp').orderBy('seq').limit(limit + 1).execute();
80
+ const page = rows.slice(0, limit);
81
+ const last = page.at(-1);
82
+ return {
83
+ logs: page.map((row)=>row.data),
84
+ ...rows.length > limit && last !== undefined ? {
85
+ cursor: encodeCursor(last.timestamp, last.seq)
86
+ } : {}
87
+ };
88
+ },
89
+ async getTraceLogs (traceID) {
90
+ const rows = await db.selectFrom('hozon_logs').select('data').where('trace_id', '=', traceID).orderBy('timestamp').orderBy('seq').execute();
91
+ // addLogs enforces paired IDs for every traced row.
92
+ return rows.map((row)=>row.data);
93
+ },
94
+ async deleteByTrace (traceIDs) {
95
+ if (traceIDs.length === 0) return 0;
96
+ return withStoreTransaction(db, async (trx)=>{
97
+ let count = 0;
98
+ for (const ids of chunk(traceIDs)){
99
+ const result = await trx.deleteFrom('hozon_logs').where('trace_id', 'in', ids).executeTakeFirstOrThrow();
100
+ count += Number(result.numDeletedRows);
101
+ }
102
+ return count;
103
+ });
104
+ },
105
+ async deleteBefore (time, params) {
106
+ return withStoreTransaction(db, async (trx)=>{
107
+ if (params?.keepTraceIDs === undefined || params.keepTraceIDs.length === 0) {
108
+ const result = await trx.deleteFrom('hozon_logs').where('timestamp', '<', time).executeTakeFirstOrThrow();
109
+ return Number(result.numDeletedRows);
110
+ }
111
+ return withKeepSet(trx, {
112
+ table: 'hozon_keep_log',
113
+ ids: params.keepTraceIDs
114
+ }, async (selectKeep)=>{
115
+ const result = await trx.deleteFrom('hozon_logs').where('timestamp', '<', time).where((eb)=>eb.or([
116
+ eb('trace_id', 'is', null),
117
+ eb('trace_id', 'not in', selectKeep())
118
+ ])).executeTakeFirstOrThrow();
119
+ return Number(result.numDeletedRows);
120
+ });
121
+ });
122
+ }
123
+ };
124
+ }
@@ -0,0 +1,5 @@
1
+ export declare function encodeCategory(segments: Array<string>): string;
2
+ export declare function categoryRange(prefix: Array<string>): {
3
+ gte: string;
4
+ lt: string;
5
+ };
@@ -0,0 +1,15 @@
1
+ const SEPARATOR = '\u001f';
2
+ export function encodeCategory(segments) {
3
+ for (const segment of segments){
4
+ if (segment.includes(SEPARATOR)) throw new TypeError('Category segment contains \\u001f');
5
+ }
6
+ return segments.length === 0 ? '' : `${segments.join(SEPARATOR)}${SEPARATOR}`;
7
+ }
8
+ export function categoryRange(prefix) {
9
+ const gte = encodeCategory(prefix);
10
+ // Advance the final separator, so every descendant sorts below the upper bound.
11
+ return {
12
+ gte,
13
+ lt: `${gte.slice(0, -1)} `
14
+ };
15
+ }
@@ -0,0 +1,6 @@
1
+ import type { StoreDefinition, StoreProvider } from '@hozon/db';
2
+ import type { LogTables } from './tables.js';
3
+ import type { LogStore } from './types.js';
4
+ export declare const LOG_STORE = "log";
5
+ export declare const logStoreDefinition: StoreDefinition<LogTables, LogStore>;
6
+ export declare function getLogStore(provider: StoreProvider): Promise<LogStore>;
@@ -0,0 +1,11 @@
1
+ import { createLogStoreAPI } from './api.js';
2
+ import { logStoreMigrations } from './migrations.js';
3
+ export const LOG_STORE = 'log';
4
+ export const logStoreDefinition = {
5
+ name: LOG_STORE,
6
+ migrations: logStoreMigrations,
7
+ createAPI: createLogStoreAPI
8
+ };
9
+ export async function getLogStore(provider) {
10
+ return provider.getStore(LOG_STORE);
11
+ }
package/lib/index.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export { categoryRange, encodeCategory } from './category.js';
2
+ export { getLogStore, LOG_STORE, logStoreDefinition } from './definition.js';
3
+ export type { LogTables } from './tables.js';
4
+ export type { LogLevel, LogStore, QueryLogsParams, StoredLog, TracedLog } from './types.js';
5
+ export { isTracedLog } from './types.js';
package/lib/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { categoryRange, encodeCategory } from './category.js';
2
+ export { getLogStore, LOG_STORE, logStoreDefinition } from './definition.js';
3
+ export { isTracedLog } from './types.js';
@@ -0,0 +1,3 @@
1
+ import type { MigrationContext } from '@hozon/db';
2
+ import type { Migration } from 'kysely/migration';
3
+ export declare function logStoreMigrations(ctx: MigrationContext): Record<string, Migration>;
@@ -0,0 +1,29 @@
1
+ import { sql } from 'kysely';
2
+ export function logStoreMigrations(ctx) {
3
+ return {
4
+ '0-init': {
5
+ async up (db) {
6
+ await db.schema.createTable('hozon_logs').addColumn('seq', ctx.types.serial, (column)=>{
7
+ const primary = column.primaryKey();
8
+ return ctx.kind === 'sqlite' ? primary.autoIncrement() : primary;
9
+ }).addColumn('timestamp', ctx.types.double, (column)=>column.notNull()).addColumn('level', ctx.types.text, (column)=>column.notNull()).addColumn('category', ctx.types.text, (column)=>{
10
+ const category = column.notNull();
11
+ return ctx.kind === 'postgres' ? category.modifyFront(sql`collate "C"`) : category;
12
+ }).addColumn('trace_id', ctx.types.text).addColumn('span_id', ctx.types.text).addColumn('data', ctx.types.json, (column)=>column.notNull()).execute();
13
+ await db.schema.createIndex('hozon_logs_timestamp').on('hozon_logs').column('timestamp').execute();
14
+ await db.schema.createIndex('hozon_logs_trace_timestamp_seq').on('hozon_logs').columns([
15
+ 'trace_id',
16
+ 'timestamp',
17
+ 'seq'
18
+ ]).execute();
19
+ await db.schema.createIndex('hozon_logs_level_timestamp').on('hozon_logs').columns([
20
+ 'level',
21
+ 'timestamp'
22
+ ]).execute();
23
+ },
24
+ async down (db) {
25
+ await db.schema.dropTable('hozon_logs').execute();
26
+ }
27
+ }
28
+ };
29
+ }
@@ -0,0 +1,13 @@
1
+ import type { ColumnType, Generated } from 'kysely';
2
+ import type { LogLevel, StoredLog } from './types.js';
3
+ export type LogTables = {
4
+ hozon_logs: {
5
+ seq: Generated<number>;
6
+ timestamp: number;
7
+ level: LogLevel;
8
+ category: string;
9
+ trace_id: string | null;
10
+ span_id: string | null;
11
+ data: ColumnType<StoredLog, unknown, unknown>;
12
+ };
13
+ };
package/lib/tables.js ADDED
@@ -0,0 +1 @@
1
+ export { };
package/lib/types.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ import type { JSONValue } from '@sozai/json';
2
+ export type LogLevel = 'trace' | 'debug' | 'info' | 'warning' | 'error' | 'fatal';
3
+ export type StoredLog = {
4
+ traceID?: string;
5
+ spanID?: string;
6
+ timestamp: number;
7
+ level: LogLevel;
8
+ category: Array<string>;
9
+ message: string;
10
+ properties: Record<string, JSONValue>;
11
+ };
12
+ export type TracedLog = StoredLog & {
13
+ traceID: string;
14
+ spanID: string;
15
+ };
16
+ export declare function isTracedLog(log: StoredLog): log is TracedLog;
17
+ export type QueryLogsParams = {
18
+ from?: number;
19
+ to?: number;
20
+ levels?: Array<LogLevel>;
21
+ categoryPrefix?: Array<string>;
22
+ traceID?: string;
23
+ limit: number;
24
+ cursor?: string;
25
+ };
26
+ export type LogStore = {
27
+ addLogs(logs: Array<StoredLog>): Promise<void>;
28
+ queryLogs(params: QueryLogsParams): Promise<{
29
+ logs: Array<StoredLog>;
30
+ cursor?: string;
31
+ }>;
32
+ getTraceLogs(traceID: string): Promise<Array<TracedLog>>;
33
+ deleteByTrace(traceIDs: Array<string>): Promise<number>;
34
+ /** An empty or omitted keepTraceIDs keeps nothing. */
35
+ deleteBefore(time: number, params?: {
36
+ keepTraceIDs?: Array<string>;
37
+ }): Promise<number>;
38
+ };
package/lib/types.js ADDED
@@ -0,0 +1,3 @@
1
+ export function isTracedLog(log) {
2
+ return log.traceID !== undefined && log.spanID !== undefined;
3
+ }
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@hozon/store-log",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Portable structured log store for Hozon",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/TairuFramework/hozon.git",
8
+ "directory": "packages/store-log"
9
+ },
10
+ "license": "MIT",
11
+ "sideEffects": false,
12
+ "type": "module",
13
+ "exports": {
14
+ ".": "./lib/index.js"
15
+ },
16
+ "files": [
17
+ "lib/*"
18
+ ],
19
+ "dependencies": {
20
+ "@hozon/adapter": "^0.1.0",
21
+ "@hozon/db": "^0.1.0",
22
+ "@sozai/json": "^0.3.0",
23
+ "kysely": "^0.29.6"
24
+ },
25
+ "devDependencies": {
26
+ "@hozon/node-sqlite": "^0.1.0",
27
+ "@types/node": "^26.6.4",
28
+ "del-cli": "^7.0.0",
29
+ "vitest": "5.0.3"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "scripts": {
35
+ "build": "pnpm run build:clean && pnpm run build:js && pnpm run build:types",
36
+ "build:clean": "del-cli lib",
37
+ "build:js": "del-cli \"lib/**/*.js\" && swc src -d ./lib --config-file ../../node_modules/@kigu/dev/swc.json --strip-leading-paths",
38
+ "build:types": "del-cli \"lib/**/*.d.ts\" \"lib/**/*.d.ts.map\" && tsc --emitDeclarationOnly --skipLibCheck",
39
+ "build:types:ci": "tsc --emitDeclarationOnly --skipLibCheck --declarationMap false",
40
+ "test": "pnpm run test:types && pnpm run test:unit",
41
+ "test:types": "tsc --noEmit --skipLibCheck -p tsconfig.test.json",
42
+ "test:unit": "vitest run"
43
+ }
6
44
  }