@aventoapp/framework 0.2.1 → 0.2.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.
@@ -0,0 +1,109 @@
1
+ // src/server/db/mongo.js
2
+ import mongoose from "mongoose";
3
+ var MongoConnection = class {
4
+ constructor(config = {}) {
5
+ this.config = {
6
+ host: config.host || process.env.MONGO_HOST || "localhost",
7
+ port: config.port || process.env.MONGO_PORT || 27017,
8
+ database: config.database || process.env.MONGO_DB || "avento",
9
+ user: config.user || process.env.MONGO_USER || "",
10
+ password: config.password || process.env.MONGO_PASSWORD || "",
11
+ options: config.options || {}
12
+ };
13
+ this.connection = null;
14
+ }
15
+ /**
16
+ * Build MongoDB connection URI
17
+ */
18
+ _buildUri() {
19
+ const { host, port, database, user, password } = this.config;
20
+ if (user && password) {
21
+ return `mongodb://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${host}:${port}/${database}`;
22
+ }
23
+ return `mongodb://${host}:${port}/${database}`;
24
+ }
25
+ /**
26
+ * Connect to MongoDB
27
+ */
28
+ async connect() {
29
+ if (this.connection && this.connection.readyState === 1) {
30
+ return this.connection;
31
+ }
32
+ const uri = this.config.uri || this._buildUri();
33
+ const options = {
34
+ maxPoolSize: 10,
35
+ serverSelectionTimeoutMS: 5e3,
36
+ socketTimeoutMS: 45e3,
37
+ ...this.config.options
38
+ };
39
+ try {
40
+ this.connection = await mongoose.connect(uri, options);
41
+ console.log(`[MongoDB] Connected to ${this.config.host}:${this.config.port}/${this.config.database}`);
42
+ mongoose.connection.on("error", (err) => {
43
+ console.error("[MongoDB] Connection error:", err);
44
+ });
45
+ mongoose.connection.on("disconnected", () => {
46
+ console.log("[MongoDB] Disconnected");
47
+ });
48
+ return this.connection;
49
+ } catch (err) {
50
+ console.error("[MongoDB] Connection failed:", err.message);
51
+ throw err;
52
+ }
53
+ }
54
+ /**
55
+ * Get the Mongoose connection
56
+ */
57
+ getConnection() {
58
+ return mongoose.connection;
59
+ }
60
+ /**
61
+ * Get or create a model (with tenant scoping support)
62
+ * @param {string} name - Model name
63
+ * @param {Object} schema - Mongoose schema definition
64
+ * @param {Object} options - Schema options
65
+ */
66
+ createModel(name, schemaDefinition, options = {}) {
67
+ const tenantedSchema = {
68
+ tenant_id: {
69
+ type: mongoose.Schema.Types.ObjectId,
70
+ required: true,
71
+ index: true
72
+ },
73
+ ...schemaDefinition
74
+ };
75
+ const schema = new mongoose.Schema(tenantedSchema, {
76
+ timestamps: { createdAt: "created_at", updatedAt: "updated_at" },
77
+ ...options
78
+ });
79
+ schema.index({ tenant_id: 1, created_at: -1 });
80
+ return mongoose.model(name, schema);
81
+ }
82
+ /**
83
+ * Disconnect from MongoDB
84
+ */
85
+ async disconnect() {
86
+ if (mongoose.connection.readyState !== 0) {
87
+ await mongoose.disconnect();
88
+ this.connection = null;
89
+ console.log("[MongoDB] Disconnected");
90
+ }
91
+ }
92
+ };
93
+ var defaultConnection = null;
94
+ function getMongoConnection(config) {
95
+ if (!defaultConnection) {
96
+ defaultConnection = new MongoConnection(config);
97
+ }
98
+ return defaultConnection;
99
+ }
100
+ function createMongoConnection(config) {
101
+ return new MongoConnection(config);
102
+ }
103
+ export {
104
+ MongoConnection,
105
+ createMongoConnection,
106
+ getMongoConnection,
107
+ mongoose
108
+ };
109
+ //# sourceMappingURL=mongo.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/server/db/mongo.js"],
4
+ "sourcesContent": ["import mongoose from 'mongoose';\n\n/**\n * MongoDB connection manager using Mongoose\n */\nexport class MongoConnection {\n constructor(config = {}) {\n this.config = {\n host: config.host || process.env.MONGO_HOST || 'localhost',\n port: config.port || process.env.MONGO_PORT || 27017,\n database: config.database || process.env.MONGO_DB || 'avento',\n user: config.user || process.env.MONGO_USER || '',\n password: config.password || process.env.MONGO_PASSWORD || '',\n options: config.options || {}\n };\n\n this.connection = null;\n }\n\n /**\n * Build MongoDB connection URI\n */\n _buildUri() {\n const { host, port, database, user, password } = this.config;\n\n if (user && password) {\n return `mongodb://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${host}:${port}/${database}`;\n }\n\n return `mongodb://${host}:${port}/${database}`;\n }\n\n /**\n * Connect to MongoDB\n */\n async connect() {\n if (this.connection && this.connection.readyState === 1) {\n return this.connection;\n }\n\n const uri = this.config.uri || this._buildUri();\n\n const options = {\n maxPoolSize: 10,\n serverSelectionTimeoutMS: 5000,\n socketTimeoutMS: 45000,\n ...this.config.options\n };\n\n try {\n this.connection = await mongoose.connect(uri, options);\n console.log(`[MongoDB] Connected to ${this.config.host}:${this.config.port}/${this.config.database}`);\n\n // Handle connection events\n mongoose.connection.on('error', (err) => {\n console.error('[MongoDB] Connection error:', err);\n });\n\n mongoose.connection.on('disconnected', () => {\n console.log('[MongoDB] Disconnected');\n });\n\n return this.connection;\n } catch (err) {\n console.error('[MongoDB] Connection failed:', err.message);\n throw err;\n }\n }\n\n /**\n * Get the Mongoose connection\n */\n getConnection() {\n return mongoose.connection;\n }\n\n /**\n * Get or create a model (with tenant scoping support)\n * @param {string} name - Model name\n * @param {Object} schema - Mongoose schema definition\n * @param {Object} options - Schema options\n */\n createModel(name, schemaDefinition, options = {}) {\n // Add tenant_id to all schemas by default\n const tenantedSchema = {\n tenant_id: {\n type: mongoose.Schema.Types.ObjectId,\n required: true,\n index: true\n },\n ...schemaDefinition\n };\n\n const schema = new mongoose.Schema(tenantedSchema, {\n timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' },\n ...options\n });\n\n // Add compound index for tenant + common queries\n schema.index({ tenant_id: 1, created_at: -1 });\n\n return mongoose.model(name, schema);\n }\n\n /**\n * Disconnect from MongoDB\n */\n async disconnect() {\n if (mongoose.connection.readyState !== 0) {\n await mongoose.disconnect();\n this.connection = null;\n console.log('[MongoDB] Disconnected');\n }\n }\n}\n\n// Singleton instance\nlet defaultConnection = null;\n\n/**\n * Get or create the default MongoDB connection\n */\nexport function getMongoConnection(config) {\n if (!defaultConnection) {\n defaultConnection = new MongoConnection(config);\n }\n return defaultConnection;\n}\n\n/**\n * Create a new MongoDB connection\n */\nexport function createMongoConnection(config) {\n return new MongoConnection(config);\n}\n\nexport { mongoose };\n"],
5
+ "mappings": ";AAAA,OAAO,cAAc;AAKd,IAAM,kBAAN,MAAsB;AAAA,EAC3B,YAAY,SAAS,CAAC,GAAG;AACvB,SAAK,SAAS;AAAA,MACZ,MAAM,OAAO,QAAQ,QAAQ,IAAI,cAAc;AAAA,MAC/C,MAAM,OAAO,QAAQ,QAAQ,IAAI,cAAc;AAAA,MAC/C,UAAU,OAAO,YAAY,QAAQ,IAAI,YAAY;AAAA,MACrD,MAAM,OAAO,QAAQ,QAAQ,IAAI,cAAc;AAAA,MAC/C,UAAU,OAAO,YAAY,QAAQ,IAAI,kBAAkB;AAAA,MAC3D,SAAS,OAAO,WAAW,CAAC;AAAA,IAC9B;AAEA,SAAK,aAAa;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA,EAKA,YAAY;AACV,UAAM,EAAE,MAAM,MAAM,UAAU,MAAM,SAAS,IAAI,KAAK;AAEtD,QAAI,QAAQ,UAAU;AACpB,aAAO,aAAa,mBAAmB,IAAI,CAAC,IAAI,mBAAmB,QAAQ,CAAC,IAAI,IAAI,IAAI,IAAI,IAAI,QAAQ;AAAA,IAC1G;AAEA,WAAO,aAAa,IAAI,IAAI,IAAI,IAAI,QAAQ;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,UAAU;AACd,QAAI,KAAK,cAAc,KAAK,WAAW,eAAe,GAAG;AACvD,aAAO,KAAK;AAAA,IACd;AAEA,UAAM,MAAM,KAAK,OAAO,OAAO,KAAK,UAAU;AAE9C,UAAM,UAAU;AAAA,MACd,aAAa;AAAA,MACb,0BAA0B;AAAA,MAC1B,iBAAiB;AAAA,MACjB,GAAG,KAAK,OAAO;AAAA,IACjB;AAEA,QAAI;AACF,WAAK,aAAa,MAAM,SAAS,QAAQ,KAAK,OAAO;AACr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,SAAO;AACT;AAKO,SAAS,sBAAsB,QAAQ;AAC5C,SAAO,IAAI,gBAAgB,MAAM;AACnC;",
6
+ "names": []
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aventoapp/framework",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "type": "module",
5
5
  "description": "Avento framework - server and web modules for multi-tenant SaaS apps",
6
6
  "repository": {
@@ -12,6 +12,7 @@
12
12
  "exports": {
13
13
  ".": "./dist/index.js",
14
14
  "./server": "./dist/server/index.js",
15
+ "./server/mongo": "./dist/server/mongo.js",
15
16
  "./server/workflow": "./dist/server/workflow/index.js",
16
17
  "./web": "./dist/web/index.js",
17
18
  "./shared": "./dist/shared/index.js",
@@ -34,14 +35,9 @@
34
35
  "clean": "rm -rf dist"
35
36
  },
36
37
  "dependencies": {
37
- "@emotion/react": "^11.11.0",
38
- "@emotion/styled": "^11.11.0",
39
- "@mui/icons-material": "^5.15.0",
40
- "@mui/material": "^5.15.0",
41
38
  "bcrypt": "^5.1.1",
42
39
  "express": "^4.18.2",
43
40
  "jsonwebtoken": "^9.0.2",
44
- "mongoose": "^8.0.0",
45
41
  "nodemailer": "^6.9.0",
46
42
  "passport": "^0.7.0",
47
43
  "passport-jwt": "^4.0.1",
@@ -53,7 +49,8 @@
53
49
  },
54
50
  "devDependencies": {
55
51
  "esbuild": "^0.19.0",
56
- "fake-indexeddb": "^6.0.0"
52
+ "fake-indexeddb": "^6.0.0",
53
+ "mongoose": "^8.0.0"
57
54
  },
58
55
  "peerDependencies": {
59
56
  "react": "^18.0.0",
@@ -5,10 +5,10 @@ export {
5
5
  createPostgresConnection
6
6
  } from './postgres.js';
7
7
 
8
- // Re-export all from mongo
9
- export {
10
- MongoConnection,
11
- getMongoConnection,
12
- createMongoConnection,
13
- mongoose
14
- } from './mongo.js';
8
+ // The Mongo helpers (MongoConnection, getMongoConnection,
9
+ // createMongoConnection, mongoose) are NOT re-exported here: db/mongo.js
10
+ // imports mongoose at its top, and this barrel is part of
11
+ // @aventoapp/framework/server, so every importer paid ~300 ms and ~15 MB at
12
+ // boot for it, Mongo user or not (vector#6334). Import them from
13
+ // '@aventoapp/framework/server/mongo', with mongoose installed beside it
14
+ // (the framework does not install it).
@@ -0,0 +1,10 @@
1
+ // @aventoapp/framework/server/mongo
2
+ // The Mongo helpers, kept out of the /server barrel so importing /server does
3
+ // not load mongoose (vector#6334). Install mongoose beside the framework to use
4
+ // them: the framework does not install it.
5
+ export {
6
+ MongoConnection,
7
+ getMongoConnection,
8
+ createMongoConnection,
9
+ mongoose
10
+ } from './db/mongo.js';
@@ -1,5 +1,6 @@
1
1
  // Per-field last-write-wins resolution for offline replays.
2
- // Pure builder (testable) + a thin applyFieldLWW that does the DB round-trip.
2
+ // Pure builder (testable) + applyFieldLWW, which does the DB round-trip under a
3
+ // row lock it takes itself (vector#3540).
3
4
 
4
5
  export function buildFieldLWWUpdate({ fields, fieldTimes = {}, storedFieldTs = {} }) {
5
6
  const winners = {};
@@ -15,16 +16,58 @@ export function buildFieldLWWUpdate({ fields, fieldTimes = {}, storedFieldTs = {
15
16
  return { winners, nextFieldTs };
16
17
  }
17
18
 
18
- export async function applyFieldLWW(db, {
19
- table, id, tenantId, fields, fieldTimes,
20
- idCol = 'id', tenantCol = 'tenant_id', fieldTsCol = 'field_ts',
21
- }) {
19
+ // applyFieldLWW reads field_ts and then writes it. Two replays of one record
20
+ // racing between those statements would each build field_ts from the same
21
+ // read, so the second write drops the first one's stamp and a later stale
22
+ // replay of that field wins. So the read is SELECT ... FOR UPDATE, and it runs
23
+ // inside a transaction that lasts through the UPDATE:
24
+ //
25
+ // - a client already in a transaction: that one. The lock is held until the
26
+ // caller commits; the helper never BEGINs, COMMITs, rolls back or releases.
27
+ // - a client with no transaction open: the helper BEGINs and COMMITs on it
28
+ // (ROLLBACK on error), and leaves it checked out.
29
+ // - a pool (pg.Pool's connect(), or the framework connection's getClient()):
30
+ // the helper checks out a client, runs its own transaction there, and
31
+ // releases it.
32
+ //
33
+ // A handle with only query() cannot hold a transaction across two statements
34
+ // (each query may run on a different connection), so it is refused.
35
+ export async function applyFieldLWW(db, opts) {
36
+ const { table, idCol = 'id', tenantCol = 'tenant_id', fieldTsCol = 'field_ts' } = opts;
22
37
  assertSafeIdent(table);
23
38
  assertSafeIdent(idCol);
24
39
  assertSafeIdent(tenantCol);
25
40
  assertSafeIdent(fieldTsCol);
26
41
 
27
- const readSql = `SELECT ${fieldTsCol} AS field_ts FROM ${table} WHERE ${idCol} = $1 AND ${tenantCol} = $2`;
42
+ if (isClient(db)) {
43
+ if (await inTransaction(db)) return lockedApply(db, opts);
44
+ return inOwnTransaction(db, opts);
45
+ }
46
+ const client = await checkOut(db);
47
+ try {
48
+ return await inOwnTransaction(client, opts);
49
+ } finally {
50
+ client.release();
51
+ }
52
+ }
53
+
54
+ async function inOwnTransaction(client, opts) {
55
+ await client.query('BEGIN');
56
+ try {
57
+ const result = await lockedApply(client, opts);
58
+ await client.query('COMMIT');
59
+ return result;
60
+ } catch (err) {
61
+ await client.query('ROLLBACK').catch(() => {});
62
+ throw err;
63
+ }
64
+ }
65
+
66
+ async function lockedApply(db, {
67
+ table, id, tenantId, fields, fieldTimes,
68
+ idCol = 'id', tenantCol = 'tenant_id', fieldTsCol = 'field_ts',
69
+ }) {
70
+ const readSql = `SELECT ${fieldTsCol} AS field_ts FROM ${table} WHERE ${idCol} = $1 AND ${tenantCol} = $2 FOR UPDATE`;
28
71
  const read = await db.query(readSql, [id, tenantId]);
29
72
  if (read.rows.length === 0) {
30
73
  return { applied: [], skipped: Object.keys(fields), notFound: true };
@@ -58,6 +101,55 @@ export async function applyFieldLWW(db, {
58
101
  return { applied: winnerCols, skipped };
59
102
  }
60
103
 
104
+ // A checked-out pool client has release(); a pg.Client (pooled or not) has
105
+ // getTransactionStatus() from pg 8.20 on, and a processID field in every
106
+ // version. A pool has none of them. A single pg.Client must never reach
107
+ // checkOut(): its connect() opens the socket, it does not hand out a client.
108
+ function isClient(db) {
109
+ return !!db && typeof db.query === 'function'
110
+ && (typeof db.release === 'function'
111
+ || typeof db.getTransactionStatus === 'function'
112
+ || 'processID' in db);
113
+ }
114
+
115
+ async function checkOut(db) {
116
+ let client;
117
+ // The framework's PostgresConnection: connect() initializes and returns its
118
+ // POOL; only getClient() checks a client out. A raw pg.Pool has connect().
119
+ if (db && typeof db.getClient === 'function') client = await db.getClient();
120
+ else if (db && typeof db.connect === 'function') client = await db.connect();
121
+ else {
122
+ throw new TypeError(
123
+ 'applyFieldLWW: pass a client, a pg.Pool or the framework connection. A handle with only '
124
+ + 'query() cannot hold the row lock across the read and the write.',
125
+ );
126
+ }
127
+ if (!client || typeof client.query !== 'function' || typeof client.release !== 'function') {
128
+ throw new TypeError('applyFieldLWW: the handle checked out something with no release(), so not a client.');
129
+ }
130
+ return client;
131
+ }
132
+
133
+ // pg 8.20+ tracks the server's ReadyForQuery status: 'I' idle, 'T' in a
134
+ // transaction, 'E' in a failed one. Older pg has no such method, so ask
135
+ // Postgres: SAVEPOINT is an error outside a transaction block (25P01) and
136
+ // harmless inside one.
137
+ async function inTransaction(client) {
138
+ if (typeof client.getTransactionStatus === 'function') {
139
+ const status = client.getTransactionStatus();
140
+ if (status === 'T' || status === 'E') return true;
141
+ if (status === 'I') return false;
142
+ }
143
+ try {
144
+ await client.query('SAVEPOINT avento_field_lww_probe');
145
+ } catch (err) {
146
+ if (err && err.code === '25P01') return false;
147
+ throw err;
148
+ }
149
+ await client.query('RELEASE SAVEPOINT avento_field_lww_probe');
150
+ return true;
151
+ }
152
+
61
153
  // Column/table names come from server code (never user input), but guard anyway.
62
154
  function assertSafeIdent(name) {
63
155
  if (!/^[a-z_][a-z0-9_]*$/i.test(name)) {