@mastra/clickhouse 0.11.1-alpha.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.
@@ -2,6 +2,7 @@ import type { ClickHouseClient } from '@clickhouse/client';
2
2
  import { createClient } from '@clickhouse/client';
3
3
  import { MessageList } from '@mastra/core/agent';
4
4
  import type { MastraMessageContentV2 } from '@mastra/core/agent';
5
+ import { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';
5
6
  import type { MetricResult, TestInfo } from '@mastra/core/eval';
6
7
  import type { MastraMessageV1, MastraMessageV2, StorageThreadType } from '@mastra/core/memory';
7
8
  import {
@@ -126,7 +127,12 @@ export class ClickhouseStore extends MastraStorage {
126
127
  const testInfoValue = row.test_info ? JSON.parse(row.test_info as string) : undefined;
127
128
 
128
129
  if (!resultValue || typeof resultValue !== 'object' || !('score' in resultValue)) {
129
- 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
+ });
130
136
  }
131
137
 
132
138
  return {
@@ -170,13 +176,19 @@ export class ClickhouseStore extends MastraStorage {
170
176
 
171
177
  const rows = await result.json();
172
178
  return rows.data.map((row: any) => this.transformEvalRow(row));
173
- } catch (error) {
174
- // Handle case where table doesn't exist yet
175
- 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')) {
176
181
  return [];
177
182
  }
178
- this.logger.error('Failed to get evals for the specified agent: ' + (error as any)?.message);
179
- 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
+ );
180
192
  }
181
193
  }
182
194
 
@@ -202,9 +214,16 @@ export class ClickhouseStore extends MastraStorage {
202
214
  output_format_json_quote_64bit_integers: 0,
203
215
  },
204
216
  });
205
- } catch (error) {
206
- console.error(`Error inserting into ${tableName}:`, error);
207
- 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
+ );
208
227
  }
209
228
  }
210
229
 
@@ -269,52 +288,100 @@ export class ClickhouseStore extends MastraStorage {
269
288
 
270
289
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
271
290
 
272
- const result = await this.db.query({
273
- query: `SELECT *, toDateTime64(createdAt, 3) as createdAt FROM ${TABLE_TRACES} ${whereClause} ORDER BY "createdAt" DESC LIMIT ${limit} OFFSET ${offset}`,
274
- query_params: args,
275
- clickhouse_settings: {
276
- // Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
277
- date_time_input_format: 'best_effort',
278
- date_time_output_format: 'iso',
279
- use_client_time_zone: 1,
280
- output_format_json_quote_64bit_integers: 0,
281
- },
282
- });
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
+ });
283
303
 
284
- if (!result) {
285
- return [];
286
- }
304
+ if (!result) {
305
+ return [];
306
+ }
287
307
 
288
- const resp = await result.json();
289
- const rows: any[] = resp.data;
290
- return rows.map(row => ({
291
- id: row.id,
292
- parentSpanId: row.parentSpanId,
293
- traceId: row.traceId,
294
- name: row.name,
295
- scope: row.scope,
296
- kind: row.kind,
297
- status: safelyParseJSON(row.status as string),
298
- events: safelyParseJSON(row.events as string),
299
- links: safelyParseJSON(row.links as string),
300
- attributes: safelyParseJSON(row.attributes as string),
301
- startTime: row.startTime,
302
- endTime: row.endTime,
303
- other: safelyParseJSON(row.other as string),
304
- createdAt: row.createdAt,
305
- }));
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
+ }
306
349
  }
307
350
 
308
351
  async optimizeTable({ tableName }: { tableName: TABLE_NAMES }): Promise<void> {
309
- await this.db.command({
310
- query: `OPTIMIZE TABLE ${tableName} FINAL`,
311
- });
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
+ }
312
367
  }
313
368
 
314
369
  async materializeTtl({ tableName }: { tableName: TABLE_NAMES }): Promise<void> {
315
- await this.db.command({
316
- query: `ALTER TABLE ${tableName} MATERIALIZE TTL;`,
317
- });
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
+ }
318
385
  }
319
386
 
320
387
  async createTable({
@@ -368,9 +435,16 @@ export class ClickhouseStore extends MastraStorage {
368
435
  output_format_json_quote_64bit_integers: 0,
369
436
  },
370
437
  });
371
- } catch (error) {
372
- console.error(`Error creating table ${tableName}:`, error);
373
- 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
+ );
374
448
  }
375
449
  }
376
450
 
@@ -433,11 +507,16 @@ export class ClickhouseStore extends MastraStorage {
433
507
  this.logger?.debug?.(`Added column ${columnName} to table ${tableName}`);
434
508
  }
435
509
  }
436
- } catch (error) {
437
- this.logger?.error?.(
438
- `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,
439
519
  );
440
- throw new Error(`Failed to alter table ${tableName}: ${error}`);
441
520
  }
442
521
  }
443
522
 
@@ -453,9 +532,16 @@ export class ClickhouseStore extends MastraStorage {
453
532
  output_format_json_quote_64bit_integers: 0,
454
533
  },
455
534
  });
456
- } catch (error) {
457
- console.error(`Error clearing table ${tableName}:`, error);
458
- 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
+ );
459
545
  }
460
546
  }
461
547
 
@@ -478,9 +564,16 @@ export class ClickhouseStore extends MastraStorage {
478
564
  use_client_time_zone: 1,
479
565
  },
480
566
  });
481
- } catch (error) {
482
- console.error(`Error inserting into ${tableName}:`, error);
483
- 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
+ );
484
577
  }
485
578
  }
486
579
 
@@ -529,8 +622,15 @@ export class ClickhouseStore extends MastraStorage {
529
622
  const data: R = transformRow(rows.data[0]);
530
623
  return data;
531
624
  } catch (error) {
532
- console.error(`Error loading from ${tableName}:`, error);
533
- 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
+ );
534
634
  }
535
635
  }
536
636
 
@@ -570,9 +670,16 @@ export class ClickhouseStore extends MastraStorage {
570
670
  createdAt: thread.createdAt,
571
671
  updatedAt: thread.updatedAt,
572
672
  };
573
- } catch (error) {
574
- console.error(`Error getting thread ${threadId}:`, error);
575
- 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
+ );
576
683
  }
577
684
  }
578
685
 
@@ -608,8 +715,15 @@ export class ClickhouseStore extends MastraStorage {
608
715
  updatedAt: thread.updatedAt,
609
716
  }));
610
717
  } catch (error) {
611
- console.error(`Error getting threads for resource ${resourceId}:`, error);
612
- 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
+ );
613
727
  }
614
728
  }
615
729
 
@@ -635,8 +749,15 @@ export class ClickhouseStore extends MastraStorage {
635
749
 
636
750
  return thread;
637
751
  } catch (error) {
638
- console.error('Error saving thread:', error);
639
- 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
+ );
640
761
  }
641
762
  }
642
763
 
@@ -691,8 +812,15 @@ export class ClickhouseStore extends MastraStorage {
691
812
 
692
813
  return updatedThread;
693
814
  } catch (error) {
694
- console.error('Error updating thread:', error);
695
- 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
+ );
696
824
  }
697
825
  }
698
826
 
@@ -716,8 +844,15 @@ export class ClickhouseStore extends MastraStorage {
716
844
  },
717
845
  });
718
846
  } catch (error) {
719
- console.error('Error deleting thread:', error);
720
- 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
+ );
721
856
  }
722
857
  }
723
858
 
@@ -731,7 +866,7 @@ export class ClickhouseStore extends MastraStorage {
731
866
  }: StorageGetMessagesArg & { format?: 'v1' | 'v2' }): Promise<MastraMessageV1[] | MastraMessageV2[]> {
732
867
  try {
733
868
  const messages: any[] = [];
734
- const limit = typeof selectBy?.last === `number` ? selectBy.last : 40;
869
+ const limit = this.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
735
870
  const include = selectBy?.include || [];
736
871
 
737
872
  if (include.length) {
@@ -839,8 +974,15 @@ export class ClickhouseStore extends MastraStorage {
839
974
  if (format === `v2`) return list.get.all.v2();
840
975
  return list.get.all.v1();
841
976
  } catch (error) {
842
- console.error('Error getting messages:', error);
843
- 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
+ );
844
986
  }
845
987
  }
846
988
 
@@ -911,9 +1053,15 @@ export class ClickhouseStore extends MastraStorage {
911
1053
  const list = new MessageList({ threadId, resourceId }).add(messages, 'memory');
912
1054
  if (format === `v2`) return list.get.all.v2();
913
1055
  return list.get.all.v1();
914
- } catch (error) {
915
- console.error('Error saving messages:', error);
916
- 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
+ );
917
1065
  }
918
1066
  }
919
1067
 
@@ -958,9 +1106,16 @@ export class ClickhouseStore extends MastraStorage {
958
1106
  output_format_json_quote_64bit_integers: 0,
959
1107
  },
960
1108
  });
961
- } catch (error) {
962
- console.error('Error persisting workflow snapshot:', error);
963
- 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
+ );
964
1119
  }
965
1120
  }
966
1121
 
@@ -985,9 +1140,16 @@ export class ClickhouseStore extends MastraStorage {
985
1140
  }
986
1141
 
987
1142
  return (result as any).snapshot;
988
- } catch (error) {
989
- console.error('Error loading workflow snapshot:', error);
990
- 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
+ );
991
1153
  }
992
1154
  }
993
1155
 
@@ -1100,9 +1262,16 @@ export class ClickhouseStore extends MastraStorage {
1100
1262
 
1101
1263
  // Use runs.length as total when not paginating
1102
1264
  return { runs, total: total || runs.length };
1103
- } catch (error) {
1104
- console.error('Error getting workflow runs:', error);
1105
- 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
+ );
1106
1275
  }
1107
1276
  }
1108
1277
 
@@ -1151,9 +1320,16 @@ export class ClickhouseStore extends MastraStorage {
1151
1320
  return null;
1152
1321
  }
1153
1322
  return this.parseWorkflowRun(resultJson[0]);
1154
- } catch (error) {
1155
- console.error('Error getting workflow run by ID:', error);
1156
- 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
+ );
1157
1333
  }
1158
1334
  }
1159
1335
 
@@ -1167,7 +1343,12 @@ export class ClickhouseStore extends MastraStorage {
1167
1343
  }
1168
1344
 
1169
1345
  async getTracesPaginated(_args: StorageGetTracesArg): Promise<PaginationInfo & { traces: Trace[] }> {
1170
- 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
+ });
1171
1352
  }
1172
1353
 
1173
1354
  async getThreadsByResourceIdPaginated(_args: {
@@ -1175,13 +1356,23 @@ export class ClickhouseStore extends MastraStorage {
1175
1356
  page?: number;
1176
1357
  perPage?: number;
1177
1358
  }): Promise<PaginationInfo & { threads: StorageThreadType[] }> {
1178
- 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
+ });
1179
1365
  }
1180
1366
 
1181
1367
  async getMessagesPaginated(
1182
1368
  _args: StorageGetMessagesArg,
1183
1369
  ): Promise<PaginationInfo & { messages: MastraMessageV1[] | MastraMessageV2[] }> {
1184
- 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
+ });
1185
1376
  }
1186
1377
 
1187
1378
  async close(): Promise<void> {