@zintrust/zedgi 2.8.2
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 +76 -0
- package/dist/ZedgiCacheDriver.d.ts +5 -0
- package/dist/ZedgiCacheDriver.js +62 -0
- package/dist/ZedgiDatabaseAdapter.d.ts +5 -0
- package/dist/ZedgiDatabaseAdapter.js +111 -0
- package/dist/ZedgiQueueDriver.d.ts +5 -0
- package/dist/ZedgiQueueDriver.js +62 -0
- package/dist/ZedgiRuntime.d.ts +45 -0
- package/dist/ZedgiRuntime.js +163 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +5 -0
- package/dist/register.d.ts +14 -0
- package/dist/register.js +42 -0
- package/dist/types.d.ts +63 -0
- package/dist/types.js +1 -0
- package/package.json +47 -0
package/README.md
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# @zintrust/zedgi
|
|
2
|
+
|
|
3
|
+
Zedgi HTTPS transport drivers for ZinTrust cache, database, and queue integrations.
|
|
4
|
+
|
|
5
|
+
This package lets a ZinTrust app reach Redis, MySQL, PostgreSQL, and BullMQ queue operations through a Zedgi gateway by changing driver environment variables.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @zintrust/zedgi @zedgi/zedgi-client
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
In ZinTrust monorepo builds, this package is auto-discovered when one of the Zedgi drivers is selected.
|
|
14
|
+
|
|
15
|
+
## Environment
|
|
16
|
+
|
|
17
|
+
```dotenv
|
|
18
|
+
USE_ZEDGI=true
|
|
19
|
+
ZEDGI_URL=https://YOUR_SUBDOMAIN.zedgi.app
|
|
20
|
+
ZEDGI_KEY=zk_...
|
|
21
|
+
|
|
22
|
+
# Optional. The SDK auto-pulls these when omitted.
|
|
23
|
+
ZEDGI_SIGNING_SECRET=
|
|
24
|
+
ZEDGI_PUBLIC_KEY=
|
|
25
|
+
ZEDGI_ACCOUNT_ID=
|
|
26
|
+
ZEDGI_KEY_VERSION=
|
|
27
|
+
ZEDGI_TIMEOUT=10000
|
|
28
|
+
|
|
29
|
+
# Optional signed plaintext metadata forwarded by Zedgi.
|
|
30
|
+
ZEDGI_REDIS_HEADER=
|
|
31
|
+
ZEDGI_QUEUE_HEADER=
|
|
32
|
+
ZEDGI_MYSQL_HEADER=
|
|
33
|
+
ZEDGI_POSTGRES_HEADER=
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Drivers
|
|
37
|
+
|
|
38
|
+
```dotenv
|
|
39
|
+
CACHE_DRIVER=redis-zedgi
|
|
40
|
+
DB_CONNECTION=mysql-zedgi
|
|
41
|
+
# or DB_CONNECTION=postgres-zedgi
|
|
42
|
+
# or DB_CONNECTION=pg-zedgi
|
|
43
|
+
QUEUE_DRIVER=queue-zedgi
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Zedgi stores the target host/port in its dashboard service registration. ZinTrust sends only auth/selection fields through the client SDK:
|
|
47
|
+
|
|
48
|
+
- Redis: `password`, `db`, optional `header`
|
|
49
|
+
- MySQL/Postgres: `user`, `password`, `database`, optional `ssl`, optional `header`
|
|
50
|
+
|
|
51
|
+
The package uses one shared Zedgi client/options object so account key, signing secret, and encrypted credential blobs are cached across cache, DB, and queue usage.
|
|
52
|
+
|
|
53
|
+
## Queue Support
|
|
54
|
+
|
|
55
|
+
`queue-zedgi` supports:
|
|
56
|
+
|
|
57
|
+
- `enqueue`
|
|
58
|
+
- `length`
|
|
59
|
+
- `drain`
|
|
60
|
+
- `ack`
|
|
61
|
+
|
|
62
|
+
Pull-based `dequeue` is intentionally unsupported because the Zedgi queue API does not currently expose a safe visibility-timeout claim operation. Use `queue-zedgi` for producers and monitoring, and run workers against the same Redis service directly.
|
|
63
|
+
|
|
64
|
+
## Registration
|
|
65
|
+
|
|
66
|
+
The package registers:
|
|
67
|
+
|
|
68
|
+
- Cache: `redis-zedgi`
|
|
69
|
+
- Database: `mysql-zedgi`, `postgres-zedgi`, `pg-zedgi`
|
|
70
|
+
- Queue: `queue-zedgi`
|
|
71
|
+
|
|
72
|
+
Manual registration is available with:
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
import '@zintrust/zedgi/register';
|
|
76
|
+
```
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { ErrorFactory } from '@zintrust/core/errors';
|
|
2
|
+
import { ZedgiRuntime } from './ZedgiRuntime.js';
|
|
3
|
+
const safeJsonParse = (value) => {
|
|
4
|
+
try {
|
|
5
|
+
return JSON.parse(value);
|
|
6
|
+
}
|
|
7
|
+
catch {
|
|
8
|
+
return null;
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
const normalizeTtl = (ttl, fallback) => {
|
|
12
|
+
const effective = ttl ?? fallback;
|
|
13
|
+
return Number.isFinite(effective) && effective > 0 ? Math.floor(effective) : undefined;
|
|
14
|
+
};
|
|
15
|
+
const createDriver = (config) => {
|
|
16
|
+
const redis = () => ZedgiRuntime.redis(config);
|
|
17
|
+
return {
|
|
18
|
+
async get(key) {
|
|
19
|
+
const value = await redis().get(key);
|
|
20
|
+
return value === null ? null : safeJsonParse(value);
|
|
21
|
+
},
|
|
22
|
+
async many(keys) {
|
|
23
|
+
if (keys.length === 0)
|
|
24
|
+
return [];
|
|
25
|
+
const values = await redis().pipeline(keys.map((key) => ({ command: 'GET', args: [key] })));
|
|
26
|
+
return values.map((value) => (typeof value === 'string' ? safeJsonParse(value) : null));
|
|
27
|
+
},
|
|
28
|
+
async set(key, value, ttl) {
|
|
29
|
+
const json = JSON.stringify(value);
|
|
30
|
+
const seconds = normalizeTtl(ttl, config.ttl);
|
|
31
|
+
if (seconds !== undefined) {
|
|
32
|
+
await redis().set(key, json, 'EX', seconds);
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
await redis().set(key, json);
|
|
36
|
+
},
|
|
37
|
+
async delete(key) {
|
|
38
|
+
await redis().del(key);
|
|
39
|
+
},
|
|
40
|
+
async clear() {
|
|
41
|
+
await redis().call('FLUSHDB');
|
|
42
|
+
},
|
|
43
|
+
async has(key) {
|
|
44
|
+
return (await redis().exists(key)) > 0;
|
|
45
|
+
},
|
|
46
|
+
async increment(key, amount = 1) {
|
|
47
|
+
return redis().incrby(key, amount);
|
|
48
|
+
},
|
|
49
|
+
async decrement(key, amount = 1) {
|
|
50
|
+
return redis().decrby(key, amount);
|
|
51
|
+
},
|
|
52
|
+
getRedisClient() {
|
|
53
|
+
throw ErrorFactory.createConfigError('getRedisClient() is not supported by the redis-zedgi cache driver');
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
};
|
|
57
|
+
export const ZedgiCacheDriver = Object.freeze({
|
|
58
|
+
create(config) {
|
|
59
|
+
return createDriver(config);
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
export default ZedgiCacheDriver;
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { FeatureFlags } from '@zintrust/core/config';
|
|
2
|
+
import { ErrorFactory } from '@zintrust/core/errors';
|
|
3
|
+
import { ZedgiRuntime } from './ZedgiRuntime.js';
|
|
4
|
+
const isReadStatement = (sql) => {
|
|
5
|
+
const normalized = sql.trim().replace(/^\/\*[\s\S]*?\*\//, '').trim().toLowerCase();
|
|
6
|
+
return (normalized.startsWith('select') ||
|
|
7
|
+
normalized.startsWith('show') ||
|
|
8
|
+
normalized.startsWith('describe') ||
|
|
9
|
+
normalized.startsWith('explain') ||
|
|
10
|
+
/\breturning\b/i.test(sql));
|
|
11
|
+
};
|
|
12
|
+
const nativeTypeOf = (driver) => driver === 'mysql-zedgi' ? 'mysql' : 'postgresql';
|
|
13
|
+
const normalizeResult = (result) => {
|
|
14
|
+
const rows = Array.isArray(result.rows) ? result.rows : [];
|
|
15
|
+
const rowCount = typeof result.rowCount === 'number' && Number.isFinite(result.rowCount)
|
|
16
|
+
? result.rowCount
|
|
17
|
+
: rows.length;
|
|
18
|
+
return { rows, rowCount };
|
|
19
|
+
};
|
|
20
|
+
const requireConnected = (state) => {
|
|
21
|
+
if (!state.connected) {
|
|
22
|
+
throw ErrorFactory.createConfigError('Zedgi database adapter is not connected');
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
const recordOrThrow = (state, sql, parameters) => {
|
|
26
|
+
const tx = state.transaction;
|
|
27
|
+
if (tx === undefined)
|
|
28
|
+
return undefined;
|
|
29
|
+
if (isReadStatement(sql)) {
|
|
30
|
+
throw ErrorFactory.createConfigError('Zedgi transaction callbacks cannot read intermediate query results. Only write statements can be recorded and submitted as one Zedgi batch.');
|
|
31
|
+
}
|
|
32
|
+
tx.statements.push({ sql, params: parameters });
|
|
33
|
+
return { rows: [], rowCount: 0 };
|
|
34
|
+
};
|
|
35
|
+
const createAdapter = (config) => {
|
|
36
|
+
const state = { connected: false };
|
|
37
|
+
const service = () => ZedgiRuntime.sql(config);
|
|
38
|
+
const nativeType = nativeTypeOf(config.driver);
|
|
39
|
+
const adapter = {
|
|
40
|
+
async connect() {
|
|
41
|
+
ZedgiRuntime.initialize();
|
|
42
|
+
state.connected = true;
|
|
43
|
+
},
|
|
44
|
+
async disconnect() {
|
|
45
|
+
state.connected = false;
|
|
46
|
+
},
|
|
47
|
+
async query(sql, parameters) {
|
|
48
|
+
requireConnected(state);
|
|
49
|
+
const recorded = recordOrThrow(state, sql, parameters);
|
|
50
|
+
if (recorded !== undefined)
|
|
51
|
+
return recorded;
|
|
52
|
+
return normalizeResult(await service().query(sql, parameters));
|
|
53
|
+
},
|
|
54
|
+
async queryOne(sql, parameters) {
|
|
55
|
+
requireConnected(state);
|
|
56
|
+
if (state.transaction !== undefined) {
|
|
57
|
+
throw ErrorFactory.createConfigError('Zedgi transaction callbacks cannot use queryOne because intermediate results are unavailable before the batch is submitted.');
|
|
58
|
+
}
|
|
59
|
+
const result = await adapter.query(sql, parameters);
|
|
60
|
+
return result.rows[0] ?? null;
|
|
61
|
+
},
|
|
62
|
+
async ping() {
|
|
63
|
+
requireConnected(state);
|
|
64
|
+
await service().ping();
|
|
65
|
+
},
|
|
66
|
+
async transaction(callback) {
|
|
67
|
+
requireConnected(state);
|
|
68
|
+
if (state.transaction !== undefined) {
|
|
69
|
+
throw ErrorFactory.createConfigError('Nested Zedgi database transactions are not supported');
|
|
70
|
+
}
|
|
71
|
+
const tx = { statements: [] };
|
|
72
|
+
state.transaction = tx;
|
|
73
|
+
try {
|
|
74
|
+
const result = await callback(adapter);
|
|
75
|
+
if (tx.statements.length > 0) {
|
|
76
|
+
await service().transaction(tx.statements);
|
|
77
|
+
}
|
|
78
|
+
return result;
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
throw ErrorFactory.createTryCatchError(`${nativeType} Zedgi transaction failed`, error);
|
|
82
|
+
}
|
|
83
|
+
finally {
|
|
84
|
+
state.transaction = undefined;
|
|
85
|
+
}
|
|
86
|
+
},
|
|
87
|
+
async rawQuery(sql, parameters = []) {
|
|
88
|
+
if (!FeatureFlags.isRawQueryEnabled()) {
|
|
89
|
+
throw ErrorFactory.createConfigError('Raw SQL queries are disabled. Set USE_RAW_QRY=true environment variable to enable.');
|
|
90
|
+
}
|
|
91
|
+
const result = await adapter.query(sql, parameters);
|
|
92
|
+
return result.rows;
|
|
93
|
+
},
|
|
94
|
+
getType() {
|
|
95
|
+
return nativeType;
|
|
96
|
+
},
|
|
97
|
+
isConnected() {
|
|
98
|
+
return state.connected;
|
|
99
|
+
},
|
|
100
|
+
getPlaceholder(index) {
|
|
101
|
+
return nativeType === 'postgresql' ? `$${index}` : '?';
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
return adapter;
|
|
105
|
+
};
|
|
106
|
+
export const ZedgiDatabaseAdapter = Object.freeze({
|
|
107
|
+
create(config) {
|
|
108
|
+
return createAdapter(config);
|
|
109
|
+
},
|
|
110
|
+
});
|
|
111
|
+
export default ZedgiDatabaseAdapter;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { Env } from '@zintrust/core/config';
|
|
2
|
+
import { ErrorFactory } from '@zintrust/core/errors';
|
|
3
|
+
import { generateUuid } from '@zintrust/core/utils';
|
|
4
|
+
import { ZedgiRuntime } from './ZedgiRuntime.js';
|
|
5
|
+
const resolveRequestedJobId = (payload) => {
|
|
6
|
+
const jobId = payload['jobId'];
|
|
7
|
+
if (typeof jobId === 'string' && jobId.trim().length > 0)
|
|
8
|
+
return jobId.trim();
|
|
9
|
+
return generateUuid();
|
|
10
|
+
};
|
|
11
|
+
const createJobOptions = (payload, fallbackJobId) => ({
|
|
12
|
+
jobId: resolveRequestedJobId({ ...payload, jobId: payload['jobId'] ?? fallbackJobId }),
|
|
13
|
+
delay: payload['delay'],
|
|
14
|
+
attempts: payload['attempts'] ?? Env.getInt('BULLMQ_DEFAULT_ATTEMPTS', 3),
|
|
15
|
+
priority: payload['priority'],
|
|
16
|
+
removeOnComplete: payload['removeOnComplete'] ?? Env.getInt('BULLMQ_REMOVE_ON_COMPLETE', 100),
|
|
17
|
+
removeOnFail: payload['removeOnFail'] ?? Env.getInt('BULLMQ_REMOVE_ON_FAIL', 50),
|
|
18
|
+
backoff: payload['backoff'] ?? {
|
|
19
|
+
type: Env.get('BULLMQ_BACKOFF_TYPE', 'exponential'),
|
|
20
|
+
delay: Env.getInt('BULLMQ_BACKOFF_DELAY', 2000),
|
|
21
|
+
},
|
|
22
|
+
repeat: payload['repeat'],
|
|
23
|
+
lifo: payload['lifo'] ?? false,
|
|
24
|
+
});
|
|
25
|
+
const resolveJobId = (result, fallback) => {
|
|
26
|
+
if (result !== null && typeof result === 'object') {
|
|
27
|
+
const id = result.id;
|
|
28
|
+
if (typeof id === 'string' && id.trim().length > 0)
|
|
29
|
+
return id;
|
|
30
|
+
if (typeof id === 'number' && Number.isFinite(id))
|
|
31
|
+
return String(id);
|
|
32
|
+
}
|
|
33
|
+
return fallback;
|
|
34
|
+
};
|
|
35
|
+
const createDriver = (config) => {
|
|
36
|
+
const queue = (name) => ZedgiRuntime.queue(name, config);
|
|
37
|
+
return {
|
|
38
|
+
async enqueue(queueName, payload) {
|
|
39
|
+
const fallbackJobId = resolveRequestedJobId(payload);
|
|
40
|
+
const result = await queue(queueName).add(`${queueName}-job`, payload, createJobOptions(payload, fallbackJobId));
|
|
41
|
+
return resolveJobId(result, fallbackJobId);
|
|
42
|
+
},
|
|
43
|
+
async dequeue(_queueName) {
|
|
44
|
+
throw ErrorFactory.createConfigError('queue-zedgi does not support pull-based dequeue yet because the Zedgi queue API does not expose a safe visibility-timeout claim operation. Use it for enqueue and monitoring, or run workers against the same Redis service.');
|
|
45
|
+
},
|
|
46
|
+
async ack(queueName, id) {
|
|
47
|
+
await queue(queueName).removeJob(id);
|
|
48
|
+
},
|
|
49
|
+
async length(queueName) {
|
|
50
|
+
return queue(queueName).count();
|
|
51
|
+
},
|
|
52
|
+
async drain(queueName) {
|
|
53
|
+
await queue(queueName).drain();
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
};
|
|
57
|
+
export const ZedgiQueueDriver = Object.freeze({
|
|
58
|
+
create(config) {
|
|
59
|
+
return createDriver(config);
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
export default ZedgiQueueDriver;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { type ZedgiClient } from '@zedgi/zedgi-client';
|
|
2
|
+
import type { ZedgiDatabaseConfig, ZedgiQueueConfig, ZedgiRedisCacheConfig } from './types.js';
|
|
3
|
+
export declare const ZedgiRuntime: Readonly<{
|
|
4
|
+
initialize(): ZedgiClient;
|
|
5
|
+
warm(): Promise<void>;
|
|
6
|
+
shutdown(): void;
|
|
7
|
+
redis(config?: Partial<ZedgiRedisCacheConfig | ZedgiQueueConfig>): import("@zedgi/zedgi-client").RedisClient;
|
|
8
|
+
queue(name: string, config?: Partial<ZedgiQueueConfig | ZedgiRedisCacheConfig>): Readonly<{
|
|
9
|
+
add: (jobName: string, data?: unknown, opts?: Record<string, unknown>) => Promise<import("@zedgi/zedgi-client").QueueJob | null>;
|
|
10
|
+
getJob: (id: string) => Promise<import("@zedgi/zedgi-client").QueueJob | null>;
|
|
11
|
+
getJobs: (states?: string[], start?: number, end?: number, asc?: boolean) => Promise<(import("@zedgi/zedgi-client").QueueJob | null)[]>;
|
|
12
|
+
getJobCounts: (...types: string[]) => Promise<Record<string, number>>;
|
|
13
|
+
count: () => Promise<number>;
|
|
14
|
+
pause: () => Promise<boolean>;
|
|
15
|
+
resume: () => Promise<boolean>;
|
|
16
|
+
drain: (delayed?: boolean) => Promise<boolean>;
|
|
17
|
+
clean: (grace: number, limit: number, type?: string) => Promise<string[]>;
|
|
18
|
+
removeJob: (id: string) => Promise<boolean>;
|
|
19
|
+
retryJob: (id: string) => Promise<{
|
|
20
|
+
ok: boolean;
|
|
21
|
+
status: string;
|
|
22
|
+
}>;
|
|
23
|
+
promoteJob: (id: string) => Promise<{
|
|
24
|
+
ok: boolean;
|
|
25
|
+
status: string;
|
|
26
|
+
}>;
|
|
27
|
+
obliterate: (opts?: Record<string, unknown>) => Promise<boolean>;
|
|
28
|
+
closeQueue: () => Promise<boolean>;
|
|
29
|
+
getSnapshot: () => Promise<{
|
|
30
|
+
status: string;
|
|
31
|
+
startedAt: string;
|
|
32
|
+
queues: Array<{
|
|
33
|
+
name: string;
|
|
34
|
+
counts: Record<string, number>;
|
|
35
|
+
}>;
|
|
36
|
+
}>;
|
|
37
|
+
getEvents: () => Promise<Array<{
|
|
38
|
+
event: string;
|
|
39
|
+
payload: unknown;
|
|
40
|
+
at: number;
|
|
41
|
+
}>>;
|
|
42
|
+
getRecentJobsForQueue: (limit?: number) => Promise<(import("@zedgi/zedgi-client").QueueJob | null)[]>;
|
|
43
|
+
}>;
|
|
44
|
+
sql(config: ZedgiDatabaseConfig): import("@zedgi/zedgi-client").PostgresClient | import("@zedgi/zedgi-client").MySQLClient;
|
|
45
|
+
}>;
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { createZedgiClient } from '@zedgi/zedgi-client';
|
|
2
|
+
import { Env } from '@zintrust/core/config';
|
|
3
|
+
import { ErrorFactory } from '@zintrust/core/errors';
|
|
4
|
+
import { Logger } from '@zintrust/core/logger';
|
|
5
|
+
const profiles = {
|
|
6
|
+
redis: {},
|
|
7
|
+
mysql: {},
|
|
8
|
+
postgres: {},
|
|
9
|
+
};
|
|
10
|
+
let options;
|
|
11
|
+
let client;
|
|
12
|
+
const profileNames = new WeakMap();
|
|
13
|
+
const redisCredentials = new Map();
|
|
14
|
+
const sqlCredentials = new Map();
|
|
15
|
+
const hasText = (value) => typeof value === 'string' && value.trim().length > 0;
|
|
16
|
+
const normalizeHeader = (value) => {
|
|
17
|
+
if (value === undefined || value === null)
|
|
18
|
+
return undefined;
|
|
19
|
+
if (typeof value === 'object' && !Array.isArray(value))
|
|
20
|
+
return value;
|
|
21
|
+
return undefined;
|
|
22
|
+
};
|
|
23
|
+
const parseHeaderEnv = (key) => {
|
|
24
|
+
const raw = Env.get(key, '').trim();
|
|
25
|
+
if (raw === '')
|
|
26
|
+
return undefined;
|
|
27
|
+
try {
|
|
28
|
+
const parsed = JSON.parse(raw);
|
|
29
|
+
return normalizeHeader(parsed);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return { value: raw };
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
const ensureOptions = () => {
|
|
36
|
+
if (options !== undefined)
|
|
37
|
+
return options;
|
|
38
|
+
const url = Env.get('ZEDGI_URL', '').trim();
|
|
39
|
+
const key = Env.get('ZEDGI_KEY', '').trim();
|
|
40
|
+
if (url === '')
|
|
41
|
+
throw ErrorFactory.createConfigError('ZEDGI_URL is required for Zedgi drivers');
|
|
42
|
+
if (key === '')
|
|
43
|
+
throw ErrorFactory.createConfigError('ZEDGI_KEY is required for Zedgi drivers');
|
|
44
|
+
const next = {
|
|
45
|
+
url,
|
|
46
|
+
key,
|
|
47
|
+
credentials: profiles,
|
|
48
|
+
timeout: Env.getInt('ZEDGI_TIMEOUT', 10000),
|
|
49
|
+
};
|
|
50
|
+
const signingSecret = Env.get('ZEDGI_SIGNING_SECRET', Env.get('ZEDGI_SECRET', '')).trim();
|
|
51
|
+
if (signingSecret !== '')
|
|
52
|
+
next['signingSecret'] = signingSecret;
|
|
53
|
+
const publicKey = Env.get('ZEDGI_PUBLIC_KEY', '').trim();
|
|
54
|
+
const accountId = Env.get('ZEDGI_ACCOUNT_ID', '').trim();
|
|
55
|
+
const keyVersionRaw = Env.get('ZEDGI_KEY_VERSION', '').trim();
|
|
56
|
+
if (publicKey !== '' && accountId !== '' && keyVersionRaw !== '') {
|
|
57
|
+
next['publicKey'] = publicKey;
|
|
58
|
+
next['accountId'] = accountId;
|
|
59
|
+
next['keyVersion'] = Number.parseInt(keyVersionRaw, 10);
|
|
60
|
+
}
|
|
61
|
+
options = next;
|
|
62
|
+
return options;
|
|
63
|
+
};
|
|
64
|
+
const ensureClient = () => {
|
|
65
|
+
if (client !== undefined)
|
|
66
|
+
return client;
|
|
67
|
+
client = createZedgiClient(ensureOptions());
|
|
68
|
+
return client;
|
|
69
|
+
};
|
|
70
|
+
const registerProfile = (service, profile, credential) => {
|
|
71
|
+
profiles[service] ??= {};
|
|
72
|
+
profiles[service][profile] = credential;
|
|
73
|
+
profileNames.set(credential, profile);
|
|
74
|
+
return credential;
|
|
75
|
+
};
|
|
76
|
+
const stableStringify = (value) => {
|
|
77
|
+
if (Array.isArray(value))
|
|
78
|
+
return `[${value.map((item) => stableStringify(item)).join(',')}]`;
|
|
79
|
+
if (value !== null && typeof value === 'object') {
|
|
80
|
+
const entries = Object.entries(value).sort(([a], [b]) => a.localeCompare(b));
|
|
81
|
+
return `{${entries
|
|
82
|
+
.map(([key, nested]) => `${JSON.stringify(key)}:${stableStringify(nested)}`)
|
|
83
|
+
.join(',')}}`;
|
|
84
|
+
}
|
|
85
|
+
return JSON.stringify(value);
|
|
86
|
+
};
|
|
87
|
+
const stableKey = (service, credential) => `${service}:${stableStringify(credential)}`;
|
|
88
|
+
const memoizeCredential = (service, profilePrefix, credential, cache) => {
|
|
89
|
+
const key = stableKey(service, credential);
|
|
90
|
+
const existing = cache.get(key);
|
|
91
|
+
if (existing !== undefined)
|
|
92
|
+
return existing;
|
|
93
|
+
const profile = `${profilePrefix}-${cache.size + 1}`;
|
|
94
|
+
cache.set(key, registerProfile(service, profile, credential));
|
|
95
|
+
return credential;
|
|
96
|
+
};
|
|
97
|
+
const getProfileName = (credential) => {
|
|
98
|
+
const profile = profileNames.get(credential);
|
|
99
|
+
if (profile === undefined) {
|
|
100
|
+
throw ErrorFactory.createConfigError('Zedgi credential profile was not registered');
|
|
101
|
+
}
|
|
102
|
+
return profile;
|
|
103
|
+
};
|
|
104
|
+
const redisCredentialFromConfig = (config, fallbackHeaderKey) => {
|
|
105
|
+
const credential = {};
|
|
106
|
+
if (hasText(config.password))
|
|
107
|
+
credential['password'] = config.password;
|
|
108
|
+
if (typeof config.database === 'number' && Number.isFinite(config.database)) {
|
|
109
|
+
credential['db'] = config.database;
|
|
110
|
+
}
|
|
111
|
+
const header = normalizeHeader(config.header) ?? parseHeaderEnv(fallbackHeaderKey);
|
|
112
|
+
if (header !== undefined)
|
|
113
|
+
credential['header'] = header;
|
|
114
|
+
return credential;
|
|
115
|
+
};
|
|
116
|
+
const sqlCredentialFromConfig = (config, fallbackHeaderKey) => {
|
|
117
|
+
const credential = {};
|
|
118
|
+
if (hasText(config.username))
|
|
119
|
+
credential['user'] = config.username;
|
|
120
|
+
if (hasText(config.password))
|
|
121
|
+
credential['password'] = config.password;
|
|
122
|
+
if (hasText(config.database))
|
|
123
|
+
credential['database'] = config.database;
|
|
124
|
+
if (typeof config.ssl === 'boolean')
|
|
125
|
+
credential['ssl'] = config.ssl;
|
|
126
|
+
const header = normalizeHeader(config.header) ?? parseHeaderEnv(fallbackHeaderKey);
|
|
127
|
+
if (header !== undefined)
|
|
128
|
+
credential['header'] = header;
|
|
129
|
+
return credential;
|
|
130
|
+
};
|
|
131
|
+
const resolveSqlService = (driver) => driver === 'mysql-zedgi' ? 'mysql' : 'postgres';
|
|
132
|
+
export const ZedgiRuntime = Object.freeze({
|
|
133
|
+
initialize() {
|
|
134
|
+
return ensureClient();
|
|
135
|
+
},
|
|
136
|
+
async warm() {
|
|
137
|
+
try {
|
|
138
|
+
await ensureClient().redis().ping();
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
Logger.warn('[zedgi] Warm-up ping failed', {
|
|
142
|
+
error: error instanceof Error ? error.message : String(error),
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
shutdown() {
|
|
147
|
+
client = undefined;
|
|
148
|
+
},
|
|
149
|
+
redis(config = {}) {
|
|
150
|
+
const credential = memoizeCredential('redis', 'redis', redisCredentialFromConfig(config, 'ZEDGI_REDIS_HEADER'), redisCredentials);
|
|
151
|
+
return ensureClient().redis(getProfileName(credential));
|
|
152
|
+
},
|
|
153
|
+
queue(name, config = {}) {
|
|
154
|
+
const credential = memoizeCredential('redis', 'redis', redisCredentialFromConfig(config, 'ZEDGI_QUEUE_HEADER'), redisCredentials);
|
|
155
|
+
return ensureClient().queue(name, getProfileName(credential));
|
|
156
|
+
},
|
|
157
|
+
sql(config) {
|
|
158
|
+
const service = resolveSqlService(config.driver);
|
|
159
|
+
const credential = memoizeCredential(service, service, sqlCredentialFromConfig(config, service === 'mysql' ? 'ZEDGI_MYSQL_HEADER' : 'ZEDGI_POSTGRES_HEADER'), sqlCredentials);
|
|
160
|
+
const profile = getProfileName(credential);
|
|
161
|
+
return service === 'mysql' ? ensureClient().mysql(profile) : ensureClient().postgres(profile);
|
|
162
|
+
},
|
|
163
|
+
});
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { ZedgiRuntime } from './ZedgiRuntime.js';
|
|
2
|
+
export { ZedgiCacheDriver } from './ZedgiCacheDriver.js';
|
|
3
|
+
export { ZedgiDatabaseAdapter } from './ZedgiDatabaseAdapter.js';
|
|
4
|
+
export { ZedgiQueueDriver } from './ZedgiQueueDriver.js';
|
|
5
|
+
export type { CacheDriver, DatabaseAdapter, QueryResult, QueueDriver, QueueMessage, ZedgiDatabaseConfig, ZedgiQueueConfig, ZedgiRedisCacheConfig, } from './types.js';
|
|
6
|
+
export declare const _ZINTRUST_ZEDGI_VERSION = "2.8.2";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { ZedgiRuntime } from './ZedgiRuntime.js';
|
|
2
|
+
export { ZedgiCacheDriver } from './ZedgiCacheDriver.js';
|
|
3
|
+
export { ZedgiDatabaseAdapter } from './ZedgiDatabaseAdapter.js';
|
|
4
|
+
export { ZedgiQueueDriver } from './ZedgiQueueDriver.js';
|
|
5
|
+
export const _ZINTRUST_ZEDGI_VERSION = '2.8.2';
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ZedgiQueueConfig } from './types.js';
|
|
2
|
+
type CacheRegistry = {
|
|
3
|
+
register: (driver: string, factory: (cfg: unknown) => unknown) => void;
|
|
4
|
+
};
|
|
5
|
+
type DatabaseRegistry = {
|
|
6
|
+
register: (driver: string, factory: (cfg: unknown) => unknown) => void;
|
|
7
|
+
};
|
|
8
|
+
type QueueApi = {
|
|
9
|
+
register: (driver: string, queue: unknown) => void;
|
|
10
|
+
};
|
|
11
|
+
export declare function registerZedgiCacheDriver(registry: CacheRegistry): void;
|
|
12
|
+
export declare function registerZedgiDatabaseAdapters(registry: DatabaseRegistry): void;
|
|
13
|
+
export declare function registerZedgiQueueDriver(queue: QueueApi, config?: ZedgiQueueConfig): void;
|
|
14
|
+
export {};
|
package/dist/register.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { ZedgiCacheDriver } from './ZedgiCacheDriver.js';
|
|
2
|
+
import { ZedgiDatabaseAdapter } from './ZedgiDatabaseAdapter.js';
|
|
3
|
+
import { ZedgiQueueDriver } from './ZedgiQueueDriver.js';
|
|
4
|
+
import { ZedgiRuntime } from './ZedgiRuntime.js';
|
|
5
|
+
export function registerZedgiCacheDriver(registry) {
|
|
6
|
+
registry.register('redis-zedgi', (config) => ZedgiCacheDriver.create(config));
|
|
7
|
+
}
|
|
8
|
+
export function registerZedgiDatabaseAdapters(registry) {
|
|
9
|
+
const factory = (config) => ZedgiDatabaseAdapter.create(config);
|
|
10
|
+
registry.register('mysql-zedgi', factory);
|
|
11
|
+
registry.register('postgres-zedgi', factory);
|
|
12
|
+
registry.register('pg-zedgi', (config) => ZedgiDatabaseAdapter.create({
|
|
13
|
+
...config,
|
|
14
|
+
driver: 'postgres-zedgi',
|
|
15
|
+
}));
|
|
16
|
+
}
|
|
17
|
+
export function registerZedgiQueueDriver(queue, config) {
|
|
18
|
+
queue.register('queue-zedgi', ZedgiQueueDriver.create(config ?? {
|
|
19
|
+
driver: 'queue-zedgi',
|
|
20
|
+
}));
|
|
21
|
+
}
|
|
22
|
+
const importCore = async () => {
|
|
23
|
+
try {
|
|
24
|
+
return await import('@zintrust/core');
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return {};
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
const core = (await importCore());
|
|
31
|
+
if (typeof core.CacheDriverRegistry?.register === 'function') {
|
|
32
|
+
registerZedgiCacheDriver(core.CacheDriverRegistry);
|
|
33
|
+
}
|
|
34
|
+
if (typeof core.DatabaseAdapterRegistry?.register === 'function') {
|
|
35
|
+
registerZedgiDatabaseAdapters(core.DatabaseAdapterRegistry);
|
|
36
|
+
}
|
|
37
|
+
if (typeof core.Queue?.register === 'function') {
|
|
38
|
+
registerZedgiQueueDriver(core.Queue);
|
|
39
|
+
}
|
|
40
|
+
if (core.Env?.getBool?.('USE_ZEDGI', false) === true) {
|
|
41
|
+
ZedgiRuntime.initialize();
|
|
42
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
export type ZedgiRedisCacheConfig = {
|
|
2
|
+
driver: 'redis-zedgi';
|
|
3
|
+
password?: string;
|
|
4
|
+
database?: number;
|
|
5
|
+
ttl: number;
|
|
6
|
+
header?: Record<string, unknown>;
|
|
7
|
+
};
|
|
8
|
+
export type ZedgiDatabaseConfig = {
|
|
9
|
+
driver: 'mysql-zedgi' | 'postgres-zedgi' | 'pg-zedgi';
|
|
10
|
+
database?: string;
|
|
11
|
+
username?: string;
|
|
12
|
+
password?: string;
|
|
13
|
+
ssl?: boolean;
|
|
14
|
+
header?: Record<string, unknown>;
|
|
15
|
+
};
|
|
16
|
+
export type ZedgiQueueConfig = {
|
|
17
|
+
driver: 'queue-zedgi';
|
|
18
|
+
password?: string;
|
|
19
|
+
database?: number;
|
|
20
|
+
header?: Record<string, unknown>;
|
|
21
|
+
};
|
|
22
|
+
export type CacheDriver = {
|
|
23
|
+
get<T>(key: string): Promise<T | null>;
|
|
24
|
+
many?<T>(keys: string[]): Promise<(T | null)[]>;
|
|
25
|
+
set<T>(key: string, value: T, ttl?: number): Promise<void>;
|
|
26
|
+
delete(key: string): Promise<void>;
|
|
27
|
+
clear(): Promise<void>;
|
|
28
|
+
has(key: string): Promise<boolean>;
|
|
29
|
+
increment?(key: string, amount?: number): Promise<number>;
|
|
30
|
+
decrement?(key: string, amount?: number): Promise<number>;
|
|
31
|
+
dispose?(): Promise<void>;
|
|
32
|
+
getRedisClient?(): unknown;
|
|
33
|
+
};
|
|
34
|
+
export type QueryResult = {
|
|
35
|
+
rows: Record<string, unknown>[];
|
|
36
|
+
rowCount: number;
|
|
37
|
+
lastInsertId?: string | number | bigint;
|
|
38
|
+
};
|
|
39
|
+
export type DatabaseAdapter = {
|
|
40
|
+
connect(): Promise<void>;
|
|
41
|
+
disconnect(): Promise<void>;
|
|
42
|
+
query(sql: string, parameters: unknown[]): Promise<QueryResult>;
|
|
43
|
+
queryOne(sql: string, parameters: unknown[]): Promise<Record<string, unknown> | null>;
|
|
44
|
+
ping(): Promise<void>;
|
|
45
|
+
transaction<T>(callback: (adapter: DatabaseAdapter) => Promise<T>): Promise<T>;
|
|
46
|
+
rawQuery<T = unknown>(sql: string, parameters?: unknown[]): Promise<T[]>;
|
|
47
|
+
getType(): string;
|
|
48
|
+
isConnected(): boolean;
|
|
49
|
+
getPlaceholder(index: number): string;
|
|
50
|
+
};
|
|
51
|
+
export type BullMQPayload = Record<string, unknown>;
|
|
52
|
+
export type QueueMessage<T = unknown> = {
|
|
53
|
+
id: string;
|
|
54
|
+
payload: T;
|
|
55
|
+
attempts: number;
|
|
56
|
+
};
|
|
57
|
+
export type QueueDriver = {
|
|
58
|
+
enqueue(queue: string, payload: BullMQPayload): Promise<string>;
|
|
59
|
+
dequeue<T = unknown>(queue: string): Promise<QueueMessage<T> | undefined>;
|
|
60
|
+
ack(queue: string, id: string): Promise<void>;
|
|
61
|
+
length(queue: string): Promise<number>;
|
|
62
|
+
drain(queue: string): Promise<void>;
|
|
63
|
+
};
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@zintrust/zedgi",
|
|
3
|
+
"version": "2.8.2",
|
|
4
|
+
"description": "Zedgi HTTPS transport drivers for ZinTrust cache, database, and queue.",
|
|
5
|
+
"private": false,
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"files": [
|
|
10
|
+
"dist"
|
|
11
|
+
],
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"default": "./dist/index.js"
|
|
16
|
+
},
|
|
17
|
+
"./register": {
|
|
18
|
+
"types": "./dist/register.d.ts",
|
|
19
|
+
"default": "./dist/register.js"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=20.0.0"
|
|
24
|
+
},
|
|
25
|
+
"peerDependencies": {
|
|
26
|
+
"@zintrust/core": "*"
|
|
27
|
+
},
|
|
28
|
+
"publishConfig": {
|
|
29
|
+
"access": "public"
|
|
30
|
+
},
|
|
31
|
+
"keywords": [
|
|
32
|
+
"zintrust",
|
|
33
|
+
"zedgi",
|
|
34
|
+
"redis",
|
|
35
|
+
"mysql",
|
|
36
|
+
"postgres",
|
|
37
|
+
"queue",
|
|
38
|
+
"adapter"
|
|
39
|
+
],
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"@zedgi/zedgi-client": "^1.0.3"
|
|
42
|
+
},
|
|
43
|
+
"scripts": {
|
|
44
|
+
"build": "tsc -p tsconfig.json",
|
|
45
|
+
"prepublishOnly": "npm run build"
|
|
46
|
+
}
|
|
47
|
+
}
|