@olivia-db/mastra 0.0.0-stage → 0.1.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.
@@ -0,0 +1,21 @@
1
+ import { OliviaDbClient } from "@olivia-db/client";
2
+ import { InMemoryMemory } from "@mastra/core/storage";
3
+ export declare class OliviaDbConflictError extends Error {
4
+ }
5
+ export declare class OliviaDBMemoryStorage extends InMemoryMemory {
6
+ private readonly client;
7
+ private readonly root;
8
+ private readonly seen;
9
+ private queue;
10
+ /** Set while an operation runs: Mastra's methods call each other (patchThread calls
11
+ * updateThread), and a nested call runs inside the outer one's load and write. */
12
+ private readonly inside;
13
+ constructor(client: OliviaDbClient, root?: string[]);
14
+ supportsRunFencing(): boolean;
15
+ /** One operation at a time per storage object (Mastra's code mutates the tables). */
16
+ private serial;
17
+ /** The table of InMemoryMemory's database (its `db` field) that holds `t`'s rows. */
18
+ private map;
19
+ private load;
20
+ private persist;
21
+ }
package/dist/index.js ADDED
@@ -0,0 +1,155 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ /**
3
+ * Mastra memory storage on OliviaDB (the `MemoryStorage` domain of @mastra/core 1.86.0).
4
+ *
5
+ * The thread, message and resource semantics are Mastra's own: this class extends Mastra's
6
+ * `InMemoryMemory` domain and keeps its three tables (threads, messages, resources) in OliviaDB
7
+ * agent state, one document per row. Each operation loads the tables from OliviaDB, runs Mastra's
8
+ * code, and writes the rows it changed back with compare-and-set on their versions, so
9
+ * several processes share one memory and a concurrent change is reported, not lost
10
+ * (`OliviaDbConflictError`, retry the call). Observational memory and run fencing are not kept
11
+ * in OliviaDB and are reported as unsupported.
12
+ *
13
+ * const storage = new MastraCompositeStore({ id: "oliviadb", domains: { memory: new OliviaDBMemoryStorage(client) } });
14
+ * const memory = new Memory({ storage });
15
+ */
16
+ import { AsyncLocalStorage } from "node:async_hooks";
17
+ import { OliviaDbClient, OliviaDbError } from "@olivia-db/client";
18
+ import { InMemoryDB, InMemoryMemory } from "@mastra/core/storage";
19
+ const TABLES = ["threads", "messages", "resources"];
20
+ const DATE_FIELDS = ["createdAt", "updatedAt"];
21
+ const METHODS = [
22
+ "getThreadById",
23
+ "saveThread",
24
+ "updateThread",
25
+ "patchThread",
26
+ "updateThreadMetadata",
27
+ "deleteThread",
28
+ "listMessages",
29
+ "listMessagesByResourceId",
30
+ "listMessagesById",
31
+ "saveMessages",
32
+ "updateMessages",
33
+ "deleteMessages",
34
+ "listThreads",
35
+ "copyThread",
36
+ "cloneThread",
37
+ "updateThreadResourceId",
38
+ "getResourceById",
39
+ "saveResource",
40
+ "updateResource",
41
+ "mergeResourceWorkingMemory",
42
+ "dangerouslyClearAll",
43
+ ];
44
+ export class OliviaDbConflictError extends Error {
45
+ }
46
+ export class OliviaDBMemoryStorage extends InMemoryMemory {
47
+ client;
48
+ root;
49
+ seen = new Map();
50
+ queue = Promise.resolve();
51
+ /** Set while an operation runs: Mastra's methods call each other (patchThread calls
52
+ * updateThread), and a nested call runs inside the outer one's load and write. */
53
+ inside = new AsyncLocalStorage();
54
+ constructor(client, root = ["mastra", "memory"]) {
55
+ super({ db: new InMemoryDB() });
56
+ // This storage keeps no observational memory. MemoryStorage (the base class) types the
57
+ // flags as boolean, InMemoryMemory narrows them to `true`; they are set over its fields.
58
+ Object.defineProperties(this, {
59
+ supportsObservationalMemory: { value: false },
60
+ supportsObservationalMemoryHistorySearch: { value: false },
61
+ });
62
+ this.client = client;
63
+ this.root = root;
64
+ const self = this;
65
+ for (const name of METHODS) {
66
+ const found = self[name];
67
+ if (typeof found !== "function")
68
+ continue;
69
+ const orig = found;
70
+ self[name] = (...args) => {
71
+ if (this.inside.getStore())
72
+ return orig.apply(this, args);
73
+ return this.serial(() => this.inside.run(true, async () => {
74
+ await this.load();
75
+ try {
76
+ return await orig.apply(this, args);
77
+ }
78
+ finally {
79
+ await this.persist();
80
+ }
81
+ }));
82
+ };
83
+ }
84
+ }
85
+ supportsRunFencing() {
86
+ return false;
87
+ }
88
+ /** One operation at a time per storage object (Mastra's code mutates the tables). */
89
+ serial(f) {
90
+ const r = this.queue.then(f, f);
91
+ this.queue = r.catch(() => undefined);
92
+ return r;
93
+ }
94
+ /** The table of InMemoryMemory's database (its `db` field) that holds `t`'s rows. */
95
+ map(t) {
96
+ return this.db[t];
97
+ }
98
+ async load() {
99
+ this.seen.clear();
100
+ for (const t of TABLES) {
101
+ const m = this.map(t);
102
+ m.clear();
103
+ let after;
104
+ for (;;) {
105
+ const page = await this.client.stateList([...this.root, t], { after, limit: 500 });
106
+ for (const it of page) {
107
+ const v = { ...it.value };
108
+ for (const f of DATE_FIELDS) {
109
+ const d = v[f];
110
+ if (typeof d === "string")
111
+ v[f] = new Date(d);
112
+ }
113
+ m.set(it.key, v);
114
+ this.seen.set(`${t}\u0000${it.key}`, { json: JSON.stringify(it.value), version: it.version });
115
+ }
116
+ if (page.length < 500)
117
+ break;
118
+ after = page[page.length - 1].key;
119
+ }
120
+ }
121
+ }
122
+ async persist() {
123
+ const live = new Set();
124
+ for (const t of TABLES) {
125
+ for (const [k, v] of this.map(t)) {
126
+ const id = `${t}\u0000${k}`;
127
+ live.add(id);
128
+ const json = JSON.stringify(v);
129
+ const prev = this.seen.get(id);
130
+ if (prev?.json === json)
131
+ continue;
132
+ try {
133
+ await this.client.statePut({
134
+ namespace: [...this.root, t],
135
+ key: k,
136
+ value: JSON.parse(json),
137
+ expected_version: prev?.version ?? 0,
138
+ index: false,
139
+ });
140
+ }
141
+ catch (e) {
142
+ if (e instanceof OliviaDbError && e.status === 409)
143
+ throw new OliviaDbConflictError(`${t} ${k} was changed by another process: retry`);
144
+ throw e;
145
+ }
146
+ }
147
+ }
148
+ for (const id of this.seen.keys()) {
149
+ if (live.has(id))
150
+ continue;
151
+ const [t, k] = id.split("\u0000");
152
+ await this.client.stateDelete([...this.root, t], k);
153
+ }
154
+ }
155
+ }
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@olivia-db/mastra",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Mastra memory storage backed by OliviaDB",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "src"
18
+ ],
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/OliviaDB/oliviadb-js.git",
22
+ "directory": "adapters/mastra"
23
+ },
24
+ "engines": {
25
+ "node": ">=22.18"
26
+ },
27
+ "scripts": {
28
+ "build": "tsc -p tsconfig.build.json",
29
+ "prepack": "npm run build",
30
+ "typecheck": "tsc -p .",
31
+ "test": "node --test --test-force-exit test/*.test.ts"
32
+ },
33
+ "dependencies": {
34
+ "@olivia-db/client": "0.1.0",
35
+ "@mastra/core": "1.86.0",
36
+ "@mastra/memory": "1.41.3"
37
+ }
38
+ }
package/src/index.ts ADDED
@@ -0,0 +1,160 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ /**
3
+ * Mastra memory storage on OliviaDB (the `MemoryStorage` domain of @mastra/core 1.86.0).
4
+ *
5
+ * The thread, message and resource semantics are Mastra's own: this class extends Mastra's
6
+ * `InMemoryMemory` domain and keeps its three tables (threads, messages, resources) in OliviaDB
7
+ * agent state, one document per row. Each operation loads the tables from OliviaDB, runs Mastra's
8
+ * code, and writes the rows it changed back with compare-and-set on their versions, so
9
+ * several processes share one memory and a concurrent change is reported, not lost
10
+ * (`OliviaDbConflictError`, retry the call). Observational memory and run fencing are not kept
11
+ * in OliviaDB and are reported as unsupported.
12
+ *
13
+ * const storage = new MastraCompositeStore({ id: "oliviadb", domains: { memory: new OliviaDBMemoryStorage(client) } });
14
+ * const memory = new Memory({ storage });
15
+ */
16
+ import { AsyncLocalStorage } from "node:async_hooks";
17
+ import { OliviaDbClient, OliviaDbError } from "@olivia-db/client";
18
+ import { InMemoryDB, InMemoryMemory } from "@mastra/core/storage";
19
+
20
+ const TABLES = ["threads", "messages", "resources"] as const;
21
+ type Table = (typeof TABLES)[number];
22
+ type Row = Record<string, unknown>;
23
+ const DATE_FIELDS = ["createdAt", "updatedAt"];
24
+
25
+ const METHODS = [
26
+ "getThreadById",
27
+ "saveThread",
28
+ "updateThread",
29
+ "patchThread",
30
+ "updateThreadMetadata",
31
+ "deleteThread",
32
+ "listMessages",
33
+ "listMessagesByResourceId",
34
+ "listMessagesById",
35
+ "saveMessages",
36
+ "updateMessages",
37
+ "deleteMessages",
38
+ "listThreads",
39
+ "copyThread",
40
+ "cloneThread",
41
+ "updateThreadResourceId",
42
+ "getResourceById",
43
+ "saveResource",
44
+ "updateResource",
45
+ "mergeResourceWorkingMemory",
46
+ "dangerouslyClearAll",
47
+ ];
48
+
49
+ export class OliviaDbConflictError extends Error {}
50
+
51
+ export class OliviaDBMemoryStorage extends InMemoryMemory {
52
+ private readonly client: OliviaDbClient;
53
+ private readonly root: string[];
54
+ private readonly seen = new Map<string, { json: string; version: number }>();
55
+ private queue: Promise<unknown> = Promise.resolve();
56
+ /** Set while an operation runs: Mastra's methods call each other (patchThread calls
57
+ * updateThread), and a nested call runs inside the outer one's load and write. */
58
+ private readonly inside = new AsyncLocalStorage<boolean>();
59
+
60
+ constructor(client: OliviaDbClient, root: string[] = ["mastra", "memory"]) {
61
+ super({ db: new InMemoryDB() });
62
+ // This storage keeps no observational memory. MemoryStorage (the base class) types the
63
+ // flags as boolean, InMemoryMemory narrows them to `true`; they are set over its fields.
64
+ Object.defineProperties(this, {
65
+ supportsObservationalMemory: { value: false },
66
+ supportsObservationalMemoryHistorySearch: { value: false },
67
+ });
68
+ this.client = client;
69
+ this.root = root;
70
+ const self = this as unknown as Record<string, unknown>;
71
+ for (const name of METHODS) {
72
+ const found = self[name];
73
+ if (typeof found !== "function") continue;
74
+ const orig = found as (...args: unknown[]) => Promise<unknown>;
75
+ self[name] = (...args: unknown[]) => {
76
+ if (this.inside.getStore()) return orig.apply(this, args);
77
+ return this.serial(() =>
78
+ this.inside.run(true, async () => {
79
+ await this.load();
80
+ try {
81
+ return await orig.apply(this, args);
82
+ } finally {
83
+ await this.persist();
84
+ }
85
+ }),
86
+ );
87
+ };
88
+ }
89
+ }
90
+
91
+ override supportsRunFencing(): boolean {
92
+ return false;
93
+ }
94
+
95
+ /** One operation at a time per storage object (Mastra's code mutates the tables). */
96
+ private serial<T>(f: () => Promise<T>): Promise<T> {
97
+ const r = this.queue.then(f, f);
98
+ this.queue = r.catch(() => undefined);
99
+ return r;
100
+ }
101
+
102
+ /** The table of InMemoryMemory's database (its `db` field) that holds `t`'s rows. */
103
+ private map(t: Table): Map<string, Row> {
104
+ return (this as unknown as { db: Record<Table, Map<string, Row>> }).db[t];
105
+ }
106
+
107
+ private async load(): Promise<void> {
108
+ this.seen.clear();
109
+ for (const t of TABLES) {
110
+ const m = this.map(t);
111
+ m.clear();
112
+ let after: string | undefined;
113
+ for (;;) {
114
+ const page = await this.client.stateList([...this.root, t], { after, limit: 500 });
115
+ for (const it of page) {
116
+ const v: Row = { ...(it.value as Row) };
117
+ for (const f of DATE_FIELDS) {
118
+ const d = v[f];
119
+ if (typeof d === "string") v[f] = new Date(d);
120
+ }
121
+ m.set(it.key, v);
122
+ this.seen.set(`${t}\u0000${it.key}`, { json: JSON.stringify(it.value), version: it.version });
123
+ }
124
+ if (page.length < 500) break;
125
+ after = page[page.length - 1].key;
126
+ }
127
+ }
128
+ }
129
+
130
+ private async persist(): Promise<void> {
131
+ const live = new Set<string>();
132
+ for (const t of TABLES) {
133
+ for (const [k, v] of this.map(t)) {
134
+ const id = `${t}\u0000${k}`;
135
+ live.add(id);
136
+ const json = JSON.stringify(v);
137
+ const prev = this.seen.get(id);
138
+ if (prev?.json === json) continue;
139
+ try {
140
+ await this.client.statePut({
141
+ namespace: [...this.root, t],
142
+ key: k,
143
+ value: JSON.parse(json),
144
+ expected_version: prev?.version ?? 0,
145
+ index: false,
146
+ });
147
+ } catch (e) {
148
+ if (e instanceof OliviaDbError && e.status === 409)
149
+ throw new OliviaDbConflictError(`${t} ${k} was changed by another process: retry`);
150
+ throw e;
151
+ }
152
+ }
153
+ }
154
+ for (const id of this.seen.keys()) {
155
+ if (live.has(id)) continue;
156
+ const [t, k] = id.split("\u0000");
157
+ await this.client.stateDelete([...this.root, t], k);
158
+ }
159
+ }
160
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.