@mastra/cloudflare-d1 0.0.0-scorers-ui-refactored-20250916094952 → 0.0.0-scorers-logs-20251208101616
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/CHANGELOG.md +667 -3
- package/README.md +10 -5
- package/dist/index.cjs +333 -624
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +334 -625
- package/dist/index.js.map +1 -1
- package/dist/storage/domains/memory/index.d.ts +13 -44
- package/dist/storage/domains/memory/index.d.ts.map +1 -1
- package/dist/storage/domains/operations/index.d.ts.map +1 -1
- package/dist/storage/domains/scores/index.d.ts +13 -5
- package/dist/storage/domains/scores/index.d.ts.map +1 -1
- package/dist/storage/domains/workflows/index.d.ts +3 -10
- package/dist/storage/domains/workflows/index.d.ts.map +1 -1
- package/dist/storage/index.d.ts +57 -96
- package/dist/storage/index.d.ts.map +1 -1
- package/package.json +16 -11
- package/dist/storage/domains/legacy-evals/index.d.ts +0 -20
- package/dist/storage/domains/legacy-evals/index.d.ts.map +0 -1
- package/dist/storage/domains/traces/index.d.ts +0 -18
- package/dist/storage/domains/traces/index.d.ts.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
|
|
2
|
-
import { MastraStorage, StoreOperations, ScoresStorage, TABLE_SCORERS,
|
|
2
|
+
import { MastraStorage, createStorageErrorId, StoreOperations, ScoresStorage, TABLE_SCORERS, normalizePerPage, calculatePagination, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, ensureDate, MemoryStorage, TABLE_RESOURCES, TABLE_THREADS, TABLE_MESSAGES, serializeDate, transformScoreRow as transformScoreRow$1 } from '@mastra/core/storage';
|
|
3
3
|
import Cloudflare from 'cloudflare';
|
|
4
|
-
import { parseSqlIdentifier } from '@mastra/core/utils';
|
|
5
4
|
import { MessageList } from '@mastra/core/agent';
|
|
5
|
+
import { parseSqlIdentifier } from '@mastra/core/utils';
|
|
6
|
+
import { saveScorePayloadSchema } from '@mastra/core/evals';
|
|
6
7
|
|
|
7
8
|
// src/storage/index.ts
|
|
8
9
|
var SqlBuilder = class {
|
|
@@ -241,16 +242,6 @@ function isArrayOfRecords(value) {
|
|
|
241
242
|
}
|
|
242
243
|
function deserializeValue(value, type) {
|
|
243
244
|
if (value === null || value === void 0) return null;
|
|
244
|
-
if (type === "date" && typeof value === "string") {
|
|
245
|
-
return new Date(value);
|
|
246
|
-
}
|
|
247
|
-
if (type === "jsonb" && typeof value === "string") {
|
|
248
|
-
try {
|
|
249
|
-
return JSON.parse(value);
|
|
250
|
-
} catch {
|
|
251
|
-
return value;
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
245
|
if (typeof value === "string" && (value.startsWith("{") || value.startsWith("["))) {
|
|
255
246
|
try {
|
|
256
247
|
return JSON.parse(value);
|
|
@@ -261,155 +252,7 @@ function deserializeValue(value, type) {
|
|
|
261
252
|
return value;
|
|
262
253
|
}
|
|
263
254
|
|
|
264
|
-
// src/storage/domains/
|
|
265
|
-
var LegacyEvalsStorageD1 = class extends LegacyEvalsStorage {
|
|
266
|
-
operations;
|
|
267
|
-
constructor({ operations }) {
|
|
268
|
-
super();
|
|
269
|
-
this.operations = operations;
|
|
270
|
-
}
|
|
271
|
-
async getEvals(options) {
|
|
272
|
-
const { agentName, type, page = 0, perPage = 40, dateRange } = options || {};
|
|
273
|
-
const fullTableName = this.operations.getTableName(TABLE_EVALS);
|
|
274
|
-
const conditions = [];
|
|
275
|
-
const queryParams = [];
|
|
276
|
-
if (agentName) {
|
|
277
|
-
conditions.push(`agent_name = ?`);
|
|
278
|
-
queryParams.push(agentName);
|
|
279
|
-
}
|
|
280
|
-
if (type === "test") {
|
|
281
|
-
conditions.push(`(test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL)`);
|
|
282
|
-
} else if (type === "live") {
|
|
283
|
-
conditions.push(`(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)`);
|
|
284
|
-
}
|
|
285
|
-
if (dateRange?.start) {
|
|
286
|
-
conditions.push(`created_at >= ?`);
|
|
287
|
-
queryParams.push(serializeDate(dateRange.start));
|
|
288
|
-
}
|
|
289
|
-
if (dateRange?.end) {
|
|
290
|
-
conditions.push(`created_at <= ?`);
|
|
291
|
-
queryParams.push(serializeDate(dateRange.end));
|
|
292
|
-
}
|
|
293
|
-
const countQueryBuilder = createSqlBuilder().count().from(fullTableName);
|
|
294
|
-
if (conditions.length > 0) {
|
|
295
|
-
countQueryBuilder.where(conditions.join(" AND "), ...queryParams);
|
|
296
|
-
}
|
|
297
|
-
const { sql: countSql, params: countParams } = countQueryBuilder.build();
|
|
298
|
-
try {
|
|
299
|
-
const countResult = await this.operations.executeQuery({
|
|
300
|
-
sql: countSql,
|
|
301
|
-
params: countParams,
|
|
302
|
-
first: true
|
|
303
|
-
});
|
|
304
|
-
const total = Number(countResult?.count || 0);
|
|
305
|
-
const currentOffset = page * perPage;
|
|
306
|
-
if (total === 0) {
|
|
307
|
-
return {
|
|
308
|
-
evals: [],
|
|
309
|
-
total: 0,
|
|
310
|
-
page,
|
|
311
|
-
perPage,
|
|
312
|
-
hasMore: false
|
|
313
|
-
};
|
|
314
|
-
}
|
|
315
|
-
const dataQueryBuilder = createSqlBuilder().select("*").from(fullTableName);
|
|
316
|
-
if (conditions.length > 0) {
|
|
317
|
-
dataQueryBuilder.where(conditions.join(" AND "), ...queryParams);
|
|
318
|
-
}
|
|
319
|
-
dataQueryBuilder.orderBy("created_at", "DESC").limit(perPage).offset(currentOffset);
|
|
320
|
-
const { sql: dataSql, params: dataParams } = dataQueryBuilder.build();
|
|
321
|
-
const rows = await this.operations.executeQuery({
|
|
322
|
-
sql: dataSql,
|
|
323
|
-
params: dataParams
|
|
324
|
-
});
|
|
325
|
-
const evals = (isArrayOfRecords(rows) ? rows : []).map((row) => {
|
|
326
|
-
const result = deserializeValue(row.result);
|
|
327
|
-
const testInfo = row.test_info ? deserializeValue(row.test_info) : void 0;
|
|
328
|
-
if (!result || typeof result !== "object" || !("score" in result)) {
|
|
329
|
-
throw new Error(`Invalid MetricResult format: ${JSON.stringify(result)}`);
|
|
330
|
-
}
|
|
331
|
-
return {
|
|
332
|
-
input: row.input,
|
|
333
|
-
output: row.output,
|
|
334
|
-
result,
|
|
335
|
-
agentName: row.agent_name,
|
|
336
|
-
metricName: row.metric_name,
|
|
337
|
-
instructions: row.instructions,
|
|
338
|
-
testInfo,
|
|
339
|
-
globalRunId: row.global_run_id,
|
|
340
|
-
runId: row.run_id,
|
|
341
|
-
createdAt: row.created_at
|
|
342
|
-
};
|
|
343
|
-
});
|
|
344
|
-
const hasMore = currentOffset + evals.length < total;
|
|
345
|
-
return {
|
|
346
|
-
evals,
|
|
347
|
-
total,
|
|
348
|
-
page,
|
|
349
|
-
perPage,
|
|
350
|
-
hasMore
|
|
351
|
-
};
|
|
352
|
-
} catch (error) {
|
|
353
|
-
throw new MastraError(
|
|
354
|
-
{
|
|
355
|
-
id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
|
|
356
|
-
domain: ErrorDomain.STORAGE,
|
|
357
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
358
|
-
text: `Failed to retrieve evals for agent ${agentName}: ${error instanceof Error ? error.message : String(error)}`,
|
|
359
|
-
details: { agentName: agentName ?? "", type: type ?? "" }
|
|
360
|
-
},
|
|
361
|
-
error
|
|
362
|
-
);
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
/**
|
|
366
|
-
* @deprecated use getEvals instead
|
|
367
|
-
*/
|
|
368
|
-
async getEvalsByAgentName(agentName, type) {
|
|
369
|
-
const fullTableName = this.operations.getTableName(TABLE_EVALS);
|
|
370
|
-
try {
|
|
371
|
-
let query = createSqlBuilder().select("*").from(fullTableName).where("agent_name = ?", agentName);
|
|
372
|
-
if (type === "test") {
|
|
373
|
-
query = query.andWhere("test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL");
|
|
374
|
-
} else if (type === "live") {
|
|
375
|
-
query = query.andWhere("(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)");
|
|
376
|
-
}
|
|
377
|
-
query.orderBy("created_at", "DESC");
|
|
378
|
-
const { sql, params } = query.build();
|
|
379
|
-
const results = await this.operations.executeQuery({ sql, params });
|
|
380
|
-
return isArrayOfRecords(results) ? results.map((row) => {
|
|
381
|
-
const result = deserializeValue(row.result);
|
|
382
|
-
const testInfo = row.test_info ? deserializeValue(row.test_info) : void 0;
|
|
383
|
-
return {
|
|
384
|
-
input: row.input || "",
|
|
385
|
-
output: row.output || "",
|
|
386
|
-
result,
|
|
387
|
-
agentName: row.agent_name || "",
|
|
388
|
-
metricName: row.metric_name || "",
|
|
389
|
-
instructions: row.instructions || "",
|
|
390
|
-
runId: row.run_id || "",
|
|
391
|
-
globalRunId: row.global_run_id || "",
|
|
392
|
-
createdAt: row.created_at || "",
|
|
393
|
-
testInfo
|
|
394
|
-
};
|
|
395
|
-
}) : [];
|
|
396
|
-
} catch (error) {
|
|
397
|
-
const mastraError = new MastraError(
|
|
398
|
-
{
|
|
399
|
-
id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
|
|
400
|
-
domain: ErrorDomain.STORAGE,
|
|
401
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
402
|
-
text: `Failed to retrieve evals for agent ${agentName}: ${error instanceof Error ? error.message : String(error)}`,
|
|
403
|
-
details: { agentName }
|
|
404
|
-
},
|
|
405
|
-
error
|
|
406
|
-
);
|
|
407
|
-
this.logger?.error(mastraError.toString());
|
|
408
|
-
this.logger?.trackException(mastraError);
|
|
409
|
-
return [];
|
|
410
|
-
}
|
|
411
|
-
}
|
|
412
|
-
};
|
|
255
|
+
// src/storage/domains/memory/index.ts
|
|
413
256
|
var MemoryStorageD1 = class extends MemoryStorage {
|
|
414
257
|
operations;
|
|
415
258
|
constructor({ operations }) {
|
|
@@ -432,7 +275,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
|
|
|
432
275
|
} catch (error) {
|
|
433
276
|
const mastraError = new MastraError(
|
|
434
277
|
{
|
|
435
|
-
id: "
|
|
278
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "GET_RESOURCE_BY_ID", "FAILED"),
|
|
436
279
|
domain: ErrorDomain.STORAGE,
|
|
437
280
|
category: ErrorCategory.THIRD_PARTY,
|
|
438
281
|
text: `Error processing resource ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
@@ -471,7 +314,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
|
|
|
471
314
|
} catch (error) {
|
|
472
315
|
throw new MastraError(
|
|
473
316
|
{
|
|
474
|
-
id: "
|
|
317
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "SAVE_RESOURCE", "FAILED"),
|
|
475
318
|
domain: ErrorDomain.STORAGE,
|
|
476
319
|
category: ErrorCategory.THIRD_PARTY,
|
|
477
320
|
text: `Failed to save resource to ${fullTableName}: ${error instanceof Error ? error.message : String(error)}`,
|
|
@@ -518,7 +361,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
|
|
|
518
361
|
} catch (error) {
|
|
519
362
|
throw new MastraError(
|
|
520
363
|
{
|
|
521
|
-
id: "
|
|
364
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "UPDATE_RESOURCE", "FAILED"),
|
|
522
365
|
domain: ErrorDomain.STORAGE,
|
|
523
366
|
category: ErrorCategory.THIRD_PARTY,
|
|
524
367
|
text: `Failed to update resource ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
@@ -544,7 +387,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
|
|
|
544
387
|
} catch (error) {
|
|
545
388
|
const mastraError = new MastraError(
|
|
546
389
|
{
|
|
547
|
-
id: "
|
|
390
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "GET_THREAD_BY_ID", "FAILED"),
|
|
548
391
|
domain: ErrorDomain.STORAGE,
|
|
549
392
|
category: ErrorCategory.THIRD_PARTY,
|
|
550
393
|
text: `Error processing thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
@@ -557,39 +400,22 @@ var MemoryStorageD1 = class extends MemoryStorage {
|
|
|
557
400
|
return null;
|
|
558
401
|
}
|
|
559
402
|
}
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
try {
|
|
566
|
-
const query = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId);
|
|
567
|
-
const { sql, params } = query.build();
|
|
568
|
-
const results = await this.operations.executeQuery({ sql, params });
|
|
569
|
-
return (isArrayOfRecords(results) ? results : []).map((thread) => ({
|
|
570
|
-
...thread,
|
|
571
|
-
createdAt: ensureDate(thread.createdAt),
|
|
572
|
-
updatedAt: ensureDate(thread.updatedAt),
|
|
573
|
-
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata || "{}") : thread.metadata || {}
|
|
574
|
-
}));
|
|
575
|
-
} catch (error) {
|
|
576
|
-
const mastraError = new MastraError(
|
|
403
|
+
async listThreadsByResourceId(args) {
|
|
404
|
+
const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
|
|
405
|
+
const perPage = normalizePerPage(perPageInput, 100);
|
|
406
|
+
if (page < 0) {
|
|
407
|
+
throw new MastraError(
|
|
577
408
|
{
|
|
578
|
-
id: "
|
|
409
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "LIST_THREADS_BY_RESOURCE_ID", "INVALID_PAGE"),
|
|
579
410
|
domain: ErrorDomain.STORAGE,
|
|
580
|
-
category: ErrorCategory.
|
|
581
|
-
|
|
582
|
-
details: { resourceId }
|
|
411
|
+
category: ErrorCategory.USER,
|
|
412
|
+
details: { page }
|
|
583
413
|
},
|
|
584
|
-
|
|
414
|
+
new Error("page must be >= 0")
|
|
585
415
|
);
|
|
586
|
-
this.logger?.error(mastraError.toString());
|
|
587
|
-
this.logger?.trackException(mastraError);
|
|
588
|
-
return [];
|
|
589
416
|
}
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
const { resourceId, page, perPage } = args;
|
|
417
|
+
const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
418
|
+
const { field, direction } = this.parseOrderBy(orderBy);
|
|
593
419
|
const fullTableName = this.operations.getTableName(TABLE_THREADS);
|
|
594
420
|
const mapRowToStorageThreadType = (row) => ({
|
|
595
421
|
...row,
|
|
@@ -601,20 +427,21 @@ var MemoryStorageD1 = class extends MemoryStorage {
|
|
|
601
427
|
const countQuery = createSqlBuilder().count().from(fullTableName).where("resourceId = ?", resourceId);
|
|
602
428
|
const countResult = await this.operations.executeQuery(countQuery.build());
|
|
603
429
|
const total = Number(countResult?.[0]?.count ?? 0);
|
|
604
|
-
const
|
|
430
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
431
|
+
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId).orderBy(field, direction).limit(limitValue).offset(offset);
|
|
605
432
|
const results = await this.operations.executeQuery(selectQuery.build());
|
|
606
433
|
const threads = results.map(mapRowToStorageThreadType);
|
|
607
434
|
return {
|
|
608
435
|
threads,
|
|
609
436
|
total,
|
|
610
437
|
page,
|
|
611
|
-
perPage,
|
|
612
|
-
hasMore:
|
|
438
|
+
perPage: perPageForResponse,
|
|
439
|
+
hasMore: perPageInput === false ? false : offset + perPage < total
|
|
613
440
|
};
|
|
614
441
|
} catch (error) {
|
|
615
442
|
const mastraError = new MastraError(
|
|
616
443
|
{
|
|
617
|
-
id: "
|
|
444
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "LIST_THREADS_BY_RESOURCE_ID", "FAILED"),
|
|
618
445
|
domain: ErrorDomain.STORAGE,
|
|
619
446
|
category: ErrorCategory.THIRD_PARTY,
|
|
620
447
|
text: `Error getting threads by resourceId ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
@@ -628,7 +455,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
|
|
|
628
455
|
threads: [],
|
|
629
456
|
total: 0,
|
|
630
457
|
page,
|
|
631
|
-
perPage,
|
|
458
|
+
perPage: perPageForResponse,
|
|
632
459
|
hasMore: false
|
|
633
460
|
};
|
|
634
461
|
}
|
|
@@ -661,7 +488,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
|
|
|
661
488
|
} catch (error) {
|
|
662
489
|
throw new MastraError(
|
|
663
490
|
{
|
|
664
|
-
id: "
|
|
491
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "SAVE_THREAD", "FAILED"),
|
|
665
492
|
domain: ErrorDomain.STORAGE,
|
|
666
493
|
category: ErrorCategory.THIRD_PARTY,
|
|
667
494
|
text: `Failed to save thread to ${fullTableName}: ${error instanceof Error ? error.message : String(error)}`,
|
|
@@ -704,7 +531,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
|
|
|
704
531
|
} catch (error) {
|
|
705
532
|
throw new MastraError(
|
|
706
533
|
{
|
|
707
|
-
id: "
|
|
534
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "UPDATE_THREAD", "FAILED"),
|
|
708
535
|
domain: ErrorDomain.STORAGE,
|
|
709
536
|
category: ErrorCategory.THIRD_PARTY,
|
|
710
537
|
text: `Failed to update thread ${id}: ${error instanceof Error ? error.message : String(error)}`,
|
|
@@ -727,7 +554,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
|
|
|
727
554
|
} catch (error) {
|
|
728
555
|
throw new MastraError(
|
|
729
556
|
{
|
|
730
|
-
id: "
|
|
557
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "DELETE_THREAD", "FAILED"),
|
|
731
558
|
domain: ErrorDomain.STORAGE,
|
|
732
559
|
category: ErrorCategory.THIRD_PARTY,
|
|
733
560
|
text: `Failed to delete thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
@@ -738,8 +565,8 @@ var MemoryStorageD1 = class extends MemoryStorage {
|
|
|
738
565
|
}
|
|
739
566
|
}
|
|
740
567
|
async saveMessages(args) {
|
|
741
|
-
const { messages
|
|
742
|
-
if (messages.length === 0) return [];
|
|
568
|
+
const { messages } = args;
|
|
569
|
+
if (messages.length === 0) return { messages: [] };
|
|
743
570
|
try {
|
|
744
571
|
const now = /* @__PURE__ */ new Date();
|
|
745
572
|
const threadId = messages[0]?.threadId;
|
|
@@ -787,12 +614,11 @@ var MemoryStorageD1 = class extends MemoryStorage {
|
|
|
787
614
|
]);
|
|
788
615
|
this.logger.debug(`Saved ${messages.length} messages`);
|
|
789
616
|
const list = new MessageList().add(messages, "memory");
|
|
790
|
-
|
|
791
|
-
return list.get.all.v1();
|
|
617
|
+
return { messages: list.get.all.db() };
|
|
792
618
|
} catch (error) {
|
|
793
619
|
throw new MastraError(
|
|
794
620
|
{
|
|
795
|
-
id: "
|
|
621
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "SAVE_MESSAGES", "FAILED"),
|
|
796
622
|
domain: ErrorDomain.STORAGE,
|
|
797
623
|
category: ErrorCategory.THIRD_PARTY,
|
|
798
624
|
text: `Failed to save messages: ${error instanceof Error ? error.message : String(error)}`
|
|
@@ -801,24 +627,25 @@ var MemoryStorageD1 = class extends MemoryStorage {
|
|
|
801
627
|
);
|
|
802
628
|
}
|
|
803
629
|
}
|
|
804
|
-
async _getIncludedMessages(
|
|
805
|
-
if (!
|
|
806
|
-
const include = selectBy?.include;
|
|
807
|
-
if (!include) return null;
|
|
630
|
+
async _getIncludedMessages(include) {
|
|
631
|
+
if (!include || include.length === 0) return null;
|
|
808
632
|
const unionQueries = [];
|
|
809
633
|
const params = [];
|
|
810
634
|
let paramIdx = 1;
|
|
635
|
+
const tableName = this.operations.getTableName(TABLE_MESSAGES);
|
|
811
636
|
for (const inc of include) {
|
|
812
637
|
const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
|
|
813
|
-
const searchId = inc.threadId || threadId;
|
|
814
638
|
unionQueries.push(`
|
|
815
639
|
SELECT * FROM (
|
|
816
|
-
WITH
|
|
640
|
+
WITH target_thread AS (
|
|
641
|
+
SELECT thread_id FROM ${tableName} WHERE id = ?
|
|
642
|
+
),
|
|
643
|
+
ordered_messages AS (
|
|
817
644
|
SELECT
|
|
818
645
|
*,
|
|
819
646
|
ROW_NUMBER() OVER (ORDER BY createdAt ASC) AS row_num
|
|
820
|
-
FROM ${
|
|
821
|
-
WHERE thread_id =
|
|
647
|
+
FROM ${tableName}
|
|
648
|
+
WHERE thread_id = (SELECT thread_id FROM target_thread)
|
|
822
649
|
)
|
|
823
650
|
SELECT
|
|
824
651
|
m.id,
|
|
@@ -841,7 +668,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
|
|
|
841
668
|
)
|
|
842
669
|
) AS query_${paramIdx}
|
|
843
670
|
`);
|
|
844
|
-
params.push(
|
|
671
|
+
params.push(id, id, id, withNextMessages, withPreviousMessages);
|
|
845
672
|
paramIdx++;
|
|
846
673
|
}
|
|
847
674
|
const finalQuery = unionQueries.join(" UNION ALL ") + " ORDER BY createdAt ASC";
|
|
@@ -859,74 +686,8 @@ var MemoryStorageD1 = class extends MemoryStorage {
|
|
|
859
686
|
});
|
|
860
687
|
return processedMessages;
|
|
861
688
|
}
|
|
862
|
-
async
|
|
863
|
-
|
|
864
|
-
resourceId,
|
|
865
|
-
selectBy,
|
|
866
|
-
format
|
|
867
|
-
}) {
|
|
868
|
-
try {
|
|
869
|
-
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
870
|
-
const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
|
|
871
|
-
const limit = resolveMessageLimit({
|
|
872
|
-
last: selectBy?.last,
|
|
873
|
-
defaultLimit: 40
|
|
874
|
-
});
|
|
875
|
-
const include = selectBy?.include || [];
|
|
876
|
-
const messages = [];
|
|
877
|
-
if (include.length) {
|
|
878
|
-
const includeResult = await this._getIncludedMessages(threadId, selectBy);
|
|
879
|
-
if (Array.isArray(includeResult)) messages.push(...includeResult);
|
|
880
|
-
}
|
|
881
|
-
const excludeIds = messages.map((m) => m.id);
|
|
882
|
-
const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId"]).from(fullTableName).where("thread_id = ?", threadId);
|
|
883
|
-
if (excludeIds.length > 0) {
|
|
884
|
-
query.andWhere(`id NOT IN (${excludeIds.map(() => "?").join(",")})`, ...excludeIds);
|
|
885
|
-
}
|
|
886
|
-
query.orderBy("createdAt", "DESC").limit(limit);
|
|
887
|
-
const { sql, params } = query.build();
|
|
888
|
-
const result = await this.operations.executeQuery({ sql, params });
|
|
889
|
-
if (Array.isArray(result)) messages.push(...result);
|
|
890
|
-
messages.sort((a, b) => {
|
|
891
|
-
const aRecord = a;
|
|
892
|
-
const bRecord = b;
|
|
893
|
-
const timeA = new Date(aRecord.createdAt).getTime();
|
|
894
|
-
const timeB = new Date(bRecord.createdAt).getTime();
|
|
895
|
-
return timeA - timeB;
|
|
896
|
-
});
|
|
897
|
-
const processedMessages = messages.map((message) => {
|
|
898
|
-
const processedMsg = {};
|
|
899
|
-
for (const [key, value] of Object.entries(message)) {
|
|
900
|
-
if (key === `type` && value === `v2`) continue;
|
|
901
|
-
processedMsg[key] = deserializeValue(value);
|
|
902
|
-
}
|
|
903
|
-
return processedMsg;
|
|
904
|
-
});
|
|
905
|
-
this.logger.debug(`Retrieved ${messages.length} messages for thread ${threadId}`);
|
|
906
|
-
const list = new MessageList().add(processedMessages, "memory");
|
|
907
|
-
if (format === `v2`) return list.get.all.v2();
|
|
908
|
-
return list.get.all.v1();
|
|
909
|
-
} catch (error) {
|
|
910
|
-
const mastraError = new MastraError(
|
|
911
|
-
{
|
|
912
|
-
id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_ERROR",
|
|
913
|
-
domain: ErrorDomain.STORAGE,
|
|
914
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
915
|
-
text: `Failed to retrieve messages for thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
916
|
-
details: { threadId, resourceId: resourceId ?? "" }
|
|
917
|
-
},
|
|
918
|
-
error
|
|
919
|
-
);
|
|
920
|
-
this.logger?.error(mastraError.toString());
|
|
921
|
-
this.logger?.trackException(mastraError);
|
|
922
|
-
throw mastraError;
|
|
923
|
-
}
|
|
924
|
-
}
|
|
925
|
-
async getMessagesById({
|
|
926
|
-
messageIds,
|
|
927
|
-
format
|
|
928
|
-
}) {
|
|
929
|
-
if (messageIds.length === 0) return [];
|
|
689
|
+
async listMessagesById({ messageIds }) {
|
|
690
|
+
if (messageIds.length === 0) return { messages: [] };
|
|
930
691
|
const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
|
|
931
692
|
const messages = [];
|
|
932
693
|
try {
|
|
@@ -945,12 +706,11 @@ var MemoryStorageD1 = class extends MemoryStorage {
|
|
|
945
706
|
});
|
|
946
707
|
this.logger.debug(`Retrieved ${messages.length} messages`);
|
|
947
708
|
const list = new MessageList().add(processedMessages, "memory");
|
|
948
|
-
|
|
949
|
-
return list.get.all.v2();
|
|
709
|
+
return { messages: list.get.all.db() };
|
|
950
710
|
} catch (error) {
|
|
951
711
|
const mastraError = new MastraError(
|
|
952
712
|
{
|
|
953
|
-
id: "
|
|
713
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "LIST_MESSAGES_BY_ID", "FAILED"),
|
|
954
714
|
domain: ErrorDomain.STORAGE,
|
|
955
715
|
category: ErrorCategory.THIRD_PARTY,
|
|
956
716
|
text: `Failed to retrieve messages by ID: ${error instanceof Error ? error.message : String(error)}`,
|
|
@@ -963,118 +723,158 @@ var MemoryStorageD1 = class extends MemoryStorage {
|
|
|
963
723
|
throw mastraError;
|
|
964
724
|
}
|
|
965
725
|
}
|
|
966
|
-
async
|
|
967
|
-
threadId,
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
726
|
+
async listMessages(args) {
|
|
727
|
+
const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
|
|
728
|
+
const threadIds = Array.isArray(threadId) ? threadId : [threadId];
|
|
729
|
+
if (threadIds.length === 0 || threadIds.some((id) => !id.trim())) {
|
|
730
|
+
throw new MastraError(
|
|
731
|
+
{
|
|
732
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "LIST_MESSAGES", "INVALID_THREAD_ID"),
|
|
733
|
+
domain: ErrorDomain.STORAGE,
|
|
734
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
735
|
+
details: { threadId: Array.isArray(threadId) ? threadId.join(",") : threadId }
|
|
736
|
+
},
|
|
737
|
+
new Error("threadId must be a non-empty string or array of non-empty strings")
|
|
738
|
+
);
|
|
739
|
+
}
|
|
740
|
+
if (page < 0) {
|
|
741
|
+
throw new MastraError(
|
|
742
|
+
{
|
|
743
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "LIST_MESSAGES", "INVALID_PAGE"),
|
|
744
|
+
domain: ErrorDomain.STORAGE,
|
|
745
|
+
category: ErrorCategory.USER,
|
|
746
|
+
details: { page }
|
|
747
|
+
},
|
|
748
|
+
new Error("page must be >= 0")
|
|
749
|
+
);
|
|
750
|
+
}
|
|
751
|
+
const perPage = normalizePerPage(perPageInput, 40);
|
|
752
|
+
const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
977
753
|
try {
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
754
|
+
const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
|
|
755
|
+
let query = `
|
|
756
|
+
SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
|
|
757
|
+
FROM ${fullTableName}
|
|
758
|
+
WHERE thread_id = ?
|
|
759
|
+
`;
|
|
760
|
+
const queryParams = [threadId];
|
|
761
|
+
if (resourceId) {
|
|
762
|
+
query += ` AND resourceId = ?`;
|
|
763
|
+
queryParams.push(resourceId);
|
|
982
764
|
}
|
|
983
|
-
const
|
|
984
|
-
if (
|
|
985
|
-
|
|
765
|
+
const dateRange = filter?.dateRange;
|
|
766
|
+
if (dateRange?.start) {
|
|
767
|
+
const startDate = dateRange.start instanceof Date ? serializeDate(dateRange.start) : serializeDate(new Date(dateRange.start));
|
|
768
|
+
query += ` AND createdAt >= ?`;
|
|
769
|
+
queryParams.push(startDate);
|
|
986
770
|
}
|
|
987
|
-
if (
|
|
988
|
-
|
|
771
|
+
if (dateRange?.end) {
|
|
772
|
+
const endDate = dateRange.end instanceof Date ? serializeDate(dateRange.end) : serializeDate(new Date(dateRange.end));
|
|
773
|
+
query += ` AND createdAt <= ?`;
|
|
774
|
+
queryParams.push(endDate);
|
|
989
775
|
}
|
|
990
|
-
const
|
|
776
|
+
const { field, direction } = this.parseOrderBy(orderBy, "ASC");
|
|
777
|
+
query += ` ORDER BY "${field}" ${direction}`;
|
|
778
|
+
if (perPage !== Number.MAX_SAFE_INTEGER) {
|
|
779
|
+
query += ` LIMIT ? OFFSET ?`;
|
|
780
|
+
queryParams.push(perPage, offset);
|
|
781
|
+
}
|
|
782
|
+
const results = await this.operations.executeQuery({ sql: query, params: queryParams });
|
|
783
|
+
const paginatedMessages = (isArrayOfRecords(results) ? results : []).map((message) => {
|
|
784
|
+
const processedMsg = {};
|
|
785
|
+
for (const [key, value] of Object.entries(message)) {
|
|
786
|
+
if (key === `type` && value === `v2`) continue;
|
|
787
|
+
processedMsg[key] = deserializeValue(value);
|
|
788
|
+
}
|
|
789
|
+
return processedMsg;
|
|
790
|
+
});
|
|
791
|
+
const paginatedCount = paginatedMessages.length;
|
|
792
|
+
let countQuery = `SELECT count() as count FROM ${fullTableName} WHERE thread_id = ?`;
|
|
793
|
+
const countParams = [threadId];
|
|
794
|
+
if (resourceId) {
|
|
795
|
+
countQuery += ` AND resourceId = ?`;
|
|
796
|
+
countParams.push(resourceId);
|
|
797
|
+
}
|
|
798
|
+
if (dateRange?.start) {
|
|
799
|
+
const startDate = dateRange.start instanceof Date ? serializeDate(dateRange.start) : serializeDate(new Date(dateRange.start));
|
|
800
|
+
countQuery += ` AND createdAt >= ?`;
|
|
801
|
+
countParams.push(startDate);
|
|
802
|
+
}
|
|
803
|
+
if (dateRange?.end) {
|
|
804
|
+
const endDate = dateRange.end instanceof Date ? serializeDate(dateRange.end) : serializeDate(new Date(dateRange.end));
|
|
805
|
+
countQuery += ` AND createdAt <= ?`;
|
|
806
|
+
countParams.push(endDate);
|
|
807
|
+
}
|
|
808
|
+
const countResult = await this.operations.executeQuery({ sql: countQuery, params: countParams });
|
|
991
809
|
const total = Number(countResult[0]?.count ?? 0);
|
|
992
|
-
if (total === 0 &&
|
|
810
|
+
if (total === 0 && paginatedCount === 0 && (!include || include.length === 0)) {
|
|
993
811
|
return {
|
|
994
812
|
messages: [],
|
|
995
813
|
total: 0,
|
|
996
814
|
page,
|
|
997
|
-
perPage,
|
|
815
|
+
perPage: perPageForResponse,
|
|
998
816
|
hasMore: false
|
|
999
817
|
};
|
|
1000
818
|
}
|
|
1001
|
-
const
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
if (selectBy?.last && selectBy.last > 0) {
|
|
1015
|
-
query = `
|
|
1016
|
-
SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
|
|
1017
|
-
FROM ${fullTableName}
|
|
1018
|
-
WHERE thread_id = ?
|
|
1019
|
-
${fromDate ? "AND createdAt >= ?" : ""}
|
|
1020
|
-
${toDate ? "AND createdAt <= ?" : ""}
|
|
1021
|
-
${excludeCondition}
|
|
1022
|
-
ORDER BY createdAt DESC
|
|
1023
|
-
LIMIT ?
|
|
1024
|
-
`;
|
|
1025
|
-
queryParams.push(selectBy.last);
|
|
1026
|
-
} else {
|
|
1027
|
-
query = `
|
|
1028
|
-
SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
|
|
1029
|
-
FROM ${fullTableName}
|
|
1030
|
-
WHERE thread_id = ?
|
|
1031
|
-
${fromDate ? "AND createdAt >= ?" : ""}
|
|
1032
|
-
${toDate ? "AND createdAt <= ?" : ""}
|
|
1033
|
-
${excludeCondition}
|
|
1034
|
-
ORDER BY createdAt DESC
|
|
1035
|
-
LIMIT ? OFFSET ?
|
|
1036
|
-
`;
|
|
1037
|
-
queryParams.push(perPage, page * perPage);
|
|
819
|
+
const messageIds = new Set(paginatedMessages.map((m) => m.id));
|
|
820
|
+
let includeMessages = [];
|
|
821
|
+
if (include && include.length > 0) {
|
|
822
|
+
const includeResult = await this._getIncludedMessages(include);
|
|
823
|
+
if (Array.isArray(includeResult)) {
|
|
824
|
+
includeMessages = includeResult;
|
|
825
|
+
for (const includeMsg of includeMessages) {
|
|
826
|
+
if (!messageIds.has(includeMsg.id)) {
|
|
827
|
+
paginatedMessages.push(includeMsg);
|
|
828
|
+
messageIds.add(includeMsg.id);
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
}
|
|
1038
832
|
}
|
|
1039
|
-
const
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
833
|
+
const list = new MessageList().add(paginatedMessages, "memory");
|
|
834
|
+
let finalMessages = list.get.all.db();
|
|
835
|
+
finalMessages = finalMessages.sort((a, b) => {
|
|
836
|
+
const isDateField = field === "createdAt" || field === "updatedAt";
|
|
837
|
+
const aValue = isDateField ? new Date(a[field]).getTime() : a[field];
|
|
838
|
+
const bValue = isDateField ? new Date(b[field]).getTime() : b[field];
|
|
839
|
+
if (aValue === bValue) {
|
|
840
|
+
return a.id.localeCompare(b.id);
|
|
1045
841
|
}
|
|
1046
|
-
|
|
842
|
+
if (typeof aValue === "number" && typeof bValue === "number") {
|
|
843
|
+
return direction === "ASC" ? aValue - bValue : bValue - aValue;
|
|
844
|
+
}
|
|
845
|
+
return direction === "ASC" ? String(aValue).localeCompare(String(bValue)) : String(bValue).localeCompare(String(aValue));
|
|
1047
846
|
});
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
const list = new MessageList().add(processedMessages, "memory");
|
|
1052
|
-
messages.push(...format === `v2` ? list.get.all.v2() : list.get.all.v1());
|
|
847
|
+
const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
|
|
848
|
+
const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
|
|
849
|
+
const hasMore = perPageInput === false ? false : allThreadMessagesReturned ? false : offset + paginatedCount < total;
|
|
1053
850
|
return {
|
|
1054
|
-
messages,
|
|
851
|
+
messages: finalMessages,
|
|
1055
852
|
total,
|
|
1056
853
|
page,
|
|
1057
|
-
perPage,
|
|
1058
|
-
hasMore
|
|
854
|
+
perPage: perPageForResponse,
|
|
855
|
+
hasMore
|
|
1059
856
|
};
|
|
1060
857
|
} catch (error) {
|
|
1061
858
|
const mastraError = new MastraError(
|
|
1062
859
|
{
|
|
1063
|
-
id: "
|
|
860
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "LIST_MESSAGES", "FAILED"),
|
|
1064
861
|
domain: ErrorDomain.STORAGE,
|
|
1065
862
|
category: ErrorCategory.THIRD_PARTY,
|
|
1066
|
-
text: `Failed to
|
|
1067
|
-
details: {
|
|
863
|
+
text: `Failed to list messages for thread ${Array.isArray(threadId) ? threadId.join(",") : threadId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
864
|
+
details: {
|
|
865
|
+
threadId: Array.isArray(threadId) ? threadId.join(",") : threadId,
|
|
866
|
+
resourceId: resourceId ?? ""
|
|
867
|
+
}
|
|
1068
868
|
},
|
|
1069
869
|
error
|
|
1070
870
|
);
|
|
1071
|
-
this.logger?.error(mastraError.toString());
|
|
1072
|
-
this.logger?.trackException(mastraError);
|
|
871
|
+
this.logger?.error?.(mastraError.toString());
|
|
872
|
+
this.logger?.trackException?.(mastraError);
|
|
1073
873
|
return {
|
|
1074
874
|
messages: [],
|
|
1075
875
|
total: 0,
|
|
1076
876
|
page,
|
|
1077
|
-
perPage,
|
|
877
|
+
perPage: perPageForResponse,
|
|
1078
878
|
hasMore: false
|
|
1079
879
|
};
|
|
1080
880
|
}
|
|
@@ -1170,7 +970,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
|
|
|
1170
970
|
} catch (error) {
|
|
1171
971
|
throw new MastraError(
|
|
1172
972
|
{
|
|
1173
|
-
id: "
|
|
973
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "UPDATE_MESSAGES", "FAILED"),
|
|
1174
974
|
domain: ErrorDomain.STORAGE,
|
|
1175
975
|
category: ErrorCategory.THIRD_PARTY,
|
|
1176
976
|
details: { count: messages.length }
|
|
@@ -1239,7 +1039,7 @@ var StoreOperationsD1 = class extends StoreOperations {
|
|
|
1239
1039
|
} catch (error) {
|
|
1240
1040
|
throw new MastraError(
|
|
1241
1041
|
{
|
|
1242
|
-
id: "
|
|
1042
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "WORKERS_BINDING_QUERY", "FAILED"),
|
|
1243
1043
|
domain: ErrorDomain.STORAGE,
|
|
1244
1044
|
category: ErrorCategory.THIRD_PARTY,
|
|
1245
1045
|
details: { sql }
|
|
@@ -1271,7 +1071,7 @@ var StoreOperationsD1 = class extends StoreOperations {
|
|
|
1271
1071
|
} catch (error) {
|
|
1272
1072
|
throw new MastraError(
|
|
1273
1073
|
{
|
|
1274
|
-
id: "
|
|
1074
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "REST_QUERY", "FAILED"),
|
|
1275
1075
|
domain: ErrorDomain.STORAGE,
|
|
1276
1076
|
category: ErrorCategory.THIRD_PARTY,
|
|
1277
1077
|
details: { sql }
|
|
@@ -1352,7 +1152,7 @@ var StoreOperationsD1 = class extends StoreOperations {
|
|
|
1352
1152
|
} catch (error) {
|
|
1353
1153
|
throw new MastraError(
|
|
1354
1154
|
{
|
|
1355
|
-
id: "
|
|
1155
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "CREATE_TABLE", "FAILED"),
|
|
1356
1156
|
domain: ErrorDomain.STORAGE,
|
|
1357
1157
|
category: ErrorCategory.THIRD_PARTY,
|
|
1358
1158
|
details: { tableName }
|
|
@@ -1371,7 +1171,7 @@ var StoreOperationsD1 = class extends StoreOperations {
|
|
|
1371
1171
|
} catch (error) {
|
|
1372
1172
|
throw new MastraError(
|
|
1373
1173
|
{
|
|
1374
|
-
id: "
|
|
1174
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "CLEAR_TABLE", "FAILED"),
|
|
1375
1175
|
domain: ErrorDomain.STORAGE,
|
|
1376
1176
|
category: ErrorCategory.THIRD_PARTY,
|
|
1377
1177
|
details: { tableName }
|
|
@@ -1389,7 +1189,7 @@ var StoreOperationsD1 = class extends StoreOperations {
|
|
|
1389
1189
|
} catch (error) {
|
|
1390
1190
|
throw new MastraError(
|
|
1391
1191
|
{
|
|
1392
|
-
id: "
|
|
1192
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "DROP_TABLE", "FAILED"),
|
|
1393
1193
|
domain: ErrorDomain.STORAGE,
|
|
1394
1194
|
category: ErrorCategory.THIRD_PARTY,
|
|
1395
1195
|
details: { tableName }
|
|
@@ -1415,7 +1215,7 @@ var StoreOperationsD1 = class extends StoreOperations {
|
|
|
1415
1215
|
} catch (error) {
|
|
1416
1216
|
throw new MastraError(
|
|
1417
1217
|
{
|
|
1418
|
-
id: "
|
|
1218
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "ALTER_TABLE", "FAILED"),
|
|
1419
1219
|
domain: ErrorDomain.STORAGE,
|
|
1420
1220
|
category: ErrorCategory.THIRD_PARTY,
|
|
1421
1221
|
details: { tableName: args.tableName }
|
|
@@ -1436,7 +1236,7 @@ var StoreOperationsD1 = class extends StoreOperations {
|
|
|
1436
1236
|
} catch (error) {
|
|
1437
1237
|
throw new MastraError(
|
|
1438
1238
|
{
|
|
1439
|
-
id: "
|
|
1239
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "INSERT", "FAILED"),
|
|
1440
1240
|
domain: ErrorDomain.STORAGE,
|
|
1441
1241
|
category: ErrorCategory.THIRD_PARTY,
|
|
1442
1242
|
details: { tableName }
|
|
@@ -1460,7 +1260,7 @@ var StoreOperationsD1 = class extends StoreOperations {
|
|
|
1460
1260
|
} catch (error) {
|
|
1461
1261
|
throw new MastraError(
|
|
1462
1262
|
{
|
|
1463
|
-
id: "
|
|
1263
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "BATCH_INSERT", "FAILED"),
|
|
1464
1264
|
domain: ErrorDomain.STORAGE,
|
|
1465
1265
|
category: ErrorCategory.THIRD_PARTY,
|
|
1466
1266
|
details: { tableName }
|
|
@@ -1497,7 +1297,7 @@ var StoreOperationsD1 = class extends StoreOperations {
|
|
|
1497
1297
|
} catch (error) {
|
|
1498
1298
|
throw new MastraError(
|
|
1499
1299
|
{
|
|
1500
|
-
id: "
|
|
1300
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "LOAD", "FAILED"),
|
|
1501
1301
|
domain: ErrorDomain.STORAGE,
|
|
1502
1302
|
category: ErrorCategory.THIRD_PARTY,
|
|
1503
1303
|
details: { tableName }
|
|
@@ -1555,7 +1355,7 @@ var StoreOperationsD1 = class extends StoreOperations {
|
|
|
1555
1355
|
} catch (error) {
|
|
1556
1356
|
throw new MastraError(
|
|
1557
1357
|
{
|
|
1558
|
-
id: "
|
|
1358
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "BATCH_UPSERT", "FAILED"),
|
|
1559
1359
|
domain: ErrorDomain.STORAGE,
|
|
1560
1360
|
category: ErrorCategory.THIRD_PARTY,
|
|
1561
1361
|
text: `Failed to batch upsert into ${tableName}: ${error instanceof Error ? error.message : String(error)}`,
|
|
@@ -1567,19 +1367,12 @@ var StoreOperationsD1 = class extends StoreOperations {
|
|
|
1567
1367
|
}
|
|
1568
1368
|
};
|
|
1569
1369
|
function transformScoreRow(row) {
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
deserialized.metadata = safelyParseJSON(row.metadata);
|
|
1577
|
-
deserialized.additionalContext = safelyParseJSON(row.additionalContext);
|
|
1578
|
-
deserialized.runtimeContext = safelyParseJSON(row.runtimeContext);
|
|
1579
|
-
deserialized.entity = safelyParseJSON(row.entity);
|
|
1580
|
-
deserialized.createdAt = row.createdAtZ || row.createdAt;
|
|
1581
|
-
deserialized.updatedAt = row.updatedAtZ || row.updatedAt;
|
|
1582
|
-
return deserialized;
|
|
1370
|
+
return transformScoreRow$1(row, {
|
|
1371
|
+
preferredTimestampFields: {
|
|
1372
|
+
createdAt: "createdAtZ",
|
|
1373
|
+
updatedAt: "updatedAtZ"
|
|
1374
|
+
}
|
|
1375
|
+
});
|
|
1583
1376
|
}
|
|
1584
1377
|
var ScoresStorageD1 = class extends ScoresStorage {
|
|
1585
1378
|
operations;
|
|
@@ -1600,7 +1393,7 @@ var ScoresStorageD1 = class extends ScoresStorage {
|
|
|
1600
1393
|
} catch (error) {
|
|
1601
1394
|
throw new MastraError(
|
|
1602
1395
|
{
|
|
1603
|
-
id: "
|
|
1396
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "GET_SCORE_BY_ID", "FAILED"),
|
|
1604
1397
|
domain: ErrorDomain.STORAGE,
|
|
1605
1398
|
category: ErrorCategory.THIRD_PARTY
|
|
1606
1399
|
},
|
|
@@ -1609,12 +1402,31 @@ var ScoresStorageD1 = class extends ScoresStorage {
|
|
|
1609
1402
|
}
|
|
1610
1403
|
}
|
|
1611
1404
|
async saveScore(score) {
|
|
1405
|
+
let parsedScore;
|
|
1406
|
+
try {
|
|
1407
|
+
parsedScore = saveScorePayloadSchema.parse(score);
|
|
1408
|
+
} catch (error) {
|
|
1409
|
+
throw new MastraError(
|
|
1410
|
+
{
|
|
1411
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "SAVE_SCORE", "VALIDATION_FAILED"),
|
|
1412
|
+
domain: ErrorDomain.STORAGE,
|
|
1413
|
+
category: ErrorCategory.USER,
|
|
1414
|
+
details: {
|
|
1415
|
+
scorer: score.scorer?.id ?? "unknown",
|
|
1416
|
+
entityId: score.entityId ?? "unknown",
|
|
1417
|
+
entityType: score.entityType ?? "unknown",
|
|
1418
|
+
traceId: score.traceId ?? "",
|
|
1419
|
+
spanId: score.spanId ?? ""
|
|
1420
|
+
}
|
|
1421
|
+
},
|
|
1422
|
+
error
|
|
1423
|
+
);
|
|
1424
|
+
}
|
|
1425
|
+
const id = crypto.randomUUID();
|
|
1612
1426
|
try {
|
|
1613
|
-
const id = crypto.randomUUID();
|
|
1614
1427
|
const fullTableName = this.operations.getTableName(TABLE_SCORERS);
|
|
1615
|
-
const { input, ...rest } = score;
|
|
1616
1428
|
const serializedRecord = {};
|
|
1617
|
-
for (const [key, value] of Object.entries(
|
|
1429
|
+
for (const [key, value] of Object.entries(parsedScore)) {
|
|
1618
1430
|
if (value !== null && value !== void 0) {
|
|
1619
1431
|
if (typeof value === "object") {
|
|
1620
1432
|
serializedRecord[key] = JSON.stringify(value);
|
|
@@ -1625,29 +1437,29 @@ var ScoresStorageD1 = class extends ScoresStorage {
|
|
|
1625
1437
|
serializedRecord[key] = null;
|
|
1626
1438
|
}
|
|
1627
1439
|
}
|
|
1440
|
+
const now = /* @__PURE__ */ new Date();
|
|
1628
1441
|
serializedRecord.id = id;
|
|
1629
|
-
serializedRecord.
|
|
1630
|
-
serializedRecord.
|
|
1631
|
-
serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1442
|
+
serializedRecord.createdAt = now.toISOString();
|
|
1443
|
+
serializedRecord.updatedAt = now.toISOString();
|
|
1632
1444
|
const columns = Object.keys(serializedRecord);
|
|
1633
1445
|
const values = Object.values(serializedRecord);
|
|
1634
1446
|
const query = createSqlBuilder().insert(fullTableName, columns, values);
|
|
1635
1447
|
const { sql, params } = query.build();
|
|
1636
1448
|
await this.operations.executeQuery({ sql, params });
|
|
1637
|
-
|
|
1638
|
-
return { score: scoreFromDb };
|
|
1449
|
+
return { score: { ...parsedScore, id, createdAt: now, updatedAt: now } };
|
|
1639
1450
|
} catch (error) {
|
|
1640
1451
|
throw new MastraError(
|
|
1641
1452
|
{
|
|
1642
|
-
id: "
|
|
1453
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "SAVE_SCORE", "FAILED"),
|
|
1643
1454
|
domain: ErrorDomain.STORAGE,
|
|
1644
|
-
category: ErrorCategory.THIRD_PARTY
|
|
1455
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1456
|
+
details: { id }
|
|
1645
1457
|
},
|
|
1646
1458
|
error
|
|
1647
1459
|
);
|
|
1648
1460
|
}
|
|
1649
1461
|
}
|
|
1650
|
-
async
|
|
1462
|
+
async listScoresByScorerId({
|
|
1651
1463
|
scorerId,
|
|
1652
1464
|
entityId,
|
|
1653
1465
|
entityType,
|
|
@@ -1655,6 +1467,9 @@ var ScoresStorageD1 = class extends ScoresStorage {
|
|
|
1655
1467
|
pagination
|
|
1656
1468
|
}) {
|
|
1657
1469
|
try {
|
|
1470
|
+
const { page, perPage: perPageInput } = pagination;
|
|
1471
|
+
const perPage = normalizePerPage(perPageInput, 100);
|
|
1472
|
+
const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
1658
1473
|
const fullTableName = this.operations.getTableName(TABLE_SCORERS);
|
|
1659
1474
|
const countQuery = createSqlBuilder().count().from(fullTableName).where("scorerId = ?", scorerId);
|
|
1660
1475
|
if (entityId) {
|
|
@@ -1672,13 +1487,15 @@ var ScoresStorageD1 = class extends ScoresStorage {
|
|
|
1672
1487
|
return {
|
|
1673
1488
|
pagination: {
|
|
1674
1489
|
total: 0,
|
|
1675
|
-
page
|
|
1676
|
-
perPage:
|
|
1490
|
+
page,
|
|
1491
|
+
perPage: perPageForResponse,
|
|
1677
1492
|
hasMore: false
|
|
1678
1493
|
},
|
|
1679
1494
|
scores: []
|
|
1680
1495
|
};
|
|
1681
1496
|
}
|
|
1497
|
+
const end = perPageInput === false ? total : start + perPage;
|
|
1498
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
1682
1499
|
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId);
|
|
1683
1500
|
if (entityId) {
|
|
1684
1501
|
selectQuery.andWhere("entityId = ?", entityId);
|
|
@@ -1689,23 +1506,23 @@ var ScoresStorageD1 = class extends ScoresStorage {
|
|
|
1689
1506
|
if (source) {
|
|
1690
1507
|
selectQuery.andWhere("source = ?", source);
|
|
1691
1508
|
}
|
|
1692
|
-
selectQuery.limit(
|
|
1509
|
+
selectQuery.limit(limitValue).offset(start);
|
|
1693
1510
|
const { sql, params } = selectQuery.build();
|
|
1694
1511
|
const results = await this.operations.executeQuery({ sql, params });
|
|
1695
1512
|
const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
|
|
1696
1513
|
return {
|
|
1697
1514
|
pagination: {
|
|
1698
1515
|
total,
|
|
1699
|
-
page
|
|
1700
|
-
perPage:
|
|
1701
|
-
hasMore:
|
|
1516
|
+
page,
|
|
1517
|
+
perPage: perPageForResponse,
|
|
1518
|
+
hasMore: end < total
|
|
1702
1519
|
},
|
|
1703
1520
|
scores
|
|
1704
1521
|
};
|
|
1705
1522
|
} catch (error) {
|
|
1706
1523
|
throw new MastraError(
|
|
1707
1524
|
{
|
|
1708
|
-
id: "
|
|
1525
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "GET_SCORES_BY_SCORER_ID", "FAILED"),
|
|
1709
1526
|
domain: ErrorDomain.STORAGE,
|
|
1710
1527
|
category: ErrorCategory.THIRD_PARTY
|
|
1711
1528
|
},
|
|
@@ -1713,11 +1530,14 @@ var ScoresStorageD1 = class extends ScoresStorage {
|
|
|
1713
1530
|
);
|
|
1714
1531
|
}
|
|
1715
1532
|
}
|
|
1716
|
-
async
|
|
1533
|
+
async listScoresByRunId({
|
|
1717
1534
|
runId,
|
|
1718
1535
|
pagination
|
|
1719
1536
|
}) {
|
|
1720
1537
|
try {
|
|
1538
|
+
const { page, perPage: perPageInput } = pagination;
|
|
1539
|
+
const perPage = normalizePerPage(perPageInput, 100);
|
|
1540
|
+
const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
1721
1541
|
const fullTableName = this.operations.getTableName(TABLE_SCORERS);
|
|
1722
1542
|
const countQuery = createSqlBuilder().count().from(fullTableName).where("runId = ?", runId);
|
|
1723
1543
|
const countResult = await this.operations.executeQuery(countQuery.build());
|
|
@@ -1726,30 +1546,32 @@ var ScoresStorageD1 = class extends ScoresStorage {
|
|
|
1726
1546
|
return {
|
|
1727
1547
|
pagination: {
|
|
1728
1548
|
total: 0,
|
|
1729
|
-
page
|
|
1730
|
-
perPage:
|
|
1549
|
+
page,
|
|
1550
|
+
perPage: perPageForResponse,
|
|
1731
1551
|
hasMore: false
|
|
1732
1552
|
},
|
|
1733
1553
|
scores: []
|
|
1734
1554
|
};
|
|
1735
1555
|
}
|
|
1736
|
-
const
|
|
1556
|
+
const end = perPageInput === false ? total : start + perPage;
|
|
1557
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
1558
|
+
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("runId = ?", runId).limit(limitValue).offset(start);
|
|
1737
1559
|
const { sql, params } = selectQuery.build();
|
|
1738
1560
|
const results = await this.operations.executeQuery({ sql, params });
|
|
1739
1561
|
const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
|
|
1740
1562
|
return {
|
|
1741
1563
|
pagination: {
|
|
1742
1564
|
total,
|
|
1743
|
-
page
|
|
1744
|
-
perPage:
|
|
1745
|
-
hasMore:
|
|
1565
|
+
page,
|
|
1566
|
+
perPage: perPageForResponse,
|
|
1567
|
+
hasMore: end < total
|
|
1746
1568
|
},
|
|
1747
1569
|
scores
|
|
1748
1570
|
};
|
|
1749
1571
|
} catch (error) {
|
|
1750
1572
|
throw new MastraError(
|
|
1751
1573
|
{
|
|
1752
|
-
id: "
|
|
1574
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "GET_SCORES_BY_RUN_ID", "FAILED"),
|
|
1753
1575
|
domain: ErrorDomain.STORAGE,
|
|
1754
1576
|
category: ErrorCategory.THIRD_PARTY
|
|
1755
1577
|
},
|
|
@@ -1757,12 +1579,15 @@ var ScoresStorageD1 = class extends ScoresStorage {
|
|
|
1757
1579
|
);
|
|
1758
1580
|
}
|
|
1759
1581
|
}
|
|
1760
|
-
async
|
|
1582
|
+
async listScoresByEntityId({
|
|
1761
1583
|
entityId,
|
|
1762
1584
|
entityType,
|
|
1763
1585
|
pagination
|
|
1764
1586
|
}) {
|
|
1765
1587
|
try {
|
|
1588
|
+
const { page, perPage: perPageInput } = pagination;
|
|
1589
|
+
const perPage = normalizePerPage(perPageInput, 100);
|
|
1590
|
+
const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
1766
1591
|
const fullTableName = this.operations.getTableName(TABLE_SCORERS);
|
|
1767
1592
|
const countQuery = createSqlBuilder().count().from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType);
|
|
1768
1593
|
const countResult = await this.operations.executeQuery(countQuery.build());
|
|
@@ -1771,30 +1596,32 @@ var ScoresStorageD1 = class extends ScoresStorage {
|
|
|
1771
1596
|
return {
|
|
1772
1597
|
pagination: {
|
|
1773
1598
|
total: 0,
|
|
1774
|
-
page
|
|
1775
|
-
perPage:
|
|
1599
|
+
page,
|
|
1600
|
+
perPage: perPageForResponse,
|
|
1776
1601
|
hasMore: false
|
|
1777
1602
|
},
|
|
1778
1603
|
scores: []
|
|
1779
1604
|
};
|
|
1780
1605
|
}
|
|
1781
|
-
const
|
|
1606
|
+
const end = perPageInput === false ? total : start + perPage;
|
|
1607
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
1608
|
+
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType).limit(limitValue).offset(start);
|
|
1782
1609
|
const { sql, params } = selectQuery.build();
|
|
1783
1610
|
const results = await this.operations.executeQuery({ sql, params });
|
|
1784
1611
|
const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
|
|
1785
1612
|
return {
|
|
1786
1613
|
pagination: {
|
|
1787
1614
|
total,
|
|
1788
|
-
page
|
|
1789
|
-
perPage:
|
|
1790
|
-
hasMore:
|
|
1615
|
+
page,
|
|
1616
|
+
perPage: perPageForResponse,
|
|
1617
|
+
hasMore: end < total
|
|
1791
1618
|
},
|
|
1792
1619
|
scores
|
|
1793
1620
|
};
|
|
1794
1621
|
} catch (error) {
|
|
1795
1622
|
throw new MastraError(
|
|
1796
1623
|
{
|
|
1797
|
-
id: "
|
|
1624
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "GET_SCORES_BY_ENTITY_ID", "FAILED"),
|
|
1798
1625
|
domain: ErrorDomain.STORAGE,
|
|
1799
1626
|
category: ErrorCategory.THIRD_PARTY
|
|
1800
1627
|
},
|
|
@@ -1802,128 +1629,56 @@ var ScoresStorageD1 = class extends ScoresStorage {
|
|
|
1802
1629
|
);
|
|
1803
1630
|
}
|
|
1804
1631
|
}
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
operations;
|
|
1811
|
-
constructor({ operations }) {
|
|
1812
|
-
super();
|
|
1813
|
-
this.operations = operations;
|
|
1814
|
-
}
|
|
1815
|
-
async getTraces(args) {
|
|
1816
|
-
const paginatedArgs = {
|
|
1817
|
-
name: args.name,
|
|
1818
|
-
scope: args.scope,
|
|
1819
|
-
page: args.page,
|
|
1820
|
-
perPage: args.perPage,
|
|
1821
|
-
attributes: args.attributes,
|
|
1822
|
-
filters: args.filters,
|
|
1823
|
-
dateRange: args.fromDate || args.toDate ? {
|
|
1824
|
-
start: args.fromDate,
|
|
1825
|
-
end: args.toDate
|
|
1826
|
-
} : void 0
|
|
1827
|
-
};
|
|
1828
|
-
try {
|
|
1829
|
-
const result = await this.getTracesPaginated(paginatedArgs);
|
|
1830
|
-
return result.traces;
|
|
1831
|
-
} catch (error) {
|
|
1832
|
-
throw new MastraError(
|
|
1833
|
-
{
|
|
1834
|
-
id: "CLOUDFLARE_D1_STORAGE_GET_TRACES_ERROR",
|
|
1835
|
-
domain: ErrorDomain.STORAGE,
|
|
1836
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
1837
|
-
text: `Failed to retrieve traces: ${error instanceof Error ? error.message : String(error)}`,
|
|
1838
|
-
details: {
|
|
1839
|
-
name: args.name ?? "",
|
|
1840
|
-
scope: args.scope ?? ""
|
|
1841
|
-
}
|
|
1842
|
-
},
|
|
1843
|
-
error
|
|
1844
|
-
);
|
|
1845
|
-
}
|
|
1846
|
-
}
|
|
1847
|
-
async getTracesPaginated(args) {
|
|
1848
|
-
const { name, scope, page = 0, perPage = 100, attributes, dateRange } = args;
|
|
1849
|
-
const fromDate = dateRange?.start;
|
|
1850
|
-
const toDate = dateRange?.end;
|
|
1851
|
-
const fullTableName = this.operations.getTableName(TABLE_TRACES);
|
|
1632
|
+
async listScoresBySpan({
|
|
1633
|
+
traceId,
|
|
1634
|
+
spanId,
|
|
1635
|
+
pagination
|
|
1636
|
+
}) {
|
|
1852
1637
|
try {
|
|
1853
|
-
const
|
|
1854
|
-
const
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
}
|
|
1859
|
-
if (scope) {
|
|
1860
|
-
dataQuery.andWhere("scope = ?", scope);
|
|
1861
|
-
countQuery.andWhere("scope = ?", scope);
|
|
1862
|
-
}
|
|
1863
|
-
if (attributes && Object.keys(attributes).length > 0) {
|
|
1864
|
-
for (const [key, value] of Object.entries(attributes)) {
|
|
1865
|
-
dataQuery.jsonLike("attributes", key, value);
|
|
1866
|
-
countQuery.jsonLike("attributes", key, value);
|
|
1867
|
-
}
|
|
1868
|
-
}
|
|
1869
|
-
if (fromDate) {
|
|
1870
|
-
const fromDateStr = fromDate instanceof Date ? fromDate.toISOString() : fromDate;
|
|
1871
|
-
dataQuery.andWhere("createdAt >= ?", fromDateStr);
|
|
1872
|
-
countQuery.andWhere("createdAt >= ?", fromDateStr);
|
|
1873
|
-
}
|
|
1874
|
-
if (toDate) {
|
|
1875
|
-
const toDateStr = toDate instanceof Date ? toDate.toISOString() : toDate;
|
|
1876
|
-
dataQuery.andWhere("createdAt <= ?", toDateStr);
|
|
1877
|
-
countQuery.andWhere("createdAt <= ?", toDateStr);
|
|
1878
|
-
}
|
|
1879
|
-
const allDataResult = await this.operations.executeQuery(
|
|
1880
|
-
createSqlBuilder().select("*").from(fullTableName).where("1=1").build()
|
|
1881
|
-
);
|
|
1882
|
-
console.log("allDataResult", allDataResult);
|
|
1638
|
+
const { page, perPage: perPageInput } = pagination;
|
|
1639
|
+
const perPage = normalizePerPage(perPageInput, 100);
|
|
1640
|
+
const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
1641
|
+
const fullTableName = this.operations.getTableName(TABLE_SCORERS);
|
|
1642
|
+
const countQuery = createSqlBuilder().count().from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId);
|
|
1883
1643
|
const countResult = await this.operations.executeQuery(countQuery.build());
|
|
1884
|
-
const total = Number(countResult?.[0]?.count ?? 0);
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1644
|
+
const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
|
|
1645
|
+
if (total === 0) {
|
|
1646
|
+
return {
|
|
1647
|
+
pagination: {
|
|
1648
|
+
total: 0,
|
|
1649
|
+
page,
|
|
1650
|
+
perPage: perPageForResponse,
|
|
1651
|
+
hasMore: false
|
|
1652
|
+
},
|
|
1653
|
+
scores: []
|
|
1654
|
+
};
|
|
1655
|
+
}
|
|
1656
|
+
const end = perPageInput === false ? total : start + perPage;
|
|
1657
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
1658
|
+
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId).orderBy("createdAt", "DESC").limit(limitValue).offset(start);
|
|
1659
|
+
const { sql, params } = selectQuery.build();
|
|
1660
|
+
const results = await this.operations.executeQuery({ sql, params });
|
|
1661
|
+
const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
|
|
1897
1662
|
return {
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1663
|
+
pagination: {
|
|
1664
|
+
total,
|
|
1665
|
+
page,
|
|
1666
|
+
perPage: perPageForResponse,
|
|
1667
|
+
hasMore: end < total
|
|
1668
|
+
},
|
|
1669
|
+
scores
|
|
1903
1670
|
};
|
|
1904
1671
|
} catch (error) {
|
|
1905
|
-
|
|
1672
|
+
throw new MastraError(
|
|
1906
1673
|
{
|
|
1907
|
-
id: "
|
|
1674
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "GET_SCORES_BY_SPAN", "FAILED"),
|
|
1908
1675
|
domain: ErrorDomain.STORAGE,
|
|
1909
|
-
category: ErrorCategory.THIRD_PARTY
|
|
1910
|
-
text: `Failed to retrieve traces: ${error instanceof Error ? error.message : String(error)}`,
|
|
1911
|
-
details: { name: name ?? "", scope: scope ?? "" }
|
|
1676
|
+
category: ErrorCategory.THIRD_PARTY
|
|
1912
1677
|
},
|
|
1913
1678
|
error
|
|
1914
1679
|
);
|
|
1915
|
-
this.logger?.error(mastraError.toString());
|
|
1916
|
-
this.logger?.trackException(mastraError);
|
|
1917
|
-
return { traces: [], total: 0, page, perPage, hasMore: false };
|
|
1918
1680
|
}
|
|
1919
1681
|
}
|
|
1920
|
-
async batchTraceInsert({ records }) {
|
|
1921
|
-
this.logger.debug("Batch inserting traces", { count: records.length });
|
|
1922
|
-
await this.operations.batchInsert({
|
|
1923
|
-
tableName: TABLE_TRACES,
|
|
1924
|
-
records
|
|
1925
|
-
});
|
|
1926
|
-
}
|
|
1927
1682
|
};
|
|
1928
1683
|
var WorkflowsStorageD1 = class extends WorkflowsStorage {
|
|
1929
1684
|
operations;
|
|
@@ -1936,7 +1691,7 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
|
|
|
1936
1691
|
// runId,
|
|
1937
1692
|
// stepId,
|
|
1938
1693
|
// result,
|
|
1939
|
-
//
|
|
1694
|
+
// requestContext,
|
|
1940
1695
|
}) {
|
|
1941
1696
|
throw new Error("Method not implemented.");
|
|
1942
1697
|
}
|
|
@@ -1987,7 +1742,7 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
|
|
|
1987
1742
|
} catch (error) {
|
|
1988
1743
|
throw new MastraError(
|
|
1989
1744
|
{
|
|
1990
|
-
id: "
|
|
1745
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "PERSIST_WORKFLOW_SNAPSHOT", "FAILED"),
|
|
1991
1746
|
domain: ErrorDomain.STORAGE,
|
|
1992
1747
|
category: ErrorCategory.THIRD_PARTY,
|
|
1993
1748
|
text: `Failed to persist workflow snapshot: ${error instanceof Error ? error.message : String(error)}`,
|
|
@@ -2012,7 +1767,7 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
|
|
|
2012
1767
|
} catch (error) {
|
|
2013
1768
|
throw new MastraError(
|
|
2014
1769
|
{
|
|
2015
|
-
id: "
|
|
1770
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "LOAD_WORKFLOW_SNAPSHOT", "FAILED"),
|
|
2016
1771
|
domain: ErrorDomain.STORAGE,
|
|
2017
1772
|
category: ErrorCategory.THIRD_PARTY,
|
|
2018
1773
|
text: `Failed to load workflow snapshot: ${error instanceof Error ? error.message : String(error)}`,
|
|
@@ -2040,19 +1795,24 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
|
|
|
2040
1795
|
resourceId: row.resourceId
|
|
2041
1796
|
};
|
|
2042
1797
|
}
|
|
2043
|
-
async
|
|
1798
|
+
async listWorkflowRuns({
|
|
2044
1799
|
workflowName,
|
|
2045
1800
|
fromDate,
|
|
2046
1801
|
toDate,
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
resourceId
|
|
1802
|
+
page,
|
|
1803
|
+
perPage,
|
|
1804
|
+
resourceId,
|
|
1805
|
+
status
|
|
2050
1806
|
} = {}) {
|
|
2051
1807
|
const fullTableName = this.operations.getTableName(TABLE_WORKFLOW_SNAPSHOT);
|
|
2052
1808
|
try {
|
|
2053
1809
|
const builder = createSqlBuilder().select().from(fullTableName);
|
|
2054
1810
|
const countBuilder = createSqlBuilder().count().from(fullTableName);
|
|
2055
1811
|
if (workflowName) builder.whereAnd("workflow_name = ?", workflowName);
|
|
1812
|
+
if (status) {
|
|
1813
|
+
builder.whereAnd("json_extract(snapshot, '$.status') = ?", status);
|
|
1814
|
+
countBuilder.whereAnd("json_extract(snapshot, '$.status') = ?", status);
|
|
1815
|
+
}
|
|
2056
1816
|
if (resourceId) {
|
|
2057
1817
|
const hasResourceId = await this.operations.hasColumn(fullTableName, "resourceId");
|
|
2058
1818
|
if (hasResourceId) {
|
|
@@ -2071,11 +1831,14 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
|
|
|
2071
1831
|
countBuilder.whereAnd("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
|
|
2072
1832
|
}
|
|
2073
1833
|
builder.orderBy("createdAt", "DESC");
|
|
2074
|
-
if (typeof
|
|
2075
|
-
|
|
1834
|
+
if (typeof perPage === "number" && typeof page === "number") {
|
|
1835
|
+
const offset = page * perPage;
|
|
1836
|
+
builder.limit(perPage);
|
|
1837
|
+
builder.offset(offset);
|
|
1838
|
+
}
|
|
2076
1839
|
const { sql, params } = builder.build();
|
|
2077
1840
|
let total = 0;
|
|
2078
|
-
if (
|
|
1841
|
+
if (perPage !== void 0 && page !== void 0) {
|
|
2079
1842
|
const { sql: countSql, params: countParams } = countBuilder.build();
|
|
2080
1843
|
const countResult = await this.operations.executeQuery({
|
|
2081
1844
|
sql: countSql,
|
|
@@ -2090,7 +1853,7 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
|
|
|
2090
1853
|
} catch (error) {
|
|
2091
1854
|
throw new MastraError(
|
|
2092
1855
|
{
|
|
2093
|
-
id: "
|
|
1856
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "LIST_WORKFLOW_RUNS", "FAILED"),
|
|
2094
1857
|
domain: ErrorDomain.STORAGE,
|
|
2095
1858
|
category: ErrorCategory.THIRD_PARTY,
|
|
2096
1859
|
text: `Failed to retrieve workflow runs: ${error instanceof Error ? error.message : String(error)}`,
|
|
@@ -2127,7 +1890,7 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
|
|
|
2127
1890
|
} catch (error) {
|
|
2128
1891
|
throw new MastraError(
|
|
2129
1892
|
{
|
|
2130
|
-
id: "
|
|
1893
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "GET_WORKFLOW_RUN_BY_ID", "FAILED"),
|
|
2131
1894
|
domain: ErrorDomain.STORAGE,
|
|
2132
1895
|
category: ErrorCategory.THIRD_PARTY,
|
|
2133
1896
|
text: `Failed to retrieve workflow run by ID: ${error instanceof Error ? error.message : String(error)}`,
|
|
@@ -2152,7 +1915,7 @@ var D1Store = class extends MastraStorage {
|
|
|
2152
1915
|
*/
|
|
2153
1916
|
constructor(config) {
|
|
2154
1917
|
try {
|
|
2155
|
-
super({ name: "D1" });
|
|
1918
|
+
super({ id: config.id, name: "D1", disableInit: config.disableInit });
|
|
2156
1919
|
if (config.tablePrefix && !/^[a-zA-Z0-9_]*$/.test(config.tablePrefix)) {
|
|
2157
1920
|
throw new Error("Invalid tablePrefix: only letters, numbers, and underscores are allowed.");
|
|
2158
1921
|
}
|
|
@@ -2190,7 +1953,7 @@ var D1Store = class extends MastraStorage {
|
|
|
2190
1953
|
} catch (error) {
|
|
2191
1954
|
throw new MastraError(
|
|
2192
1955
|
{
|
|
2193
|
-
id: "
|
|
1956
|
+
id: createStorageErrorId("CLOUDFLARE_D1", "INITIALIZATION", "FAILED"),
|
|
2194
1957
|
domain: ErrorDomain.STORAGE,
|
|
2195
1958
|
category: ErrorCategory.SYSTEM,
|
|
2196
1959
|
text: "Error initializing D1Store"
|
|
@@ -2206,12 +1969,6 @@ var D1Store = class extends MastraStorage {
|
|
|
2206
1969
|
const scores = new ScoresStorageD1({
|
|
2207
1970
|
operations
|
|
2208
1971
|
});
|
|
2209
|
-
const legacyEvals = new LegacyEvalsStorageD1({
|
|
2210
|
-
operations
|
|
2211
|
-
});
|
|
2212
|
-
const traces = new TracesStorageD1({
|
|
2213
|
-
operations
|
|
2214
|
-
});
|
|
2215
1972
|
const workflows = new WorkflowsStorageD1({
|
|
2216
1973
|
operations
|
|
2217
1974
|
});
|
|
@@ -2221,8 +1978,6 @@ var D1Store = class extends MastraStorage {
|
|
|
2221
1978
|
this.stores = {
|
|
2222
1979
|
operations,
|
|
2223
1980
|
scores,
|
|
2224
|
-
legacyEvals,
|
|
2225
|
-
traces,
|
|
2226
1981
|
workflows,
|
|
2227
1982
|
memory
|
|
2228
1983
|
};
|
|
@@ -2233,7 +1988,8 @@ var D1Store = class extends MastraStorage {
|
|
|
2233
1988
|
resourceWorkingMemory: true,
|
|
2234
1989
|
hasColumn: true,
|
|
2235
1990
|
createTable: true,
|
|
2236
|
-
deleteMessages: false
|
|
1991
|
+
deleteMessages: false,
|
|
1992
|
+
listScoresBySpan: true
|
|
2237
1993
|
};
|
|
2238
1994
|
}
|
|
2239
1995
|
async createTable({
|
|
@@ -2273,15 +2029,6 @@ var D1Store = class extends MastraStorage {
|
|
|
2273
2029
|
async getThreadById({ threadId }) {
|
|
2274
2030
|
return this.stores.memory.getThreadById({ threadId });
|
|
2275
2031
|
}
|
|
2276
|
-
/**
|
|
2277
|
-
* @deprecated use getThreadsByResourceIdPaginated instead
|
|
2278
|
-
*/
|
|
2279
|
-
async getThreadsByResourceId({ resourceId }) {
|
|
2280
|
-
return this.stores.memory.getThreadsByResourceId({ resourceId });
|
|
2281
|
-
}
|
|
2282
|
-
async getThreadsByResourceIdPaginated(args) {
|
|
2283
|
-
return this.stores.memory.getThreadsByResourceIdPaginated(args);
|
|
2284
|
-
}
|
|
2285
2032
|
async saveThread({ thread }) {
|
|
2286
2033
|
return this.stores.memory.saveThread({ thread });
|
|
2287
2034
|
}
|
|
@@ -2298,34 +2045,14 @@ var D1Store = class extends MastraStorage {
|
|
|
2298
2045
|
async saveMessages(args) {
|
|
2299
2046
|
return this.stores.memory.saveMessages(args);
|
|
2300
2047
|
}
|
|
2301
|
-
async getMessages({
|
|
2302
|
-
threadId,
|
|
2303
|
-
selectBy,
|
|
2304
|
-
format
|
|
2305
|
-
}) {
|
|
2306
|
-
return this.stores.memory.getMessages({ threadId, selectBy, format });
|
|
2307
|
-
}
|
|
2308
|
-
async getMessagesById({
|
|
2309
|
-
messageIds,
|
|
2310
|
-
format
|
|
2311
|
-
}) {
|
|
2312
|
-
return this.stores.memory.getMessagesById({ messageIds, format });
|
|
2313
|
-
}
|
|
2314
|
-
async getMessagesPaginated({
|
|
2315
|
-
threadId,
|
|
2316
|
-
selectBy,
|
|
2317
|
-
format
|
|
2318
|
-
}) {
|
|
2319
|
-
return this.stores.memory.getMessagesPaginated({ threadId, selectBy, format });
|
|
2320
|
-
}
|
|
2321
2048
|
async updateWorkflowResults({
|
|
2322
2049
|
workflowName,
|
|
2323
2050
|
runId,
|
|
2324
2051
|
stepId,
|
|
2325
2052
|
result,
|
|
2326
|
-
|
|
2053
|
+
requestContext
|
|
2327
2054
|
}) {
|
|
2328
|
-
return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result,
|
|
2055
|
+
return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
|
|
2329
2056
|
}
|
|
2330
2057
|
async updateWorkflowState({
|
|
2331
2058
|
workflowName,
|
|
@@ -2345,15 +2072,8 @@ var D1Store = class extends MastraStorage {
|
|
|
2345
2072
|
async loadWorkflowSnapshot(params) {
|
|
2346
2073
|
return this.stores.workflows.loadWorkflowSnapshot(params);
|
|
2347
2074
|
}
|
|
2348
|
-
async
|
|
2349
|
-
|
|
2350
|
-
fromDate,
|
|
2351
|
-
toDate,
|
|
2352
|
-
limit,
|
|
2353
|
-
offset,
|
|
2354
|
-
resourceId
|
|
2355
|
-
} = {}) {
|
|
2356
|
-
return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
|
|
2075
|
+
async listWorkflowRuns(args = {}) {
|
|
2076
|
+
return this.stores.workflows.listWorkflowRuns(args);
|
|
2357
2077
|
}
|
|
2358
2078
|
async getWorkflowRunById({
|
|
2359
2079
|
runId,
|
|
@@ -2369,24 +2089,6 @@ var D1Store = class extends MastraStorage {
|
|
|
2369
2089
|
async batchInsert({ tableName, records }) {
|
|
2370
2090
|
return this.stores.operations.batchInsert({ tableName, records });
|
|
2371
2091
|
}
|
|
2372
|
-
/**
|
|
2373
|
-
* @deprecated use getTracesPaginated instead
|
|
2374
|
-
*/
|
|
2375
|
-
async getTraces(args) {
|
|
2376
|
-
return this.stores.traces.getTraces(args);
|
|
2377
|
-
}
|
|
2378
|
-
async getTracesPaginated(args) {
|
|
2379
|
-
return this.stores.traces.getTracesPaginated(args);
|
|
2380
|
-
}
|
|
2381
|
-
/**
|
|
2382
|
-
* @deprecated use getEvals instead
|
|
2383
|
-
*/
|
|
2384
|
-
async getEvalsByAgentName(agentName, type) {
|
|
2385
|
-
return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
|
|
2386
|
-
}
|
|
2387
|
-
async getEvals(options) {
|
|
2388
|
-
return this.stores.legacyEvals.getEvals(options);
|
|
2389
|
-
}
|
|
2390
2092
|
async updateMessages(_args) {
|
|
2391
2093
|
return this.stores.memory.updateMessages(_args);
|
|
2392
2094
|
}
|
|
@@ -2406,34 +2108,41 @@ var D1Store = class extends MastraStorage {
|
|
|
2406
2108
|
async getScoreById({ id: _id }) {
|
|
2407
2109
|
return this.stores.scores.getScoreById({ id: _id });
|
|
2408
2110
|
}
|
|
2409
|
-
async saveScore(
|
|
2410
|
-
return this.stores.scores.saveScore(
|
|
2111
|
+
async saveScore(score) {
|
|
2112
|
+
return this.stores.scores.saveScore(score);
|
|
2411
2113
|
}
|
|
2412
|
-
async
|
|
2114
|
+
async listScoresByRunId({
|
|
2413
2115
|
runId: _runId,
|
|
2414
2116
|
pagination: _pagination
|
|
2415
2117
|
}) {
|
|
2416
|
-
return this.stores.scores.
|
|
2118
|
+
return this.stores.scores.listScoresByRunId({ runId: _runId, pagination: _pagination });
|
|
2417
2119
|
}
|
|
2418
|
-
async
|
|
2120
|
+
async listScoresByEntityId({
|
|
2419
2121
|
entityId: _entityId,
|
|
2420
2122
|
entityType: _entityType,
|
|
2421
2123
|
pagination: _pagination
|
|
2422
2124
|
}) {
|
|
2423
|
-
return this.stores.scores.
|
|
2125
|
+
return this.stores.scores.listScoresByEntityId({
|
|
2424
2126
|
entityId: _entityId,
|
|
2425
2127
|
entityType: _entityType,
|
|
2426
2128
|
pagination: _pagination
|
|
2427
2129
|
});
|
|
2428
2130
|
}
|
|
2429
|
-
async
|
|
2131
|
+
async listScoresByScorerId({
|
|
2430
2132
|
scorerId,
|
|
2431
2133
|
pagination,
|
|
2432
2134
|
entityId,
|
|
2433
2135
|
entityType,
|
|
2434
2136
|
source
|
|
2435
2137
|
}) {
|
|
2436
|
-
return this.stores.scores.
|
|
2138
|
+
return this.stores.scores.listScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
|
|
2139
|
+
}
|
|
2140
|
+
async listScoresBySpan({
|
|
2141
|
+
traceId,
|
|
2142
|
+
spanId,
|
|
2143
|
+
pagination
|
|
2144
|
+
}) {
|
|
2145
|
+
return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
|
|
2437
2146
|
}
|
|
2438
2147
|
/**
|
|
2439
2148
|
* Close the database connection
|