@mastra/cloudflare-d1 0.0.0-remove-cloud-span-transform-20250425214156 → 0.0.0-remove-unused-model-providers-api-20251030210744
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 +1244 -0
- package/LICENSE.md +11 -42
- package/README.md +15 -0
- package/dist/index.cjs +1988 -562
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +2 -5
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1972 -546
- package/dist/index.js.map +1 -0
- package/dist/storage/domains/memory/index.d.ts +91 -0
- package/dist/storage/domains/memory/index.d.ts.map +1 -0
- package/dist/storage/domains/operations/index.d.ts +72 -0
- package/dist/storage/domains/operations/index.d.ts.map +1 -0
- package/dist/storage/domains/scores/index.d.ts +60 -0
- package/dist/storage/domains/scores/index.d.ts.map +1 -0
- package/dist/storage/domains/utils.d.ts +3 -0
- package/dist/storage/domains/utils.d.ts.map +1 -0
- package/dist/storage/domains/workflows/index.d.ts +45 -0
- package/dist/storage/domains/workflows/index.d.ts.map +1 -0
- package/dist/storage/index.d.ts +261 -0
- package/dist/storage/index.d.ts.map +1 -0
- package/dist/storage/sql-builder.d.ts +128 -0
- package/dist/storage/sql-builder.d.ts.map +1 -0
- package/dist/storage/test-utils.d.ts +19 -0
- package/dist/storage/test-utils.d.ts.map +1 -0
- package/package.json +32 -17
- package/dist/_tsup-dts-rollup.d.cts +0 -313
- package/dist/_tsup-dts-rollup.d.ts +0 -313
- package/dist/index.d.cts +0 -5
package/dist/index.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
|
|
2
|
+
import { MastraStorage, StoreOperations, ScoresStorage, TABLE_SCORERS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, ensureDate, MemoryStorage, TABLE_RESOURCES, TABLE_THREADS, TABLE_MESSAGES, resolveMessageLimit, serializeDate, safelyParseJSON } from '@mastra/core/storage';
|
|
2
3
|
import Cloudflare from 'cloudflare';
|
|
4
|
+
import { MessageList } from '@mastra/core/agent';
|
|
5
|
+
import { parseSqlIdentifier } from '@mastra/core/utils';
|
|
6
|
+
import { saveScorePayloadSchema } from '@mastra/core/scores';
|
|
3
7
|
|
|
4
8
|
// src/storage/index.ts
|
|
5
|
-
|
|
6
|
-
// src/storage/sql-builder.ts
|
|
7
9
|
var SqlBuilder = class {
|
|
8
10
|
sql = "";
|
|
9
11
|
params = [];
|
|
@@ -13,12 +15,15 @@ var SqlBuilder = class {
|
|
|
13
15
|
if (!columns || Array.isArray(columns) && columns.length === 0) {
|
|
14
16
|
this.sql = "SELECT *";
|
|
15
17
|
} else {
|
|
16
|
-
|
|
18
|
+
const cols = Array.isArray(columns) ? columns : [columns];
|
|
19
|
+
const parsedCols = cols.map((col) => parseSelectIdentifier(col));
|
|
20
|
+
this.sql = `SELECT ${parsedCols.join(", ")}`;
|
|
17
21
|
}
|
|
18
22
|
return this;
|
|
19
23
|
}
|
|
20
24
|
from(table) {
|
|
21
|
-
|
|
25
|
+
const parsedTableName = parseSqlIdentifier(table, "table name");
|
|
26
|
+
this.sql += ` FROM ${parsedTableName}`;
|
|
22
27
|
return this;
|
|
23
28
|
}
|
|
24
29
|
/**
|
|
@@ -55,7 +60,11 @@ var SqlBuilder = class {
|
|
|
55
60
|
return this;
|
|
56
61
|
}
|
|
57
62
|
orderBy(column, direction = "ASC") {
|
|
58
|
-
|
|
63
|
+
const parsedColumn = parseSqlIdentifier(column, "column name");
|
|
64
|
+
if (!["ASC", "DESC"].includes(direction)) {
|
|
65
|
+
throw new Error(`Invalid sort direction: ${direction}`);
|
|
66
|
+
}
|
|
67
|
+
this.sql += ` ORDER BY ${parsedColumn} ${direction}`;
|
|
59
68
|
return this;
|
|
60
69
|
}
|
|
61
70
|
limit(count) {
|
|
@@ -68,6 +77,10 @@ var SqlBuilder = class {
|
|
|
68
77
|
this.params.push(count);
|
|
69
78
|
return this;
|
|
70
79
|
}
|
|
80
|
+
count() {
|
|
81
|
+
this.sql += "SELECT COUNT(*) AS count";
|
|
82
|
+
return this;
|
|
83
|
+
}
|
|
71
84
|
/**
|
|
72
85
|
* Insert a row, or update specific columns on conflict (upsert).
|
|
73
86
|
* @param table Table name
|
|
@@ -77,27 +90,33 @@ var SqlBuilder = class {
|
|
|
77
90
|
* @param updateMap Object mapping columns to update to their new value (e.g. { name: 'excluded.name' })
|
|
78
91
|
*/
|
|
79
92
|
insert(table, columns, values, conflictColumns, updateMap) {
|
|
80
|
-
const
|
|
93
|
+
const parsedTableName = parseSqlIdentifier(table, "table name");
|
|
94
|
+
const parsedColumns = columns.map((col) => parseSqlIdentifier(col, "column name"));
|
|
95
|
+
const placeholders = parsedColumns.map(() => "?").join(", ");
|
|
81
96
|
if (conflictColumns && updateMap) {
|
|
97
|
+
const parsedConflictColumns = conflictColumns.map((col) => parseSqlIdentifier(col, "column name"));
|
|
82
98
|
const updateClause = Object.entries(updateMap).map(([col, expr]) => `${col} = ${expr}`).join(", ");
|
|
83
|
-
this.sql = `INSERT INTO ${
|
|
99
|
+
this.sql = `INSERT INTO ${parsedTableName} (${parsedColumns.join(", ")}) VALUES (${placeholders}) ON CONFLICT(${parsedConflictColumns.join(", ")}) DO UPDATE SET ${updateClause}`;
|
|
84
100
|
this.params.push(...values);
|
|
85
101
|
return this;
|
|
86
102
|
}
|
|
87
|
-
this.sql = `INSERT INTO ${
|
|
103
|
+
this.sql = `INSERT INTO ${parsedTableName} (${parsedColumns.join(", ")}) VALUES (${placeholders})`;
|
|
88
104
|
this.params.push(...values);
|
|
89
105
|
return this;
|
|
90
106
|
}
|
|
91
107
|
// Update operations
|
|
92
108
|
update(table, columns, values) {
|
|
93
|
-
const
|
|
94
|
-
|
|
109
|
+
const parsedTableName = parseSqlIdentifier(table, "table name");
|
|
110
|
+
const parsedColumns = columns.map((col) => parseSqlIdentifier(col, "column name"));
|
|
111
|
+
const setClause = parsedColumns.map((col) => `${col} = ?`).join(", ");
|
|
112
|
+
this.sql = `UPDATE ${parsedTableName} SET ${setClause}`;
|
|
95
113
|
this.params.push(...values);
|
|
96
114
|
return this;
|
|
97
115
|
}
|
|
98
116
|
// Delete operations
|
|
99
117
|
delete(table) {
|
|
100
|
-
|
|
118
|
+
const parsedTableName = parseSqlIdentifier(table, "table name");
|
|
119
|
+
this.sql = `DELETE FROM ${parsedTableName}`;
|
|
101
120
|
return this;
|
|
102
121
|
}
|
|
103
122
|
/**
|
|
@@ -108,9 +127,16 @@ var SqlBuilder = class {
|
|
|
108
127
|
* @returns The builder instance
|
|
109
128
|
*/
|
|
110
129
|
createTable(table, columnDefinitions, tableConstraints) {
|
|
111
|
-
const
|
|
130
|
+
const parsedTableName = parseSqlIdentifier(table, "table name");
|
|
131
|
+
const parsedColumnDefinitions = columnDefinitions.map((def) => {
|
|
132
|
+
const colName = def.split(/\s+/)[0];
|
|
133
|
+
if (!colName) throw new Error("Empty column name in definition");
|
|
134
|
+
parseSqlIdentifier(colName, "column name");
|
|
135
|
+
return def;
|
|
136
|
+
});
|
|
137
|
+
const columns = parsedColumnDefinitions.join(", ");
|
|
112
138
|
const constraints = tableConstraints && tableConstraints.length > 0 ? ", " + tableConstraints.join(", ") : "";
|
|
113
|
-
this.sql = `CREATE TABLE IF NOT EXISTS ${
|
|
139
|
+
this.sql = `CREATE TABLE IF NOT EXISTS ${parsedTableName} (${columns}${constraints})`;
|
|
114
140
|
return this;
|
|
115
141
|
}
|
|
116
142
|
/**
|
|
@@ -133,13 +159,10 @@ var SqlBuilder = class {
|
|
|
133
159
|
* @returns The builder instance
|
|
134
160
|
*/
|
|
135
161
|
createIndex(indexName, tableName, columnName, indexType = "") {
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
raw(sql, ...params) {
|
|
141
|
-
this.sql = sql;
|
|
142
|
-
this.params.push(...params);
|
|
162
|
+
const parsedIndexName = parseSqlIdentifier(indexName, "index name");
|
|
163
|
+
const parsedTableName = parseSqlIdentifier(tableName, "table name");
|
|
164
|
+
const parsedColumnName = parseSqlIdentifier(columnName, "column name");
|
|
165
|
+
this.sql = `CREATE ${indexType ? indexType + " " : ""}INDEX IF NOT EXISTS ${parsedIndexName} ON ${parsedTableName}(${parsedColumnName})`;
|
|
143
166
|
return this;
|
|
144
167
|
}
|
|
145
168
|
/**
|
|
@@ -149,11 +172,12 @@ var SqlBuilder = class {
|
|
|
149
172
|
* @param exact If true, will not add % wildcards
|
|
150
173
|
*/
|
|
151
174
|
like(column, value, exact = false) {
|
|
175
|
+
const parsedColumnName = parseSqlIdentifier(column, "column name");
|
|
152
176
|
const likeValue = exact ? value : `%${value}%`;
|
|
153
177
|
if (this.whereAdded) {
|
|
154
|
-
this.sql += ` AND ${
|
|
178
|
+
this.sql += ` AND ${parsedColumnName} LIKE ?`;
|
|
155
179
|
} else {
|
|
156
|
-
this.sql += ` WHERE ${
|
|
180
|
+
this.sql += ` WHERE ${parsedColumnName} LIKE ?`;
|
|
157
181
|
this.whereAdded = true;
|
|
158
182
|
}
|
|
159
183
|
this.params.push(likeValue);
|
|
@@ -166,11 +190,13 @@ var SqlBuilder = class {
|
|
|
166
190
|
* @param value The value to match
|
|
167
191
|
*/
|
|
168
192
|
jsonLike(column, key, value) {
|
|
169
|
-
const
|
|
193
|
+
const parsedColumnName = parseSqlIdentifier(column, "column name");
|
|
194
|
+
const parsedKey = parseSqlIdentifier(key, "key name");
|
|
195
|
+
const jsonPattern = `%"${parsedKey}":"${value}"%`;
|
|
170
196
|
if (this.whereAdded) {
|
|
171
|
-
this.sql += ` AND ${
|
|
197
|
+
this.sql += ` AND ${parsedColumnName} LIKE ?`;
|
|
172
198
|
} else {
|
|
173
|
-
this.sql += ` WHERE ${
|
|
199
|
+
this.sql += ` WHERE ${parsedColumnName} LIKE ?`;
|
|
174
200
|
this.whereAdded = true;
|
|
175
201
|
}
|
|
176
202
|
this.params.push(jsonPattern);
|
|
@@ -200,331 +226,153 @@ var SqlBuilder = class {
|
|
|
200
226
|
function createSqlBuilder() {
|
|
201
227
|
return new SqlBuilder();
|
|
202
228
|
}
|
|
229
|
+
var SQL_IDENTIFIER_PATTERN = /^[a-zA-Z0-9_]+(\s+AS\s+[a-zA-Z0-9_]+)?$/;
|
|
230
|
+
function parseSelectIdentifier(column) {
|
|
231
|
+
if (column !== "*" && !SQL_IDENTIFIER_PATTERN.test(column)) {
|
|
232
|
+
throw new Error(
|
|
233
|
+
`Invalid column name: "${column}". Must be "*" or a valid identifier (letters, numbers, underscores), optionally with "AS alias".`
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
return column;
|
|
237
|
+
}
|
|
203
238
|
|
|
204
|
-
// src/storage/
|
|
239
|
+
// src/storage/domains/utils.ts
|
|
205
240
|
function isArrayOfRecords(value) {
|
|
206
241
|
return value && Array.isArray(value) && value.length > 0;
|
|
207
242
|
}
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
databaseId;
|
|
212
|
-
binding;
|
|
213
|
-
// D1Database binding
|
|
214
|
-
tablePrefix;
|
|
215
|
-
/**
|
|
216
|
-
* Creates a new D1Store instance
|
|
217
|
-
* @param config Configuration for D1 access (either REST API or Workers Binding API)
|
|
218
|
-
*/
|
|
219
|
-
constructor(config) {
|
|
220
|
-
super({ name: "D1" });
|
|
221
|
-
this.tablePrefix = config.tablePrefix || "";
|
|
222
|
-
if ("binding" in config) {
|
|
223
|
-
if (!config.binding) {
|
|
224
|
-
throw new Error("D1 binding is required when using Workers Binding API");
|
|
225
|
-
}
|
|
226
|
-
this.binding = config.binding;
|
|
227
|
-
this.logger.info("Using D1 Workers Binding API");
|
|
228
|
-
} else {
|
|
229
|
-
if (!config.accountId || !config.databaseId || !config.apiToken) {
|
|
230
|
-
throw new Error("accountId, databaseId, and apiToken are required when using REST API");
|
|
231
|
-
}
|
|
232
|
-
this.accountId = config.accountId;
|
|
233
|
-
this.databaseId = config.databaseId;
|
|
234
|
-
this.client = new Cloudflare({
|
|
235
|
-
apiToken: config.apiToken
|
|
236
|
-
});
|
|
237
|
-
this.logger.info("Using D1 REST API");
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
// Helper method to get the full table name with prefix
|
|
241
|
-
getTableName(tableName) {
|
|
242
|
-
return `${this.tablePrefix}${tableName}`;
|
|
243
|
-
}
|
|
244
|
-
formatSqlParams(params) {
|
|
245
|
-
return params.map((p) => p === void 0 || p === null ? null : p);
|
|
246
|
-
}
|
|
247
|
-
// Helper method to create SQL indexes for better query performance
|
|
248
|
-
async createIndexIfNotExists(tableName, columnName, indexType = "") {
|
|
249
|
-
const fullTableName = this.getTableName(tableName);
|
|
250
|
-
const indexName = `idx_${tableName}_${columnName}`;
|
|
251
|
-
try {
|
|
252
|
-
const checkQuery = createSqlBuilder().checkIndexExists(indexName, fullTableName);
|
|
253
|
-
const { sql: checkSql, params: checkParams } = checkQuery.build();
|
|
254
|
-
const indexExists = await this.executeQuery({
|
|
255
|
-
sql: checkSql,
|
|
256
|
-
params: checkParams,
|
|
257
|
-
first: true
|
|
258
|
-
});
|
|
259
|
-
if (!indexExists) {
|
|
260
|
-
const createQuery = createSqlBuilder().createIndex(indexName, fullTableName, columnName, indexType);
|
|
261
|
-
const { sql: createSql, params: createParams } = createQuery.build();
|
|
262
|
-
await this.executeQuery({ sql: createSql, params: createParams });
|
|
263
|
-
this.logger.debug(`Created index ${indexName} on ${fullTableName}(${columnName})`);
|
|
264
|
-
}
|
|
265
|
-
} catch (error) {
|
|
266
|
-
this.logger.error(`Error creating index on ${fullTableName}(${columnName}):`, {
|
|
267
|
-
message: error instanceof Error ? error.message : String(error)
|
|
268
|
-
});
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
async executeWorkersBindingQuery({
|
|
272
|
-
sql,
|
|
273
|
-
params = [],
|
|
274
|
-
first = false
|
|
275
|
-
}) {
|
|
276
|
-
if (!this.binding) {
|
|
277
|
-
throw new Error("Workers binding is not configured");
|
|
278
|
-
}
|
|
279
|
-
try {
|
|
280
|
-
const statement = this.binding.prepare(sql);
|
|
281
|
-
const formattedParams = this.formatSqlParams(params);
|
|
282
|
-
let result;
|
|
283
|
-
if (formattedParams.length > 0) {
|
|
284
|
-
if (first) {
|
|
285
|
-
result = await statement.bind(...formattedParams).first();
|
|
286
|
-
if (!result) return null;
|
|
287
|
-
return result;
|
|
288
|
-
} else {
|
|
289
|
-
result = await statement.bind(...formattedParams).all();
|
|
290
|
-
const results = result.results || [];
|
|
291
|
-
if (result.meta) {
|
|
292
|
-
this.logger.debug("Query metadata", { meta: result.meta });
|
|
293
|
-
}
|
|
294
|
-
return results;
|
|
295
|
-
}
|
|
296
|
-
} else {
|
|
297
|
-
if (first) {
|
|
298
|
-
result = await statement.first();
|
|
299
|
-
if (!result) return null;
|
|
300
|
-
return result;
|
|
301
|
-
} else {
|
|
302
|
-
result = await statement.all();
|
|
303
|
-
const results = result.results || [];
|
|
304
|
-
if (result.meta) {
|
|
305
|
-
this.logger.debug("Query metadata", { meta: result.meta });
|
|
306
|
-
}
|
|
307
|
-
return results;
|
|
308
|
-
}
|
|
309
|
-
}
|
|
310
|
-
} catch (workerError) {
|
|
311
|
-
this.logger.error("Workers Binding API error", {
|
|
312
|
-
message: workerError instanceof Error ? workerError.message : String(workerError),
|
|
313
|
-
sql
|
|
314
|
-
});
|
|
315
|
-
throw new Error(`D1 Workers API error: ${workerError.message}`);
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
async executeRestQuery({
|
|
319
|
-
sql,
|
|
320
|
-
params = [],
|
|
321
|
-
first = false
|
|
322
|
-
}) {
|
|
323
|
-
if (!this.client || !this.accountId || !this.databaseId) {
|
|
324
|
-
throw new Error("Missing required REST API configuration");
|
|
325
|
-
}
|
|
326
|
-
try {
|
|
327
|
-
const response = await this.client.d1.database.query(this.databaseId, {
|
|
328
|
-
account_id: this.accountId,
|
|
329
|
-
sql,
|
|
330
|
-
params: this.formatSqlParams(params)
|
|
331
|
-
});
|
|
332
|
-
const result = response.result || [];
|
|
333
|
-
const results = result.flatMap((r) => r.results || []);
|
|
334
|
-
if (first) {
|
|
335
|
-
const firstResult = isArrayOfRecords(results) && results.length > 0 ? results[0] : null;
|
|
336
|
-
if (!firstResult) return null;
|
|
337
|
-
return firstResult;
|
|
338
|
-
}
|
|
339
|
-
return results;
|
|
340
|
-
} catch (restError) {
|
|
341
|
-
this.logger.error("REST API error", {
|
|
342
|
-
message: restError instanceof Error ? restError.message : String(restError),
|
|
343
|
-
sql
|
|
344
|
-
});
|
|
345
|
-
throw new Error(`D1 REST API error: ${restError.message}`);
|
|
346
|
-
}
|
|
347
|
-
}
|
|
348
|
-
/**
|
|
349
|
-
* Execute a SQL query against the D1 database
|
|
350
|
-
* @param options Query options including SQL, parameters, and whether to return only the first result
|
|
351
|
-
* @returns Query results as an array or a single object if first=true
|
|
352
|
-
*/
|
|
353
|
-
async executeQuery(options) {
|
|
354
|
-
const { sql, params = [], first = false } = options;
|
|
243
|
+
function deserializeValue(value, type) {
|
|
244
|
+
if (value === null || value === void 0) return null;
|
|
245
|
+
if (typeof value === "string" && (value.startsWith("{") || value.startsWith("["))) {
|
|
355
246
|
try {
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
} else if (this.client && this.accountId && this.databaseId) {
|
|
360
|
-
return this.executeRestQuery({ sql, params, first });
|
|
361
|
-
} else {
|
|
362
|
-
throw new Error("No valid D1 configuration provided");
|
|
363
|
-
}
|
|
364
|
-
} catch (error) {
|
|
365
|
-
this.logger.error("Error executing SQL query", {
|
|
366
|
-
message: error instanceof Error ? error.message : String(error),
|
|
367
|
-
sql,
|
|
368
|
-
params,
|
|
369
|
-
first
|
|
370
|
-
});
|
|
371
|
-
throw new Error(`D1 query error: ${error.message}`);
|
|
372
|
-
}
|
|
373
|
-
}
|
|
374
|
-
// Helper to convert storage type to SQL type
|
|
375
|
-
getSqlType(type) {
|
|
376
|
-
switch (type) {
|
|
377
|
-
case "text":
|
|
378
|
-
return "TEXT";
|
|
379
|
-
case "timestamp":
|
|
380
|
-
return "TIMESTAMP";
|
|
381
|
-
case "integer":
|
|
382
|
-
return "INTEGER";
|
|
383
|
-
case "bigint":
|
|
384
|
-
return "INTEGER";
|
|
385
|
-
// SQLite doesn't have a separate BIGINT type
|
|
386
|
-
case "jsonb":
|
|
387
|
-
return "TEXT";
|
|
388
|
-
// Store JSON as TEXT in SQLite
|
|
389
|
-
default:
|
|
390
|
-
return "TEXT";
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
ensureDate(date) {
|
|
394
|
-
if (!date) return void 0;
|
|
395
|
-
return date instanceof Date ? date : new Date(date);
|
|
396
|
-
}
|
|
397
|
-
serializeDate(date) {
|
|
398
|
-
if (!date) return void 0;
|
|
399
|
-
const dateObj = this.ensureDate(date);
|
|
400
|
-
return dateObj?.toISOString();
|
|
401
|
-
}
|
|
402
|
-
// Helper to serialize objects to JSON strings
|
|
403
|
-
serializeValue(value) {
|
|
404
|
-
if (value === null || value === void 0) return null;
|
|
405
|
-
if (value instanceof Date) {
|
|
406
|
-
return this.serializeDate(value);
|
|
407
|
-
}
|
|
408
|
-
if (typeof value === "object") {
|
|
409
|
-
return JSON.stringify(value);
|
|
247
|
+
return JSON.parse(value);
|
|
248
|
+
} catch {
|
|
249
|
+
return value;
|
|
410
250
|
}
|
|
411
|
-
return value;
|
|
412
251
|
}
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
} catch {
|
|
423
|
-
return value;
|
|
424
|
-
}
|
|
425
|
-
}
|
|
426
|
-
if (typeof value === "string" && (value.startsWith("{") || value.startsWith("["))) {
|
|
427
|
-
try {
|
|
428
|
-
return JSON.parse(value);
|
|
429
|
-
} catch {
|
|
430
|
-
return value;
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
return value;
|
|
252
|
+
return value;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// src/storage/domains/memory/index.ts
|
|
256
|
+
var MemoryStorageD1 = class extends MemoryStorage {
|
|
257
|
+
operations;
|
|
258
|
+
constructor({ operations }) {
|
|
259
|
+
super();
|
|
260
|
+
this.operations = operations;
|
|
434
261
|
}
|
|
435
|
-
async
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
const fullTableName = this.getTableName(tableName);
|
|
440
|
-
const columnDefinitions = Object.entries(schema).map(([colName, colDef]) => {
|
|
441
|
-
const type = this.getSqlType(colDef.type);
|
|
442
|
-
const nullable = colDef.nullable === false ? "NOT NULL" : "";
|
|
443
|
-
const primaryKey = colDef.primaryKey ? "PRIMARY KEY" : "";
|
|
444
|
-
return `${colName} ${type} ${nullable} ${primaryKey}`.trim();
|
|
262
|
+
async getResourceById({ resourceId }) {
|
|
263
|
+
const resource = await this.operations.load({
|
|
264
|
+
tableName: TABLE_RESOURCES,
|
|
265
|
+
keys: { id: resourceId }
|
|
445
266
|
});
|
|
446
|
-
|
|
447
|
-
if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
|
|
448
|
-
tableConstraints.push("UNIQUE (workflow_name, run_id)");
|
|
449
|
-
}
|
|
450
|
-
const query = createSqlBuilder().createTable(fullTableName, columnDefinitions, tableConstraints);
|
|
451
|
-
const { sql, params } = query.build();
|
|
267
|
+
if (!resource) return null;
|
|
452
268
|
try {
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
}
|
|
459
|
-
throw new Error(`Failed to create table ${fullTableName}: ${error}`);
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
async clearTable({ tableName }) {
|
|
463
|
-
const fullTableName = this.getTableName(tableName);
|
|
464
|
-
try {
|
|
465
|
-
const query = createSqlBuilder().delete(fullTableName);
|
|
466
|
-
const { sql, params } = query.build();
|
|
467
|
-
await this.executeQuery({ sql, params });
|
|
468
|
-
this.logger.debug(`Cleared table ${fullTableName}`);
|
|
269
|
+
return {
|
|
270
|
+
...resource,
|
|
271
|
+
createdAt: ensureDate(resource.createdAt),
|
|
272
|
+
updatedAt: ensureDate(resource.updatedAt),
|
|
273
|
+
metadata: typeof resource.metadata === "string" ? JSON.parse(resource.metadata || "{}") : resource.metadata
|
|
274
|
+
};
|
|
469
275
|
} catch (error) {
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
276
|
+
const mastraError = new MastraError(
|
|
277
|
+
{
|
|
278
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_RESOURCE_BY_ID_ERROR",
|
|
279
|
+
domain: ErrorDomain.STORAGE,
|
|
280
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
281
|
+
text: `Error processing resource ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
282
|
+
details: { resourceId }
|
|
283
|
+
},
|
|
284
|
+
error
|
|
285
|
+
);
|
|
286
|
+
this.logger?.error(mastraError.toString());
|
|
287
|
+
this.logger?.trackException(mastraError);
|
|
288
|
+
return null;
|
|
480
289
|
}
|
|
481
|
-
return processedRecord;
|
|
482
290
|
}
|
|
483
|
-
async
|
|
484
|
-
const fullTableName = this.getTableName(
|
|
485
|
-
const
|
|
291
|
+
async saveResource({ resource }) {
|
|
292
|
+
const fullTableName = this.operations.getTableName(TABLE_RESOURCES);
|
|
293
|
+
const resourceToSave = {
|
|
294
|
+
id: resource.id,
|
|
295
|
+
workingMemory: resource.workingMemory,
|
|
296
|
+
metadata: resource.metadata ? JSON.stringify(resource.metadata) : null,
|
|
297
|
+
createdAt: resource.createdAt,
|
|
298
|
+
updatedAt: resource.updatedAt
|
|
299
|
+
};
|
|
300
|
+
const processedRecord = await this.operations.processRecord(resourceToSave);
|
|
486
301
|
const columns = Object.keys(processedRecord);
|
|
487
302
|
const values = Object.values(processedRecord);
|
|
488
|
-
const
|
|
303
|
+
const updateMap = {
|
|
304
|
+
workingMemory: "excluded.workingMemory",
|
|
305
|
+
metadata: "excluded.metadata",
|
|
306
|
+
createdAt: "excluded.createdAt",
|
|
307
|
+
updatedAt: "excluded.updatedAt"
|
|
308
|
+
};
|
|
309
|
+
const query = createSqlBuilder().insert(fullTableName, columns, values, ["id"], updateMap);
|
|
489
310
|
const { sql, params } = query.build();
|
|
490
311
|
try {
|
|
491
|
-
await this.executeQuery({ sql, params });
|
|
312
|
+
await this.operations.executeQuery({ sql, params });
|
|
313
|
+
return resource;
|
|
492
314
|
} catch (error) {
|
|
493
|
-
|
|
494
|
-
|
|
315
|
+
throw new MastraError(
|
|
316
|
+
{
|
|
317
|
+
id: "CLOUDFLARE_D1_STORAGE_SAVE_RESOURCE_ERROR",
|
|
318
|
+
domain: ErrorDomain.STORAGE,
|
|
319
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
320
|
+
text: `Failed to save resource to ${fullTableName}: ${error instanceof Error ? error.message : String(error)}`,
|
|
321
|
+
details: { resourceId: resource.id }
|
|
322
|
+
},
|
|
323
|
+
error
|
|
324
|
+
);
|
|
495
325
|
}
|
|
496
326
|
}
|
|
497
|
-
async
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
327
|
+
async updateResource({
|
|
328
|
+
resourceId,
|
|
329
|
+
workingMemory,
|
|
330
|
+
metadata
|
|
331
|
+
}) {
|
|
332
|
+
const existingResource = await this.getResourceById({ resourceId });
|
|
333
|
+
if (!existingResource) {
|
|
334
|
+
const newResource = {
|
|
335
|
+
id: resourceId,
|
|
336
|
+
workingMemory,
|
|
337
|
+
metadata: metadata || {},
|
|
338
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
339
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
340
|
+
};
|
|
341
|
+
return this.saveResource({ resource: newResource });
|
|
508
342
|
}
|
|
509
|
-
|
|
343
|
+
const updatedAt = /* @__PURE__ */ new Date();
|
|
344
|
+
const updatedResource = {
|
|
345
|
+
...existingResource,
|
|
346
|
+
workingMemory: workingMemory !== void 0 ? workingMemory : existingResource.workingMemory,
|
|
347
|
+
metadata: {
|
|
348
|
+
...existingResource.metadata,
|
|
349
|
+
...metadata
|
|
350
|
+
},
|
|
351
|
+
updatedAt
|
|
352
|
+
};
|
|
353
|
+
const fullTableName = this.operations.getTableName(TABLE_RESOURCES);
|
|
354
|
+
const columns = ["workingMemory", "metadata", "updatedAt"];
|
|
355
|
+
const values = [updatedResource.workingMemory, JSON.stringify(updatedResource.metadata), updatedAt.toISOString()];
|
|
356
|
+
const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", resourceId);
|
|
510
357
|
const { sql, params } = query.build();
|
|
511
358
|
try {
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
const processedResult = {};
|
|
515
|
-
for (const [key, value] of Object.entries(result)) {
|
|
516
|
-
processedResult[key] = this.deserializeValue(value);
|
|
517
|
-
}
|
|
518
|
-
return processedResult;
|
|
359
|
+
await this.operations.executeQuery({ sql, params });
|
|
360
|
+
return updatedResource;
|
|
519
361
|
} catch (error) {
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
362
|
+
throw new MastraError(
|
|
363
|
+
{
|
|
364
|
+
id: "CLOUDFLARE_D1_STORAGE_UPDATE_RESOURCE_ERROR",
|
|
365
|
+
domain: ErrorDomain.STORAGE,
|
|
366
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
367
|
+
text: `Failed to update resource ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
368
|
+
details: { resourceId }
|
|
369
|
+
},
|
|
370
|
+
error
|
|
371
|
+
);
|
|
524
372
|
}
|
|
525
373
|
}
|
|
526
374
|
async getThreadById({ threadId }) {
|
|
527
|
-
const thread = await this.load({
|
|
375
|
+
const thread = await this.operations.load({
|
|
528
376
|
tableName: TABLE_THREADS,
|
|
529
377
|
keys: { id: threadId }
|
|
530
378
|
});
|
|
@@ -532,47 +380,113 @@ var D1Store = class extends MastraStorage {
|
|
|
532
380
|
try {
|
|
533
381
|
return {
|
|
534
382
|
...thread,
|
|
535
|
-
createdAt:
|
|
536
|
-
updatedAt:
|
|
383
|
+
createdAt: ensureDate(thread.createdAt),
|
|
384
|
+
updatedAt: ensureDate(thread.updatedAt),
|
|
537
385
|
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata || "{}") : thread.metadata || {}
|
|
538
386
|
};
|
|
539
387
|
} catch (error) {
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
388
|
+
const mastraError = new MastraError(
|
|
389
|
+
{
|
|
390
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_THREAD_BY_ID_ERROR",
|
|
391
|
+
domain: ErrorDomain.STORAGE,
|
|
392
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
393
|
+
text: `Error processing thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
394
|
+
details: { threadId }
|
|
395
|
+
},
|
|
396
|
+
error
|
|
397
|
+
);
|
|
398
|
+
this.logger?.error(mastraError.toString());
|
|
399
|
+
this.logger?.trackException(mastraError);
|
|
543
400
|
return null;
|
|
544
401
|
}
|
|
545
402
|
}
|
|
403
|
+
/**
|
|
404
|
+
* @deprecated use getThreadsByResourceIdPaginated instead
|
|
405
|
+
*/
|
|
546
406
|
async getThreadsByResourceId({ resourceId }) {
|
|
547
|
-
const fullTableName = this.getTableName(TABLE_THREADS);
|
|
407
|
+
const fullTableName = this.operations.getTableName(TABLE_THREADS);
|
|
548
408
|
try {
|
|
549
409
|
const query = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId);
|
|
550
410
|
const { sql, params } = query.build();
|
|
551
|
-
const results = await this.executeQuery({ sql, params });
|
|
411
|
+
const results = await this.operations.executeQuery({ sql, params });
|
|
552
412
|
return (isArrayOfRecords(results) ? results : []).map((thread) => ({
|
|
553
413
|
...thread,
|
|
554
|
-
createdAt:
|
|
555
|
-
updatedAt:
|
|
414
|
+
createdAt: ensureDate(thread.createdAt),
|
|
415
|
+
updatedAt: ensureDate(thread.updatedAt),
|
|
556
416
|
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata || "{}") : thread.metadata || {}
|
|
557
417
|
}));
|
|
558
418
|
} catch (error) {
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
419
|
+
const mastraError = new MastraError(
|
|
420
|
+
{
|
|
421
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_THREADS_BY_RESOURCE_ID_ERROR",
|
|
422
|
+
domain: ErrorDomain.STORAGE,
|
|
423
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
424
|
+
text: `Error getting threads by resourceId ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
425
|
+
details: { resourceId }
|
|
426
|
+
},
|
|
427
|
+
error
|
|
428
|
+
);
|
|
429
|
+
this.logger?.error(mastraError.toString());
|
|
430
|
+
this.logger?.trackException(mastraError);
|
|
562
431
|
return [];
|
|
563
432
|
}
|
|
564
433
|
}
|
|
434
|
+
async getThreadsByResourceIdPaginated(args) {
|
|
435
|
+
const { resourceId, page, perPage } = args;
|
|
436
|
+
const fullTableName = this.operations.getTableName(TABLE_THREADS);
|
|
437
|
+
const mapRowToStorageThreadType = (row) => ({
|
|
438
|
+
...row,
|
|
439
|
+
createdAt: ensureDate(row.createdAt),
|
|
440
|
+
updatedAt: ensureDate(row.updatedAt),
|
|
441
|
+
metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata || "{}") : row.metadata || {}
|
|
442
|
+
});
|
|
443
|
+
try {
|
|
444
|
+
const countQuery = createSqlBuilder().count().from(fullTableName).where("resourceId = ?", resourceId);
|
|
445
|
+
const countResult = await this.operations.executeQuery(countQuery.build());
|
|
446
|
+
const total = Number(countResult?.[0]?.count ?? 0);
|
|
447
|
+
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId).orderBy("createdAt", "DESC").limit(perPage).offset(page * perPage);
|
|
448
|
+
const results = await this.operations.executeQuery(selectQuery.build());
|
|
449
|
+
const threads = results.map(mapRowToStorageThreadType);
|
|
450
|
+
return {
|
|
451
|
+
threads,
|
|
452
|
+
total,
|
|
453
|
+
page,
|
|
454
|
+
perPage,
|
|
455
|
+
hasMore: page * perPage + threads.length < total
|
|
456
|
+
};
|
|
457
|
+
} catch (error) {
|
|
458
|
+
const mastraError = new MastraError(
|
|
459
|
+
{
|
|
460
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_ERROR",
|
|
461
|
+
domain: ErrorDomain.STORAGE,
|
|
462
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
463
|
+
text: `Error getting threads by resourceId ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
464
|
+
details: { resourceId }
|
|
465
|
+
},
|
|
466
|
+
error
|
|
467
|
+
);
|
|
468
|
+
this.logger?.error(mastraError.toString());
|
|
469
|
+
this.logger?.trackException(mastraError);
|
|
470
|
+
return {
|
|
471
|
+
threads: [],
|
|
472
|
+
total: 0,
|
|
473
|
+
page,
|
|
474
|
+
perPage,
|
|
475
|
+
hasMore: false
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
}
|
|
565
479
|
async saveThread({ thread }) {
|
|
566
|
-
const fullTableName = this.getTableName(TABLE_THREADS);
|
|
480
|
+
const fullTableName = this.operations.getTableName(TABLE_THREADS);
|
|
567
481
|
const threadToSave = {
|
|
568
482
|
id: thread.id,
|
|
569
483
|
resourceId: thread.resourceId,
|
|
570
484
|
title: thread.title,
|
|
571
485
|
metadata: thread.metadata ? JSON.stringify(thread.metadata) : null,
|
|
572
|
-
createdAt: thread.createdAt,
|
|
573
|
-
updatedAt: thread.updatedAt
|
|
486
|
+
createdAt: thread.createdAt.toISOString(),
|
|
487
|
+
updatedAt: thread.updatedAt.toISOString()
|
|
574
488
|
};
|
|
575
|
-
const processedRecord = await this.processRecord(threadToSave);
|
|
489
|
+
const processedRecord = await this.operations.processRecord(threadToSave);
|
|
576
490
|
const columns = Object.keys(processedRecord);
|
|
577
491
|
const values = Object.values(processedRecord);
|
|
578
492
|
const updateMap = {
|
|
@@ -585,11 +499,19 @@ var D1Store = class extends MastraStorage {
|
|
|
585
499
|
const query = createSqlBuilder().insert(fullTableName, columns, values, ["id"], updateMap);
|
|
586
500
|
const { sql, params } = query.build();
|
|
587
501
|
try {
|
|
588
|
-
await this.executeQuery({ sql, params });
|
|
502
|
+
await this.operations.executeQuery({ sql, params });
|
|
589
503
|
return thread;
|
|
590
504
|
} catch (error) {
|
|
591
|
-
|
|
592
|
-
|
|
505
|
+
throw new MastraError(
|
|
506
|
+
{
|
|
507
|
+
id: "CLOUDFLARE_D1_STORAGE_SAVE_THREAD_ERROR",
|
|
508
|
+
domain: ErrorDomain.STORAGE,
|
|
509
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
510
|
+
text: `Failed to save thread to ${fullTableName}: ${error instanceof Error ? error.message : String(error)}`,
|
|
511
|
+
details: { threadId: thread.id }
|
|
512
|
+
},
|
|
513
|
+
error
|
|
514
|
+
);
|
|
593
515
|
}
|
|
594
516
|
}
|
|
595
517
|
async updateThread({
|
|
@@ -598,20 +520,21 @@ var D1Store = class extends MastraStorage {
|
|
|
598
520
|
metadata
|
|
599
521
|
}) {
|
|
600
522
|
const thread = await this.getThreadById({ threadId: id });
|
|
601
|
-
if (!thread) {
|
|
602
|
-
throw new Error(`Thread ${id} not found`);
|
|
603
|
-
}
|
|
604
|
-
const fullTableName = this.getTableName(TABLE_THREADS);
|
|
605
|
-
const mergedMetadata = {
|
|
606
|
-
...typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
607
|
-
...metadata
|
|
608
|
-
};
|
|
609
|
-
const columns = ["title", "metadata", "updatedAt"];
|
|
610
|
-
const values = [title, JSON.stringify(mergedMetadata), (/* @__PURE__ */ new Date()).toISOString()];
|
|
611
|
-
const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", id);
|
|
612
|
-
const { sql, params } = query.build();
|
|
613
523
|
try {
|
|
614
|
-
|
|
524
|
+
if (!thread) {
|
|
525
|
+
throw new Error(`Thread ${id} not found`);
|
|
526
|
+
}
|
|
527
|
+
const fullTableName = this.operations.getTableName(TABLE_THREADS);
|
|
528
|
+
const mergedMetadata = {
|
|
529
|
+
...typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
530
|
+
...metadata
|
|
531
|
+
};
|
|
532
|
+
const updatedAt = /* @__PURE__ */ new Date();
|
|
533
|
+
const columns = ["title", "metadata", "updatedAt"];
|
|
534
|
+
const values = [title, JSON.stringify(mergedMetadata), updatedAt.toISOString()];
|
|
535
|
+
const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", id);
|
|
536
|
+
const { sql, params } = query.build();
|
|
537
|
+
await this.operations.executeQuery({ sql, params });
|
|
615
538
|
return {
|
|
616
539
|
...thread,
|
|
617
540
|
title,
|
|
@@ -619,40 +542,64 @@ var D1Store = class extends MastraStorage {
|
|
|
619
542
|
...typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
620
543
|
...metadata
|
|
621
544
|
},
|
|
622
|
-
updatedAt
|
|
545
|
+
updatedAt
|
|
623
546
|
};
|
|
624
547
|
} catch (error) {
|
|
625
|
-
|
|
626
|
-
|
|
548
|
+
throw new MastraError(
|
|
549
|
+
{
|
|
550
|
+
id: "CLOUDFLARE_D1_STORAGE_UPDATE_THREAD_ERROR",
|
|
551
|
+
domain: ErrorDomain.STORAGE,
|
|
552
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
553
|
+
text: `Failed to update thread ${id}: ${error instanceof Error ? error.message : String(error)}`,
|
|
554
|
+
details: { threadId: id }
|
|
555
|
+
},
|
|
556
|
+
error
|
|
557
|
+
);
|
|
627
558
|
}
|
|
628
559
|
}
|
|
629
560
|
async deleteThread({ threadId }) {
|
|
630
|
-
const fullTableName = this.getTableName(TABLE_THREADS);
|
|
561
|
+
const fullTableName = this.operations.getTableName(TABLE_THREADS);
|
|
631
562
|
try {
|
|
632
563
|
const deleteThreadQuery = createSqlBuilder().delete(fullTableName).where("id = ?", threadId);
|
|
633
564
|
const { sql: threadSql, params: threadParams } = deleteThreadQuery.build();
|
|
634
|
-
await this.executeQuery({ sql: threadSql, params: threadParams });
|
|
635
|
-
const messagesTableName = this.getTableName(TABLE_MESSAGES);
|
|
565
|
+
await this.operations.executeQuery({ sql: threadSql, params: threadParams });
|
|
566
|
+
const messagesTableName = this.operations.getTableName(TABLE_MESSAGES);
|
|
636
567
|
const deleteMessagesQuery = createSqlBuilder().delete(messagesTableName).where("thread_id = ?", threadId);
|
|
637
568
|
const { sql: messagesSql, params: messagesParams } = deleteMessagesQuery.build();
|
|
638
|
-
await this.executeQuery({ sql: messagesSql, params: messagesParams });
|
|
569
|
+
await this.operations.executeQuery({ sql: messagesSql, params: messagesParams });
|
|
639
570
|
} catch (error) {
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
571
|
+
throw new MastraError(
|
|
572
|
+
{
|
|
573
|
+
id: "CLOUDFLARE_D1_STORAGE_DELETE_THREAD_ERROR",
|
|
574
|
+
domain: ErrorDomain.STORAGE,
|
|
575
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
576
|
+
text: `Failed to delete thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
577
|
+
details: { threadId }
|
|
578
|
+
},
|
|
579
|
+
error
|
|
580
|
+
);
|
|
644
581
|
}
|
|
645
582
|
}
|
|
646
|
-
|
|
647
|
-
|
|
583
|
+
async saveMessages(args) {
|
|
584
|
+
const { messages, format = "v1" } = args;
|
|
648
585
|
if (messages.length === 0) return [];
|
|
649
586
|
try {
|
|
650
587
|
const now = /* @__PURE__ */ new Date();
|
|
588
|
+
const threadId = messages[0]?.threadId;
|
|
651
589
|
for (const [i, message] of messages.entries()) {
|
|
652
590
|
if (!message.id) throw new Error(`Message at index ${i} missing id`);
|
|
653
|
-
if (!message.threadId)
|
|
654
|
-
|
|
655
|
-
|
|
591
|
+
if (!message.threadId) {
|
|
592
|
+
throw new Error(`Message at index ${i} missing threadId`);
|
|
593
|
+
}
|
|
594
|
+
if (!message.content) {
|
|
595
|
+
throw new Error(`Message at index ${i} missing content`);
|
|
596
|
+
}
|
|
597
|
+
if (!message.role) {
|
|
598
|
+
throw new Error(`Message at index ${i} missing role`);
|
|
599
|
+
}
|
|
600
|
+
if (!message.resourceId) {
|
|
601
|
+
throw new Error(`Message at index ${i} missing resourceId`);
|
|
602
|
+
}
|
|
656
603
|
const thread = await this.getThreadById({ threadId: message.threadId });
|
|
657
604
|
if (!thread) {
|
|
658
605
|
throw new Error(`Thread ${message.threadId} not found`);
|
|
@@ -666,74 +613,122 @@ var D1Store = class extends MastraStorage {
|
|
|
666
613
|
content: typeof message.content === "string" ? message.content : JSON.stringify(message.content),
|
|
667
614
|
createdAt: createdAt.toISOString(),
|
|
668
615
|
role: message.role,
|
|
669
|
-
type: message.type
|
|
616
|
+
type: message.type || "v2",
|
|
617
|
+
resourceId: message.resourceId
|
|
670
618
|
};
|
|
671
619
|
});
|
|
672
|
-
await
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
620
|
+
await Promise.all([
|
|
621
|
+
this.operations.batchUpsert({
|
|
622
|
+
tableName: TABLE_MESSAGES,
|
|
623
|
+
records: messagesToInsert
|
|
624
|
+
}),
|
|
625
|
+
// Update thread's updatedAt timestamp
|
|
626
|
+
this.operations.executeQuery({
|
|
627
|
+
sql: `UPDATE ${this.operations.getTableName(TABLE_THREADS)} SET updatedAt = ? WHERE id = ?`,
|
|
628
|
+
params: [now.toISOString(), threadId]
|
|
629
|
+
})
|
|
630
|
+
]);
|
|
676
631
|
this.logger.debug(`Saved ${messages.length} messages`);
|
|
677
|
-
|
|
632
|
+
const list = new MessageList().add(messages, "memory");
|
|
633
|
+
if (format === `v2`) return list.get.all.v2();
|
|
634
|
+
return list.get.all.v1();
|
|
678
635
|
} catch (error) {
|
|
679
|
-
|
|
680
|
-
|
|
636
|
+
throw new MastraError(
|
|
637
|
+
{
|
|
638
|
+
id: "CLOUDFLARE_D1_STORAGE_SAVE_MESSAGES_ERROR",
|
|
639
|
+
domain: ErrorDomain.STORAGE,
|
|
640
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
641
|
+
text: `Failed to save messages: ${error instanceof Error ? error.message : String(error)}`
|
|
642
|
+
},
|
|
643
|
+
error
|
|
644
|
+
);
|
|
681
645
|
}
|
|
682
646
|
}
|
|
683
|
-
async
|
|
684
|
-
|
|
685
|
-
const
|
|
686
|
-
|
|
687
|
-
const
|
|
647
|
+
async _getIncludedMessages(threadId, selectBy) {
|
|
648
|
+
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
649
|
+
const include = selectBy?.include;
|
|
650
|
+
if (!include) return null;
|
|
651
|
+
const unionQueries = [];
|
|
652
|
+
const params = [];
|
|
653
|
+
let paramIdx = 1;
|
|
654
|
+
for (const inc of include) {
|
|
655
|
+
const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
|
|
656
|
+
const searchId = inc.threadId || threadId;
|
|
657
|
+
unionQueries.push(`
|
|
658
|
+
SELECT * FROM (
|
|
659
|
+
WITH ordered_messages AS (
|
|
660
|
+
SELECT
|
|
661
|
+
*,
|
|
662
|
+
ROW_NUMBER() OVER (ORDER BY createdAt ASC) AS row_num
|
|
663
|
+
FROM ${this.operations.getTableName(TABLE_MESSAGES)}
|
|
664
|
+
WHERE thread_id = ?
|
|
665
|
+
)
|
|
666
|
+
SELECT
|
|
667
|
+
m.id,
|
|
668
|
+
m.content,
|
|
669
|
+
m.role,
|
|
670
|
+
m.type,
|
|
671
|
+
m.createdAt,
|
|
672
|
+
m.thread_id AS threadId,
|
|
673
|
+
m.resourceId
|
|
674
|
+
FROM ordered_messages m
|
|
675
|
+
WHERE m.id = ?
|
|
676
|
+
OR EXISTS (
|
|
677
|
+
SELECT 1 FROM ordered_messages target
|
|
678
|
+
WHERE target.id = ?
|
|
679
|
+
AND (
|
|
680
|
+
(m.row_num <= target.row_num + ? AND m.row_num > target.row_num)
|
|
681
|
+
OR
|
|
682
|
+
(m.row_num >= target.row_num - ? AND m.row_num < target.row_num)
|
|
683
|
+
)
|
|
684
|
+
)
|
|
685
|
+
) AS query_${paramIdx}
|
|
686
|
+
`);
|
|
687
|
+
params.push(searchId, id, id, withNextMessages, withPreviousMessages);
|
|
688
|
+
paramIdx++;
|
|
689
|
+
}
|
|
690
|
+
const finalQuery = unionQueries.join(" UNION ALL ") + " ORDER BY createdAt ASC";
|
|
691
|
+
const messages = await this.operations.executeQuery({ sql: finalQuery, params });
|
|
692
|
+
if (!Array.isArray(messages)) {
|
|
693
|
+
return [];
|
|
694
|
+
}
|
|
695
|
+
const processedMessages = messages.map((message) => {
|
|
696
|
+
const processedMsg = {};
|
|
697
|
+
for (const [key, value] of Object.entries(message)) {
|
|
698
|
+
if (key === `type` && value === `v2`) continue;
|
|
699
|
+
processedMsg[key] = deserializeValue(value);
|
|
700
|
+
}
|
|
701
|
+
return processedMsg;
|
|
702
|
+
});
|
|
703
|
+
return processedMessages;
|
|
704
|
+
}
|
|
705
|
+
async getMessages({
|
|
706
|
+
threadId,
|
|
707
|
+
resourceId,
|
|
708
|
+
selectBy,
|
|
709
|
+
format
|
|
710
|
+
}) {
|
|
688
711
|
try {
|
|
712
|
+
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
713
|
+
const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
|
|
714
|
+
const limit = resolveMessageLimit({
|
|
715
|
+
last: selectBy?.last,
|
|
716
|
+
defaultLimit: 40
|
|
717
|
+
});
|
|
718
|
+
const include = selectBy?.include || [];
|
|
719
|
+
const messages = [];
|
|
689
720
|
if (include.length) {
|
|
690
|
-
const
|
|
691
|
-
const nextMax = Math.max(...include.map((i) => i.withNextMessages || 0));
|
|
692
|
-
const includeIds = include.map((i) => i.id);
|
|
693
|
-
const sql2 = `
|
|
694
|
-
WITH ordered_messages AS (
|
|
695
|
-
SELECT
|
|
696
|
-
*,
|
|
697
|
-
ROW_NUMBER() OVER (ORDER BY createdAt DESC) AS row_num
|
|
698
|
-
FROM ${fullTableName}
|
|
699
|
-
WHERE thread_id = ?
|
|
700
|
-
)
|
|
701
|
-
SELECT
|
|
702
|
-
m.id,
|
|
703
|
-
m.content,
|
|
704
|
-
m.role,
|
|
705
|
-
m.type,
|
|
706
|
-
m.createdAt,
|
|
707
|
-
m.thread_id AS "threadId"
|
|
708
|
-
FROM ordered_messages m
|
|
709
|
-
WHERE m.id IN (${includeIds.map(() => "?").join(",")})
|
|
710
|
-
OR EXISTS (
|
|
711
|
-
SELECT 1 FROM ordered_messages target
|
|
712
|
-
WHERE target.id IN (${includeIds.map(() => "?").join(",")})
|
|
713
|
-
AND (
|
|
714
|
-
(m.row_num <= target.row_num + ? AND m.row_num > target.row_num)
|
|
715
|
-
OR
|
|
716
|
-
(m.row_num >= target.row_num - ? AND m.row_num < target.row_num)
|
|
717
|
-
)
|
|
718
|
-
)
|
|
719
|
-
ORDER BY m.createdAt DESC
|
|
720
|
-
`;
|
|
721
|
-
const params2 = [
|
|
722
|
-
threadId,
|
|
723
|
-
...includeIds,
|
|
724
|
-
// for m.id IN (...)
|
|
725
|
-
...includeIds,
|
|
726
|
-
// for target.id IN (...)
|
|
727
|
-
prevMax,
|
|
728
|
-
nextMax
|
|
729
|
-
];
|
|
730
|
-
const includeResult = await this.executeQuery({ sql: sql2, params: params2 });
|
|
721
|
+
const includeResult = await this._getIncludedMessages(threadId, selectBy);
|
|
731
722
|
if (Array.isArray(includeResult)) messages.push(...includeResult);
|
|
732
723
|
}
|
|
733
724
|
const excludeIds = messages.map((m) => m.id);
|
|
734
|
-
|
|
725
|
+
const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId"]).from(fullTableName).where("thread_id = ?", threadId);
|
|
726
|
+
if (excludeIds.length > 0) {
|
|
727
|
+
query.andWhere(`id NOT IN (${excludeIds.map(() => "?").join(",")})`, ...excludeIds);
|
|
728
|
+
}
|
|
729
|
+
query.orderBy("createdAt", "DESC").limit(limit);
|
|
735
730
|
const { sql, params } = query.build();
|
|
736
|
-
const result = await this.executeQuery({ sql, params });
|
|
731
|
+
const result = await this.operations.executeQuery({ sql, params });
|
|
737
732
|
if (Array.isArray(result)) messages.push(...result);
|
|
738
733
|
messages.sort((a, b) => {
|
|
739
734
|
const aRecord = a;
|
|
@@ -745,43 +740,1178 @@ var D1Store = class extends MastraStorage {
|
|
|
745
740
|
const processedMessages = messages.map((message) => {
|
|
746
741
|
const processedMsg = {};
|
|
747
742
|
for (const [key, value] of Object.entries(message)) {
|
|
748
|
-
|
|
743
|
+
if (key === `type` && value === `v2`) continue;
|
|
744
|
+
processedMsg[key] = deserializeValue(value);
|
|
749
745
|
}
|
|
750
746
|
return processedMsg;
|
|
751
747
|
});
|
|
752
748
|
this.logger.debug(`Retrieved ${messages.length} messages for thread ${threadId}`);
|
|
753
|
-
|
|
749
|
+
const list = new MessageList().add(processedMessages, "memory");
|
|
750
|
+
if (format === `v2`) return list.get.all.v2();
|
|
751
|
+
return list.get.all.v1();
|
|
754
752
|
} catch (error) {
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
753
|
+
const mastraError = new MastraError(
|
|
754
|
+
{
|
|
755
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_ERROR",
|
|
756
|
+
domain: ErrorDomain.STORAGE,
|
|
757
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
758
|
+
text: `Failed to retrieve messages for thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
759
|
+
details: { threadId, resourceId: resourceId ?? "" }
|
|
760
|
+
},
|
|
761
|
+
error
|
|
762
|
+
);
|
|
763
|
+
this.logger?.error(mastraError.toString());
|
|
764
|
+
this.logger?.trackException(mastraError);
|
|
765
|
+
throw mastraError;
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
async listMessagesById({ messageIds }) {
|
|
769
|
+
if (messageIds.length === 0) return [];
|
|
770
|
+
const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
|
|
771
|
+
const messages = [];
|
|
772
|
+
try {
|
|
773
|
+
const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId", "resourceId"]).from(fullTableName).where(`id in (${messageIds.map(() => "?").join(",")})`, ...messageIds);
|
|
774
|
+
query.orderBy("createdAt", "DESC");
|
|
775
|
+
const { sql, params } = query.build();
|
|
776
|
+
const result = await this.operations.executeQuery({ sql, params });
|
|
777
|
+
if (Array.isArray(result)) messages.push(...result);
|
|
778
|
+
const processedMessages = messages.map((message) => {
|
|
779
|
+
const processedMsg = {};
|
|
780
|
+
for (const [key, value] of Object.entries(message)) {
|
|
781
|
+
if (key === `type` && value === `v2`) continue;
|
|
782
|
+
processedMsg[key] = deserializeValue(value);
|
|
783
|
+
}
|
|
784
|
+
return processedMsg;
|
|
758
785
|
});
|
|
759
|
-
|
|
786
|
+
this.logger.debug(`Retrieved ${messages.length} messages`);
|
|
787
|
+
const list = new MessageList().add(processedMessages, "memory");
|
|
788
|
+
return list.get.all.v2();
|
|
789
|
+
} catch (error) {
|
|
790
|
+
const mastraError = new MastraError(
|
|
791
|
+
{
|
|
792
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_BY_ID_ERROR",
|
|
793
|
+
domain: ErrorDomain.STORAGE,
|
|
794
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
795
|
+
text: `Failed to retrieve messages by ID: ${error instanceof Error ? error.message : String(error)}`,
|
|
796
|
+
details: { messageIds: JSON.stringify(messageIds) }
|
|
797
|
+
},
|
|
798
|
+
error
|
|
799
|
+
);
|
|
800
|
+
this.logger?.error(mastraError.toString());
|
|
801
|
+
this.logger?.trackException(mastraError);
|
|
802
|
+
throw mastraError;
|
|
760
803
|
}
|
|
761
804
|
}
|
|
762
|
-
async
|
|
763
|
-
|
|
805
|
+
async listMessages(args) {
|
|
806
|
+
const { threadId, resourceId, include, filter, limit, offset = 0, orderBy } = args;
|
|
807
|
+
if (!threadId.trim()) {
|
|
808
|
+
throw new MastraError(
|
|
809
|
+
{
|
|
810
|
+
id: "STORAGE_CLOUDFLARE_D1_LIST_MESSAGES_INVALID_THREAD_ID",
|
|
811
|
+
domain: ErrorDomain.STORAGE,
|
|
812
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
813
|
+
details: { threadId }
|
|
814
|
+
},
|
|
815
|
+
new Error("threadId must be a non-empty string")
|
|
816
|
+
);
|
|
817
|
+
}
|
|
818
|
+
try {
|
|
819
|
+
let perPage = 40;
|
|
820
|
+
if (limit !== void 0) {
|
|
821
|
+
if (limit === false) {
|
|
822
|
+
perPage = Number.MAX_SAFE_INTEGER;
|
|
823
|
+
} else if (limit === 0) {
|
|
824
|
+
perPage = 0;
|
|
825
|
+
} else if (typeof limit === "number" && limit > 0) {
|
|
826
|
+
perPage = limit;
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
const page = perPage === 0 ? 0 : Math.floor(offset / perPage);
|
|
830
|
+
const sortField = orderBy?.field || "createdAt";
|
|
831
|
+
const sortDirection = orderBy?.direction || "DESC";
|
|
832
|
+
const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
|
|
833
|
+
let query = `
|
|
834
|
+
SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
|
|
835
|
+
FROM ${fullTableName}
|
|
836
|
+
WHERE thread_id = ?
|
|
837
|
+
`;
|
|
838
|
+
const queryParams = [threadId];
|
|
839
|
+
if (resourceId) {
|
|
840
|
+
query += ` AND resourceId = ?`;
|
|
841
|
+
queryParams.push(resourceId);
|
|
842
|
+
}
|
|
843
|
+
const dateRange = filter?.dateRange;
|
|
844
|
+
if (dateRange?.start) {
|
|
845
|
+
const startDate = dateRange.start instanceof Date ? serializeDate(dateRange.start) : serializeDate(new Date(dateRange.start));
|
|
846
|
+
query += ` AND createdAt >= ?`;
|
|
847
|
+
queryParams.push(startDate);
|
|
848
|
+
}
|
|
849
|
+
if (dateRange?.end) {
|
|
850
|
+
const endDate = dateRange.end instanceof Date ? serializeDate(dateRange.end) : serializeDate(new Date(dateRange.end));
|
|
851
|
+
query += ` AND createdAt <= ?`;
|
|
852
|
+
queryParams.push(endDate);
|
|
853
|
+
}
|
|
854
|
+
const orderByField = sortField === "createdAt" ? "createdAt" : `"${sortField}"`;
|
|
855
|
+
const orderByDirection = sortDirection === "ASC" ? "ASC" : "DESC";
|
|
856
|
+
query += ` ORDER BY ${orderByField} ${orderByDirection}`;
|
|
857
|
+
if (perPage !== Number.MAX_SAFE_INTEGER) {
|
|
858
|
+
query += ` LIMIT ? OFFSET ?`;
|
|
859
|
+
queryParams.push(perPage, offset);
|
|
860
|
+
}
|
|
861
|
+
const results = await this.operations.executeQuery({ sql: query, params: queryParams });
|
|
862
|
+
const paginatedMessages = (isArrayOfRecords(results) ? results : []).map((message) => {
|
|
863
|
+
const processedMsg = {};
|
|
864
|
+
for (const [key, value] of Object.entries(message)) {
|
|
865
|
+
if (key === `type` && value === `v2`) continue;
|
|
866
|
+
processedMsg[key] = deserializeValue(value);
|
|
867
|
+
}
|
|
868
|
+
return processedMsg;
|
|
869
|
+
});
|
|
870
|
+
const paginatedCount = paginatedMessages.length;
|
|
871
|
+
let countQuery = `SELECT count() as count FROM ${fullTableName} WHERE thread_id = ?`;
|
|
872
|
+
const countParams = [threadId];
|
|
873
|
+
if (resourceId) {
|
|
874
|
+
countQuery += ` AND resourceId = ?`;
|
|
875
|
+
countParams.push(resourceId);
|
|
876
|
+
}
|
|
877
|
+
if (dateRange?.start) {
|
|
878
|
+
const startDate = dateRange.start instanceof Date ? serializeDate(dateRange.start) : serializeDate(new Date(dateRange.start));
|
|
879
|
+
countQuery += ` AND createdAt >= ?`;
|
|
880
|
+
countParams.push(startDate);
|
|
881
|
+
}
|
|
882
|
+
if (dateRange?.end) {
|
|
883
|
+
const endDate = dateRange.end instanceof Date ? serializeDate(dateRange.end) : serializeDate(new Date(dateRange.end));
|
|
884
|
+
countQuery += ` AND createdAt <= ?`;
|
|
885
|
+
countParams.push(endDate);
|
|
886
|
+
}
|
|
887
|
+
const countResult = await this.operations.executeQuery({ sql: countQuery, params: countParams });
|
|
888
|
+
const total = Number(countResult[0]?.count ?? 0);
|
|
889
|
+
if (total === 0 && paginatedCount === 0) {
|
|
890
|
+
return {
|
|
891
|
+
messages: [],
|
|
892
|
+
total: 0,
|
|
893
|
+
page,
|
|
894
|
+
perPage,
|
|
895
|
+
hasMore: false
|
|
896
|
+
};
|
|
897
|
+
}
|
|
898
|
+
const messageIds = new Set(paginatedMessages.map((m) => m.id));
|
|
899
|
+
let includeMessages = [];
|
|
900
|
+
if (include && include.length > 0) {
|
|
901
|
+
const selectBy = { include };
|
|
902
|
+
const includeResult = await this._getIncludedMessages(threadId, selectBy);
|
|
903
|
+
if (Array.isArray(includeResult)) {
|
|
904
|
+
includeMessages = includeResult;
|
|
905
|
+
for (const includeMsg of includeMessages) {
|
|
906
|
+
if (!messageIds.has(includeMsg.id)) {
|
|
907
|
+
paginatedMessages.push(includeMsg);
|
|
908
|
+
messageIds.add(includeMsg.id);
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
const list = new MessageList().add(paginatedMessages, "memory");
|
|
914
|
+
let finalMessages = list.get.all.v2();
|
|
915
|
+
finalMessages = finalMessages.sort((a, b) => {
|
|
916
|
+
const aValue = sortField === "createdAt" ? new Date(a.createdAt).getTime() : a[sortField];
|
|
917
|
+
const bValue = sortField === "createdAt" ? new Date(b.createdAt).getTime() : b[sortField];
|
|
918
|
+
if (aValue === bValue) {
|
|
919
|
+
return a.id.localeCompare(b.id);
|
|
920
|
+
}
|
|
921
|
+
return sortDirection === "ASC" ? aValue - bValue : bValue - aValue;
|
|
922
|
+
});
|
|
923
|
+
const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
|
|
924
|
+
const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
|
|
925
|
+
const hasMore = limit === false ? false : allThreadMessagesReturned ? false : offset + paginatedCount < total;
|
|
926
|
+
return {
|
|
927
|
+
messages: finalMessages,
|
|
928
|
+
total,
|
|
929
|
+
page,
|
|
930
|
+
perPage,
|
|
931
|
+
hasMore
|
|
932
|
+
};
|
|
933
|
+
} catch (error) {
|
|
934
|
+
const mastraError = new MastraError(
|
|
935
|
+
{
|
|
936
|
+
id: "CLOUDFLARE_D1_STORAGE_LIST_MESSAGES_ERROR",
|
|
937
|
+
domain: ErrorDomain.STORAGE,
|
|
938
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
939
|
+
text: `Failed to list messages for thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
940
|
+
details: {
|
|
941
|
+
threadId,
|
|
942
|
+
resourceId: resourceId ?? ""
|
|
943
|
+
}
|
|
944
|
+
},
|
|
945
|
+
error
|
|
946
|
+
);
|
|
947
|
+
this.logger?.error?.(mastraError.toString());
|
|
948
|
+
this.logger?.trackException?.(mastraError);
|
|
949
|
+
return {
|
|
950
|
+
messages: [],
|
|
951
|
+
total: 0,
|
|
952
|
+
page: Math.floor(offset / (limit === false ? Number.MAX_SAFE_INTEGER : limit || 40)),
|
|
953
|
+
perPage: limit === false ? Number.MAX_SAFE_INTEGER : limit || 40,
|
|
954
|
+
hasMore: false
|
|
955
|
+
};
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
/**
|
|
959
|
+
* @todo When migrating from getThreadsByResourceIdPaginated to this method,
|
|
960
|
+
* implement orderBy and sortDirection support for full sorting capabilities
|
|
961
|
+
*/
|
|
962
|
+
async listThreadsByResourceId(args) {
|
|
963
|
+
const { resourceId, limit, offset } = args;
|
|
964
|
+
const page = Math.floor(offset / limit);
|
|
965
|
+
const perPage = limit;
|
|
966
|
+
return this.getThreadsByResourceIdPaginated({ resourceId, page, perPage });
|
|
967
|
+
}
|
|
968
|
+
async getMessagesPaginated({
|
|
969
|
+
threadId,
|
|
970
|
+
resourceId,
|
|
971
|
+
selectBy,
|
|
972
|
+
format
|
|
973
|
+
}) {
|
|
974
|
+
const { dateRange, page = 0, perPage: perPageInput } = selectBy?.pagination || {};
|
|
975
|
+
const { start: fromDate, end: toDate } = dateRange || {};
|
|
976
|
+
const perPage = perPageInput !== void 0 ? perPageInput : resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
|
|
977
|
+
const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
|
|
978
|
+
const messages = [];
|
|
979
|
+
try {
|
|
980
|
+
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
981
|
+
if (selectBy?.include?.length) {
|
|
982
|
+
const includeResult = await this._getIncludedMessages(threadId, selectBy);
|
|
983
|
+
if (Array.isArray(includeResult)) messages.push(...includeResult);
|
|
984
|
+
}
|
|
985
|
+
const countQuery = createSqlBuilder().count().from(fullTableName).where("thread_id = ?", threadId);
|
|
986
|
+
if (fromDate) {
|
|
987
|
+
countQuery.andWhere("createdAt >= ?", serializeDate(fromDate));
|
|
988
|
+
}
|
|
989
|
+
if (toDate) {
|
|
990
|
+
countQuery.andWhere("createdAt <= ?", serializeDate(toDate));
|
|
991
|
+
}
|
|
992
|
+
const countResult = await this.operations.executeQuery(countQuery.build());
|
|
993
|
+
const total = Number(countResult[0]?.count ?? 0);
|
|
994
|
+
if (total === 0 && messages.length === 0) {
|
|
995
|
+
return {
|
|
996
|
+
messages: [],
|
|
997
|
+
total: 0,
|
|
998
|
+
page,
|
|
999
|
+
perPage,
|
|
1000
|
+
hasMore: false
|
|
1001
|
+
};
|
|
1002
|
+
}
|
|
1003
|
+
const excludeIds = messages.map((m) => m.id);
|
|
1004
|
+
const excludeCondition = excludeIds.length > 0 ? `AND id NOT IN (${excludeIds.map(() => "?").join(",")})` : "";
|
|
1005
|
+
let query;
|
|
1006
|
+
let queryParams = [threadId];
|
|
1007
|
+
if (fromDate) {
|
|
1008
|
+
queryParams.push(serializeDate(fromDate));
|
|
1009
|
+
}
|
|
1010
|
+
if (toDate) {
|
|
1011
|
+
queryParams.push(serializeDate(toDate));
|
|
1012
|
+
}
|
|
1013
|
+
if (excludeIds.length > 0) {
|
|
1014
|
+
queryParams.push(...excludeIds);
|
|
1015
|
+
}
|
|
1016
|
+
if (selectBy?.last && selectBy.last > 0) {
|
|
1017
|
+
query = `
|
|
1018
|
+
SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
|
|
1019
|
+
FROM ${fullTableName}
|
|
1020
|
+
WHERE thread_id = ?
|
|
1021
|
+
${fromDate ? "AND createdAt >= ?" : ""}
|
|
1022
|
+
${toDate ? "AND createdAt <= ?" : ""}
|
|
1023
|
+
${excludeCondition}
|
|
1024
|
+
ORDER BY createdAt DESC
|
|
1025
|
+
LIMIT ?
|
|
1026
|
+
`;
|
|
1027
|
+
queryParams.push(selectBy.last);
|
|
1028
|
+
} else {
|
|
1029
|
+
query = `
|
|
1030
|
+
SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
|
|
1031
|
+
FROM ${fullTableName}
|
|
1032
|
+
WHERE thread_id = ?
|
|
1033
|
+
${fromDate ? "AND createdAt >= ?" : ""}
|
|
1034
|
+
${toDate ? "AND createdAt <= ?" : ""}
|
|
1035
|
+
${excludeCondition}
|
|
1036
|
+
ORDER BY createdAt DESC
|
|
1037
|
+
LIMIT ? OFFSET ?
|
|
1038
|
+
`;
|
|
1039
|
+
queryParams.push(perPage, page * perPage);
|
|
1040
|
+
}
|
|
1041
|
+
const results = await this.operations.executeQuery({ sql: query, params: queryParams });
|
|
1042
|
+
const processedMessages = results.map((message) => {
|
|
1043
|
+
const processedMsg = {};
|
|
1044
|
+
for (const [key, value] of Object.entries(message)) {
|
|
1045
|
+
if (key === `type` && value === `v2`) continue;
|
|
1046
|
+
processedMsg[key] = deserializeValue(value);
|
|
1047
|
+
}
|
|
1048
|
+
return processedMsg;
|
|
1049
|
+
});
|
|
1050
|
+
if (selectBy?.last) {
|
|
1051
|
+
processedMessages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
|
|
1052
|
+
}
|
|
1053
|
+
const list = new MessageList().add(processedMessages, "memory");
|
|
1054
|
+
messages.push(...format === `v2` ? list.get.all.v2() : list.get.all.v1());
|
|
1055
|
+
return {
|
|
1056
|
+
messages,
|
|
1057
|
+
total,
|
|
1058
|
+
page,
|
|
1059
|
+
perPage,
|
|
1060
|
+
hasMore: selectBy?.last ? false : page * perPage + messages.length < total
|
|
1061
|
+
};
|
|
1062
|
+
} catch (error) {
|
|
1063
|
+
const mastraError = new MastraError(
|
|
1064
|
+
{
|
|
1065
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_PAGINATED_ERROR",
|
|
1066
|
+
domain: ErrorDomain.STORAGE,
|
|
1067
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1068
|
+
text: `Failed to retrieve messages for thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
1069
|
+
details: { threadId, resourceId: resourceId ?? "" }
|
|
1070
|
+
},
|
|
1071
|
+
error
|
|
1072
|
+
);
|
|
1073
|
+
this.logger?.error(mastraError.toString());
|
|
1074
|
+
this.logger?.trackException(mastraError);
|
|
1075
|
+
return {
|
|
1076
|
+
messages: [],
|
|
1077
|
+
total: 0,
|
|
1078
|
+
page,
|
|
1079
|
+
perPage,
|
|
1080
|
+
hasMore: false
|
|
1081
|
+
};
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
async updateMessages(args) {
|
|
1085
|
+
const { messages } = args;
|
|
1086
|
+
this.logger.debug("Updating messages", { count: messages.length });
|
|
1087
|
+
if (!messages.length) {
|
|
1088
|
+
return [];
|
|
1089
|
+
}
|
|
1090
|
+
const messageIds = messages.map((m) => m.id);
|
|
1091
|
+
const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
|
|
1092
|
+
const threadsTableName = this.operations.getTableName(TABLE_THREADS);
|
|
1093
|
+
try {
|
|
1094
|
+
const placeholders = messageIds.map(() => "?").join(",");
|
|
1095
|
+
const selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${fullTableName} WHERE id IN (${placeholders})`;
|
|
1096
|
+
const existingMessages = await this.operations.executeQuery({ sql: selectQuery, params: messageIds });
|
|
1097
|
+
if (existingMessages.length === 0) {
|
|
1098
|
+
return [];
|
|
1099
|
+
}
|
|
1100
|
+
const parsedExistingMessages = existingMessages.map((msg) => {
|
|
1101
|
+
if (typeof msg.content === "string") {
|
|
1102
|
+
try {
|
|
1103
|
+
msg.content = JSON.parse(msg.content);
|
|
1104
|
+
} catch {
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
return msg;
|
|
1108
|
+
});
|
|
1109
|
+
const threadIdsToUpdate = /* @__PURE__ */ new Set();
|
|
1110
|
+
const updateQueries = [];
|
|
1111
|
+
for (const existingMessage of parsedExistingMessages) {
|
|
1112
|
+
const updatePayload = messages.find((m) => m.id === existingMessage.id);
|
|
1113
|
+
if (!updatePayload) continue;
|
|
1114
|
+
const { id, ...fieldsToUpdate } = updatePayload;
|
|
1115
|
+
if (Object.keys(fieldsToUpdate).length === 0) continue;
|
|
1116
|
+
threadIdsToUpdate.add(existingMessage.threadId);
|
|
1117
|
+
if ("threadId" in updatePayload && updatePayload.threadId && updatePayload.threadId !== existingMessage.threadId) {
|
|
1118
|
+
threadIdsToUpdate.add(updatePayload.threadId);
|
|
1119
|
+
}
|
|
1120
|
+
const setClauses = [];
|
|
1121
|
+
const values = [];
|
|
1122
|
+
const updatableFields = { ...fieldsToUpdate };
|
|
1123
|
+
if (updatableFields.content) {
|
|
1124
|
+
const existingContent = existingMessage.content || {};
|
|
1125
|
+
const newContent = {
|
|
1126
|
+
...existingContent,
|
|
1127
|
+
...updatableFields.content,
|
|
1128
|
+
// Deep merge metadata if it exists on both
|
|
1129
|
+
...existingContent?.metadata && updatableFields.content.metadata ? {
|
|
1130
|
+
metadata: {
|
|
1131
|
+
...existingContent.metadata,
|
|
1132
|
+
...updatableFields.content.metadata
|
|
1133
|
+
}
|
|
1134
|
+
} : {}
|
|
1135
|
+
};
|
|
1136
|
+
setClauses.push(`content = ?`);
|
|
1137
|
+
values.push(JSON.stringify(newContent));
|
|
1138
|
+
delete updatableFields.content;
|
|
1139
|
+
}
|
|
1140
|
+
for (const key in updatableFields) {
|
|
1141
|
+
if (Object.prototype.hasOwnProperty.call(updatableFields, key)) {
|
|
1142
|
+
const dbColumn = key === "threadId" ? "thread_id" : key;
|
|
1143
|
+
setClauses.push(`${dbColumn} = ?`);
|
|
1144
|
+
values.push(updatableFields[key]);
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
if (setClauses.length > 0) {
|
|
1148
|
+
values.push(id);
|
|
1149
|
+
const updateQuery = `UPDATE ${fullTableName} SET ${setClauses.join(", ")} WHERE id = ?`;
|
|
1150
|
+
updateQueries.push({ sql: updateQuery, params: values });
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
for (const query of updateQueries) {
|
|
1154
|
+
await this.operations.executeQuery(query);
|
|
1155
|
+
}
|
|
1156
|
+
if (threadIdsToUpdate.size > 0) {
|
|
1157
|
+
const threadPlaceholders = Array.from(threadIdsToUpdate).map(() => "?").join(",");
|
|
1158
|
+
const threadUpdateQuery = `UPDATE ${threadsTableName} SET updatedAt = ? WHERE id IN (${threadPlaceholders})`;
|
|
1159
|
+
const threadUpdateParams = [(/* @__PURE__ */ new Date()).toISOString(), ...Array.from(threadIdsToUpdate)];
|
|
1160
|
+
await this.operations.executeQuery({ sql: threadUpdateQuery, params: threadUpdateParams });
|
|
1161
|
+
}
|
|
1162
|
+
const updatedMessages = await this.operations.executeQuery({ sql: selectQuery, params: messageIds });
|
|
1163
|
+
return updatedMessages.map((message) => {
|
|
1164
|
+
if (typeof message.content === "string") {
|
|
1165
|
+
try {
|
|
1166
|
+
message.content = JSON.parse(message.content);
|
|
1167
|
+
} catch {
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
return message;
|
|
1171
|
+
});
|
|
1172
|
+
} catch (error) {
|
|
1173
|
+
throw new MastraError(
|
|
1174
|
+
{
|
|
1175
|
+
id: "CLOUDFLARE_D1_STORAGE_UPDATE_MESSAGES_FAILED",
|
|
1176
|
+
domain: ErrorDomain.STORAGE,
|
|
1177
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1178
|
+
details: { count: messages.length }
|
|
1179
|
+
},
|
|
1180
|
+
error
|
|
1181
|
+
);
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
};
|
|
1185
|
+
var StoreOperationsD1 = class extends StoreOperations {
|
|
1186
|
+
client;
|
|
1187
|
+
binding;
|
|
1188
|
+
tablePrefix;
|
|
1189
|
+
constructor(config) {
|
|
1190
|
+
super();
|
|
1191
|
+
this.client = config.client;
|
|
1192
|
+
this.binding = config.binding;
|
|
1193
|
+
this.tablePrefix = config.tablePrefix || "";
|
|
1194
|
+
}
|
|
1195
|
+
async hasColumn(table, column) {
|
|
1196
|
+
const fullTableName = table.startsWith(this.tablePrefix) ? table : `${this.tablePrefix}${table}`;
|
|
1197
|
+
const sql = `PRAGMA table_info(${fullTableName});`;
|
|
1198
|
+
const result = await this.executeQuery({ sql, params: [] });
|
|
1199
|
+
if (!result || !Array.isArray(result)) return false;
|
|
1200
|
+
return result.some((col) => col.name === column || col.name === column.toLowerCase());
|
|
1201
|
+
}
|
|
1202
|
+
getTableName(tableName) {
|
|
1203
|
+
return `${this.tablePrefix}${tableName}`;
|
|
1204
|
+
}
|
|
1205
|
+
formatSqlParams(params) {
|
|
1206
|
+
return params.map((p) => p === void 0 || p === null ? null : p);
|
|
1207
|
+
}
|
|
1208
|
+
async executeWorkersBindingQuery({
|
|
1209
|
+
sql,
|
|
1210
|
+
params = [],
|
|
1211
|
+
first = false
|
|
1212
|
+
}) {
|
|
1213
|
+
if (!this.binding) {
|
|
1214
|
+
throw new Error("Workers binding is not configured");
|
|
1215
|
+
}
|
|
1216
|
+
try {
|
|
1217
|
+
const statement = this.binding.prepare(sql);
|
|
1218
|
+
const formattedParams = this.formatSqlParams(params);
|
|
1219
|
+
let result;
|
|
1220
|
+
if (formattedParams.length > 0) {
|
|
1221
|
+
if (first) {
|
|
1222
|
+
result = await statement.bind(...formattedParams).first();
|
|
1223
|
+
if (!result) return null;
|
|
1224
|
+
return result;
|
|
1225
|
+
} else {
|
|
1226
|
+
result = await statement.bind(...formattedParams).all();
|
|
1227
|
+
const results = result.results || [];
|
|
1228
|
+
return results;
|
|
1229
|
+
}
|
|
1230
|
+
} else {
|
|
1231
|
+
if (first) {
|
|
1232
|
+
result = await statement.first();
|
|
1233
|
+
if (!result) return null;
|
|
1234
|
+
return result;
|
|
1235
|
+
} else {
|
|
1236
|
+
result = await statement.all();
|
|
1237
|
+
const results = result.results || [];
|
|
1238
|
+
return results;
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
} catch (error) {
|
|
1242
|
+
throw new MastraError(
|
|
1243
|
+
{
|
|
1244
|
+
id: "CLOUDFLARE_D1_STORE_OPERATIONS_WORKERS_BINDING_QUERY_FAILED",
|
|
1245
|
+
domain: ErrorDomain.STORAGE,
|
|
1246
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1247
|
+
details: { sql }
|
|
1248
|
+
},
|
|
1249
|
+
error
|
|
1250
|
+
);
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
async executeRestQuery({
|
|
1254
|
+
sql,
|
|
1255
|
+
params = [],
|
|
1256
|
+
first = false
|
|
1257
|
+
}) {
|
|
1258
|
+
if (!this.client) {
|
|
1259
|
+
throw new Error("D1 client is not configured");
|
|
1260
|
+
}
|
|
1261
|
+
try {
|
|
1262
|
+
const formattedParams = this.formatSqlParams(params);
|
|
1263
|
+
const response = await this.client.query({
|
|
1264
|
+
sql,
|
|
1265
|
+
params: formattedParams
|
|
1266
|
+
});
|
|
1267
|
+
const result = response.result || [];
|
|
1268
|
+
const results = result.flatMap((r) => r.results || []);
|
|
1269
|
+
if (first) {
|
|
1270
|
+
return results[0] || null;
|
|
1271
|
+
}
|
|
1272
|
+
return results;
|
|
1273
|
+
} catch (error) {
|
|
1274
|
+
throw new MastraError(
|
|
1275
|
+
{
|
|
1276
|
+
id: "CLOUDFLARE_D1_STORE_OPERATIONS_REST_QUERY_FAILED",
|
|
1277
|
+
domain: ErrorDomain.STORAGE,
|
|
1278
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1279
|
+
details: { sql }
|
|
1280
|
+
},
|
|
1281
|
+
error
|
|
1282
|
+
);
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
async executeQuery(options) {
|
|
1286
|
+
if (this.binding) {
|
|
1287
|
+
return this.executeWorkersBindingQuery(options);
|
|
1288
|
+
} else if (this.client) {
|
|
1289
|
+
return this.executeRestQuery(options);
|
|
1290
|
+
} else {
|
|
1291
|
+
throw new Error("Neither binding nor client is configured");
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
async getTableColumns(tableName) {
|
|
1295
|
+
try {
|
|
1296
|
+
const sql = `PRAGMA table_info(${tableName})`;
|
|
1297
|
+
const result = await this.executeQuery({ sql });
|
|
1298
|
+
if (!result || !Array.isArray(result)) {
|
|
1299
|
+
return [];
|
|
1300
|
+
}
|
|
1301
|
+
return result.map((row) => ({
|
|
1302
|
+
name: row.name,
|
|
1303
|
+
type: row.type
|
|
1304
|
+
}));
|
|
1305
|
+
} catch (error) {
|
|
1306
|
+
this.logger.warn(`Failed to get table columns for ${tableName}:`, error);
|
|
1307
|
+
return [];
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
serializeValue(value) {
|
|
1311
|
+
if (value === null || value === void 0) {
|
|
1312
|
+
return null;
|
|
1313
|
+
}
|
|
1314
|
+
if (value instanceof Date) {
|
|
1315
|
+
return value.toISOString();
|
|
1316
|
+
}
|
|
1317
|
+
if (typeof value === "object") {
|
|
1318
|
+
return JSON.stringify(value);
|
|
1319
|
+
}
|
|
1320
|
+
return value;
|
|
1321
|
+
}
|
|
1322
|
+
getSqlType(type) {
|
|
1323
|
+
switch (type) {
|
|
1324
|
+
case "bigint":
|
|
1325
|
+
return "INTEGER";
|
|
1326
|
+
// SQLite uses INTEGER for all integer sizes
|
|
1327
|
+
case "jsonb":
|
|
1328
|
+
return "TEXT";
|
|
1329
|
+
// Store JSON as TEXT in SQLite
|
|
1330
|
+
default:
|
|
1331
|
+
return super.getSqlType(type);
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
async createTable({
|
|
1335
|
+
tableName,
|
|
1336
|
+
schema
|
|
1337
|
+
}) {
|
|
1338
|
+
try {
|
|
1339
|
+
const fullTableName = this.getTableName(tableName);
|
|
1340
|
+
const columnDefinitions = Object.entries(schema).map(([colName, colDef]) => {
|
|
1341
|
+
const type = this.getSqlType(colDef.type);
|
|
1342
|
+
const nullable = colDef.nullable === false ? "NOT NULL" : "";
|
|
1343
|
+
const primaryKey = colDef.primaryKey ? "PRIMARY KEY" : "";
|
|
1344
|
+
return `${colName} ${type} ${nullable} ${primaryKey}`.trim();
|
|
1345
|
+
});
|
|
1346
|
+
const tableConstraints = [];
|
|
1347
|
+
if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
|
|
1348
|
+
tableConstraints.push("UNIQUE (workflow_name, run_id)");
|
|
1349
|
+
}
|
|
1350
|
+
const query = createSqlBuilder().createTable(fullTableName, columnDefinitions, tableConstraints);
|
|
1351
|
+
const { sql, params } = query.build();
|
|
1352
|
+
await this.executeQuery({ sql, params });
|
|
1353
|
+
this.logger.debug(`Created table ${fullTableName}`);
|
|
1354
|
+
} catch (error) {
|
|
1355
|
+
throw new MastraError(
|
|
1356
|
+
{
|
|
1357
|
+
id: "CLOUDFLARE_D1_STORE_OPERATIONS_CREATE_TABLE_FAILED",
|
|
1358
|
+
domain: ErrorDomain.STORAGE,
|
|
1359
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1360
|
+
details: { tableName }
|
|
1361
|
+
},
|
|
1362
|
+
error
|
|
1363
|
+
);
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
async clearTable({ tableName }) {
|
|
1367
|
+
try {
|
|
1368
|
+
const fullTableName = this.getTableName(tableName);
|
|
1369
|
+
const query = createSqlBuilder().delete(fullTableName);
|
|
1370
|
+
const { sql, params } = query.build();
|
|
1371
|
+
await this.executeQuery({ sql, params });
|
|
1372
|
+
this.logger.debug(`Cleared table ${fullTableName}`);
|
|
1373
|
+
} catch (error) {
|
|
1374
|
+
throw new MastraError(
|
|
1375
|
+
{
|
|
1376
|
+
id: "CLOUDFLARE_D1_STORE_OPERATIONS_CLEAR_TABLE_FAILED",
|
|
1377
|
+
domain: ErrorDomain.STORAGE,
|
|
1378
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1379
|
+
details: { tableName }
|
|
1380
|
+
},
|
|
1381
|
+
error
|
|
1382
|
+
);
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
async dropTable({ tableName }) {
|
|
1386
|
+
try {
|
|
1387
|
+
const fullTableName = this.getTableName(tableName);
|
|
1388
|
+
const sql = `DROP TABLE IF EXISTS ${fullTableName}`;
|
|
1389
|
+
await this.executeQuery({ sql });
|
|
1390
|
+
this.logger.debug(`Dropped table ${fullTableName}`);
|
|
1391
|
+
} catch (error) {
|
|
1392
|
+
throw new MastraError(
|
|
1393
|
+
{
|
|
1394
|
+
id: "CLOUDFLARE_D1_STORE_OPERATIONS_DROP_TABLE_FAILED",
|
|
1395
|
+
domain: ErrorDomain.STORAGE,
|
|
1396
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1397
|
+
details: { tableName }
|
|
1398
|
+
},
|
|
1399
|
+
error
|
|
1400
|
+
);
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
async alterTable(args) {
|
|
1404
|
+
try {
|
|
1405
|
+
const fullTableName = this.getTableName(args.tableName);
|
|
1406
|
+
const existingColumns = await this.getTableColumns(fullTableName);
|
|
1407
|
+
const existingColumnNames = new Set(existingColumns.map((col) => col.name));
|
|
1408
|
+
for (const [columnName, column] of Object.entries(args.schema)) {
|
|
1409
|
+
if (!existingColumnNames.has(columnName) && args.ifNotExists.includes(columnName)) {
|
|
1410
|
+
const sqlType = this.getSqlType(column.type);
|
|
1411
|
+
const defaultValue = this.getDefaultValue(column.type);
|
|
1412
|
+
const sql = `ALTER TABLE ${fullTableName} ADD COLUMN ${columnName} ${sqlType} ${defaultValue}`;
|
|
1413
|
+
await this.executeQuery({ sql });
|
|
1414
|
+
this.logger.debug(`Added column ${columnName} to table ${fullTableName}`);
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
} catch (error) {
|
|
1418
|
+
throw new MastraError(
|
|
1419
|
+
{
|
|
1420
|
+
id: "CLOUDFLARE_D1_STORE_OPERATIONS_ALTER_TABLE_FAILED",
|
|
1421
|
+
domain: ErrorDomain.STORAGE,
|
|
1422
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1423
|
+
details: { tableName: args.tableName }
|
|
1424
|
+
},
|
|
1425
|
+
error
|
|
1426
|
+
);
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
async insert({ tableName, record }) {
|
|
1430
|
+
try {
|
|
1431
|
+
const fullTableName = this.getTableName(tableName);
|
|
1432
|
+
const processedRecord = await this.processRecord(record);
|
|
1433
|
+
const columns = Object.keys(processedRecord);
|
|
1434
|
+
const values = Object.values(processedRecord);
|
|
1435
|
+
const query = createSqlBuilder().insert(fullTableName, columns, values);
|
|
1436
|
+
const { sql, params } = query.build();
|
|
1437
|
+
await this.executeQuery({ sql, params });
|
|
1438
|
+
} catch (error) {
|
|
1439
|
+
throw new MastraError(
|
|
1440
|
+
{
|
|
1441
|
+
id: "CLOUDFLARE_D1_STORE_OPERATIONS_INSERT_FAILED",
|
|
1442
|
+
domain: ErrorDomain.STORAGE,
|
|
1443
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1444
|
+
details: { tableName }
|
|
1445
|
+
},
|
|
1446
|
+
error
|
|
1447
|
+
);
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
async batchInsert({ tableName, records }) {
|
|
1451
|
+
try {
|
|
1452
|
+
if (records.length === 0) return;
|
|
1453
|
+
const fullTableName = this.getTableName(tableName);
|
|
1454
|
+
const processedRecords = await Promise.all(records.map((record) => this.processRecord(record)));
|
|
1455
|
+
const columns = Object.keys(processedRecords[0] || {});
|
|
1456
|
+
for (const record of processedRecords) {
|
|
1457
|
+
const values = Object.values(record);
|
|
1458
|
+
const query = createSqlBuilder().insert(fullTableName, columns, values);
|
|
1459
|
+
const { sql, params } = query.build();
|
|
1460
|
+
await this.executeQuery({ sql, params });
|
|
1461
|
+
}
|
|
1462
|
+
} catch (error) {
|
|
1463
|
+
throw new MastraError(
|
|
1464
|
+
{
|
|
1465
|
+
id: "CLOUDFLARE_D1_STORE_OPERATIONS_BATCH_INSERT_FAILED",
|
|
1466
|
+
domain: ErrorDomain.STORAGE,
|
|
1467
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1468
|
+
details: { tableName }
|
|
1469
|
+
},
|
|
1470
|
+
error
|
|
1471
|
+
);
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
async load({ tableName, keys }) {
|
|
1475
|
+
try {
|
|
1476
|
+
const fullTableName = this.getTableName(tableName);
|
|
1477
|
+
const query = createSqlBuilder().select("*").from(fullTableName);
|
|
1478
|
+
let firstKey = true;
|
|
1479
|
+
for (const [key, value] of Object.entries(keys)) {
|
|
1480
|
+
if (firstKey) {
|
|
1481
|
+
query.where(`${key} = ?`, value);
|
|
1482
|
+
firstKey = false;
|
|
1483
|
+
} else {
|
|
1484
|
+
query.andWhere(`${key} = ?`, value);
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
query.orderBy("createdAt", "DESC");
|
|
1488
|
+
query.limit(1);
|
|
1489
|
+
const { sql, params } = query.build();
|
|
1490
|
+
const result = await this.executeQuery({ sql, params, first: true });
|
|
1491
|
+
if (!result) {
|
|
1492
|
+
return null;
|
|
1493
|
+
}
|
|
1494
|
+
const deserializedResult = {};
|
|
1495
|
+
for (const [key, value] of Object.entries(result)) {
|
|
1496
|
+
deserializedResult[key] = deserializeValue(value);
|
|
1497
|
+
}
|
|
1498
|
+
return deserializedResult;
|
|
1499
|
+
} catch (error) {
|
|
1500
|
+
throw new MastraError(
|
|
1501
|
+
{
|
|
1502
|
+
id: "CLOUDFLARE_D1_STORE_OPERATIONS_LOAD_FAILED",
|
|
1503
|
+
domain: ErrorDomain.STORAGE,
|
|
1504
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1505
|
+
details: { tableName }
|
|
1506
|
+
},
|
|
1507
|
+
error
|
|
1508
|
+
);
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
async processRecord(record) {
|
|
1512
|
+
const processed = {};
|
|
1513
|
+
for (const [key, value] of Object.entries(record)) {
|
|
1514
|
+
processed[key] = this.serializeValue(value);
|
|
1515
|
+
}
|
|
1516
|
+
return processed;
|
|
1517
|
+
}
|
|
1518
|
+
/**
|
|
1519
|
+
* Upsert multiple records in a batch operation
|
|
1520
|
+
* @param tableName The table to insert into
|
|
1521
|
+
* @param records The records to insert
|
|
1522
|
+
*/
|
|
1523
|
+
async batchUpsert({ tableName, records }) {
|
|
1524
|
+
if (records.length === 0) return;
|
|
1525
|
+
const fullTableName = this.getTableName(tableName);
|
|
1526
|
+
try {
|
|
1527
|
+
const batchSize = 50;
|
|
1528
|
+
for (let i = 0; i < records.length; i += batchSize) {
|
|
1529
|
+
const batch = records.slice(i, i + batchSize);
|
|
1530
|
+
const recordsToInsert = batch;
|
|
1531
|
+
if (recordsToInsert.length > 0) {
|
|
1532
|
+
const firstRecord = recordsToInsert[0];
|
|
1533
|
+
const columns = Object.keys(firstRecord || {});
|
|
1534
|
+
for (const record of recordsToInsert) {
|
|
1535
|
+
const values = columns.map((col) => {
|
|
1536
|
+
if (!record) return null;
|
|
1537
|
+
const value = typeof col === "string" ? record[col] : null;
|
|
1538
|
+
return this.serializeValue(value);
|
|
1539
|
+
});
|
|
1540
|
+
const recordToUpsert = columns.reduce(
|
|
1541
|
+
(acc, col) => {
|
|
1542
|
+
if (col !== "createdAt") acc[col] = `excluded.${col}`;
|
|
1543
|
+
return acc;
|
|
1544
|
+
},
|
|
1545
|
+
{}
|
|
1546
|
+
);
|
|
1547
|
+
const query = createSqlBuilder().insert(fullTableName, columns, values, ["id"], recordToUpsert);
|
|
1548
|
+
const { sql, params } = query.build();
|
|
1549
|
+
await this.executeQuery({ sql, params });
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
this.logger.debug(
|
|
1553
|
+
`Processed batch ${Math.floor(i / batchSize) + 1} of ${Math.ceil(records.length / batchSize)}`
|
|
1554
|
+
);
|
|
1555
|
+
}
|
|
1556
|
+
this.logger.debug(`Successfully batch upserted ${records.length} records into ${tableName}`);
|
|
1557
|
+
} catch (error) {
|
|
1558
|
+
throw new MastraError(
|
|
1559
|
+
{
|
|
1560
|
+
id: "CLOUDFLARE_D1_STORAGE_BATCH_UPSERT_ERROR",
|
|
1561
|
+
domain: ErrorDomain.STORAGE,
|
|
1562
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1563
|
+
text: `Failed to batch upsert into ${tableName}: ${error instanceof Error ? error.message : String(error)}`,
|
|
1564
|
+
details: { tableName }
|
|
1565
|
+
},
|
|
1566
|
+
error
|
|
1567
|
+
);
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
};
|
|
1571
|
+
function transformScoreRow(row) {
|
|
1572
|
+
const deserialized = { ...row };
|
|
1573
|
+
deserialized.input = safelyParseJSON(row.input);
|
|
1574
|
+
deserialized.output = safelyParseJSON(row.output);
|
|
1575
|
+
deserialized.scorer = safelyParseJSON(row.scorer);
|
|
1576
|
+
deserialized.preprocessStepResult = safelyParseJSON(row.preprocessStepResult);
|
|
1577
|
+
deserialized.analyzeStepResult = safelyParseJSON(row.analyzeStepResult);
|
|
1578
|
+
deserialized.metadata = safelyParseJSON(row.metadata);
|
|
1579
|
+
deserialized.additionalContext = safelyParseJSON(row.additionalContext);
|
|
1580
|
+
deserialized.requestContext = safelyParseJSON(row.requestContext);
|
|
1581
|
+
deserialized.entity = safelyParseJSON(row.entity);
|
|
1582
|
+
deserialized.createdAt = row.createdAtZ || row.createdAt;
|
|
1583
|
+
deserialized.updatedAt = row.updatedAtZ || row.updatedAt;
|
|
1584
|
+
return deserialized;
|
|
1585
|
+
}
|
|
1586
|
+
var ScoresStorageD1 = class extends ScoresStorage {
|
|
1587
|
+
operations;
|
|
1588
|
+
constructor({ operations }) {
|
|
1589
|
+
super();
|
|
1590
|
+
this.operations = operations;
|
|
1591
|
+
}
|
|
1592
|
+
async getScoreById({ id }) {
|
|
1593
|
+
try {
|
|
1594
|
+
const fullTableName = this.operations.getTableName(TABLE_SCORERS);
|
|
1595
|
+
const query = createSqlBuilder().select("*").from(fullTableName).where("id = ?", id);
|
|
1596
|
+
const { sql, params } = query.build();
|
|
1597
|
+
const result = await this.operations.executeQuery({ sql, params, first: true });
|
|
1598
|
+
if (!result) {
|
|
1599
|
+
return null;
|
|
1600
|
+
}
|
|
1601
|
+
return transformScoreRow(result);
|
|
1602
|
+
} catch (error) {
|
|
1603
|
+
throw new MastraError(
|
|
1604
|
+
{
|
|
1605
|
+
id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORE_BY_ID_FAILED",
|
|
1606
|
+
domain: ErrorDomain.STORAGE,
|
|
1607
|
+
category: ErrorCategory.THIRD_PARTY
|
|
1608
|
+
},
|
|
1609
|
+
error
|
|
1610
|
+
);
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
async saveScore(score) {
|
|
1614
|
+
let parsedScore;
|
|
1615
|
+
try {
|
|
1616
|
+
parsedScore = saveScorePayloadSchema.parse(score);
|
|
1617
|
+
} catch (error) {
|
|
1618
|
+
throw new MastraError(
|
|
1619
|
+
{
|
|
1620
|
+
id: "CLOUDFLARE_D1_STORE_SCORES_SAVE_SCORE_FAILED_INVALID_SCORE_PAYLOAD",
|
|
1621
|
+
domain: ErrorDomain.STORAGE,
|
|
1622
|
+
category: ErrorCategory.USER,
|
|
1623
|
+
details: { scoreId: score.id }
|
|
1624
|
+
},
|
|
1625
|
+
error
|
|
1626
|
+
);
|
|
1627
|
+
}
|
|
1628
|
+
try {
|
|
1629
|
+
const id = crypto.randomUUID();
|
|
1630
|
+
const fullTableName = this.operations.getTableName(TABLE_SCORERS);
|
|
1631
|
+
const serializedRecord = {};
|
|
1632
|
+
for (const [key, value] of Object.entries(parsedScore)) {
|
|
1633
|
+
if (value !== null && value !== void 0) {
|
|
1634
|
+
if (typeof value === "object") {
|
|
1635
|
+
serializedRecord[key] = JSON.stringify(value);
|
|
1636
|
+
} else {
|
|
1637
|
+
serializedRecord[key] = value;
|
|
1638
|
+
}
|
|
1639
|
+
} else {
|
|
1640
|
+
serializedRecord[key] = null;
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
serializedRecord.id = id;
|
|
1644
|
+
serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1645
|
+
serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1646
|
+
const columns = Object.keys(serializedRecord);
|
|
1647
|
+
const values = Object.values(serializedRecord);
|
|
1648
|
+
const query = createSqlBuilder().insert(fullTableName, columns, values);
|
|
1649
|
+
const { sql, params } = query.build();
|
|
1650
|
+
await this.operations.executeQuery({ sql, params });
|
|
1651
|
+
const scoreFromDb = await this.getScoreById({ id });
|
|
1652
|
+
return { score: scoreFromDb };
|
|
1653
|
+
} catch (error) {
|
|
1654
|
+
throw new MastraError(
|
|
1655
|
+
{
|
|
1656
|
+
id: "CLOUDFLARE_D1_STORE_SCORES_SAVE_SCORE_FAILED",
|
|
1657
|
+
domain: ErrorDomain.STORAGE,
|
|
1658
|
+
category: ErrorCategory.THIRD_PARTY
|
|
1659
|
+
},
|
|
1660
|
+
error
|
|
1661
|
+
);
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
async getScoresByScorerId({
|
|
1665
|
+
scorerId,
|
|
1666
|
+
entityId,
|
|
1667
|
+
entityType,
|
|
1668
|
+
source,
|
|
1669
|
+
pagination
|
|
1670
|
+
}) {
|
|
1671
|
+
try {
|
|
1672
|
+
const fullTableName = this.operations.getTableName(TABLE_SCORERS);
|
|
1673
|
+
const countQuery = createSqlBuilder().count().from(fullTableName).where("scorerId = ?", scorerId);
|
|
1674
|
+
if (entityId) {
|
|
1675
|
+
countQuery.andWhere("entityId = ?", entityId);
|
|
1676
|
+
}
|
|
1677
|
+
if (entityType) {
|
|
1678
|
+
countQuery.andWhere("entityType = ?", entityType);
|
|
1679
|
+
}
|
|
1680
|
+
if (source) {
|
|
1681
|
+
countQuery.andWhere("source = ?", source);
|
|
1682
|
+
}
|
|
1683
|
+
const countResult = await this.operations.executeQuery(countQuery.build());
|
|
1684
|
+
const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
|
|
1685
|
+
if (total === 0) {
|
|
1686
|
+
return {
|
|
1687
|
+
pagination: {
|
|
1688
|
+
total: 0,
|
|
1689
|
+
page: pagination.page,
|
|
1690
|
+
perPage: pagination.perPage,
|
|
1691
|
+
hasMore: false
|
|
1692
|
+
},
|
|
1693
|
+
scores: []
|
|
1694
|
+
};
|
|
1695
|
+
}
|
|
1696
|
+
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId);
|
|
1697
|
+
if (entityId) {
|
|
1698
|
+
selectQuery.andWhere("entityId = ?", entityId);
|
|
1699
|
+
}
|
|
1700
|
+
if (entityType) {
|
|
1701
|
+
selectQuery.andWhere("entityType = ?", entityType);
|
|
1702
|
+
}
|
|
1703
|
+
if (source) {
|
|
1704
|
+
selectQuery.andWhere("source = ?", source);
|
|
1705
|
+
}
|
|
1706
|
+
selectQuery.limit(pagination.perPage).offset(pagination.page * pagination.perPage);
|
|
1707
|
+
const { sql, params } = selectQuery.build();
|
|
1708
|
+
const results = await this.operations.executeQuery({ sql, params });
|
|
1709
|
+
const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
|
|
1710
|
+
return {
|
|
1711
|
+
pagination: {
|
|
1712
|
+
total,
|
|
1713
|
+
page: pagination.page,
|
|
1714
|
+
perPage: pagination.perPage,
|
|
1715
|
+
hasMore: total > (pagination.page + 1) * pagination.perPage
|
|
1716
|
+
},
|
|
1717
|
+
scores
|
|
1718
|
+
};
|
|
1719
|
+
} catch (error) {
|
|
1720
|
+
throw new MastraError(
|
|
1721
|
+
{
|
|
1722
|
+
id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_SCORER_ID_FAILED",
|
|
1723
|
+
domain: ErrorDomain.STORAGE,
|
|
1724
|
+
category: ErrorCategory.THIRD_PARTY
|
|
1725
|
+
},
|
|
1726
|
+
error
|
|
1727
|
+
);
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
async getScoresByRunId({
|
|
1731
|
+
runId,
|
|
1732
|
+
pagination
|
|
1733
|
+
}) {
|
|
1734
|
+
try {
|
|
1735
|
+
const fullTableName = this.operations.getTableName(TABLE_SCORERS);
|
|
1736
|
+
const countQuery = createSqlBuilder().count().from(fullTableName).where("runId = ?", runId);
|
|
1737
|
+
const countResult = await this.operations.executeQuery(countQuery.build());
|
|
1738
|
+
const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
|
|
1739
|
+
if (total === 0) {
|
|
1740
|
+
return {
|
|
1741
|
+
pagination: {
|
|
1742
|
+
total: 0,
|
|
1743
|
+
page: pagination.page,
|
|
1744
|
+
perPage: pagination.perPage,
|
|
1745
|
+
hasMore: false
|
|
1746
|
+
},
|
|
1747
|
+
scores: []
|
|
1748
|
+
};
|
|
1749
|
+
}
|
|
1750
|
+
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("runId = ?", runId).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
|
|
1751
|
+
const { sql, params } = selectQuery.build();
|
|
1752
|
+
const results = await this.operations.executeQuery({ sql, params });
|
|
1753
|
+
const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
|
|
1754
|
+
return {
|
|
1755
|
+
pagination: {
|
|
1756
|
+
total,
|
|
1757
|
+
page: pagination.page,
|
|
1758
|
+
perPage: pagination.perPage,
|
|
1759
|
+
hasMore: total > (pagination.page + 1) * pagination.perPage
|
|
1760
|
+
},
|
|
1761
|
+
scores
|
|
1762
|
+
};
|
|
1763
|
+
} catch (error) {
|
|
1764
|
+
throw new MastraError(
|
|
1765
|
+
{
|
|
1766
|
+
id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_RUN_ID_FAILED",
|
|
1767
|
+
domain: ErrorDomain.STORAGE,
|
|
1768
|
+
category: ErrorCategory.THIRD_PARTY
|
|
1769
|
+
},
|
|
1770
|
+
error
|
|
1771
|
+
);
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
async getScoresByEntityId({
|
|
1775
|
+
entityId,
|
|
1776
|
+
entityType,
|
|
1777
|
+
pagination
|
|
1778
|
+
}) {
|
|
1779
|
+
try {
|
|
1780
|
+
const fullTableName = this.operations.getTableName(TABLE_SCORERS);
|
|
1781
|
+
const countQuery = createSqlBuilder().count().from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType);
|
|
1782
|
+
const countResult = await this.operations.executeQuery(countQuery.build());
|
|
1783
|
+
const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
|
|
1784
|
+
if (total === 0) {
|
|
1785
|
+
return {
|
|
1786
|
+
pagination: {
|
|
1787
|
+
total: 0,
|
|
1788
|
+
page: pagination.page,
|
|
1789
|
+
perPage: pagination.perPage,
|
|
1790
|
+
hasMore: false
|
|
1791
|
+
},
|
|
1792
|
+
scores: []
|
|
1793
|
+
};
|
|
1794
|
+
}
|
|
1795
|
+
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
|
|
1796
|
+
const { sql, params } = selectQuery.build();
|
|
1797
|
+
const results = await this.operations.executeQuery({ sql, params });
|
|
1798
|
+
const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
|
|
1799
|
+
return {
|
|
1800
|
+
pagination: {
|
|
1801
|
+
total,
|
|
1802
|
+
page: pagination.page,
|
|
1803
|
+
perPage: pagination.perPage,
|
|
1804
|
+
hasMore: total > (pagination.page + 1) * pagination.perPage
|
|
1805
|
+
},
|
|
1806
|
+
scores
|
|
1807
|
+
};
|
|
1808
|
+
} catch (error) {
|
|
1809
|
+
throw new MastraError(
|
|
1810
|
+
{
|
|
1811
|
+
id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_ENTITY_ID_FAILED",
|
|
1812
|
+
domain: ErrorDomain.STORAGE,
|
|
1813
|
+
category: ErrorCategory.THIRD_PARTY
|
|
1814
|
+
},
|
|
1815
|
+
error
|
|
1816
|
+
);
|
|
1817
|
+
}
|
|
1818
|
+
}
|
|
1819
|
+
async getScoresBySpan({
|
|
1820
|
+
traceId,
|
|
1821
|
+
spanId,
|
|
1822
|
+
pagination
|
|
1823
|
+
}) {
|
|
1824
|
+
try {
|
|
1825
|
+
const fullTableName = this.operations.getTableName(TABLE_SCORERS);
|
|
1826
|
+
const countQuery = createSqlBuilder().count().from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId);
|
|
1827
|
+
const countResult = await this.operations.executeQuery(countQuery.build());
|
|
1828
|
+
const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
|
|
1829
|
+
if (total === 0) {
|
|
1830
|
+
return {
|
|
1831
|
+
pagination: {
|
|
1832
|
+
total: 0,
|
|
1833
|
+
page: pagination.page,
|
|
1834
|
+
perPage: pagination.perPage,
|
|
1835
|
+
hasMore: false
|
|
1836
|
+
},
|
|
1837
|
+
scores: []
|
|
1838
|
+
};
|
|
1839
|
+
}
|
|
1840
|
+
const limit = pagination.perPage + 1;
|
|
1841
|
+
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId).orderBy("createdAt", "DESC").limit(limit).offset(pagination.page * pagination.perPage);
|
|
1842
|
+
const { sql, params } = selectQuery.build();
|
|
1843
|
+
const results = await this.operations.executeQuery({ sql, params });
|
|
1844
|
+
const rows = Array.isArray(results) ? results : [];
|
|
1845
|
+
const scores = rows.slice(0, pagination.perPage).map(transformScoreRow);
|
|
1846
|
+
return {
|
|
1847
|
+
pagination: {
|
|
1848
|
+
total,
|
|
1849
|
+
page: pagination.page,
|
|
1850
|
+
perPage: pagination.perPage,
|
|
1851
|
+
hasMore: rows.length > pagination.perPage
|
|
1852
|
+
},
|
|
1853
|
+
scores
|
|
1854
|
+
};
|
|
1855
|
+
} catch (error) {
|
|
1856
|
+
throw new MastraError(
|
|
1857
|
+
{
|
|
1858
|
+
id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_SPAN_FAILED",
|
|
1859
|
+
domain: ErrorDomain.STORAGE,
|
|
1860
|
+
category: ErrorCategory.THIRD_PARTY
|
|
1861
|
+
},
|
|
1862
|
+
error
|
|
1863
|
+
);
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
};
|
|
1867
|
+
var WorkflowsStorageD1 = class extends WorkflowsStorage {
|
|
1868
|
+
operations;
|
|
1869
|
+
constructor({ operations }) {
|
|
1870
|
+
super();
|
|
1871
|
+
this.operations = operations;
|
|
1872
|
+
}
|
|
1873
|
+
updateWorkflowResults({
|
|
1874
|
+
// workflowName,
|
|
1875
|
+
// runId,
|
|
1876
|
+
// stepId,
|
|
1877
|
+
// result,
|
|
1878
|
+
// requestContext,
|
|
1879
|
+
}) {
|
|
1880
|
+
throw new Error("Method not implemented.");
|
|
1881
|
+
}
|
|
1882
|
+
updateWorkflowState({
|
|
1883
|
+
// workflowName,
|
|
1884
|
+
// runId,
|
|
1885
|
+
// opts,
|
|
1886
|
+
}) {
|
|
1887
|
+
throw new Error("Method not implemented.");
|
|
1888
|
+
}
|
|
1889
|
+
async persistWorkflowSnapshot({
|
|
1890
|
+
workflowName,
|
|
764
1891
|
runId,
|
|
1892
|
+
resourceId,
|
|
765
1893
|
snapshot
|
|
766
1894
|
}) {
|
|
767
|
-
const fullTableName = this.getTableName(TABLE_WORKFLOW_SNAPSHOT);
|
|
1895
|
+
const fullTableName = this.operations.getTableName(TABLE_WORKFLOW_SNAPSHOT);
|
|
768
1896
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
769
|
-
const currentSnapshot = await this.load({
|
|
1897
|
+
const currentSnapshot = await this.operations.load({
|
|
770
1898
|
tableName: TABLE_WORKFLOW_SNAPSHOT,
|
|
771
1899
|
keys: { workflow_name: workflowName, run_id: runId }
|
|
772
1900
|
});
|
|
773
1901
|
const persisting = currentSnapshot ? {
|
|
774
1902
|
...currentSnapshot,
|
|
1903
|
+
resourceId,
|
|
775
1904
|
snapshot: JSON.stringify(snapshot),
|
|
776
1905
|
updatedAt: now
|
|
777
1906
|
} : {
|
|
778
1907
|
workflow_name: workflowName,
|
|
779
1908
|
run_id: runId,
|
|
1909
|
+
resourceId,
|
|
780
1910
|
snapshot,
|
|
781
1911
|
createdAt: now,
|
|
782
1912
|
updatedAt: now
|
|
783
1913
|
};
|
|
784
|
-
const processedRecord = await this.processRecord(persisting);
|
|
1914
|
+
const processedRecord = await this.operations.processRecord(persisting);
|
|
785
1915
|
const columns = Object.keys(processedRecord);
|
|
786
1916
|
const values = Object.values(processedRecord);
|
|
787
1917
|
const updateMap = {
|
|
@@ -792,139 +1922,433 @@ var D1Store = class extends MastraStorage {
|
|
|
792
1922
|
const query = createSqlBuilder().insert(fullTableName, columns, values, ["workflow_name", "run_id"], updateMap);
|
|
793
1923
|
const { sql, params } = query.build();
|
|
794
1924
|
try {
|
|
795
|
-
await this.executeQuery({ sql, params });
|
|
1925
|
+
await this.operations.executeQuery({ sql, params });
|
|
796
1926
|
} catch (error) {
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
1927
|
+
throw new MastraError(
|
|
1928
|
+
{
|
|
1929
|
+
id: "CLOUDFLARE_D1_STORAGE_PERSIST_WORKFLOW_SNAPSHOT_ERROR",
|
|
1930
|
+
domain: ErrorDomain.STORAGE,
|
|
1931
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1932
|
+
text: `Failed to persist workflow snapshot: ${error instanceof Error ? error.message : String(error)}`,
|
|
1933
|
+
details: { workflowName, runId }
|
|
1934
|
+
},
|
|
1935
|
+
error
|
|
1936
|
+
);
|
|
801
1937
|
}
|
|
802
1938
|
}
|
|
803
1939
|
async loadWorkflowSnapshot(params) {
|
|
804
1940
|
const { workflowName, runId } = params;
|
|
805
1941
|
this.logger.debug("Loading workflow snapshot", { workflowName, runId });
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
1942
|
+
try {
|
|
1943
|
+
const d = await this.operations.load({
|
|
1944
|
+
tableName: TABLE_WORKFLOW_SNAPSHOT,
|
|
1945
|
+
keys: {
|
|
1946
|
+
workflow_name: workflowName,
|
|
1947
|
+
run_id: runId
|
|
1948
|
+
}
|
|
1949
|
+
});
|
|
1950
|
+
return d ? d.snapshot : null;
|
|
1951
|
+
} catch (error) {
|
|
1952
|
+
throw new MastraError(
|
|
1953
|
+
{
|
|
1954
|
+
id: "CLOUDFLARE_D1_STORAGE_LOAD_WORKFLOW_SNAPSHOT_ERROR",
|
|
1955
|
+
domain: ErrorDomain.STORAGE,
|
|
1956
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1957
|
+
text: `Failed to load workflow snapshot: ${error instanceof Error ? error.message : String(error)}`,
|
|
1958
|
+
details: { workflowName, runId }
|
|
1959
|
+
},
|
|
1960
|
+
error
|
|
1961
|
+
);
|
|
1962
|
+
}
|
|
1963
|
+
}
|
|
1964
|
+
parseWorkflowRun(row) {
|
|
1965
|
+
let parsedSnapshot = row.snapshot;
|
|
1966
|
+
if (typeof parsedSnapshot === "string") {
|
|
1967
|
+
try {
|
|
1968
|
+
parsedSnapshot = JSON.parse(row.snapshot);
|
|
1969
|
+
} catch (e) {
|
|
1970
|
+
console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
|
|
811
1971
|
}
|
|
812
|
-
}
|
|
813
|
-
return
|
|
1972
|
+
}
|
|
1973
|
+
return {
|
|
1974
|
+
workflowName: row.workflow_name,
|
|
1975
|
+
runId: row.run_id,
|
|
1976
|
+
snapshot: parsedSnapshot,
|
|
1977
|
+
createdAt: ensureDate(row.createdAt),
|
|
1978
|
+
updatedAt: ensureDate(row.updatedAt),
|
|
1979
|
+
resourceId: row.resourceId
|
|
1980
|
+
};
|
|
814
1981
|
}
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
1982
|
+
async listWorkflowRuns({
|
|
1983
|
+
workflowName,
|
|
1984
|
+
fromDate,
|
|
1985
|
+
toDate,
|
|
1986
|
+
limit,
|
|
1987
|
+
offset,
|
|
1988
|
+
resourceId
|
|
1989
|
+
} = {}) {
|
|
1990
|
+
const fullTableName = this.operations.getTableName(TABLE_WORKFLOW_SNAPSHOT);
|
|
823
1991
|
try {
|
|
824
|
-
const
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
const value = typeof col === "string" ? record[col] : null;
|
|
835
|
-
return this.serializeValue(value);
|
|
836
|
-
});
|
|
837
|
-
const query = createSqlBuilder().insert(fullTableName, columns, values);
|
|
838
|
-
const { sql, params } = query.build();
|
|
839
|
-
await this.executeQuery({ sql, params });
|
|
840
|
-
}
|
|
1992
|
+
const builder = createSqlBuilder().select().from(fullTableName);
|
|
1993
|
+
const countBuilder = createSqlBuilder().count().from(fullTableName);
|
|
1994
|
+
if (workflowName) builder.whereAnd("workflow_name = ?", workflowName);
|
|
1995
|
+
if (resourceId) {
|
|
1996
|
+
const hasResourceId = await this.operations.hasColumn(fullTableName, "resourceId");
|
|
1997
|
+
if (hasResourceId) {
|
|
1998
|
+
builder.whereAnd("resourceId = ?", resourceId);
|
|
1999
|
+
countBuilder.whereAnd("resourceId = ?", resourceId);
|
|
2000
|
+
} else {
|
|
2001
|
+
console.warn(`[${fullTableName}] resourceId column not found. Skipping resourceId filter.`);
|
|
841
2002
|
}
|
|
842
|
-
this.logger.debug(
|
|
843
|
-
`Processed batch ${Math.floor(i / batchSize) + 1} of ${Math.ceil(records.length / batchSize)}`
|
|
844
|
-
);
|
|
845
2003
|
}
|
|
846
|
-
|
|
2004
|
+
if (fromDate) {
|
|
2005
|
+
builder.whereAnd("createdAt >= ?", fromDate instanceof Date ? fromDate.toISOString() : fromDate);
|
|
2006
|
+
countBuilder.whereAnd("createdAt >= ?", fromDate instanceof Date ? fromDate.toISOString() : fromDate);
|
|
2007
|
+
}
|
|
2008
|
+
if (toDate) {
|
|
2009
|
+
builder.whereAnd("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
|
|
2010
|
+
countBuilder.whereAnd("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
|
|
2011
|
+
}
|
|
2012
|
+
builder.orderBy("createdAt", "DESC");
|
|
2013
|
+
if (typeof limit === "number") builder.limit(limit);
|
|
2014
|
+
if (typeof offset === "number") builder.offset(offset);
|
|
2015
|
+
const { sql, params } = builder.build();
|
|
2016
|
+
let total = 0;
|
|
2017
|
+
if (limit !== void 0 && offset !== void 0) {
|
|
2018
|
+
const { sql: countSql, params: countParams } = countBuilder.build();
|
|
2019
|
+
const countResult = await this.operations.executeQuery({
|
|
2020
|
+
sql: countSql,
|
|
2021
|
+
params: countParams,
|
|
2022
|
+
first: true
|
|
2023
|
+
});
|
|
2024
|
+
total = Number(countResult?.count ?? 0);
|
|
2025
|
+
}
|
|
2026
|
+
const results = await this.operations.executeQuery({ sql, params });
|
|
2027
|
+
const runs = (isArrayOfRecords(results) ? results : []).map((row) => this.parseWorkflowRun(row));
|
|
2028
|
+
return { runs, total: total || runs.length };
|
|
847
2029
|
} catch (error) {
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
2030
|
+
throw new MastraError(
|
|
2031
|
+
{
|
|
2032
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_WORKFLOW_RUNS_ERROR",
|
|
2033
|
+
domain: ErrorDomain.STORAGE,
|
|
2034
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
2035
|
+
text: `Failed to retrieve workflow runs: ${error instanceof Error ? error.message : String(error)}`,
|
|
2036
|
+
details: {
|
|
2037
|
+
workflowName: workflowName ?? "",
|
|
2038
|
+
resourceId: resourceId ?? ""
|
|
2039
|
+
}
|
|
2040
|
+
},
|
|
2041
|
+
error
|
|
2042
|
+
);
|
|
852
2043
|
}
|
|
853
2044
|
}
|
|
854
|
-
async
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
page,
|
|
858
|
-
perPage,
|
|
859
|
-
attributes
|
|
2045
|
+
async getWorkflowRunById({
|
|
2046
|
+
runId,
|
|
2047
|
+
workflowName
|
|
860
2048
|
}) {
|
|
861
|
-
const fullTableName = this.getTableName(
|
|
2049
|
+
const fullTableName = this.operations.getTableName(TABLE_WORKFLOW_SNAPSHOT);
|
|
862
2050
|
try {
|
|
863
|
-
const
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
query.andWhere("scope = ?", scope);
|
|
2051
|
+
const conditions = [];
|
|
2052
|
+
const params = [];
|
|
2053
|
+
if (runId) {
|
|
2054
|
+
conditions.push("run_id = ?");
|
|
2055
|
+
params.push(runId);
|
|
869
2056
|
}
|
|
870
|
-
if (
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
}
|
|
2057
|
+
if (workflowName) {
|
|
2058
|
+
conditions.push("workflow_name = ?");
|
|
2059
|
+
params.push(workflowName);
|
|
874
2060
|
}
|
|
875
|
-
|
|
876
|
-
const
|
|
877
|
-
const
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
2061
|
+
const whereClause = conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";
|
|
2062
|
+
const sql = `SELECT * FROM ${fullTableName} ${whereClause} ORDER BY createdAt DESC LIMIT 1`;
|
|
2063
|
+
const result = await this.operations.executeQuery({ sql, params, first: true });
|
|
2064
|
+
if (!result) return null;
|
|
2065
|
+
return this.parseWorkflowRun(result);
|
|
2066
|
+
} catch (error) {
|
|
2067
|
+
throw new MastraError(
|
|
2068
|
+
{
|
|
2069
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_WORKFLOW_RUN_BY_ID_ERROR",
|
|
2070
|
+
domain: ErrorDomain.STORAGE,
|
|
2071
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
2072
|
+
text: `Failed to retrieve workflow run by ID: ${error instanceof Error ? error.message : String(error)}`,
|
|
2073
|
+
details: { runId, workflowName: workflowName ?? "" }
|
|
2074
|
+
},
|
|
2075
|
+
error
|
|
2076
|
+
);
|
|
889
2077
|
}
|
|
890
2078
|
}
|
|
891
|
-
|
|
892
|
-
|
|
2079
|
+
};
|
|
2080
|
+
|
|
2081
|
+
// src/storage/index.ts
|
|
2082
|
+
var D1Store = class extends MastraStorage {
|
|
2083
|
+
client;
|
|
2084
|
+
binding;
|
|
2085
|
+
// D1Database binding
|
|
2086
|
+
tablePrefix;
|
|
2087
|
+
stores;
|
|
2088
|
+
/**
|
|
2089
|
+
* Creates a new D1Store instance
|
|
2090
|
+
* @param config Configuration for D1 access (either REST API or Workers Binding API)
|
|
2091
|
+
*/
|
|
2092
|
+
constructor(config) {
|
|
893
2093
|
try {
|
|
894
|
-
|
|
895
|
-
if (
|
|
896
|
-
|
|
897
|
-
} else if (type === "live") {
|
|
898
|
-
query = query.andWhere("(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)");
|
|
2094
|
+
super({ name: "D1" });
|
|
2095
|
+
if (config.tablePrefix && !/^[a-zA-Z0-9_]*$/.test(config.tablePrefix)) {
|
|
2096
|
+
throw new Error("Invalid tablePrefix: only letters, numbers, and underscores are allowed.");
|
|
899
2097
|
}
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
2098
|
+
this.tablePrefix = config.tablePrefix || "";
|
|
2099
|
+
if ("binding" in config) {
|
|
2100
|
+
if (!config.binding) {
|
|
2101
|
+
throw new Error("D1 binding is required when using Workers Binding API");
|
|
2102
|
+
}
|
|
2103
|
+
this.binding = config.binding;
|
|
2104
|
+
this.logger.info("Using D1 Workers Binding API");
|
|
2105
|
+
} else if ("client" in config) {
|
|
2106
|
+
if (!config.client) {
|
|
2107
|
+
throw new Error("D1 client is required when using D1ClientConfig");
|
|
2108
|
+
}
|
|
2109
|
+
this.client = config.client;
|
|
2110
|
+
this.logger.info("Using D1 Client");
|
|
2111
|
+
} else {
|
|
2112
|
+
if (!config.accountId || !config.databaseId || !config.apiToken) {
|
|
2113
|
+
throw new Error("accountId, databaseId, and apiToken are required when using REST API");
|
|
2114
|
+
}
|
|
2115
|
+
const cfClient = new Cloudflare({
|
|
2116
|
+
apiToken: config.apiToken
|
|
2117
|
+
});
|
|
2118
|
+
this.client = {
|
|
2119
|
+
query: ({ sql, params }) => {
|
|
2120
|
+
return cfClient.d1.database.query(config.databaseId, {
|
|
2121
|
+
account_id: config.accountId,
|
|
2122
|
+
sql,
|
|
2123
|
+
params
|
|
2124
|
+
});
|
|
2125
|
+
}
|
|
917
2126
|
};
|
|
918
|
-
|
|
2127
|
+
this.logger.info("Using D1 REST API");
|
|
2128
|
+
}
|
|
919
2129
|
} catch (error) {
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
2130
|
+
throw new MastraError(
|
|
2131
|
+
{
|
|
2132
|
+
id: "CLOUDFLARE_D1_STORAGE_INITIALIZATION_ERROR",
|
|
2133
|
+
domain: ErrorDomain.STORAGE,
|
|
2134
|
+
category: ErrorCategory.SYSTEM,
|
|
2135
|
+
text: "Error initializing D1Store"
|
|
2136
|
+
},
|
|
2137
|
+
error
|
|
2138
|
+
);
|
|
924
2139
|
}
|
|
2140
|
+
const operations = new StoreOperationsD1({
|
|
2141
|
+
client: this.client,
|
|
2142
|
+
binding: this.binding,
|
|
2143
|
+
tablePrefix: this.tablePrefix
|
|
2144
|
+
});
|
|
2145
|
+
const scores = new ScoresStorageD1({
|
|
2146
|
+
operations
|
|
2147
|
+
});
|
|
2148
|
+
const workflows = new WorkflowsStorageD1({
|
|
2149
|
+
operations
|
|
2150
|
+
});
|
|
2151
|
+
const memory = new MemoryStorageD1({
|
|
2152
|
+
operations
|
|
2153
|
+
});
|
|
2154
|
+
this.stores = {
|
|
2155
|
+
operations,
|
|
2156
|
+
scores,
|
|
2157
|
+
workflows,
|
|
2158
|
+
memory
|
|
2159
|
+
};
|
|
925
2160
|
}
|
|
926
|
-
|
|
927
|
-
|
|
2161
|
+
get supports() {
|
|
2162
|
+
return {
|
|
2163
|
+
selectByIncludeResourceScope: true,
|
|
2164
|
+
resourceWorkingMemory: true,
|
|
2165
|
+
hasColumn: true,
|
|
2166
|
+
createTable: true,
|
|
2167
|
+
deleteMessages: false,
|
|
2168
|
+
getScoresBySpan: true
|
|
2169
|
+
};
|
|
2170
|
+
}
|
|
2171
|
+
async createTable({
|
|
2172
|
+
tableName,
|
|
2173
|
+
schema
|
|
2174
|
+
}) {
|
|
2175
|
+
return this.stores.operations.createTable({ tableName, schema });
|
|
2176
|
+
}
|
|
2177
|
+
/**
|
|
2178
|
+
* Alters table schema to add columns if they don't exist
|
|
2179
|
+
* @param tableName Name of the table
|
|
2180
|
+
* @param schema Schema of the table
|
|
2181
|
+
* @param ifNotExists Array of column names to add if they don't exist
|
|
2182
|
+
*/
|
|
2183
|
+
async alterTable({
|
|
2184
|
+
tableName,
|
|
2185
|
+
schema,
|
|
2186
|
+
ifNotExists
|
|
2187
|
+
}) {
|
|
2188
|
+
return this.stores.operations.alterTable({ tableName, schema, ifNotExists });
|
|
2189
|
+
}
|
|
2190
|
+
async clearTable({ tableName }) {
|
|
2191
|
+
return this.stores.operations.clearTable({ tableName });
|
|
2192
|
+
}
|
|
2193
|
+
async dropTable({ tableName }) {
|
|
2194
|
+
return this.stores.operations.dropTable({ tableName });
|
|
2195
|
+
}
|
|
2196
|
+
async hasColumn(table, column) {
|
|
2197
|
+
return this.stores.operations.hasColumn(table, column);
|
|
2198
|
+
}
|
|
2199
|
+
async insert({ tableName, record }) {
|
|
2200
|
+
return this.stores.operations.insert({ tableName, record });
|
|
2201
|
+
}
|
|
2202
|
+
async load({ tableName, keys }) {
|
|
2203
|
+
return this.stores.operations.load({ tableName, keys });
|
|
2204
|
+
}
|
|
2205
|
+
async getThreadById({ threadId }) {
|
|
2206
|
+
return this.stores.memory.getThreadById({ threadId });
|
|
2207
|
+
}
|
|
2208
|
+
/**
|
|
2209
|
+
* @deprecated use getThreadsByResourceIdPaginated instead
|
|
2210
|
+
*/
|
|
2211
|
+
async getThreadsByResourceId({ resourceId }) {
|
|
2212
|
+
return this.stores.memory.getThreadsByResourceId({ resourceId });
|
|
2213
|
+
}
|
|
2214
|
+
async getThreadsByResourceIdPaginated(args) {
|
|
2215
|
+
return this.stores.memory.getThreadsByResourceIdPaginated(args);
|
|
2216
|
+
}
|
|
2217
|
+
async saveThread({ thread }) {
|
|
2218
|
+
return this.stores.memory.saveThread({ thread });
|
|
2219
|
+
}
|
|
2220
|
+
async updateThread({
|
|
2221
|
+
id,
|
|
2222
|
+
title,
|
|
2223
|
+
metadata
|
|
2224
|
+
}) {
|
|
2225
|
+
return this.stores.memory.updateThread({ id, title, metadata });
|
|
2226
|
+
}
|
|
2227
|
+
async deleteThread({ threadId }) {
|
|
2228
|
+
return this.stores.memory.deleteThread({ threadId });
|
|
2229
|
+
}
|
|
2230
|
+
async saveMessages(args) {
|
|
2231
|
+
return this.stores.memory.saveMessages(args);
|
|
2232
|
+
}
|
|
2233
|
+
async getMessages({
|
|
2234
|
+
threadId,
|
|
2235
|
+
selectBy,
|
|
2236
|
+
format
|
|
2237
|
+
}) {
|
|
2238
|
+
return this.stores.memory.getMessages({ threadId, selectBy, format });
|
|
2239
|
+
}
|
|
2240
|
+
async getMessagesPaginated({
|
|
2241
|
+
threadId,
|
|
2242
|
+
selectBy,
|
|
2243
|
+
format
|
|
2244
|
+
}) {
|
|
2245
|
+
return this.stores.memory.getMessagesPaginated({ threadId, selectBy, format });
|
|
2246
|
+
}
|
|
2247
|
+
async updateWorkflowResults({
|
|
2248
|
+
workflowName,
|
|
2249
|
+
runId,
|
|
2250
|
+
stepId,
|
|
2251
|
+
result,
|
|
2252
|
+
requestContext
|
|
2253
|
+
}) {
|
|
2254
|
+
return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
|
|
2255
|
+
}
|
|
2256
|
+
async updateWorkflowState({
|
|
2257
|
+
workflowName,
|
|
2258
|
+
runId,
|
|
2259
|
+
opts
|
|
2260
|
+
}) {
|
|
2261
|
+
return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
|
|
2262
|
+
}
|
|
2263
|
+
async persistWorkflowSnapshot({
|
|
2264
|
+
workflowName,
|
|
2265
|
+
runId,
|
|
2266
|
+
resourceId,
|
|
2267
|
+
snapshot
|
|
2268
|
+
}) {
|
|
2269
|
+
return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
|
|
2270
|
+
}
|
|
2271
|
+
async loadWorkflowSnapshot(params) {
|
|
2272
|
+
return this.stores.workflows.loadWorkflowSnapshot(params);
|
|
2273
|
+
}
|
|
2274
|
+
async listWorkflowRuns({
|
|
2275
|
+
workflowName,
|
|
2276
|
+
fromDate,
|
|
2277
|
+
toDate,
|
|
2278
|
+
limit,
|
|
2279
|
+
offset,
|
|
2280
|
+
resourceId
|
|
2281
|
+
} = {}) {
|
|
2282
|
+
return this.stores.workflows.listWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
|
|
2283
|
+
}
|
|
2284
|
+
async getWorkflowRunById({
|
|
2285
|
+
runId,
|
|
2286
|
+
workflowName
|
|
2287
|
+
}) {
|
|
2288
|
+
return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
|
|
2289
|
+
}
|
|
2290
|
+
/**
|
|
2291
|
+
* Insert multiple records in a batch operation
|
|
2292
|
+
* @param tableName The table to insert into
|
|
2293
|
+
* @param records The records to insert
|
|
2294
|
+
*/
|
|
2295
|
+
async batchInsert({ tableName, records }) {
|
|
2296
|
+
return this.stores.operations.batchInsert({ tableName, records });
|
|
2297
|
+
}
|
|
2298
|
+
async updateMessages(_args) {
|
|
2299
|
+
return this.stores.memory.updateMessages(_args);
|
|
2300
|
+
}
|
|
2301
|
+
async getResourceById({ resourceId }) {
|
|
2302
|
+
return this.stores.memory.getResourceById({ resourceId });
|
|
2303
|
+
}
|
|
2304
|
+
async saveResource({ resource }) {
|
|
2305
|
+
return this.stores.memory.saveResource({ resource });
|
|
2306
|
+
}
|
|
2307
|
+
async updateResource({
|
|
2308
|
+
resourceId,
|
|
2309
|
+
workingMemory,
|
|
2310
|
+
metadata
|
|
2311
|
+
}) {
|
|
2312
|
+
return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
|
|
2313
|
+
}
|
|
2314
|
+
async getScoreById({ id: _id }) {
|
|
2315
|
+
return this.stores.scores.getScoreById({ id: _id });
|
|
2316
|
+
}
|
|
2317
|
+
async saveScore(_score) {
|
|
2318
|
+
return this.stores.scores.saveScore(_score);
|
|
2319
|
+
}
|
|
2320
|
+
async getScoresByRunId({
|
|
2321
|
+
runId: _runId,
|
|
2322
|
+
pagination: _pagination
|
|
2323
|
+
}) {
|
|
2324
|
+
return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
|
|
2325
|
+
}
|
|
2326
|
+
async getScoresByEntityId({
|
|
2327
|
+
entityId: _entityId,
|
|
2328
|
+
entityType: _entityType,
|
|
2329
|
+
pagination: _pagination
|
|
2330
|
+
}) {
|
|
2331
|
+
return this.stores.scores.getScoresByEntityId({
|
|
2332
|
+
entityId: _entityId,
|
|
2333
|
+
entityType: _entityType,
|
|
2334
|
+
pagination: _pagination
|
|
2335
|
+
});
|
|
2336
|
+
}
|
|
2337
|
+
async getScoresByScorerId({
|
|
2338
|
+
scorerId,
|
|
2339
|
+
pagination,
|
|
2340
|
+
entityId,
|
|
2341
|
+
entityType,
|
|
2342
|
+
source
|
|
2343
|
+
}) {
|
|
2344
|
+
return this.stores.scores.getScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
|
|
2345
|
+
}
|
|
2346
|
+
async getScoresBySpan({
|
|
2347
|
+
traceId,
|
|
2348
|
+
spanId,
|
|
2349
|
+
pagination
|
|
2350
|
+
}) {
|
|
2351
|
+
return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination });
|
|
928
2352
|
}
|
|
929
2353
|
/**
|
|
930
2354
|
* Close the database connection
|
|
@@ -936,3 +2360,5 @@ var D1Store = class extends MastraStorage {
|
|
|
936
2360
|
};
|
|
937
2361
|
|
|
938
2362
|
export { D1Store };
|
|
2363
|
+
//# sourceMappingURL=index.js.map
|
|
2364
|
+
//# sourceMappingURL=index.js.map
|