@kosha-ai/integration-clickhouse 0.7.0 → 0.8.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.
@@ -0,0 +1,2 @@
1
+ export { clickhouse, clickhouse as default, ClickHouseConnectionError, } from './lib/integration-clickhouse.js';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,UAAU,IAAI,OAAO,EACrB,yBAAyB,GAC1B,MAAM,iCAAiC,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { clickhouse, clickhouse as default, ClickHouseConnectionError, } from './lib/integration-clickhouse.js';
@@ -0,0 +1,13 @@
1
+ import type { KoshaIntegration } from '@kosha-ai/integration-sdk';
2
+ export declare class ClickHouseConnectionError extends Error {
3
+ constructor(message: string);
4
+ }
5
+ /**
6
+ * A ClickHouse server, reached over its HTTP interface — but as a database,
7
+ * not a REST API, hence `query` rather than `api`. Every call is read-only:
8
+ * Kosha has no write path for this integration regardless of what the
9
+ * connected ClickHouse user is otherwise allowed to do.
10
+ */
11
+ export declare function clickhouse(): KoshaIntegration;
12
+ export default clickhouse;
13
+ //# sourceMappingURL=integration-clickhouse.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"integration-clickhouse.d.ts","sourceRoot":"","sources":["../../src/lib/integration-clickhouse.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAIV,gBAAgB,EAEjB,MAAM,2BAA2B,CAAC;AAInC,qBAAa,yBAA0B,SAAQ,KAAK;gBACtC,OAAO,EAAE,MAAM;CAI5B;AA6KD;;;;;GAKG;AACH,wBAAgB,UAAU,IAAI,gBAAgB,CAuF7C;AAED,eAAe,UAAU,CAAC"}
@@ -0,0 +1,215 @@
1
+ import { ClickHouseLogLevel, createClient, } from '@clickhouse/client';
2
+ import { assertAllowedHost, assertPrivateHost, basic as basicAuth, defineIntegration, packageDirs, } from '@kosha-ai/integration-sdk';
3
+ const { docsPath, migrationsPath } = packageDirs(import.meta.url);
4
+ export class ClickHouseConnectionError extends Error {
5
+ constructor(message) {
6
+ super(message);
7
+ this.name = 'ClickHouseConnectionError';
8
+ }
9
+ }
10
+ const DEFAULT_PORTS = { https: 8443, http: 8123 };
11
+ const MAX_EXECUTION_TIME_SECONDS = 30;
12
+ // A little longer than the server-side limit, so a slow query reports
13
+ // ClickHouse's own timeout error rather than the client giving up first.
14
+ const REQUEST_TIMEOUT_MS = (MAX_EXECUTION_TIME_SECONDS + 5) * 1000;
15
+ // The whole result is held in Kosha's memory before it is returned, so a
16
+ // query that would return more is refused by ClickHouse rather than loaded.
17
+ const MAX_RESULT_ROWS = 10_000;
18
+ const MAX_RESULT_BYTES = 50 * 1024 * 1024;
19
+ function required(fields, key) {
20
+ const value = fields?.[key];
21
+ if (typeof value !== 'string' || value.trim() === '') {
22
+ throw new ClickHouseConnectionError(`${key} is missing from this configuration`);
23
+ }
24
+ return value;
25
+ }
26
+ /**
27
+ * `accessToken` is `base64(username:password)` — the same encoding
28
+ * `envelopeForCredential`'s `BASIC` case in the server produces for every
29
+ * Basic-auth integration.
30
+ */
31
+ function decodeCredential(credential) {
32
+ const [username, ...rest] = Buffer.from(credential.accessToken, 'base64')
33
+ .toString('utf8')
34
+ .split(':');
35
+ if (!username) {
36
+ throw new ClickHouseConnectionError('Credential did not decode to a username and password');
37
+ }
38
+ return { username, password: rest.join(':') };
39
+ }
40
+ /**
41
+ * `url` is the server's full HTTP address, `https://host:port` or
42
+ * `http://host:port`. The server already refused any other scheme when the
43
+ * configuration was saved (a `url` field); it is checked again here because a
44
+ * row saved before that check, or written straight to the table, never went
45
+ * through it.
46
+ */
47
+ function parseUrl(raw) {
48
+ let url;
49
+ try {
50
+ url = new URL(raw.trim());
51
+ }
52
+ catch {
53
+ throw new ClickHouseConnectionError(`url must be a full address such as https://host:8443, not ${raw}`);
54
+ }
55
+ const protocol = url.protocol.slice(0, -1);
56
+ if (protocol !== 'https' && protocol !== 'http') {
57
+ throw new ClickHouseConnectionError(`url must start with https:// or http://, not ${raw}`);
58
+ }
59
+ // `URL` drops a port that equals the scheme's own default (443, 80), so read
60
+ // it back from what was written before falling back to ClickHouse's ports.
61
+ const authority = raw
62
+ .trim()
63
+ .replace(/^[a-z]+:\/\//i, '')
64
+ .split(/[/?#]/)[0];
65
+ const written = url.port || /:(\d+)$/.exec(authority)?.[1];
66
+ return {
67
+ protocol,
68
+ // An IPv6 literal comes back bracketed; the host checks want it bare.
69
+ host: url.hostname.replace(/^\[|\]$/g, ''),
70
+ port: written ? Number(written) : DEFAULT_PORTS[protocol],
71
+ };
72
+ }
73
+ function targetOf(fields, credential) {
74
+ const { username, password } = decodeCredential(credential);
75
+ const { protocol, host, port } = parseUrl(required(fields, 'url'));
76
+ const urlHost = host.includes(':') ? `[${host}]` : host;
77
+ return {
78
+ url: `${protocol}://${urlHost}:${port}`,
79
+ protocol,
80
+ host,
81
+ database: required(fields, 'database'),
82
+ username,
83
+ password,
84
+ };
85
+ }
86
+ /**
87
+ * Opens a fresh client, hands it to `fn`, and always closes it.
88
+ *
89
+ * Read-only is enforced by ClickHouse itself: every request carries
90
+ * `readonly=1`, which the server applies before running the statement and
91
+ * which rejects INSERT/ALTER/CREATE/DROP — Kosha never parses the SQL text.
92
+ * `1` rather than `2` because `1` also forbids the query from changing any
93
+ * setting itself, so a `SETTINGS max_execution_time=…` clause cannot lift
94
+ * the timeout sent alongside it (settings on the request are still
95
+ * accepted). ClickHouse has no transactions to roll back, so this setting is
96
+ * the whole of the guarantee.
97
+ *
98
+ * No connection pooling across calls: every call builds and closes its own
99
+ * client, so no two calls — or tenants — ever share one.
100
+ */
101
+ async function withReadOnlyClient(fields, credential, fn) {
102
+ const target = targetOf(fields, credential);
103
+ // Re-checked on every call, not only when the configuration was saved: a
104
+ // hostname that resolved yesterday may not today. Over http the username
105
+ // and password travel in the clear, so http is refused unless every address
106
+ // the host resolves to is private.
107
+ await assertAllowedHost(target.host);
108
+ if (target.protocol === 'http')
109
+ await assertPrivateHost(target.host);
110
+ const client = createClient({
111
+ url: target.url,
112
+ username: target.username,
113
+ password: target.password,
114
+ database: target.database,
115
+ request_timeout: REQUEST_TIMEOUT_MS,
116
+ // A refused query is the caller's to read, in the response Kosha sends
117
+ // back; left on, the client also prints every one as an error, stack and
118
+ // all, to the server's log.
119
+ log: { level: ClickHouseLogLevel.OFF },
120
+ clickhouse_settings: {
121
+ readonly: '1',
122
+ max_execution_time: MAX_EXECUTION_TIME_SECONDS,
123
+ // `throw`, not `break`: a cut-off result would look complete.
124
+ max_result_rows: String(MAX_RESULT_ROWS),
125
+ max_result_bytes: String(MAX_RESULT_BYTES),
126
+ result_overflow_mode: 'throw',
127
+ },
128
+ });
129
+ try {
130
+ return await fn(client);
131
+ }
132
+ finally {
133
+ await client.close().catch(() => undefined);
134
+ }
135
+ }
136
+ /**
137
+ * A ClickHouse server, reached over its HTTP interface — but as a database,
138
+ * not a REST API, hence `query` rather than `api`. Every call is read-only:
139
+ * Kosha has no write path for this integration regardless of what the
140
+ * connected ClickHouse user is otherwise allowed to do.
141
+ */
142
+ export function clickhouse() {
143
+ return defineIntegration({
144
+ key: 'clickhouse',
145
+ name: 'ClickHouse',
146
+ docsPath,
147
+ migrationsPath,
148
+ auth: basicAuth(),
149
+ configFields: [
150
+ {
151
+ key: 'url',
152
+ label: 'URL',
153
+ type: 'url',
154
+ required: true,
155
+ help: 'The ClickHouse HTTP address, https://host:port or http://host:port (the port defaults to 8443 for https, 8123 for http), e.g. https://abc123.us-east-1.aws.clickhouse.cloud:8443. http is refused unless the host resolves only to private addresses, since the password would otherwise cross the internet unencrypted.',
156
+ },
157
+ {
158
+ key: 'database',
159
+ label: 'Database',
160
+ type: 'string',
161
+ required: true,
162
+ },
163
+ ],
164
+ query: {
165
+ readOnly: true,
166
+ async run({ credential, fields, sql, params }) {
167
+ // ClickHouse binds named, typed parameters ({name:Type}), which a
168
+ // positional array cannot describe.
169
+ // TODO: support named params, e.g. { "id": 42 } for {id:UInt32}.
170
+ // Today the query API only accepts params as a list ([42]), which
171
+ // ClickHouse cannot use, so callers must write values into the SQL.
172
+ // Allowing an object needs changes in the request DTO, the server's
173
+ // QueryRequest type and the SDK; then pass it here as `query_params`.
174
+ if (params && params.length > 0) {
175
+ throw new ClickHouseConnectionError('ClickHouse does not support positional params; inline the values in the SQL');
176
+ }
177
+ return withReadOnlyClient(fields, credential, async (client) => {
178
+ const result = await client.query({ query: sql, format: 'JSON' });
179
+ // The type argument is one row; the client wraps it in
180
+ // ClickHouse's JSON envelope (`meta`, `data`, `rows`).
181
+ const json = await result.json();
182
+ return {
183
+ rows: json.data,
184
+ fields: (json.meta ?? []).map((column) => column.name),
185
+ rowCount: json.rows ?? json.data.length,
186
+ };
187
+ });
188
+ },
189
+ },
190
+ identity: {
191
+ /**
192
+ * `http` is unusable here — it is bound to no base URL — so it is
193
+ * ignored; the same real connection this integration will later query
194
+ * with is what proves the credential.
195
+ */
196
+ async fetchAccount({ accessToken, fields }) {
197
+ const credential = { accessToken };
198
+ const { host, database } = targetOf(fields, credential);
199
+ const user = await withReadOnlyClient(fields, credential, async (client) => {
200
+ const result = await client.query({
201
+ query: 'SELECT currentUser() AS user',
202
+ format: 'JSONEachRow',
203
+ });
204
+ const [row] = await result.json();
205
+ if (!row?.user) {
206
+ throw new ClickHouseConnectionError('ClickHouse did not report the current user');
207
+ }
208
+ return row.user;
209
+ });
210
+ return { externalAccountId: `${user}@${host}/${database}` };
211
+ },
212
+ },
213
+ });
214
+ }
215
+ export default clickhouse;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kosha-ai/integration-clickhouse",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "ClickHouse integration for Kosha: read-only queries against a connected ClickHouse server",
5
5
  "keywords": [
6
6
  "kosha",
@@ -48,9 +48,9 @@
48
48
  "key": "clickhouse"
49
49
  },
50
50
  "peerDependencies": {
51
- "@kosha-ai/integration-sdk": "0.7.0"
51
+ "@kosha-ai/integration-sdk": "0.8.0"
52
52
  },
53
53
  "devDependencies": {
54
- "@kosha-ai/integration-sdk": "0.7.0"
54
+ "@kosha-ai/integration-sdk": "0.8.0"
55
55
  }
56
56
  }