-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
421 lines (377 loc) · 12.8 KB
/
server.ts
File metadata and controls
421 lines (377 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
import * as path from 'path'
import express from 'express'
import cors from 'cors'
import { ZenStackMiddleware } from '@zenstackhq/server/express'
import { ZModelConfig } from './zmodel-parser'
import { getNodeModulesFolder, getPrismaVersion, getZenStackVersion } from './utils/version-utils'
import { blue, grey, red } from 'colors'
import semver from 'semver'
import { CliError } from './cli-error'
import SuperJSON from 'superjson'
export interface ServerOptions {
zenstackPath: string | undefined
port: number
zmodelConfig: ZModelConfig
zmodelSchemaDir: string
logLevel?: string[]
}
type EnhancementKind = 'password' | 'omit' | 'policy' | 'validation' | 'delegate' | 'encryption'
// enable all enhancements except policy
const Enhancements: EnhancementKind[] = ['password', 'omit', 'validation', 'delegate', 'encryption']
const VALID_OPS = new Set([
'findMany',
'findUnique',
'findFirst',
'create',
'createMany',
'createManyAndReturn',
'update',
'updateMany',
'updateManyAndReturn',
'upsert',
'delete',
'deleteMany',
'count',
'aggregate',
'groupBy',
'exists',
])
/**
* Resolve the absolute path to the Prisma schema directory
*/
function resolvePrismaSchemaDir(config: ZModelConfig, zmodelSchemaDir: string): string {
if (!config.prismaSchemaPath) {
// Default: prisma directory relative to zmodel schema dir
return path.join(zmodelSchemaDir, './prisma')
}
if (path.isAbsolute(config.prismaSchemaPath)) {
// Already absolute, use as is
return path.dirname(config.prismaSchemaPath)
}
// Relative to zmodel schema dir
return path.dirname(path.join(zmodelSchemaDir, config.prismaSchemaPath))
}
/**
* Resolve SQLite file URL to absolute path
*/
function resolveSQLitePath(filePath: string, prismaSchemaDir: string): string {
// If already absolute, return as is
if (path.isAbsolute(filePath)) {
return filePath
}
// Convert relative path to absolute, relative to prisma schema directory
return path.join(prismaSchemaDir, filePath)
}
function redactDatabaseUrl(url: string): string {
try {
const parsedUrl = new URL(url)
if (parsedUrl.password) {
parsedUrl.password = '***'
}
if (parsedUrl.username) {
parsedUrl.username = '***'
}
return parsedUrl.toString()
} catch {
// If URL parsing fails, return the original (might be a file path for SQLite)
return url
}
}
/**
* Create database adapter based on provider
*/
function createAdapter(config: ZModelConfig, zmodelSchemaDir: string): any {
const { provider, url } = config.datasource
switch (provider) {
case 'sqlite': {
try {
// Check if URL is already absolute, otherwise resolve relative paths
let resolvedUrl = url.trim()
if (resolvedUrl.startsWith('file:')) {
const filePath = resolvedUrl.substring(5)
if (!path.isAbsolute(filePath)) {
// Only resolve prisma schema dir if needed for relative paths
const prismaSchemaDir = resolvePrismaSchemaDir(config, zmodelSchemaDir)
resolvedUrl = `file:${resolveSQLitePath(filePath, prismaSchemaDir)}`
}
}
const { PrismaBetterSQLite3 } = require('@prisma/adapter-better-sqlite3')
console.log(grey(`Connecting to SQLite database at: ${resolvedUrl}`))
return new PrismaBetterSQLite3({
url: resolvedUrl,
})
} catch (error) {
throw new CliError(
'SQLite adapter dependencies not found. Install with: npm install better-sqlite3 @prisma/adapter-better-sqlite3'
)
}
}
case 'postgresql': {
try {
const { PrismaPg } = require('@prisma/adapter-pg')
console.log(grey(`Connecting to PostgreSQL database at: ${redactDatabaseUrl(url)}`))
return new PrismaPg({ connectionString: url })
} catch (error) {
throw new CliError(
'PostgreSQL adapter dependencies not found. Install with: npm install pg @prisma/adapter-pg'
)
}
}
case 'mysql': {
try {
const { PrismaMariaDB } = require('@prisma/adapter-mariadb')
console.log(grey(`Connecting to MySQL/MariaDB database at: ${redactDatabaseUrl(url)}`))
return new PrismaMariaDB({
url,
})
} catch (error) {
throw new CliError(
'MySQL/MariaDB adapter dependencies not found. Install with: npm install mariadb @prisma/adapter-mariadb'
)
}
}
default:
throw new CliError(`Unsupported database provider: ${provider}`)
}
}
/**
* Loads PrismaClient, ModelMeta, enhance, and Enum modules for ZenStack
*/
async function loadZenStackModules(
zmodelConfig: ZModelConfig,
zmodelSchemaDir: string,
zenstackPath?: string
) {
// Register tsx to handle .ts files
require('tsx/cjs/api').register()
// Load ZenStack modules
let modelMeta: any
let enums: any
// Load Prisma Client - either from custom output or default @prisma/client
let PrismaClient: any
let enhanceFunc: any
const generator = zmodelConfig.generator
if (generator.output) {
// Use custom output path - resolve relative to zmodel schema file directory
const prismaClientPath = path.isAbsolute(generator.output)
? path.join(generator.output, 'client')
: path.join(resolvePrismaSchemaDir(zmodelConfig, zmodelSchemaDir), generator.output, 'client')
console.log(grey(`Loading Prisma client from: ${prismaClientPath}`))
let prismaModule
try {
prismaModule = require(prismaClientPath)
} catch (err) {
throw new CliError(
`Failed to load Prisma client module from custom output path: ${prismaClientPath}. ` +
`Please ensure the Prisma client has been generated by running 'prisma generate'.`
)
}
PrismaClient = prismaModule.PrismaClient
enums = prismaModule.$Enums || {}
} else {
// Use default @prisma/client - will now resolve from project's node_modules
// Add the first node_modules directory up from zmodelSchemaDir for pnpm monorepo
let foundNodeModules = getNodeModulesFolder(zmodelSchemaDir)
if (foundNodeModules && !module.paths.includes(foundNodeModules)) {
module.paths.unshift(foundNodeModules)
}
console.log(grey(`Loading Prisma client from: @prisma/client`))
const prismaModule = require('@prisma/client')
PrismaClient = prismaModule.PrismaClient
enums = prismaModule.$Enums || {}
}
const zenstackAbsPath = zenstackPath
? path.isAbsolute(zenstackPath)
? zenstackPath
: path.join(process.cwd(), zenstackPath)
: undefined
try {
if (zenstackAbsPath) {
modelMeta = require(path.join(zenstackAbsPath, 'model-meta')).default
enhanceFunc = require(path.join(zenstackAbsPath, 'enhance')).enhance
} else {
modelMeta = require('@zenstackhq/runtime/model-meta').default
enhanceFunc = require('@zenstackhq/runtime').enhance
}
} catch {
throw new CliError(
`Failed to load ZenStack generated model meta from: ${zenstackAbsPath || '@zenstackhq/runtime'}\n` +
`Please run \`zenstack generate\` first or specify the correct output directory of ZenStack generated modules using the \`-z\` option.`
)
}
if (!modelMeta.models) {
throw new CliError(`Generated model meta not found. Please run \`zenstack generate\` first.`)
}
const zenstackVersion = getZenStackVersion()
return { PrismaClient, modelMeta, enums, zenstackVersion, enhanceFunc }
}
function makeError(message: string, status = 400) {
return { status, body: { error: message } }
}
function lowerCaseFirst(input: string) {
return input.charAt(0).toLowerCase() + input.slice(1)
}
function isValidModel(modelMeta: any, modelName: string): boolean {
return lowerCaseFirst(modelName) in modelMeta.models
}
function processRequestPayload(args: any) {
if (args === null || args === undefined) {
return args
}
const { meta, ...rest } = args
if (meta?.serialization) {
// superjson deserialization
return SuperJSON.deserialize({ json: rest, meta: meta.serialization })
} else {
return args
}
}
async function handleTransaction(modelMeta: any, client: any, requestBody: unknown) {
const processedOps: Array<{ model: string; op: string; args: unknown }> = []
if (!requestBody || !Array.isArray(requestBody) || requestBody.length === 0) {
return makeError('request body must be a non-empty array of operations')
}
for (let i = 0; i < requestBody.length; i++) {
const item = requestBody[i]
if (!item || typeof item !== 'object') {
return makeError(`operation at index ${i} must be an object`)
}
const { model: itemModel, op: itemOp, args: itemArgs } = item as any
if (!itemModel || typeof itemModel !== 'string') {
return makeError(`operation at index ${i} is missing a valid "model" field`)
}
if (!itemOp || typeof itemOp !== 'string') {
return makeError(`operation at index ${i} is missing a valid "op" field`)
}
if (!VALID_OPS.has(itemOp)) {
return makeError(`operation at index ${i} has invalid op: ${itemOp}`)
}
if (!isValidModel(modelMeta, itemModel)) {
return makeError(`operation at index ${i} has unknown model: ${itemModel}`)
}
if (
itemArgs !== undefined &&
itemArgs !== null &&
(typeof itemArgs !== 'object' || Array.isArray(itemArgs))
) {
return makeError(`operation at index ${i} has invalid "args" field`)
}
processedOps.push({
model: lowerCaseFirst(itemModel),
op: itemOp,
args: processRequestPayload(itemArgs),
})
}
try {
const clientResult = await client.$transaction(async (tx: any) => {
const result: any[] = []
for (const { model, op, args } of processedOps) {
result.push(await (tx as any)[model][op](args))
}
return result
})
const { json, meta } = SuperJSON.serialize(clientResult)
const responseBody: any = { data: json }
if (meta) {
responseBody.meta = { serialization: meta }
}
const response = { status: 200, body: responseBody }
return response
} catch (err) {
console.error('error occurred when handling "$transaction" request:', err)
return makeError(
'Transaction failed: ' + (err instanceof Error ? err.message : String(err)),
500
)
}
}
/**
* Start the Express server with ZenStack proxy
*/
export async function startServer(options: ServerOptions) {
const { zenstackPath, port, zmodelConfig, zmodelSchemaDir } = options
const { PrismaClient, modelMeta, enums, zenstackVersion, enhanceFunc } =
await loadZenStackModules(zmodelConfig, zmodelSchemaDir, zenstackPath)
const prismaVersion = getPrismaVersion()
const isPrisma7 = prismaVersion ? semver.gte(prismaVersion, '7.0.0') : false
const isClientEngine = isPrisma7 || zmodelConfig.generator.engineType === 'client'
const prisma = new PrismaClient({
adapter: isClientEngine ? createAdapter(zmodelConfig, zmodelSchemaDir) : null,
log: options.logLevel || [],
})
// Explicitly check the connection by running a simple query
try {
await prisma.$queryRaw`SELECT 1`
} catch (err) {
throw new CliError('Database connection failed: ' + err)
}
const app = express()
app.use(cors())
app.use(express.json({ limit: '5mb' }))
app.use(express.urlencoded({ extended: true, limit: '5mb' }))
// ZenStack API endpoint
app.post('/api/model/\\$transaction/sequential', async (_req, res) => {
const response = await handleTransaction(
modelMeta,
enhanceFunc(
prisma,
{},
{
kinds: Enhancements,
}
),
_req.body
)
res.status(response.status).json(response.body)
})
app.use(
'/api/model',
ZenStackMiddleware({
getPrisma: () => {
return enhanceFunc(
prisma,
{},
{
kinds: Enhancements,
}
)
},
})
)
// Schema metadata endpoint
app.get('/api/schema', (_req, res: express.Response) => {
const result = { ...modelMeta, enums: enums, zenstackVersion }
res.json(result)
})
const server = app.listen(port, () => {
console.log(`ZenStack proxy server is running on port: ${port}`)
console.log(`ZenStack Studio is running at: ${blue('https://studio.zenstack.dev')}`)
})
server.on('error', (err: NodeJS.ErrnoException) => {
if (err.code === 'EADDRINUSE') {
console.error(
red(
`Port ${options.port} is already in use. Please choose a different port using -p option.`
)
)
} else {
throw new CliError(`Failed to start the server: ${err.message}`)
}
process.exit(1)
})
// Graceful shutdown
process.on('SIGTERM', async () => {
server.close(() => {
console.log('\nZenStack proxy server closed')
})
await prisma.$disconnect()
process.exit(0)
})
process.on('SIGINT', async () => {
server.close(() => {
console.log('\nZenStack proxy server closed')
})
await prisma.$disconnect()
process.exit(0)
})
}