@mastra/mongodb 1.7.4 → 1.8.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { v4 } from '@lukeed/uuid';
2
2
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
3
- import { createVectorErrorId, AgentsStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, createStorageErrorId, normalizePerPage, calculatePagination, BackgroundTasksStorage, TABLE_BACKGROUND_TASKS, BlobStore, TABLE_SKILL_BLOBS, DatasetsStorage, TABLE_DATASETS, TABLE_DATASET_ITEMS, TABLE_DATASET_VERSIONS, ensureDate, safelyParseJSON, TABLE_EXPERIMENTS, TABLE_EXPERIMENT_RESULTS, ExperimentsStorage, MCPClientsStorage, TABLE_MCP_CLIENTS, TABLE_MCP_CLIENT_VERSIONS, MCPServersStorage, TABLE_MCP_SERVERS, TABLE_MCP_SERVER_VERSIONS, MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, ObservabilityStorage, TABLE_SPANS, listTracesArgsSchema, toTraceSpans, PromptBlocksStorage, TABLE_PROMPT_BLOCKS, TABLE_PROMPT_BLOCK_VERSIONS, ScorerDefinitionsStorage, TABLE_SCORER_DEFINITIONS, TABLE_SCORER_DEFINITION_VERSIONS, ScoresStorage, TABLE_SCORERS, SkillsStorage, TABLE_SKILLS, TABLE_SKILL_VERSIONS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, WorkspacesStorage, TABLE_WORKSPACES, TABLE_WORKSPACE_VERSIONS, MastraCompositeStore, TraceStatus, transformScoreRow as transformScoreRow$1 } from '@mastra/core/storage';
3
+ import { createVectorErrorId, AgentsStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, createStorageErrorId, normalizePerPage, calculatePagination, BackgroundTasksStorage, TABLE_BACKGROUND_TASKS, BlobStore, TABLE_SKILL_BLOBS, DatasetsStorage, TABLE_DATASETS, TABLE_DATASET_ITEMS, TABLE_DATASET_VERSIONS, ensureDate, safelyParseJSON, TABLE_EXPERIMENTS, TABLE_EXPERIMENT_RESULTS, ExperimentsStorage, MCPClientsStorage, TABLE_MCP_CLIENTS, TABLE_MCP_CLIENT_VERSIONS, MCPServersStorage, TABLE_MCP_SERVERS, TABLE_MCP_SERVER_VERSIONS, MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, ObservabilityStorage, TABLE_SPANS, listTracesArgsSchema, toTraceSpans, PromptBlocksStorage, TABLE_PROMPT_BLOCKS, TABLE_PROMPT_BLOCK_VERSIONS, SchedulesStorage, TABLE_SCHEDULES, TABLE_SCHEDULE_TRIGGERS, ScorerDefinitionsStorage, TABLE_SCORER_DEFINITIONS, TABLE_SCORER_DEFINITION_VERSIONS, ScoresStorage, TABLE_SCORERS, SkillsStorage, TABLE_SKILLS, TABLE_SKILL_VERSIONS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, WorkspacesStorage, TABLE_WORKSPACES, TABLE_WORKSPACE_VERSIONS, MastraCompositeStore, TraceStatus, transformScoreRow as transformScoreRow$1 } from '@mastra/core/storage';
4
4
  import { MastraVector, validateUpsertInput, validateVectorValues } from '@mastra/core/vector';
5
5
  import { MongoClient } from 'mongodb';
6
6
  import { BaseFilterTranslator } from '@mastra/core/vector/filter';
@@ -12,7 +12,7 @@ import { saveScorePayloadSchema } from '@mastra/core/evals';
12
12
 
13
13
  // package.json
14
14
  var package_default = {
15
- version: "1.7.4"};
15
+ version: "1.8.0-alpha.1"};
16
16
  var MongoDBFilterTranslator = class extends BaseFilterTranslator {
17
17
  getSupportedOperators() {
18
18
  return {
@@ -7593,6 +7593,228 @@ var MongoDBPromptBlocksStorage = class _MongoDBPromptBlocksStorage extends Promp
7593
7593
  return result;
7594
7594
  }
7595
7595
  };
7596
+ function scheduleToDoc(schedule) {
7597
+ return {
7598
+ id: schedule.id,
7599
+ target: schedule.target,
7600
+ cron: schedule.cron,
7601
+ timezone: schedule.timezone ?? null,
7602
+ status: schedule.status,
7603
+ next_fire_at: schedule.nextFireAt,
7604
+ last_fire_at: schedule.lastFireAt ?? null,
7605
+ last_run_id: schedule.lastRunId ?? null,
7606
+ created_at: schedule.createdAt,
7607
+ updated_at: schedule.updatedAt,
7608
+ metadata: schedule.metadata ?? null,
7609
+ owner_type: schedule.ownerType ?? null,
7610
+ owner_id: schedule.ownerId ?? null
7611
+ };
7612
+ }
7613
+ function docToSchedule(doc) {
7614
+ const target = doc.target;
7615
+ if (!target) {
7616
+ throw new Error(`Schedule ${doc.id} has invalid target`);
7617
+ }
7618
+ const schedule = {
7619
+ id: String(doc.id),
7620
+ target,
7621
+ cron: String(doc.cron),
7622
+ status: String(doc.status),
7623
+ nextFireAt: Number(doc.next_fire_at),
7624
+ createdAt: Number(doc.created_at),
7625
+ updatedAt: Number(doc.updated_at)
7626
+ };
7627
+ if (doc.timezone != null) schedule.timezone = String(doc.timezone);
7628
+ if (doc.last_fire_at != null) schedule.lastFireAt = Number(doc.last_fire_at);
7629
+ if (doc.last_run_id != null) schedule.lastRunId = String(doc.last_run_id);
7630
+ if (doc.metadata != null) schedule.metadata = doc.metadata;
7631
+ if (doc.owner_type != null) schedule.ownerType = String(doc.owner_type);
7632
+ if (doc.owner_id != null) schedule.ownerId = String(doc.owner_id);
7633
+ return schedule;
7634
+ }
7635
+ function triggerToDoc(trigger) {
7636
+ return {
7637
+ id: trigger.id ?? crypto.randomUUID(),
7638
+ schedule_id: trigger.scheduleId,
7639
+ run_id: trigger.runId,
7640
+ scheduled_fire_at: trigger.scheduledFireAt,
7641
+ actual_fire_at: trigger.actualFireAt,
7642
+ outcome: trigger.outcome,
7643
+ error: trigger.error ?? null,
7644
+ trigger_kind: trigger.triggerKind ?? "schedule-fire",
7645
+ parent_trigger_id: trigger.parentTriggerId ?? null,
7646
+ metadata: trigger.metadata ?? null
7647
+ };
7648
+ }
7649
+ function docToTrigger(doc) {
7650
+ const trigger = {
7651
+ id: doc.id != null ? String(doc.id) : void 0,
7652
+ scheduleId: String(doc.schedule_id),
7653
+ runId: doc.run_id != null ? String(doc.run_id) : null,
7654
+ scheduledFireAt: Number(doc.scheduled_fire_at),
7655
+ actualFireAt: Number(doc.actual_fire_at),
7656
+ outcome: String(doc.outcome),
7657
+ triggerKind: doc.trigger_kind != null ? String(doc.trigger_kind) : "schedule-fire"
7658
+ };
7659
+ if (doc.error != null) trigger.error = String(doc.error);
7660
+ if (doc.parent_trigger_id != null) trigger.parentTriggerId = String(doc.parent_trigger_id);
7661
+ if (doc.metadata != null) trigger.metadata = doc.metadata;
7662
+ return trigger;
7663
+ }
7664
+ var SchedulesMongoDB = class _SchedulesMongoDB extends SchedulesStorage {
7665
+ #connector;
7666
+ #skipDefaultIndexes;
7667
+ #indexes;
7668
+ static MANAGED_COLLECTIONS = [TABLE_SCHEDULES, TABLE_SCHEDULE_TRIGGERS];
7669
+ constructor(config) {
7670
+ super();
7671
+ this.#connector = resolveMongoDBConfig(config);
7672
+ this.#skipDefaultIndexes = config.skipDefaultIndexes;
7673
+ this.#indexes = config.indexes?.filter(
7674
+ (idx) => _SchedulesMongoDB.MANAGED_COLLECTIONS.includes(idx.collection)
7675
+ );
7676
+ }
7677
+ getSchedulesCollection() {
7678
+ return this.#connector.getCollection(TABLE_SCHEDULES);
7679
+ }
7680
+ getTriggersCollection() {
7681
+ return this.#connector.getCollection(TABLE_SCHEDULE_TRIGGERS);
7682
+ }
7683
+ getDefaultIndexDefinitions() {
7684
+ return [
7685
+ { collection: TABLE_SCHEDULES, keys: { id: 1 }, options: { unique: true } },
7686
+ { collection: TABLE_SCHEDULES, keys: { status: 1, next_fire_at: 1 } },
7687
+ { collection: TABLE_SCHEDULES, keys: { "target.workflowId": 1 } },
7688
+ { collection: TABLE_SCHEDULES, keys: { owner_type: 1, owner_id: 1 } },
7689
+ { collection: TABLE_SCHEDULE_TRIGGERS, keys: { id: 1 }, options: { unique: true } },
7690
+ { collection: TABLE_SCHEDULE_TRIGGERS, keys: { schedule_id: 1, actual_fire_at: -1 } },
7691
+ { collection: TABLE_SCHEDULE_TRIGGERS, keys: { parent_trigger_id: 1 } }
7692
+ ];
7693
+ }
7694
+ async createDefaultIndexes() {
7695
+ if (this.#skipDefaultIndexes) return;
7696
+ for (const indexDef of this.getDefaultIndexDefinitions()) {
7697
+ try {
7698
+ const collection = await this.#connector.getCollection(indexDef.collection);
7699
+ await collection.createIndex(indexDef.keys, indexDef.options);
7700
+ } catch (error) {
7701
+ this.logger?.warn?.(`Failed to create index on ${indexDef.collection}:`, error);
7702
+ }
7703
+ }
7704
+ }
7705
+ async createCustomIndexes() {
7706
+ if (!this.#indexes || this.#indexes.length === 0) return;
7707
+ for (const indexDef of this.#indexes) {
7708
+ try {
7709
+ const collection = await this.#connector.getCollection(indexDef.collection);
7710
+ await collection.createIndex(indexDef.keys, indexDef.options);
7711
+ } catch (error) {
7712
+ this.logger?.warn?.(`Failed to create custom index on ${indexDef.collection}:`, error);
7713
+ }
7714
+ }
7715
+ }
7716
+ async init() {
7717
+ await this.createDefaultIndexes();
7718
+ await this.createCustomIndexes();
7719
+ }
7720
+ async dangerouslyClearAll() {
7721
+ const triggers = await this.getTriggersCollection();
7722
+ await triggers.deleteMany({});
7723
+ const schedules = await this.getSchedulesCollection();
7724
+ await schedules.deleteMany({});
7725
+ }
7726
+ async createSchedule(schedule) {
7727
+ const collection = await this.getSchedulesCollection();
7728
+ const existing = await collection.findOne({ id: schedule.id });
7729
+ if (existing) {
7730
+ throw new Error(`Schedule with id "${schedule.id}" already exists`);
7731
+ }
7732
+ await collection.insertOne(scheduleToDoc(schedule));
7733
+ return schedule;
7734
+ }
7735
+ async getSchedule(id) {
7736
+ const collection = await this.getSchedulesCollection();
7737
+ const doc = await collection.findOne({ id });
7738
+ return doc ? docToSchedule(doc) : null;
7739
+ }
7740
+ async listSchedules(filter) {
7741
+ const query = {};
7742
+ if (filter?.status) query.status = filter.status;
7743
+ if (filter?.workflowId) query["target.workflowId"] = filter.workflowId;
7744
+ if (filter?.ownerType !== void 0) {
7745
+ query.owner_type = filter.ownerType === null ? null : filter.ownerType;
7746
+ }
7747
+ if (filter?.ownerId !== void 0) {
7748
+ query.owner_id = filter.ownerId === null ? null : filter.ownerId;
7749
+ }
7750
+ const collection = await this.getSchedulesCollection();
7751
+ const docs = await collection.find(query).sort({ created_at: 1 }).toArray();
7752
+ return docs.map(docToSchedule);
7753
+ }
7754
+ async listDueSchedules(now, limit) {
7755
+ const cap = limit ?? 100;
7756
+ const collection = await this.getSchedulesCollection();
7757
+ const docs = await collection.find({ status: "active", next_fire_at: { $lte: now } }).sort({ next_fire_at: 1 }).limit(cap).toArray();
7758
+ return docs.map(docToSchedule);
7759
+ }
7760
+ async updateSchedule(id, patch) {
7761
+ const $set = {};
7762
+ if ("cron" in patch && patch.cron !== void 0) $set.cron = patch.cron;
7763
+ if ("timezone" in patch) $set.timezone = patch.timezone ?? null;
7764
+ if ("status" in patch && patch.status !== void 0) $set.status = patch.status;
7765
+ if ("nextFireAt" in patch && patch.nextFireAt !== void 0) $set.next_fire_at = patch.nextFireAt;
7766
+ if ("target" in patch && patch.target !== void 0) $set.target = patch.target;
7767
+ if ("metadata" in patch) $set.metadata = patch.metadata ?? null;
7768
+ if ("ownerType" in patch) $set.owner_type = patch.ownerType ?? null;
7769
+ if ("ownerId" in patch) $set.owner_id = patch.ownerId ?? null;
7770
+ $set.updated_at = Date.now();
7771
+ const collection = await this.getSchedulesCollection();
7772
+ const result = await collection.findOneAndUpdate({ id }, { $set }, { returnDocument: "after" });
7773
+ if (!result) throw new Error(`Schedule ${id} not found`);
7774
+ return docToSchedule(result);
7775
+ }
7776
+ async updateScheduleNextFire(id, expectedNextFireAt, newNextFireAt, lastFireAt, lastRunId) {
7777
+ const collection = await this.getSchedulesCollection();
7778
+ const result = await collection.updateOne(
7779
+ { id, next_fire_at: expectedNextFireAt, status: "active" },
7780
+ {
7781
+ $set: {
7782
+ next_fire_at: newNextFireAt,
7783
+ last_fire_at: lastFireAt,
7784
+ last_run_id: lastRunId,
7785
+ updated_at: Date.now()
7786
+ }
7787
+ }
7788
+ );
7789
+ return result.matchedCount > 0;
7790
+ }
7791
+ async deleteSchedule(id) {
7792
+ const triggers = await this.getTriggersCollection();
7793
+ await triggers.deleteMany({ schedule_id: id });
7794
+ const schedules = await this.getSchedulesCollection();
7795
+ await schedules.deleteOne({ id });
7796
+ }
7797
+ async recordTrigger(trigger) {
7798
+ const collection = await this.getTriggersCollection();
7799
+ await collection.insertOne(triggerToDoc(trigger));
7800
+ }
7801
+ async listTriggers(scheduleId, opts) {
7802
+ const query = { schedule_id: scheduleId };
7803
+ if (opts?.fromActualFireAt != null || opts?.toActualFireAt != null) {
7804
+ const range = {};
7805
+ if (opts?.fromActualFireAt != null) range.$gte = opts.fromActualFireAt;
7806
+ if (opts?.toActualFireAt != null) range.$lt = opts.toActualFireAt;
7807
+ query.actual_fire_at = range;
7808
+ }
7809
+ const collection = await this.getTriggersCollection();
7810
+ let cursor = collection.find(query).sort({ actual_fire_at: -1 });
7811
+ if (opts?.limit != null) {
7812
+ cursor = cursor.limit(Math.floor(opts.limit));
7813
+ }
7814
+ const docs = await cursor.toArray();
7815
+ return docs.map(docToTrigger);
7816
+ }
7817
+ };
7596
7818
  var SNAPSHOT_FIELDS5 = [
7597
7819
  "name",
7598
7820
  "description",
@@ -10105,6 +10327,7 @@ var MongoDBStore = class extends MastraCompositeStore {
10105
10327
  const datasets = new MongoDBDatasetsStorage(domainConfig);
10106
10328
  const experiments = new MongoDBExperimentsStorage(domainConfig);
10107
10329
  const backgroundTasks = new BackgroundTasksStorageMongoDB(domainConfig);
10330
+ const schedules = new SchedulesMongoDB(domainConfig);
10108
10331
  this.stores = {
10109
10332
  memory,
10110
10333
  scores,
@@ -10120,7 +10343,8 @@ var MongoDBStore = class extends MastraCompositeStore {
10120
10343
  blobs,
10121
10344
  backgroundTasks,
10122
10345
  datasets,
10123
- experiments
10346
+ experiments,
10347
+ schedules
10124
10348
  };
10125
10349
  }
10126
10350
  /**
@@ -10239,6 +10463,6 @@ Example Complex Query:
10239
10463
  ]
10240
10464
  }`;
10241
10465
 
10242
- export { BackgroundTasksStorageMongoDB, MONGODB_PROMPT, MemoryStorageMongoDB, MongoDBAgentsStorage, MongoDBBlobStore, MongoDBDatasetsStorage, MongoDBExperimentsStorage, MongoDBMCPClientsStorage, MongoDBMCPServersStorage, MongoDBPromptBlocksStorage, MongoDBScorerDefinitionsStorage, MongoDBSkillsStorage, MongoDBStore, MongoDBVector, MongoDBWorkspacesStorage, ObservabilityMongoDB, ScoresStorageMongoDB, WorkflowsStorageMongoDB };
10466
+ export { BackgroundTasksStorageMongoDB, MONGODB_PROMPT, MemoryStorageMongoDB, MongoDBAgentsStorage, MongoDBBlobStore, MongoDBDatasetsStorage, MongoDBExperimentsStorage, MongoDBMCPClientsStorage, MongoDBMCPServersStorage, MongoDBPromptBlocksStorage, MongoDBScorerDefinitionsStorage, MongoDBSkillsStorage, MongoDBStore, MongoDBVector, MongoDBWorkspacesStorage, ObservabilityMongoDB, SchedulesMongoDB, ScoresStorageMongoDB, WorkflowsStorageMongoDB };
10243
10467
  //# sourceMappingURL=index.js.map
10244
10468
  //# sourceMappingURL=index.js.map