@mastra/cloudflare-d1 1.4.2 → 1.4.3

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/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { ErrorCategory, ErrorDomain, MastraError } from "@mastra/core/error";
2
- import { BackgroundTasksStorage, MastraCompositeStore, MemoryStorage, RUN_FENCING_TABLE_SCHEMAS, RunFenceConflictError, ScoresStorage, TABLE_BACKGROUND_TASKS, TABLE_MEMORY_RUN_FENCES, TABLE_MESSAGES, TABLE_RESOURCES, TABLE_SCHEMAS, TABLE_SCORERS, TABLE_THREADS, TABLE_WORKFLOW_RUN_OWNERS, TABLE_WORKFLOW_SNAPSHOT, WorkflowsStorage, calculatePagination, createStorageErrorId, ensureDate, getDefaultValue, getSqlType, isRunFenceConflictError, matchesRunFence, normalizePerPage, resolveRunFence, serializeDate, transformScoreRow, validateStorageMetadataFilter } from "@mastra/core/storage";
2
+ import { BackgroundTasksStorage, MastraCompositeStore, MemoryStorage, RUN_FENCING_TABLE_SCHEMAS, RunFenceConflictError, ScoresStorage, TABLE_BACKGROUND_TASKS, TABLE_MEMORY_RUN_FENCES, TABLE_MESSAGES, TABLE_RESOURCES, TABLE_SCHEMAS, TABLE_SCORERS, TABLE_THREADS, TABLE_WORKFLOW_RUN_OWNERS, TABLE_WORKFLOW_SNAPSHOT, WorkflowsStorage, calculatePagination, createStorageErrorId, ensureDate, executeRetentionPrune, getDefaultValue, getSqlType, isRunFenceConflictError, matchesRunFence, normalizePerPage, resolveRetentionTargets, resolveRunFence, retentionCutoffMs, serializeDate, transformScoreRow, validateStorageMetadataFilter } from "@mastra/core/storage";
3
3
  import Cloudflare from "cloudflare";
4
4
  import { MastraBase } from "@mastra/core/base";
5
5
  import { parseSqlIdentifier } from "@mastra/core/utils";
@@ -423,6 +423,21 @@ var D1DB = class extends MastraBase {
423
423
  }, error);
424
424
  }
425
425
  }
426
+ /**
427
+ * Delete up to `limit` rows keyed by `runId` whose epoch-ms `column` is older
428
+ * than `cutoff`. Used to prune the run fencing tables.
429
+ */
430
+ async pruneRunRows({ tableName, column, cutoff, limit }) {
431
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(column)) throw new Error(`Invalid retention identifier: ${tableName}.${column}`);
432
+ const table = this.getTableName(tableName);
433
+ const rows = await this.executeQuery({
434
+ sql: `DELETE FROM ${table} WHERE runId IN (
435
+ SELECT runId FROM ${table} WHERE ${column} < ? ORDER BY ${column} LIMIT ?
436
+ ) RETURNING runId`,
437
+ params: [cutoff, limit]
438
+ });
439
+ return Array.isArray(rows) ? rows.length : 0;
440
+ }
426
441
  async executeQuery(options) {
427
442
  if (this.binding) return this.executeWorkersBindingQuery(options);
428
443
  else if (this.client) return this.executeRestQuery(options);
@@ -1040,7 +1055,18 @@ function addSqliteMetadataValuePredicate(conditions, params, path, value) {
1040
1055
  conditions.push(`CASE WHEN json_valid(content) THEN json_type(content, ?) = ? AND json_extract(content, ?) = ? ELSE 0 END`);
1041
1056
  params.push(path, value ? "true" : "false", path, value ? 1 : 0);
1042
1057
  }
1043
- var MemoryStorageD1 = class extends MemoryStorage {
1058
+ var MemoryStorageD1 = class MemoryStorageD1 extends MemoryStorage {
1059
+ /**
1060
+ * Tables `prune()` can clean up. Run fences anchor on `retiredAt` (epoch ms), which stays unset until the
1061
+ * execution holding the fence settles, so a running execution's fence is
1062
+ * never pruned.
1063
+ */
1064
+ static retentionTables = { runFences: {
1065
+ table: TABLE_MEMORY_RUN_FENCES,
1066
+ column: "retiredAt",
1067
+ indexed: false,
1068
+ anchorType: "epoch-ms"
1069
+ } };
1044
1070
  supportsPartialThreadUpdate = true;
1045
1071
  #db;
1046
1072
  constructor(config) {
@@ -1070,6 +1096,24 @@ var MemoryStorageD1 = class extends MemoryStorage {
1070
1096
  schema: RUN_FENCING_TABLE_SCHEMAS[TABLE_MEMORY_RUN_FENCES]
1071
1097
  });
1072
1098
  }
1099
+ async prune(policies, options) {
1100
+ return executeRetentionPrune({
1101
+ domain: "memory",
1102
+ targets: resolveRetentionTargets({
1103
+ policies,
1104
+ descriptor: MemoryStorageD1.retentionTables,
1105
+ order: ["runFences"]
1106
+ }),
1107
+ options,
1108
+ cutoffFor: (target, now) => retentionCutoffMs(target.policy, now),
1109
+ deleteBatch: (_target, cutoff, limit) => this.#db.pruneRunRows({
1110
+ tableName: TABLE_MEMORY_RUN_FENCES,
1111
+ column: "retiredAt",
1112
+ cutoff: Number(cutoff),
1113
+ limit
1114
+ })
1115
+ });
1116
+ }
1073
1117
  async dangerouslyClearAll() {
1074
1118
  await this.#db.clearTable({ tableName: TABLE_MESSAGES });
1075
1119
  await this.#db.clearTable({ tableName: TABLE_THREADS });
@@ -2294,7 +2338,18 @@ function toRunOwnershipRecord(runId, row) {
2294
2338
  live: leaseExpiresAt !== null && leaseExpiresAt > Number(row.nowMs)
2295
2339
  };
2296
2340
  }
2297
- var WorkflowsStorageD1 = class extends WorkflowsStorage {
2341
+ var WorkflowsStorageD1 = class WorkflowsStorageD1 extends WorkflowsStorage {
2342
+ /**
2343
+ * Tables `prune()` can clean up. Run ownership records anchor on `updatedAt` (epoch ms), which every
2344
+ * claim, renewal and release refreshes, so a live execution's record is never
2345
+ * older than its renew interval.
2346
+ */
2347
+ static retentionTables = { runOwnership: {
2348
+ table: TABLE_WORKFLOW_RUN_OWNERS,
2349
+ column: "updatedAt",
2350
+ indexed: false,
2351
+ anchorType: "epoch-ms"
2352
+ } };
2298
2353
  #db;
2299
2354
  constructor(config) {
2300
2355
  super();
@@ -2313,6 +2368,24 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
2313
2368
  schema: RUN_FENCING_TABLE_SCHEMAS[TABLE_WORKFLOW_RUN_OWNERS]
2314
2369
  });
2315
2370
  }
2371
+ async prune(policies, options) {
2372
+ return executeRetentionPrune({
2373
+ domain: "workflows",
2374
+ targets: resolveRetentionTargets({
2375
+ policies,
2376
+ descriptor: WorkflowsStorageD1.retentionTables,
2377
+ order: ["runOwnership"]
2378
+ }),
2379
+ options,
2380
+ cutoffFor: (target, now) => retentionCutoffMs(target.policy, now),
2381
+ deleteBatch: (_target, cutoff, limit) => this.#db.pruneRunRows({
2382
+ tableName: TABLE_WORKFLOW_RUN_OWNERS,
2383
+ column: "updatedAt",
2384
+ cutoff: Number(cutoff),
2385
+ limit
2386
+ })
2387
+ });
2388
+ }
2316
2389
  async dangerouslyClearAll() {
2317
2390
  await this.#db.clearTable({ tableName: TABLE_WORKFLOW_SNAPSHOT });
2318
2391
  await this.#db.clearTable({ tableName: TABLE_WORKFLOW_RUN_OWNERS });