@mastra/clickhouse 0.11.0 → 0.11.1-alpha.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,6 +1,8 @@
1
1
  import type { ClickHouseClient } from '@clickhouse/client';
2
2
  import { createClient } from '@clickhouse/client';
3
3
  import { MessageList } from '@mastra/core/agent';
4
+ import type { MastraMessageContentV2 } from '@mastra/core/agent';
5
+ import { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';
4
6
  import type { MetricResult, TestInfo } from '@mastra/core/eval';
5
7
  import type { MastraMessageV1, MastraMessageV2, StorageThreadType } from '@mastra/core/memory';
6
8
  import {
@@ -125,7 +127,12 @@ export class ClickhouseStore extends MastraStorage {
125
127
  const testInfoValue = row.test_info ? JSON.parse(row.test_info as string) : undefined;
126
128
 
127
129
  if (!resultValue || typeof resultValue !== 'object' || !('score' in resultValue)) {
128
- throw new Error(`Invalid MetricResult format: ${JSON.stringify(resultValue)}`);
130
+ throw new MastraError({
131
+ id: 'CLICKHOUSE_STORAGE_INVALID_METRIC_FORMAT',
132
+ text: `Invalid MetricResult format: ${JSON.stringify(resultValue)}`,
133
+ domain: ErrorDomain.STORAGE,
134
+ category: ErrorCategory.USER,
135
+ });
129
136
  }
130
137
 
131
138
  return {
@@ -169,13 +176,19 @@ export class ClickhouseStore extends MastraStorage {
169
176
 
170
177
  const rows = await result.json();
171
178
  return rows.data.map((row: any) => this.transformEvalRow(row));
172
- } catch (error) {
173
- // Handle case where table doesn't exist yet
174
- if (error instanceof Error && error.message.includes('no such table')) {
179
+ } catch (error: any) {
180
+ if (error?.message?.includes('no such table') || error?.message?.includes('does not exist')) {
175
181
  return [];
176
182
  }
177
- this.logger.error('Failed to get evals for the specified agent: ' + (error as any)?.message);
178
- throw error;
183
+ throw new MastraError(
184
+ {
185
+ id: 'CLICKHOUSE_STORAGE_GET_EVALS_BY_AGENT_FAILED',
186
+ domain: ErrorDomain.STORAGE,
187
+ category: ErrorCategory.THIRD_PARTY,
188
+ details: { agentName, type: type ?? null },
189
+ },
190
+ error,
191
+ );
179
192
  }
180
193
  }
181
194
 
@@ -201,9 +214,16 @@ export class ClickhouseStore extends MastraStorage {
201
214
  output_format_json_quote_64bit_integers: 0,
202
215
  },
203
216
  });
204
- } catch (error) {
205
- console.error(`Error inserting into ${tableName}:`, error);
206
- throw error;
217
+ } catch (error: any) {
218
+ throw new MastraError(
219
+ {
220
+ id: 'CLICKHOUSE_STORAGE_BATCH_INSERT_FAILED',
221
+ domain: ErrorDomain.STORAGE,
222
+ category: ErrorCategory.THIRD_PARTY,
223
+ details: { tableName },
224
+ },
225
+ error,
226
+ );
207
227
  }
208
228
  }
209
229
 
@@ -268,52 +288,100 @@ export class ClickhouseStore extends MastraStorage {
268
288
 
269
289
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
270
290
 
271
- const result = await this.db.query({
272
- query: `SELECT *, toDateTime64(createdAt, 3) as createdAt FROM ${TABLE_TRACES} ${whereClause} ORDER BY "createdAt" DESC LIMIT ${limit} OFFSET ${offset}`,
273
- query_params: args,
274
- clickhouse_settings: {
275
- // Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
276
- date_time_input_format: 'best_effort',
277
- date_time_output_format: 'iso',
278
- use_client_time_zone: 1,
279
- output_format_json_quote_64bit_integers: 0,
280
- },
281
- });
291
+ try {
292
+ const result = await this.db.query({
293
+ query: `SELECT *, toDateTime64(createdAt, 3) as createdAt FROM ${TABLE_TRACES} ${whereClause} ORDER BY "createdAt" DESC LIMIT ${limit} OFFSET ${offset}`,
294
+ query_params: args,
295
+ clickhouse_settings: {
296
+ // Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
297
+ date_time_input_format: 'best_effort',
298
+ date_time_output_format: 'iso',
299
+ use_client_time_zone: 1,
300
+ output_format_json_quote_64bit_integers: 0,
301
+ },
302
+ });
282
303
 
283
- if (!result) {
284
- return [];
285
- }
304
+ if (!result) {
305
+ return [];
306
+ }
286
307
 
287
- const resp = await result.json();
288
- const rows: any[] = resp.data;
289
- return rows.map(row => ({
290
- id: row.id,
291
- parentSpanId: row.parentSpanId,
292
- traceId: row.traceId,
293
- name: row.name,
294
- scope: row.scope,
295
- kind: row.kind,
296
- status: safelyParseJSON(row.status as string),
297
- events: safelyParseJSON(row.events as string),
298
- links: safelyParseJSON(row.links as string),
299
- attributes: safelyParseJSON(row.attributes as string),
300
- startTime: row.startTime,
301
- endTime: row.endTime,
302
- other: safelyParseJSON(row.other as string),
303
- createdAt: row.createdAt,
304
- }));
308
+ const resp = await result.json();
309
+ const rows: any[] = resp.data;
310
+ return rows.map(row => ({
311
+ id: row.id,
312
+ parentSpanId: row.parentSpanId,
313
+ traceId: row.traceId,
314
+ name: row.name,
315
+ scope: row.scope,
316
+ kind: row.kind,
317
+ status: safelyParseJSON(row.status as string),
318
+ events: safelyParseJSON(row.events as string),
319
+ links: safelyParseJSON(row.links as string),
320
+ attributes: safelyParseJSON(row.attributes as string),
321
+ startTime: row.startTime,
322
+ endTime: row.endTime,
323
+ other: safelyParseJSON(row.other as string),
324
+ createdAt: row.createdAt,
325
+ }));
326
+ } catch (error: any) {
327
+ if (error?.message?.includes('no such table') || error?.message?.includes('does not exist')) {
328
+ return [];
329
+ }
330
+ throw new MastraError(
331
+ {
332
+ id: 'CLICKHOUSE_STORAGE_GET_TRACES_FAILED',
333
+ domain: ErrorDomain.STORAGE,
334
+ category: ErrorCategory.THIRD_PARTY,
335
+ details: {
336
+ name: name ?? null,
337
+ scope: scope ?? null,
338
+ page,
339
+ perPage,
340
+ attributes: attributes ? JSON.stringify(attributes) : null,
341
+ filters: filters ? JSON.stringify(filters) : null,
342
+ fromDate: fromDate?.toISOString() ?? null,
343
+ toDate: toDate?.toISOString() ?? null,
344
+ },
345
+ },
346
+ error,
347
+ );
348
+ }
305
349
  }
306
350
 
307
351
  async optimizeTable({ tableName }: { tableName: TABLE_NAMES }): Promise<void> {
308
- await this.db.command({
309
- query: `OPTIMIZE TABLE ${tableName} FINAL`,
310
- });
352
+ try {
353
+ await this.db.command({
354
+ query: `OPTIMIZE TABLE ${tableName} FINAL`,
355
+ });
356
+ } catch (error: any) {
357
+ throw new MastraError(
358
+ {
359
+ id: 'CLICKHOUSE_STORAGE_OPTIMIZE_TABLE_FAILED',
360
+ domain: ErrorDomain.STORAGE,
361
+ category: ErrorCategory.THIRD_PARTY,
362
+ details: { tableName },
363
+ },
364
+ error,
365
+ );
366
+ }
311
367
  }
312
368
 
313
369
  async materializeTtl({ tableName }: { tableName: TABLE_NAMES }): Promise<void> {
314
- await this.db.command({
315
- query: `ALTER TABLE ${tableName} MATERIALIZE TTL;`,
316
- });
370
+ try {
371
+ await this.db.command({
372
+ query: `ALTER TABLE ${tableName} MATERIALIZE TTL;`,
373
+ });
374
+ } catch (error: any) {
375
+ throw new MastraError(
376
+ {
377
+ id: 'CLICKHOUSE_STORAGE_MATERIALIZE_TTL_FAILED',
378
+ domain: ErrorDomain.STORAGE,
379
+ category: ErrorCategory.THIRD_PARTY,
380
+ details: { tableName },
381
+ },
382
+ error,
383
+ );
384
+ }
317
385
  }
318
386
 
319
387
  async createTable({
@@ -367,9 +435,16 @@ export class ClickhouseStore extends MastraStorage {
367
435
  output_format_json_quote_64bit_integers: 0,
368
436
  },
369
437
  });
370
- } catch (error) {
371
- console.error(`Error creating table ${tableName}:`, error);
372
- throw error;
438
+ } catch (error: any) {
439
+ throw new MastraError(
440
+ {
441
+ id: 'CLICKHOUSE_STORAGE_CREATE_TABLE_FAILED',
442
+ domain: ErrorDomain.STORAGE,
443
+ category: ErrorCategory.THIRD_PARTY,
444
+ details: { tableName },
445
+ },
446
+ error,
447
+ );
373
448
  }
374
449
  }
375
450
 
@@ -432,11 +507,16 @@ export class ClickhouseStore extends MastraStorage {
432
507
  this.logger?.debug?.(`Added column ${columnName} to table ${tableName}`);
433
508
  }
434
509
  }
435
- } catch (error) {
436
- this.logger?.error?.(
437
- `Error altering table ${tableName}: ${error instanceof Error ? error.message : String(error)}`,
510
+ } catch (error: any) {
511
+ throw new MastraError(
512
+ {
513
+ id: 'CLICKHOUSE_STORAGE_ALTER_TABLE_FAILED',
514
+ domain: ErrorDomain.STORAGE,
515
+ category: ErrorCategory.THIRD_PARTY,
516
+ details: { tableName },
517
+ },
518
+ error,
438
519
  );
439
- throw new Error(`Failed to alter table ${tableName}: ${error}`);
440
520
  }
441
521
  }
442
522
 
@@ -452,9 +532,16 @@ export class ClickhouseStore extends MastraStorage {
452
532
  output_format_json_quote_64bit_integers: 0,
453
533
  },
454
534
  });
455
- } catch (error) {
456
- console.error(`Error clearing table ${tableName}:`, error);
457
- throw error;
535
+ } catch (error: any) {
536
+ throw new MastraError(
537
+ {
538
+ id: 'CLICKHOUSE_STORAGE_CLEAR_TABLE_FAILED',
539
+ domain: ErrorDomain.STORAGE,
540
+ category: ErrorCategory.THIRD_PARTY,
541
+ details: { tableName },
542
+ },
543
+ error,
544
+ );
458
545
  }
459
546
  }
460
547
 
@@ -477,9 +564,16 @@ export class ClickhouseStore extends MastraStorage {
477
564
  use_client_time_zone: 1,
478
565
  },
479
566
  });
480
- } catch (error) {
481
- console.error(`Error inserting into ${tableName}:`, error);
482
- throw error;
567
+ } catch (error: any) {
568
+ throw new MastraError(
569
+ {
570
+ id: 'CLICKHOUSE_STORAGE_INSERT_FAILED',
571
+ domain: ErrorDomain.STORAGE,
572
+ category: ErrorCategory.THIRD_PARTY,
573
+ details: { tableName },
574
+ },
575
+ error,
576
+ );
483
577
  }
484
578
  }
485
579
 
@@ -528,8 +622,15 @@ export class ClickhouseStore extends MastraStorage {
528
622
  const data: R = transformRow(rows.data[0]);
529
623
  return data;
530
624
  } catch (error) {
531
- console.error(`Error loading from ${tableName}:`, error);
532
- throw error;
625
+ throw new MastraError(
626
+ {
627
+ id: 'CLICKHOUSE_STORAGE_LOAD_FAILED',
628
+ domain: ErrorDomain.STORAGE,
629
+ category: ErrorCategory.THIRD_PARTY,
630
+ details: { tableName },
631
+ },
632
+ error,
633
+ );
533
634
  }
534
635
  }
535
636
 
@@ -569,9 +670,16 @@ export class ClickhouseStore extends MastraStorage {
569
670
  createdAt: thread.createdAt,
570
671
  updatedAt: thread.updatedAt,
571
672
  };
572
- } catch (error) {
573
- console.error(`Error getting thread ${threadId}:`, error);
574
- throw error;
673
+ } catch (error: any) {
674
+ throw new MastraError(
675
+ {
676
+ id: 'CLICKHOUSE_STORAGE_GET_THREAD_BY_ID_FAILED',
677
+ domain: ErrorDomain.STORAGE,
678
+ category: ErrorCategory.THIRD_PARTY,
679
+ details: { threadId },
680
+ },
681
+ error,
682
+ );
575
683
  }
576
684
  }
577
685
 
@@ -607,8 +715,15 @@ export class ClickhouseStore extends MastraStorage {
607
715
  updatedAt: thread.updatedAt,
608
716
  }));
609
717
  } catch (error) {
610
- console.error(`Error getting threads for resource ${resourceId}:`, error);
611
- throw error;
718
+ throw new MastraError(
719
+ {
720
+ id: 'CLICKHOUSE_STORAGE_GET_THREADS_BY_RESOURCE_ID_FAILED',
721
+ domain: ErrorDomain.STORAGE,
722
+ category: ErrorCategory.THIRD_PARTY,
723
+ details: { resourceId },
724
+ },
725
+ error,
726
+ );
612
727
  }
613
728
  }
614
729
 
@@ -634,8 +749,15 @@ export class ClickhouseStore extends MastraStorage {
634
749
 
635
750
  return thread;
636
751
  } catch (error) {
637
- console.error('Error saving thread:', error);
638
- throw error;
752
+ throw new MastraError(
753
+ {
754
+ id: 'CLICKHOUSE_STORAGE_SAVE_THREAD_FAILED',
755
+ domain: ErrorDomain.STORAGE,
756
+ category: ErrorCategory.THIRD_PARTY,
757
+ details: { threadId: thread.id },
758
+ },
759
+ error,
760
+ );
639
761
  }
640
762
  }
641
763
 
@@ -690,8 +812,15 @@ export class ClickhouseStore extends MastraStorage {
690
812
 
691
813
  return updatedThread;
692
814
  } catch (error) {
693
- console.error('Error updating thread:', error);
694
- throw error;
815
+ throw new MastraError(
816
+ {
817
+ id: 'CLICKHOUSE_STORAGE_UPDATE_THREAD_FAILED',
818
+ domain: ErrorDomain.STORAGE,
819
+ category: ErrorCategory.THIRD_PARTY,
820
+ details: { threadId: id, title },
821
+ },
822
+ error,
823
+ );
695
824
  }
696
825
  }
697
826
 
@@ -715,8 +844,15 @@ export class ClickhouseStore extends MastraStorage {
715
844
  },
716
845
  });
717
846
  } catch (error) {
718
- console.error('Error deleting thread:', error);
719
- throw error;
847
+ throw new MastraError(
848
+ {
849
+ id: 'CLICKHOUSE_STORAGE_DELETE_THREAD_FAILED',
850
+ domain: ErrorDomain.STORAGE,
851
+ category: ErrorCategory.THIRD_PARTY,
852
+ details: { threadId },
853
+ },
854
+ error,
855
+ );
720
856
  }
721
857
  }
722
858
 
@@ -730,7 +866,7 @@ export class ClickhouseStore extends MastraStorage {
730
866
  }: StorageGetMessagesArg & { format?: 'v1' | 'v2' }): Promise<MastraMessageV1[] | MastraMessageV2[]> {
731
867
  try {
732
868
  const messages: any[] = [];
733
- const limit = typeof selectBy?.last === `number` ? selectBy.last : 40;
869
+ const limit = this.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
734
870
  const include = selectBy?.include || [];
735
871
 
736
872
  if (include.length) {
@@ -838,8 +974,15 @@ export class ClickhouseStore extends MastraStorage {
838
974
  if (format === `v2`) return list.get.all.v2();
839
975
  return list.get.all.v1();
840
976
  } catch (error) {
841
- console.error('Error getting messages:', error);
842
- throw error;
977
+ throw new MastraError(
978
+ {
979
+ id: 'CLICKHOUSE_STORAGE_GET_MESSAGES_FAILED',
980
+ domain: ErrorDomain.STORAGE,
981
+ category: ErrorCategory.THIRD_PARTY,
982
+ details: { threadId, resourceId: resourceId ?? '' },
983
+ },
984
+ error,
985
+ );
843
986
  }
844
987
  }
845
988
 
@@ -910,9 +1053,15 @@ export class ClickhouseStore extends MastraStorage {
910
1053
  const list = new MessageList({ threadId, resourceId }).add(messages, 'memory');
911
1054
  if (format === `v2`) return list.get.all.v2();
912
1055
  return list.get.all.v1();
913
- } catch (error) {
914
- console.error('Error saving messages:', error);
915
- throw error;
1056
+ } catch (error: any) {
1057
+ throw new MastraError(
1058
+ {
1059
+ id: 'CLICKHOUSE_STORAGE_SAVE_MESSAGES_FAILED',
1060
+ domain: ErrorDomain.STORAGE,
1061
+ category: ErrorCategory.THIRD_PARTY,
1062
+ },
1063
+ error,
1064
+ );
916
1065
  }
917
1066
  }
918
1067
 
@@ -957,9 +1106,16 @@ export class ClickhouseStore extends MastraStorage {
957
1106
  output_format_json_quote_64bit_integers: 0,
958
1107
  },
959
1108
  });
960
- } catch (error) {
961
- console.error('Error persisting workflow snapshot:', error);
962
- throw error;
1109
+ } catch (error: any) {
1110
+ throw new MastraError(
1111
+ {
1112
+ id: 'CLICKHOUSE_STORAGE_PERSIST_WORKFLOW_SNAPSHOT_FAILED',
1113
+ domain: ErrorDomain.STORAGE,
1114
+ category: ErrorCategory.THIRD_PARTY,
1115
+ details: { workflowName, runId },
1116
+ },
1117
+ error,
1118
+ );
963
1119
  }
964
1120
  }
965
1121
 
@@ -984,9 +1140,16 @@ export class ClickhouseStore extends MastraStorage {
984
1140
  }
985
1141
 
986
1142
  return (result as any).snapshot;
987
- } catch (error) {
988
- console.error('Error loading workflow snapshot:', error);
989
- throw error;
1143
+ } catch (error: any) {
1144
+ throw new MastraError(
1145
+ {
1146
+ id: 'CLICKHOUSE_STORAGE_LOAD_WORKFLOW_SNAPSHOT_FAILED',
1147
+ domain: ErrorDomain.STORAGE,
1148
+ category: ErrorCategory.THIRD_PARTY,
1149
+ details: { workflowName, runId },
1150
+ },
1151
+ error,
1152
+ );
990
1153
  }
991
1154
  }
992
1155
 
@@ -1099,9 +1262,16 @@ export class ClickhouseStore extends MastraStorage {
1099
1262
 
1100
1263
  // Use runs.length as total when not paginating
1101
1264
  return { runs, total: total || runs.length };
1102
- } catch (error) {
1103
- console.error('Error getting workflow runs:', error);
1104
- throw error;
1265
+ } catch (error: any) {
1266
+ throw new MastraError(
1267
+ {
1268
+ id: 'CLICKHOUSE_STORAGE_GET_WORKFLOW_RUNS_FAILED',
1269
+ domain: ErrorDomain.STORAGE,
1270
+ category: ErrorCategory.THIRD_PARTY,
1271
+ details: { workflowName: workflowName ?? '', resourceId: resourceId ?? '' },
1272
+ },
1273
+ error,
1274
+ );
1105
1275
  }
1106
1276
  }
1107
1277
 
@@ -1150,9 +1320,16 @@ export class ClickhouseStore extends MastraStorage {
1150
1320
  return null;
1151
1321
  }
1152
1322
  return this.parseWorkflowRun(resultJson[0]);
1153
- } catch (error) {
1154
- console.error('Error getting workflow run by ID:', error);
1155
- throw error;
1323
+ } catch (error: any) {
1324
+ throw new MastraError(
1325
+ {
1326
+ id: 'CLICKHOUSE_STORAGE_GET_WORKFLOW_RUN_BY_ID_FAILED',
1327
+ domain: ErrorDomain.STORAGE,
1328
+ category: ErrorCategory.THIRD_PARTY,
1329
+ details: { runId: runId ?? '', workflowName: workflowName ?? '' },
1330
+ },
1331
+ error,
1332
+ );
1156
1333
  }
1157
1334
  }
1158
1335
 
@@ -1166,7 +1343,12 @@ export class ClickhouseStore extends MastraStorage {
1166
1343
  }
1167
1344
 
1168
1345
  async getTracesPaginated(_args: StorageGetTracesArg): Promise<PaginationInfo & { traces: Trace[] }> {
1169
- throw new Error('Method not implemented.');
1346
+ throw new MastraError({
1347
+ id: 'CLICKHOUSE_STORAGE_GET_TRACES_PAGINATED_FAILED',
1348
+ domain: ErrorDomain.STORAGE,
1349
+ category: ErrorCategory.USER,
1350
+ text: 'Method not implemented.',
1351
+ });
1170
1352
  }
1171
1353
 
1172
1354
  async getThreadsByResourceIdPaginated(_args: {
@@ -1174,16 +1356,37 @@ export class ClickhouseStore extends MastraStorage {
1174
1356
  page?: number;
1175
1357
  perPage?: number;
1176
1358
  }): Promise<PaginationInfo & { threads: StorageThreadType[] }> {
1177
- throw new Error('Method not implemented.');
1359
+ throw new MastraError({
1360
+ id: 'CLICKHOUSE_STORAGE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED',
1361
+ domain: ErrorDomain.STORAGE,
1362
+ category: ErrorCategory.USER,
1363
+ text: 'Method not implemented.',
1364
+ });
1178
1365
  }
1179
1366
 
1180
1367
  async getMessagesPaginated(
1181
1368
  _args: StorageGetMessagesArg,
1182
1369
  ): Promise<PaginationInfo & { messages: MastraMessageV1[] | MastraMessageV2[] }> {
1183
- throw new Error('Method not implemented.');
1370
+ throw new MastraError({
1371
+ id: 'CLICKHOUSE_STORAGE_GET_MESSAGES_PAGINATED_FAILED',
1372
+ domain: ErrorDomain.STORAGE,
1373
+ category: ErrorCategory.USER,
1374
+ text: 'Method not implemented.',
1375
+ });
1184
1376
  }
1185
1377
 
1186
1378
  async close(): Promise<void> {
1187
1379
  await this.db.close();
1188
1380
  }
1381
+
1382
+ async updateMessages(_args: {
1383
+ messages: Partial<Omit<MastraMessageV2, 'createdAt'>> &
1384
+ {
1385
+ id: string;
1386
+ content?: { metadata?: MastraMessageContentV2['metadata']; content?: MastraMessageContentV2['content'] };
1387
+ }[];
1388
+ }): Promise<MastraMessageV2[]> {
1389
+ this.logger.error('updateMessages is not yet implemented in ClickhouseStore');
1390
+ throw new Error('Method not implemented');
1391
+ }
1189
1392
  }