@friggframework/core 2.0.0--canary.461.849e166.0 → 2.0.0--canary.474.aa465e4.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,198 @@
|
|
|
1
|
+
# MongoDB Transaction Namespace Fix
|
|
2
|
+
|
|
3
|
+
## Problem
|
|
4
|
+
|
|
5
|
+
The encryption health check was failing with the following error:
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
Cannot create namespace frigg.Credential in multi-document transaction.
|
|
9
|
+
Error code: 263
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
### Root Cause
|
|
13
|
+
|
|
14
|
+
MongoDB does not allow creating collections (namespaces) inside multi-document transactions. When Prisma tries to create a document in a collection that doesn't exist yet, MongoDB needs to implicitly create the collection. If this happens inside a transaction context, MongoDB throws error code 263.
|
|
15
|
+
|
|
16
|
+
### Technical Details
|
|
17
|
+
|
|
18
|
+
- **MongoDB Constraint**: Collections must exist before being used in multi-document transactions
|
|
19
|
+
- **Prisma Behavior**: Prisma may implicitly use transactions for certain operations
|
|
20
|
+
- **Impact**: Health checks fail on fresh databases or when collections haven't been created yet
|
|
21
|
+
|
|
22
|
+
## Solution
|
|
23
|
+
|
|
24
|
+
**Implemented a comprehensive schema initialization system that ensures all collections exist at application startup.**
|
|
25
|
+
|
|
26
|
+
### Architectural Approach
|
|
27
|
+
|
|
28
|
+
Rather than checking before each individual database operation, we take a **systematic, fail-fast approach**:
|
|
29
|
+
|
|
30
|
+
1. **Parse Prisma Schema**: Extract all collection names from the Prisma schema definition
|
|
31
|
+
2. **Initialize at Startup**: Create all collections when the database connection is established
|
|
32
|
+
3. **Fail Fast**: If there are database issues, the application fails immediately at startup rather than during runtime operations
|
|
33
|
+
4. **Idempotent**: Safe to run multiple times - only creates collections that don't exist
|
|
34
|
+
|
|
35
|
+
This follows the **"fail fast"** principle and ensures consistent state across all application instances.
|
|
36
|
+
|
|
37
|
+
### Changes Made
|
|
38
|
+
|
|
39
|
+
1. **Created MongoDB Schema Initialization** (`packages/core/database/utils/mongodb-schema-init.js`)
|
|
40
|
+
- `initializeMongoDBSchema()` - Ensures all Prisma collections exist at startup
|
|
41
|
+
- `getPrismaCollections()` - Returns list of all Prisma collection names
|
|
42
|
+
- `PRISMA_COLLECTIONS` - Constant array of all 13 Prisma collections
|
|
43
|
+
- Only runs for MongoDB (skips PostgreSQL)
|
|
44
|
+
- Fails fast if database not connected
|
|
45
|
+
|
|
46
|
+
2. **Created MongoDB Collection Utilities** (`packages/core/database/utils/mongodb-collection-utils.js`)
|
|
47
|
+
- `ensureCollectionExists(collectionName)` - Ensures a single collection exists
|
|
48
|
+
- `ensureCollectionsExist(collectionNames)` - Batch creates multiple collections
|
|
49
|
+
- `collectionExists(collectionName)` - Checks if a collection exists
|
|
50
|
+
- Handles race conditions gracefully (NamespaceExists errors)
|
|
51
|
+
|
|
52
|
+
3. **Integrated into Database Connection** (`packages/core/database/prisma.js`)
|
|
53
|
+
- Modified `connectPrisma()` to call `initializeMongoDBSchema()` after connection
|
|
54
|
+
- Ensures all collections exist before application handles requests
|
|
55
|
+
|
|
56
|
+
4. **Updated Health Check Repository** (`packages/core/database/repositories/health-check-repository-mongodb.js`)
|
|
57
|
+
- Removed per-operation collection existence checks
|
|
58
|
+
- Added documentation noting schema is initialized at startup
|
|
59
|
+
|
|
60
|
+
5. **Added Comprehensive Tests**
|
|
61
|
+
- `mongodb-schema-init.test.js` - Tests schema initialization system
|
|
62
|
+
- `mongodb-collection-utils.test.js` - Tests collection utility functions
|
|
63
|
+
- Tests error handling, race conditions, and edge cases
|
|
64
|
+
|
|
65
|
+
### Implementation Flow
|
|
66
|
+
|
|
67
|
+
```javascript
|
|
68
|
+
// 1. Application startup - connect to database
|
|
69
|
+
await connectPrisma();
|
|
70
|
+
└─> await initializeMongoDBSchema();
|
|
71
|
+
└─> await ensureCollectionsExist([
|
|
72
|
+
'User', 'Token', 'Credential', 'Entity',
|
|
73
|
+
'Integration', 'IntegrationMapping', 'Process',
|
|
74
|
+
'Sync', 'DataIdentifier', 'Association',
|
|
75
|
+
'AssociationObject', 'State', 'WebsocketConnection'
|
|
76
|
+
]);
|
|
77
|
+
|
|
78
|
+
// 2. Now all collections exist - safe to handle requests
|
|
79
|
+
// No per-operation checks needed!
|
|
80
|
+
await prisma.credential.create({ data: {...} }); // Works without namespace error
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Best Practices Followed
|
|
84
|
+
|
|
85
|
+
1. **Domain-Driven Design**: Created reusable utility module for MongoDB-specific concerns
|
|
86
|
+
2. **Hexagonal Architecture**: Infrastructure concerns (schema initialization) handled in infrastructure layer
|
|
87
|
+
3. **Test-Driven Development**: Added comprehensive tests for all utility functions
|
|
88
|
+
4. **Fail Fast Principle**: Database issues discovered at startup, not during runtime
|
|
89
|
+
5. **Idempotency**: Safe to run multiple times across multiple instances
|
|
90
|
+
6. **Error Handling**: Graceful degradation on race conditions and errors
|
|
91
|
+
7. **Documentation**: Inline comments, JSDoc, and comprehensive documentation
|
|
92
|
+
|
|
93
|
+
## Benefits
|
|
94
|
+
|
|
95
|
+
### Immediate Benefits
|
|
96
|
+
- ✅ Fixes encryption health check failures on fresh databases
|
|
97
|
+
- ✅ Prevents transaction namespace errors across **all** Prisma operations
|
|
98
|
+
- ✅ No per-operation overhead - collections created once at startup
|
|
99
|
+
- ✅ Fail fast - database issues discovered immediately at startup
|
|
100
|
+
- ✅ Idempotent - safe to run multiple times and across multiple instances
|
|
101
|
+
|
|
102
|
+
### Architectural Benefits
|
|
103
|
+
- ✅ **Clean separation of concerns**: Schema initialization is infrastructure concern, handled at startup
|
|
104
|
+
- ✅ **Follows DDD/Hexagonal Architecture**: Infrastructure layer handles database setup, repositories focus on business operations
|
|
105
|
+
- ✅ **Consistent across all environments**: Dev, test, staging, production all follow same pattern
|
|
106
|
+
- ✅ **No repository-level checks needed**: All repositories benefit automatically
|
|
107
|
+
- ✅ **Well-tested and documented**: Comprehensive test coverage and documentation
|
|
108
|
+
|
|
109
|
+
### Operational Benefits
|
|
110
|
+
- ✅ **Predictable startup**: Clear logging of schema initialization
|
|
111
|
+
- ✅ **Zero runtime overhead**: Collections created once, not on every operation
|
|
112
|
+
- ✅ **Production-ready**: Handles race conditions, errors, and edge cases gracefully
|
|
113
|
+
|
|
114
|
+
## Design Decisions
|
|
115
|
+
|
|
116
|
+
### Why Initialize at Startup?
|
|
117
|
+
|
|
118
|
+
We considered two approaches:
|
|
119
|
+
|
|
120
|
+
**❌ Per-Operation Checks (Initial approach)**
|
|
121
|
+
```javascript
|
|
122
|
+
async createCredential(data) {
|
|
123
|
+
await ensureCollectionExists('Credential'); // Check every time
|
|
124
|
+
return await prisma.credential.create({ data });
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
- Pros: Guarantees collection exists before each operation
|
|
128
|
+
- Cons: Runtime overhead, repeated checks, scattered logic
|
|
129
|
+
|
|
130
|
+
**✅ Startup Initialization (Final approach)**
|
|
131
|
+
```javascript
|
|
132
|
+
// Once at startup
|
|
133
|
+
await connectPrisma(); // Initializes all collections
|
|
134
|
+
|
|
135
|
+
// All operations just work
|
|
136
|
+
async createCredential(data) {
|
|
137
|
+
return await prisma.credential.create({ data }); // No checks needed
|
|
138
|
+
}
|
|
139
|
+
```
|
|
140
|
+
- Pros: Zero runtime overhead, centralized logic, fail fast, consistent
|
|
141
|
+
- Cons: Requires database connection at startup (already required)
|
|
142
|
+
|
|
143
|
+
### Benefits of Startup Approach
|
|
144
|
+
|
|
145
|
+
1. **Performance**: Collections created once vs. checking before every operation
|
|
146
|
+
2. **Simplicity**: No conditional logic in repositories
|
|
147
|
+
3. **Reliability**: Fail fast at startup if database has issues
|
|
148
|
+
4. **Maintainability**: Single source of truth for schema initialization
|
|
149
|
+
5. **DDD Alignment**: Infrastructure concerns handled in infrastructure layer
|
|
150
|
+
|
|
151
|
+
## Logging Output
|
|
152
|
+
|
|
153
|
+
When the application starts, you'll see clear logging:
|
|
154
|
+
|
|
155
|
+
```
|
|
156
|
+
Initializing MongoDB schema - ensuring all collections exist...
|
|
157
|
+
Created MongoDB collection: Credential
|
|
158
|
+
MongoDB schema initialization complete - 13 collections verified (45ms)
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
On subsequent startups (collections already exist):
|
|
162
|
+
```
|
|
163
|
+
Initializing MongoDB schema - ensuring all collections exist...
|
|
164
|
+
MongoDB schema initialization complete - 13 collections verified (12ms)
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
## References
|
|
168
|
+
|
|
169
|
+
- [Prisma Issue #8305](https://github.com/prisma/prisma/issues/8305) - MongoDB "Cannot create namespace" error
|
|
170
|
+
- [Mongoose Issue #6699](https://github.com/Automattic/mongoose/issues/6699) - Similar issue in Mongoose
|
|
171
|
+
- [MongoDB Transactions Documentation](https://www.mongodb.com/docs/manual/core/transactions/#transactions-and-operations) - Operations allowed in transactions
|
|
172
|
+
- [Prisma MongoDB Guide](https://www.prisma.io/docs/guides/database/mongodb) - Using Prisma with MongoDB
|
|
173
|
+
|
|
174
|
+
## Future Considerations
|
|
175
|
+
|
|
176
|
+
### Automatic Schema Sync
|
|
177
|
+
Consider enhancing the system to:
|
|
178
|
+
- Parse Prisma schema file dynamically to extract collection names
|
|
179
|
+
- Auto-detect schema changes and create new collections
|
|
180
|
+
- Provide CLI command for manual schema initialization
|
|
181
|
+
|
|
182
|
+
### Migration Support
|
|
183
|
+
For production deployments with existing data:
|
|
184
|
+
- Document migration procedures for new collections
|
|
185
|
+
- Consider pre-migration scripts for blue-green deployments
|
|
186
|
+
- Add health check for schema initialization status
|
|
187
|
+
|
|
188
|
+
### Multi-Database Support
|
|
189
|
+
The system already handles:
|
|
190
|
+
- ✅ MongoDB - Full schema initialization
|
|
191
|
+
- ✅ PostgreSQL - Skips initialization (uses Prisma migrations)
|
|
192
|
+
- Consider adding explicit migration support for DocumentDB-specific features
|
|
193
|
+
|
|
194
|
+
### Index Creation
|
|
195
|
+
Future enhancement could also create indexes at startup:
|
|
196
|
+
- Parse Prisma schema for `@@index` directives
|
|
197
|
+
- Create indexes if they don't exist
|
|
198
|
+
- Provide index health checks
|
|
@@ -18,12 +18,9 @@ const chalk = require('chalk');
|
|
|
18
18
|
function getPrismaSchemaPath(dbType, projectRoot = process.cwd()) {
|
|
19
19
|
// Try multiple locations for the schema file
|
|
20
20
|
// Priority order:
|
|
21
|
-
// 1.
|
|
22
|
-
// 2.
|
|
23
|
-
// 3. Parent node_modules (workspace/monorepo setup)
|
|
21
|
+
// 1. Local node_modules (where @friggframework/core is installed - production scenario)
|
|
22
|
+
// 2. Parent node_modules (workspace/monorepo setup)
|
|
24
23
|
const possiblePaths = [
|
|
25
|
-
// Lambda layer path - this is where the schema actually exists in deployed Lambda
|
|
26
|
-
`/opt/nodejs/node_modules/generated/prisma-${dbType}/schema.prisma`,
|
|
27
24
|
// Check where Frigg is installed via npm (production scenario)
|
|
28
25
|
path.join(projectRoot, 'node_modules', '@friggframework', 'core', `prisma-${dbType}`, 'schema.prisma'),
|
|
29
26
|
path.join(projectRoot, '..', 'node_modules', '@friggframework', 'core', `prisma-${dbType}`, 'schema.prisma')
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@friggframework/core",
|
|
3
3
|
"prettier": "@friggframework/prettier-config",
|
|
4
|
-
"version": "2.0.0--canary.
|
|
4
|
+
"version": "2.0.0--canary.474.aa465e4.0",
|
|
5
5
|
"dependencies": {
|
|
6
6
|
"@aws-sdk/client-apigatewaymanagementapi": "^3.588.0",
|
|
7
7
|
"@aws-sdk/client-kms": "^3.588.0",
|
|
@@ -38,9 +38,9 @@
|
|
|
38
38
|
}
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
|
-
"@friggframework/eslint-config": "2.0.0--canary.
|
|
42
|
-
"@friggframework/prettier-config": "2.0.0--canary.
|
|
43
|
-
"@friggframework/test": "2.0.0--canary.
|
|
41
|
+
"@friggframework/eslint-config": "2.0.0--canary.474.aa465e4.0",
|
|
42
|
+
"@friggframework/prettier-config": "2.0.0--canary.474.aa465e4.0",
|
|
43
|
+
"@friggframework/test": "2.0.0--canary.474.aa465e4.0",
|
|
44
44
|
"@prisma/client": "^6.17.0",
|
|
45
45
|
"@types/lodash": "4.17.15",
|
|
46
46
|
"@typescript-eslint/eslint-plugin": "^8.0.0",
|
|
@@ -80,5 +80,5 @@
|
|
|
80
80
|
"publishConfig": {
|
|
81
81
|
"access": "public"
|
|
82
82
|
},
|
|
83
|
-
"gitHead": "
|
|
83
|
+
"gitHead": "aa465e49207b1725bc36827e65efdd54ad879337"
|
|
84
84
|
}
|