@mastra/cloudflare-d1 1.0.4-alpha.0 → 1.0.5-alpha.0

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 CHANGED
@@ -1,5 +1,23 @@
1
1
  # @mastra/cloudflare-d1
2
2
 
3
+ ## 1.0.5-alpha.0
4
+
5
+ ### Patch Changes
6
+
7
+ - Add `BackgroundTasksStorage` domain implementation so `@mastra/core` background task execution works with any storage adapter. ([#15307](https://github.com/mastra-ai/mastra/pull/15307))
8
+
9
+ - Updated dependencies [[`d63ffdb`](https://github.com/mastra-ai/mastra/commit/d63ffdbb2c11e76fe5ea45faab44bc15460f010c)]:
10
+ - @mastra/core@1.25.1-alpha.0
11
+
12
+ ## 1.0.4
13
+
14
+ ### Patch Changes
15
+
16
+ - dependencies updates: ([#10188](https://github.com/mastra-ai/mastra/pull/10188))
17
+ - Updated dependency [`cloudflare@^5.2.0` ↗︎](https://www.npmjs.com/package/cloudflare/v/5.2.0) (from `^4.5.0`, in `dependencies`)
18
+ - Updated dependencies [[`dc514a8`](https://github.com/mastra-ai/mastra/commit/dc514a83dba5f719172dddfd2c7b858e4943d067), [`e333b77`](https://github.com/mastra-ai/mastra/commit/e333b77e2d76ba57ccec1818e08cebc1993469ff), [`dc9fc19`](https://github.com/mastra-ai/mastra/commit/dc9fc19da4437f6b508cc355f346a8856746a76b), [`60a224d`](https://github.com/mastra-ai/mastra/commit/60a224dd497240e83698cfa5bfd02e3d1d854844), [`fbf22a7`](https://github.com/mastra-ai/mastra/commit/fbf22a7ad86bcb50dcf30459f0d075e51ddeb468), [`f16d92c`](https://github.com/mastra-ai/mastra/commit/f16d92c677a119a135cebcf7e2b9f51ada7a9df4), [`949b7bf`](https://github.com/mastra-ai/mastra/commit/949b7bfd4e40f2b2cba7fef5eb3f108a02cfe938), [`404fea1`](https://github.com/mastra-ai/mastra/commit/404fea13042181f0b0c73a101392ac87c79ceae2), [`ebf5047`](https://github.com/mastra-ai/mastra/commit/ebf5047e825c38a1a356f10b214c1d4260dfcd8d), [`12c647c`](https://github.com/mastra-ai/mastra/commit/12c647cf3a26826eb72d40b42e3c8356ceae16ed), [`d084b66`](https://github.com/mastra-ai/mastra/commit/d084b6692396057e83c086b954c1857d20b58a14), [`79c699a`](https://github.com/mastra-ai/mastra/commit/79c699acf3cd8a77e11c55530431f48eb48456e9), [`62757b6`](https://github.com/mastra-ai/mastra/commit/62757b6db6e8bb86569d23ad0b514178f57053f8), [`675f15b`](https://github.com/mastra-ai/mastra/commit/675f15b7eaeea649158d228ea635be40480c584d), [`b174c63`](https://github.com/mastra-ai/mastra/commit/b174c63a093108d4e53b9bc89a078d9f66202b3f), [`819f03c`](https://github.com/mastra-ai/mastra/commit/819f03c25823373b32476413bd76be28a5d8705a), [`04160ee`](https://github.com/mastra-ai/mastra/commit/04160eedf3130003cf842ad08428c8ff69af4cc1), [`2c27503`](https://github.com/mastra-ai/mastra/commit/2c275032510d131d2cde47f99953abf0fe02c081), [`424a1df`](https://github.com/mastra-ai/mastra/commit/424a1df7bee59abb5c83717a54807fdd674a6224), [`3d70b0b`](https://github.com/mastra-ai/mastra/commit/3d70b0b3524d817173ad870768f259c06d61bd23), [`eef7cb2`](https://github.com/mastra-ai/mastra/commit/eef7cb2abe7ef15951e2fdf792a5095c6c643333), [`260fe12`](https://github.com/mastra-ai/mastra/commit/260fe1295fe7354e39d6def2775e0797a7a277f0), [`12c88a6`](https://github.com/mastra-ai/mastra/commit/12c88a6e32bf982c2fe0c6af62e65a3414519a75), [`43595bf`](https://github.com/mastra-ai/mastra/commit/43595bf7b8df1a6edce7a23b445b5124d2a0b473), [`78670e9`](https://github.com/mastra-ai/mastra/commit/78670e97e76d7422cf7025faf371b2aeafed860d), [`e8a5b0b`](https://github.com/mastra-ai/mastra/commit/e8a5b0b9bc94d12dee4150095512ca27a288d778), [`3b45a13`](https://github.com/mastra-ai/mastra/commit/3b45a138d09d040779c0aba1edbbfc1b57442d23), [`d400e7c`](https://github.com/mastra-ai/mastra/commit/d400e7c8b8d7afa6ba2c71769eace4048e3cef8e), [`f58d1a7`](https://github.com/mastra-ai/mastra/commit/f58d1a7a457588a996c3ecb53201a68f3d28c432), [`a49a929`](https://github.com/mastra-ai/mastra/commit/a49a92904968b4fc67e01effee8c7c8d0464ba85), [`8127d96`](https://github.com/mastra-ai/mastra/commit/8127d96280492e335d49b244501088dfdd59a8f1)]:
19
+ - @mastra/core@1.18.0
20
+
3
21
  ## 1.0.4-alpha.0
4
22
 
5
23
  ### Patch Changes
@@ -3,7 +3,7 @@ name: mastra-cloudflare-d1
3
3
  description: Documentation for @mastra/cloudflare-d1. Use when working with @mastra/cloudflare-d1 APIs, configuration, or implementation.
4
4
  metadata:
5
5
  package: "@mastra/cloudflare-d1"
6
- version: "1.0.4-alpha.0"
6
+ version: "1.0.5-alpha.0"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.0.4-alpha.0",
2
+ "version": "1.0.5-alpha.0",
3
3
  "package": "@mastra/cloudflare-d1",
4
4
  "exports": {},
5
5
  "modules": {}
@@ -2,7 +2,7 @@
2
2
 
3
3
  The Cloudflare D1 storage implementation provides a serverless SQL database solution using Cloudflare D1, supporting relational operations and transactional consistency.
4
4
 
5
- > **Observability Not Supported:** Cloudflare D1 storage **doesn't support the observability domain**. Traces from the `DefaultExporter` can't be persisted to D1, and Mastra Studio's observability features won't work with D1 as your only storage provider. To enable observability, use [composite storage](https://mastra.ai/reference/storage/composite) to route observability data to a supported provider like ClickHouse or PostgreSQL.
5
+ > **Observability Not Supported:** Cloudflare D1 storage **doesn't support the observability domain**. Traces from the `DefaultExporter` can't be persisted to D1, and [Studio's](https://mastra.ai/docs/studio/overview) observability features won't work with D1 as your only storage provider. To enable observability, use [composite storage](https://mastra.ai/reference/storage/composite) to route observability data to a supported provider like ClickHouse or PostgreSQL.
6
6
 
7
7
  > **Row Size Limit:** Cloudflare D1 enforces a **1 MiB maximum row size**. This limit can be exceeded when storing messages with base64-encoded attachments such as images. See [Handling large attachments](https://mastra.ai/docs/memory/storage) for workarounds including uploading attachments to external storage.
8
8
 
package/dist/index.cjs CHANGED
@@ -3,9 +3,9 @@
3
3
  var error = require('@mastra/core/error');
4
4
  var storage = require('@mastra/core/storage');
5
5
  var Cloudflare = require('cloudflare');
6
- var agent = require('@mastra/core/agent');
7
6
  var base = require('@mastra/core/base');
8
7
  var utils = require('@mastra/core/utils');
8
+ var agent = require('@mastra/core/agent');
9
9
  var evals = require('@mastra/core/evals');
10
10
 
11
11
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -730,7 +730,246 @@ var D1DB = class extends base.MastraBase {
730
730
  }
731
731
  };
732
732
 
733
- // src/storage/domains/memory/index.ts
733
+ // src/storage/domains/background-tasks/index.ts
734
+ function serializeJson(v) {
735
+ if (typeof v === "object" && v != null) return JSON.stringify(v);
736
+ return v ?? null;
737
+ }
738
+ function rowToTask(row) {
739
+ const parseJson = (val) => {
740
+ if (val == null || val === "") return void 0;
741
+ if (typeof val === "string") {
742
+ try {
743
+ return JSON.parse(val);
744
+ } catch {
745
+ return val;
746
+ }
747
+ }
748
+ return val;
749
+ };
750
+ return {
751
+ id: row.id,
752
+ status: row.status,
753
+ toolName: row.tool_name,
754
+ toolCallId: row.tool_call_id,
755
+ args: parseJson(row.args) ?? {},
756
+ agentId: row.agent_id,
757
+ threadId: row.thread_id || void 0,
758
+ resourceId: row.resource_id || void 0,
759
+ runId: row.run_id ?? "",
760
+ result: parseJson(row.result),
761
+ error: parseJson(row.error),
762
+ retryCount: Number(row.retry_count ?? 0),
763
+ maxRetries: Number(row.max_retries ?? 0),
764
+ timeoutMs: Number(row.timeout_ms ?? 3e5),
765
+ createdAt: new Date(row.createdAt),
766
+ startedAt: row.startedAt ? new Date(row.startedAt) : void 0,
767
+ completedAt: row.completedAt ? new Date(row.completedAt) : void 0
768
+ };
769
+ }
770
+ var BackgroundTasksStorageD1 = class extends storage.BackgroundTasksStorage {
771
+ #db;
772
+ constructor(config) {
773
+ super();
774
+ const resolved = resolveD1Config(config);
775
+ this.#db = new D1DB(resolved);
776
+ }
777
+ async init() {
778
+ await this.#db.createTable({ tableName: storage.TABLE_BACKGROUND_TASKS, schema: storage.TABLE_SCHEMAS[storage.TABLE_BACKGROUND_TASKS] });
779
+ }
780
+ async dangerouslyClearAll() {
781
+ await this.#db.clearTable({ tableName: storage.TABLE_BACKGROUND_TASKS });
782
+ }
783
+ async createTask(task) {
784
+ const fullTableName = this.#db.getTableName(storage.TABLE_BACKGROUND_TASKS);
785
+ const { sql, params } = createSqlBuilder().insert(
786
+ fullTableName,
787
+ [
788
+ "id",
789
+ "tool_call_id",
790
+ "tool_name",
791
+ "agent_id",
792
+ "thread_id",
793
+ "resource_id",
794
+ "run_id",
795
+ "status",
796
+ "args",
797
+ "result",
798
+ "error",
799
+ "retry_count",
800
+ "max_retries",
801
+ "timeout_ms",
802
+ "createdAt",
803
+ "startedAt",
804
+ "completedAt"
805
+ ],
806
+ [
807
+ task.id,
808
+ task.toolCallId,
809
+ task.toolName,
810
+ task.agentId,
811
+ task.threadId ?? null,
812
+ task.resourceId ?? null,
813
+ task.runId,
814
+ task.status,
815
+ serializeJson(task.args),
816
+ serializeJson(task.result),
817
+ serializeJson(task.error),
818
+ task.retryCount,
819
+ task.maxRetries,
820
+ task.timeoutMs,
821
+ task.createdAt.toISOString(),
822
+ task.startedAt?.toISOString() ?? null,
823
+ task.completedAt?.toISOString() ?? null
824
+ ]
825
+ ).build();
826
+ await this.#db.executeQuery({ sql, params });
827
+ }
828
+ async updateTask(taskId, update) {
829
+ const sets = [];
830
+ const params = [];
831
+ if ("status" in update) {
832
+ sets.push("status = ?");
833
+ params.push(update.status);
834
+ }
835
+ if ("result" in update) {
836
+ sets.push("result = ?");
837
+ params.push(serializeJson(update.result));
838
+ }
839
+ if ("error" in update) {
840
+ sets.push("error = ?");
841
+ params.push(serializeJson(update.error));
842
+ }
843
+ if ("retryCount" in update) {
844
+ sets.push("retry_count = ?");
845
+ params.push(update.retryCount);
846
+ }
847
+ if ("startedAt" in update) {
848
+ sets.push("startedAt = ?");
849
+ params.push(update.startedAt?.toISOString() ?? null);
850
+ }
851
+ if ("completedAt" in update) {
852
+ sets.push("completedAt = ?");
853
+ params.push(update.completedAt?.toISOString() ?? null);
854
+ }
855
+ if (sets.length === 0) return;
856
+ params.push(taskId);
857
+ const fullTableName = this.#db.getTableName(storage.TABLE_BACKGROUND_TASKS);
858
+ await this.#db.executeQuery({
859
+ sql: `UPDATE ${fullTableName} SET ${sets.join(", ")} WHERE id = ?`,
860
+ params
861
+ });
862
+ }
863
+ async getTask(taskId) {
864
+ const fullTableName = this.#db.getTableName(storage.TABLE_BACKGROUND_TASKS);
865
+ const { sql, params } = createSqlBuilder().select("*").from(fullTableName).where("id = ?", taskId).build();
866
+ const row = await this.#db.executeQuery({ sql, params, first: true });
867
+ return row ? rowToTask(row) : null;
868
+ }
869
+ async listTasks(filter) {
870
+ const fullTableName = this.#db.getTableName(storage.TABLE_BACKGROUND_TASKS);
871
+ let builder = createSqlBuilder().select("*").from(fullTableName);
872
+ let countBuilder = createSqlBuilder().count().from(fullTableName);
873
+ if (filter.status) {
874
+ const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
875
+ builder = builder.where(`status IN (${statuses.map(() => "?").join(",")})`, ...statuses);
876
+ countBuilder = countBuilder.where(`status IN (${statuses.map(() => "?").join(",")})`, ...statuses);
877
+ }
878
+ if (filter.agentId) {
879
+ builder = builder.whereAnd("agent_id = ?", filter.agentId);
880
+ countBuilder = countBuilder.whereAnd("agent_id = ?", filter.agentId);
881
+ }
882
+ if (filter.threadId) {
883
+ builder = builder.whereAnd("thread_id = ?", filter.threadId);
884
+ countBuilder = countBuilder.whereAnd("thread_id = ?", filter.threadId);
885
+ }
886
+ if (filter.runId) {
887
+ builder = builder.whereAnd("run_id = ?", filter.runId);
888
+ countBuilder = countBuilder.whereAnd("run_id = ?", filter.runId);
889
+ }
890
+ if (filter.toolName) {
891
+ builder = builder.whereAnd("tool_name = ?", filter.toolName);
892
+ countBuilder = countBuilder.whereAnd("tool_name = ?", filter.toolName);
893
+ }
894
+ const dateCol = filter.dateFilterBy === "startedAt" ? "startedAt" : filter.dateFilterBy === "completedAt" ? "completedAt" : "createdAt";
895
+ if (filter.fromDate) {
896
+ builder = builder.whereAnd(`${dateCol} >= ?`, filter.fromDate.toISOString());
897
+ countBuilder = countBuilder.whereAnd(`${dateCol} >= ?`, filter.fromDate.toISOString());
898
+ }
899
+ if (filter.toDate) {
900
+ builder = builder.whereAnd(`${dateCol} < ?`, filter.toDate.toISOString());
901
+ countBuilder = countBuilder.whereAnd(`${dateCol} < ?`, filter.toDate.toISOString());
902
+ }
903
+ const { sql: countSql, params: countParams } = countBuilder.build();
904
+ const countRow = await this.#db.executeQuery({ sql: countSql, params: countParams, first: true });
905
+ const total = Number(countRow?.count ?? 0);
906
+ const orderCol = filter.orderBy === "startedAt" ? "startedAt" : filter.orderBy === "completedAt" ? "completedAt" : "createdAt";
907
+ builder = builder.orderBy(orderCol, filter.orderDirection === "desc" ? "DESC" : "ASC");
908
+ if (filter.perPage != null) {
909
+ builder = builder.limit(filter.perPage);
910
+ if (filter.page != null) {
911
+ builder = builder.offset(filter.page * filter.perPage);
912
+ }
913
+ }
914
+ const { sql, params } = builder.build();
915
+ const rows = await this.#db.executeQuery({ sql, params });
916
+ return { tasks: rows.map(rowToTask), total };
917
+ }
918
+ async deleteTask(taskId) {
919
+ const fullTableName = this.#db.getTableName(storage.TABLE_BACKGROUND_TASKS);
920
+ await this.#db.executeQuery({ sql: `DELETE FROM ${fullTableName} WHERE id = ?`, params: [taskId] });
921
+ }
922
+ async deleteTasks(filter) {
923
+ const conditions = [];
924
+ const params = [];
925
+ if (filter.status) {
926
+ const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
927
+ conditions.push(`status IN (${statuses.map(() => "?").join(",")})`);
928
+ params.push(...statuses);
929
+ }
930
+ const dateCol = filter.dateFilterBy === "startedAt" ? "startedAt" : filter.dateFilterBy === "completedAt" ? "completedAt" : "createdAt";
931
+ if (filter.fromDate) {
932
+ conditions.push(`${dateCol} >= ?`);
933
+ params.push(filter.fromDate.toISOString());
934
+ }
935
+ if (filter.toDate) {
936
+ conditions.push(`${dateCol} < ?`);
937
+ params.push(filter.toDate.toISOString());
938
+ }
939
+ if (filter.agentId) {
940
+ conditions.push("agent_id = ?");
941
+ params.push(filter.agentId);
942
+ }
943
+ if (filter.runId) {
944
+ conditions.push("run_id = ?");
945
+ params.push(filter.runId);
946
+ }
947
+ if (conditions.length === 0) return;
948
+ const fullTableName = this.#db.getTableName(storage.TABLE_BACKGROUND_TASKS);
949
+ await this.#db.executeQuery({
950
+ sql: `DELETE FROM ${fullTableName} WHERE ${conditions.join(" AND ")}`,
951
+ params
952
+ });
953
+ }
954
+ async getRunningCount() {
955
+ const fullTableName = this.#db.getTableName(storage.TABLE_BACKGROUND_TASKS);
956
+ const row = await this.#db.executeQuery({
957
+ sql: `SELECT COUNT(*) as count FROM ${fullTableName} WHERE status = 'running'`,
958
+ params: [],
959
+ first: true
960
+ });
961
+ return Number(row?.count ?? 0);
962
+ }
963
+ async getRunningCountByAgent(agentId) {
964
+ const fullTableName = this.#db.getTableName(storage.TABLE_BACKGROUND_TASKS);
965
+ const row = await this.#db.executeQuery({
966
+ sql: `SELECT COUNT(*) as count FROM ${fullTableName} WHERE status = 'running' AND agent_id = ?`,
967
+ params: [agentId],
968
+ first: true
969
+ });
970
+ return Number(row?.count ?? 0);
971
+ }
972
+ };
734
973
  var MemoryStorageD1 = class extends storage.MemoryStorage {
735
974
  #db;
736
975
  constructor(config) {
@@ -2229,21 +2468,25 @@ var D1Store = class extends storage.MastraCompositeStore {
2229
2468
  let scores;
2230
2469
  let workflows;
2231
2470
  let memory;
2471
+ let backgroundTasks;
2232
2472
  if (this.binding) {
2233
2473
  const domainConfig = { binding: this.binding, tablePrefix: this.tablePrefix };
2234
2474
  scores = new ScoresStorageD1(domainConfig);
2235
2475
  workflows = new WorkflowsStorageD1(domainConfig);
2236
2476
  memory = new MemoryStorageD1(domainConfig);
2477
+ backgroundTasks = new BackgroundTasksStorageD1(domainConfig);
2237
2478
  } else {
2238
2479
  const domainConfig = { client: this.client, tablePrefix: this.tablePrefix };
2239
2480
  scores = new ScoresStorageD1(domainConfig);
2240
2481
  workflows = new WorkflowsStorageD1(domainConfig);
2241
2482
  memory = new MemoryStorageD1(domainConfig);
2483
+ backgroundTasks = new BackgroundTasksStorageD1(domainConfig);
2242
2484
  }
2243
2485
  this.stores = {
2244
2486
  scores,
2245
2487
  workflows,
2246
- memory
2488
+ memory,
2489
+ backgroundTasks
2247
2490
  };
2248
2491
  }
2249
2492
  /**
@@ -2255,6 +2498,7 @@ var D1Store = class extends storage.MastraCompositeStore {
2255
2498
  }
2256
2499
  };
2257
2500
 
2501
+ exports.BackgroundTasksStorageD1 = BackgroundTasksStorageD1;
2258
2502
  exports.D1Store = D1Store;
2259
2503
  exports.MemoryStorageD1 = MemoryStorageD1;
2260
2504
  exports.ScoresStorageD1 = ScoresStorageD1;