@ginkgolab/datasources 0.1.0 → 0.1.1

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.
@@ -1,362 +0,0 @@
1
- import { DbDialectClient } from './sqlGuard.js';
2
- import { SchemaCard } from './schema/card.js';
3
-
4
- interface DbToolDefinition {
5
- name: string;
6
- description: string;
7
- inputSchema: Record<string, unknown>;
8
- }
9
- interface DbToolsConnection {
10
- listTools(): Promise<DbToolDefinition[]>;
11
- callTool(name: string, args: Record<string, unknown>): Promise<{
12
- content: Array<{
13
- type: string;
14
- text: string;
15
- }>;
16
- isError?: boolean;
17
- }>;
18
- close(): Promise<void>;
19
- }
20
-
21
- /**
22
- * MCP 连接器网关类型契约
23
- */
24
- interface QueryCacheKey {
25
- sourceId: string;
26
- sqlHash: string;
27
- paramsHash: string;
28
- }
29
- interface ExplainCostReport {
30
- /** 语法与表结构是否通过 */
31
- isValid: boolean;
32
- /** 预估扫描行数 */
33
- estimatedRows: number;
34
- /** 预估扫描字节数(若数仓支持,如 ClickHouse/BigQuery) */
35
- estimatedBytes?: number;
36
- /** 语法或执行计划错误信息 */
37
- syntaxError?: string;
38
- /** 是否存在全表扫描高风险 */
39
- isFullTableScan: boolean;
40
- /** 是否超过扫描预算阈值 */
41
- exceedsBudget: boolean;
42
- /** 针对模型自愈的建议提示 */
43
- costWarning?: string;
44
- /** EXPLAIN 预检因方言不支持/基础设施异常而降级放行(未做成本评估) */
45
- degraded?: boolean;
46
- /** 原始 EXPLAIN 输出摘要 */
47
- planRaw?: unknown;
48
- }
49
- interface ExplainOptions {
50
- /** 单次查询最大预估扫描行数预算(默认 1,000,000) */
51
- maxScanRowsBudget?: number;
52
- /** 是否对全表扫描进行强制熔断(默认 true) */
53
- blockFullTableScan?: boolean;
54
- }
55
- interface QueryResultWithMeta {
56
- rows: Record<string, unknown>[];
57
- rowCount: number;
58
- /** 是否命中结果集缓存 */
59
- cacheHit?: boolean;
60
- /** 缓存写入时间戳 */
61
- cachedAt?: number;
62
- /** 执行耗时(毫秒) */
63
- durationMs?: number;
64
- /** 经 EXPLAIN 预检的成本报告摘要 */
65
- explainReport?: ExplainCostReport;
66
- }
67
- interface ExecuteQueryArgs {
68
- sourceId: string;
69
- sql: string;
70
- params?: unknown[];
71
- /** 是否跳过缓存强制直连数仓 */
72
- skipCache?: boolean;
73
- /** 是否跳过 EXPLAIN 成本门禁(特定受信任查询使用) */
74
- bypassExplain?: boolean;
75
- /** 自定义缓存 TTL(毫秒,缺省使用网关配置) */
76
- cacheTtlMs?: number;
77
- }
78
- interface CatalogOverviewItem {
79
- sourceId: string;
80
- name: string;
81
- type: string;
82
- tables: string[];
83
- description?: string;
84
- }
85
- interface TableDetailResource {
86
- sourceId: string;
87
- tableName: string;
88
- columns: Array<{
89
- name: string;
90
- type: string;
91
- comment?: string;
92
- }>;
93
- sampleRows: Record<string, unknown>[];
94
- }
95
- interface QueryGatewayConfig {
96
- /** 默认缓存 TTL,默认 15 分钟 (900,000 ms) */
97
- defaultCacheTtlMs?: number;
98
- /** 缓存容量最大条目数,默认 500 */
99
- maxCacheEntries?: number;
100
- /** 成本门禁默认配置 */
101
- explainOptions?: ExplainOptions;
102
- }
103
- type McpGatewayConfig = QueryGatewayConfig;
104
-
105
- interface CacheEntry<T> {
106
- key: string;
107
- data: T;
108
- cachedAt: number;
109
- ttlMs: number;
110
- }
111
- /**
112
- * 规范化 SQL:折叠结构部分的多余空白与大小写,以便精确命中相同语义的 SQL。
113
- *
114
- * 正确性约束:字符串字面量('...')与引用标识符("...")的原文必须逐字保留——
115
- * PG 的引用标识符与所有方言的字符串字面量都是大小写敏感的,
116
- * 若对整串做小写/空白折叠,"WHERE name='ABC'" 与 "WHERE name='abc'"
117
- * 会得到相同缓存键而错配结果集(参考 sqlGuard.enforceRowLimit 的字面量剥离哲学)。
118
- */
119
- declare function normalizeSqlForCache(sql: string): string;
120
- /**
121
- * 计算查询的哈希唯一指纹
122
- */
123
- declare function computeQueryHashKey(sourceId: string, sql: string, params?: unknown[]): QueryCacheKey;
124
- /**
125
- * 存储键:使用全量哈希——缓存错配会返回错误结果集,截断哈希的碰撞尾部风险不可接受。
126
- * 日志展示请使用 formatCacheKeyDisplay。
127
- */
128
- declare function formatCacheKey(key: QueryCacheKey): string;
129
- /** 日志/调试展示用的截断形态(不参与存储) */
130
- declare function formatCacheKeyDisplay(key: QueryCacheKey): string;
131
- /**
132
- * 查询级结果集 KV 缓存管理器(带 TTL 与 LRU 淘汰)
133
- */
134
- declare class QueryCacheManager<T = unknown> {
135
- private cache;
136
- private maxEntries;
137
- private defaultTtlMs;
138
- constructor(options?: {
139
- maxEntries?: number;
140
- defaultTtlMs?: number;
141
- });
142
- get(key: QueryCacheKey): {
143
- data: T;
144
- cachedAt: number;
145
- } | null;
146
- set(key: QueryCacheKey, data: T, ttlMs?: number): void;
147
- /**
148
- * 清除特定数据源或全部缓存
149
- */
150
- invalidate(sourceId?: string): void;
151
- size(): number;
152
- }
153
-
154
- interface GatewayQueryPayload {
155
- rows: Record<string, unknown>[];
156
- rowCount: number;
157
- }
158
- /**
159
- * 统一数据源查询网关与路由器:
160
- * - 统一代理数仓与数据源查询,复用共享守卫管线(只读守卫 + 缓存 + EXPLAIN 成本熔断)
161
- * - 提供两阶段 Schema 懒加载资源接口
162
- *
163
- * 注意:executeQuery 走 manager.connect 的原始连接执行,刻意绕过 tools 绑定的
164
- * 守卫拦截——守卫已由共享管线执行一次,避免自我递归与双重 EXPLAIN。
165
- */
166
- declare class QueryGateway {
167
- private cache;
168
- private manager;
169
- private config;
170
- constructor(manager: DatasourceManager, config?: QueryGatewayConfig,
171
- /** 共享缓存实例:与 manager 工具绑定同一实例,保证失效一致性 */
172
- sharedCache?: QueryCacheManager<unknown>);
173
- /**
174
- * 按数据源 ID 与工具原名检索已绑定的工具调用契约
175
- */
176
- getTool(sourceId: string, toolName: string): Promise<DatasourceToolBinding | undefined>;
177
- /**
178
- * 核心方法:执行 SQL 查询(流经共享守卫管线)
179
- */
180
- executeQuery(args: ExecuteQueryArgs): Promise<QueryResultWithMeta>;
181
- /**
182
- * 两阶段发现第一阶段:获取全量数据源及其表名概览(不含详细字段,防上下文撑爆)
183
- */
184
- listCatalogs(): Promise<CatalogOverviewItem[]>;
185
- /**
186
- * 两阶段发现第二阶段:按需拉取特定表的详细 Schema 与前 3 条样本数据
187
- */
188
- describeTableResource(sourceId: string, tableName: string): Promise<TableDetailResource>;
189
- /**
190
- * 清除网关缓存(共享实例时等同清除该源的全部缓存)
191
- */
192
- invalidateCache(sourceId?: string): void;
193
- getCacheManager(): QueryCacheManager<GatewayQueryPayload>;
194
- }
195
- /** 向后兼容别名 */
196
- declare const McpGateway: typeof QueryGateway;
197
- type McpGateway = QueryGateway;
198
-
199
- /**
200
- * 文件数据源落盘层:CSV/Excel/Parquet/JSON → DuckDB 完全覆盖式灌库 + manifest 读写。
201
- * 目录布局:<filesDir>/<sourceId>/raw/(原始文件)、analytics.duckdb、manifest.json。
202
- * 灌库采用「staging 目录构建 + 整体替换」:失败时旧数据原样保留。
203
- */
204
- declare const FILE_SOURCE_MAX_BYTES: number;
205
- declare const FILE_SOURCE_EXTENSIONS: readonly [".csv", ".xlsx", ".parquet", ".json", ".ndjson"];
206
- interface FileSourceUpload {
207
- name: string;
208
- data: Buffer;
209
- }
210
- interface FileTableInfo {
211
- table: string;
212
- fromFile: string;
213
- sheet?: string;
214
- /** 源文件格式(xlsx 经临时 CSV 灌库,format 记原始格式) */
215
- format?: "csv" | "xlsx" | "parquet" | "json" | "ndjson";
216
- rowCount: number;
217
- columns: {
218
- name: string;
219
- type: string;
220
- }[];
221
- }
222
- interface FileSourceManifest {
223
- files: {
224
- name: string;
225
- size: number;
226
- uploadedAt: string;
227
- }[];
228
- tables: FileTableInfo[];
229
- ingestedAt: string;
230
- }
231
- /** 上传文件类型校验:扩展名白名单(路由层负责大小限制与内容嗅探) */
232
- declare function isSupportedUpload(name: string): boolean;
233
- /** 表名清洗(单段输入,如 CSV 文件名):分段清洗 + 去重 */
234
- declare function sanitizeTableName(raw: string, used: Set<string>): string;
235
-
236
- /**
237
- * 数据源配置模型:专注于结构化数据(数据库连接与分析文件)
238
- * 彻底纯化,网络/外设 MCP 协议统一由 @ginkgo/harness-core 承接。
239
- */
240
- interface DbSourceConfig {
241
- id: string;
242
- name: string;
243
- kind: "db";
244
- dbType: "postgres" | "mysql" | "sqlite" | "clickhouse";
245
- /** sqlite 为文件路径(可带 sqlite: 前缀),其余为 URL 形式连接串 */
246
- connectionString: string;
247
- enabled: boolean;
248
- }
249
- /**
250
- * 文件数据源(CSV/Excel):无连接串等额外字段;
251
- * 文件内容与 DuckDB 库落盘在应用注入的 filesDir 下,配置层只持有元信息。
252
- */
253
- interface FileSourceConfig {
254
- id: string;
255
- name: string;
256
- kind: "file";
257
- enabled: boolean;
258
- }
259
- type DynamicSourceConfig = DbSourceConfig | FileSourceConfig;
260
- interface DatasourcesConfig {
261
- sources: DynamicSourceConfig[];
262
- }
263
- type DbSourceType = DbSourceConfig["dbType"];
264
- declare function isDbType(v: unknown): v is DbSourceType;
265
- /**
266
- * 从 JSON 读取配置:文件缺失返回空配置({ sources: [] });格式非法抛错。
267
- */
268
- declare function loadConfigFile(target: string): DatasourcesConfig;
269
- /** 原子写:tmp + rename;同步 fs 调用单进程内天然串行 */
270
- declare function writeConfigFile(config: DatasourcesConfig, target: string): void;
271
- type ValidateResult = {
272
- ok: true;
273
- config: DynamicSourceConfig;
274
- } | {
275
- ok: false;
276
- errors: string[];
277
- };
278
- /** 校验并规范化数据源配置(只支持 db | file) */
279
- declare function validateSourceConfig(input: unknown): ValidateResult;
280
- /** 新增或覆盖动态源(同 id 覆盖);纯函数,返回新配置对象 */
281
- declare function upsertSource(config: DatasourcesConfig, source: DynamicSourceConfig): DatasourcesConfig;
282
- /** 删除动态源;纯函数,返回新配置对象(不存在时内容不变) */
283
- declare function deleteSource(config: DatasourcesConfig, id: string): DatasourcesConfig;
284
- declare const MASKED_PLACEHOLDER = "***";
285
- /**
286
- * 脱敏连接串:隐藏 userinfo 密码与 password 类 query 参数。
287
- */
288
- declare function maskConnectionString(conn: string): string;
289
-
290
- interface DataSourceDescriptor {
291
- id: string;
292
- name: string;
293
- kind: "db" | "file";
294
- tools: string[];
295
- enabled: boolean;
296
- dbType?: DbSourceType;
297
- maskedConnectionString?: string;
298
- }
299
- interface HealthResult {
300
- ok: boolean;
301
- latencyMs: number;
302
- error?: string;
303
- }
304
- interface ActiveSourceSummary {
305
- id: string;
306
- name: string;
307
- kind: DataSourceDescriptor["kind"] | "mcp";
308
- dbType?: DbSourceType;
309
- tools: string[];
310
- }
311
- type McpConnection = DbToolsConnection;
312
- interface DatasourceToolBinding {
313
- name: string;
314
- originalName: string;
315
- description?: string;
316
- inputSchema?: unknown;
317
- call(args: Record<string, unknown>): Promise<unknown>;
318
- }
319
- /** 向后兼容别名 */
320
- type McpToolBinding = DatasourceToolBinding;
321
- interface DatasourceManager {
322
- readConfig(): DatasourcesConfig;
323
- writeConfig(c: DatasourcesConfig): void;
324
- validate(s: DynamicSourceConfig): ValidateResult;
325
- upsert(s: DynamicSourceConfig): DatasourcesConfig;
326
- delete(id: string): DatasourcesConfig;
327
- get(id: string): DynamicSourceConfig | undefined;
328
- list(): DataSourceDescriptor[];
329
- connect(s: DynamicSourceConfig): Promise<DbToolsConnection>;
330
- tools(s: DynamicSourceConfig): Promise<DatasourceToolBinding[]>;
331
- close(id: string): Promise<void>;
332
- health(s: DynamicSourceConfig): Promise<HealthResult>;
333
- resolveActive(ids: string[] | undefined): ActiveSourceSummary[];
334
- ingestFiles(id: string, uploads: FileSourceUpload[]): Promise<FileSourceManifest>;
335
- filesManifest(id: string): Promise<FileSourceManifest | null>;
336
- removeFiles(id: string): Promise<void>;
337
- getSchemaCard(id: string): Promise<{
338
- card: SchemaCard;
339
- stale: boolean;
340
- } | null>;
341
- refreshSchemaCard(id: string): Promise<void>;
342
- getDialectClient?(id: string): {
343
- client: DbDialectClient;
344
- dbType: string;
345
- } | undefined;
346
- getQueryCache?(): QueryCacheManager<unknown>;
347
- gateway?: QueryGateway;
348
- }
349
- interface CreateDatasourceManagerOptions {
350
- configPath: string;
351
- filesDir?: string;
352
- schemaCardsDir?: string;
353
- maxCacheEntries?: number;
354
- defaultCacheTtlMs?: number;
355
- explainOptions?: ExplainOptions;
356
- }
357
- declare function describeDynamicSource(s: DynamicSourceConfig): DataSourceDescriptor;
358
- declare function createDatasourceManager(opts: CreateDatasourceManagerOptions): DatasourceManager;
359
- declare function mergeToolSets(target: Record<string, unknown>, incoming: Record<string, unknown>, sourceId: string): void;
360
-
361
- export { describeDynamicSource as B, FILE_SOURCE_EXTENSIONS as F, formatCacheKey as G, formatCacheKeyDisplay as I, isDbType as J, isSupportedUpload as K, loadConfigFile as L, MASKED_PLACEHOLDER as M, maskConnectionString as N, mergeToolSets as O, normalizeSqlForCache as P, QueryCacheManager as Q, sanitizeTableName as R, upsertSource as S, validateSourceConfig as U, writeConfigFile as W, FILE_SOURCE_MAX_BYTES as k, McpGateway as q, QueryGateway as u, computeQueryHashKey as x, createDatasourceManager as y, deleteSource as z };
362
- export type { ActiveSourceSummary as A, CacheEntry as C, DatasourceToolBinding as D, ExplainOptions as E, HealthResult as H, TableDetailResource as T, ValidateResult as V, ExplainCostReport as a, CatalogOverviewItem as b, CreateDatasourceManagerOptions as c, DataSourceDescriptor as d, DatasourceManager as e, DatasourcesConfig as f, DbSourceConfig as g, DbSourceType as h, DynamicSourceConfig as i, ExecuteQueryArgs as j, FileSourceConfig as l, FileSourceManifest as m, FileSourceUpload as n, FileTableInfo as o, McpConnection as p, McpGatewayConfig as r, McpToolBinding as s, QueryCacheKey as t, QueryGatewayConfig as v, QueryResultWithMeta as w };