-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
341 lines (314 loc) · 9.73 KB
/
server.ts
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
import type { NextApiRequest, NextApiResponse } from "next";
import type { PrismaClient } from "@prisma/client/extension";
import { Sql } from "sql-template-tag";
import { serialize } from "@ungap/structured-clone";
import { debug as sharedDebug } from "./shared";
/* eslint-disable @typescript-eslint/no-explicit-any */
export type ExtendedPrismaClient = Omit<
PrismaClient,
"$on" | "$use" | "$extends" | "$transaction"
> & { $transaction: (...args: any[]) => Promise<any> };
type TransactionOptions = {
maxWait?: number;
timeout?: number;
};
interface TransactionHandler {
commit: () => Promise<void>;
exec: (args: any) => Promise<any>;
nestedTransaction: (txId: string) => Promise<TransactionHandler>;
}
type Context = {
options: any;
txId: string;
parentTxId?: string;
};
globalThis.isPrismaLocalProxy = true;
const transactionQueue = new Map<string, TransactionHandler>();
function transactionHandler(
prisma: ExtendedPrismaClient,
txid: string,
ctx: Context,
options?: TransactionOptions,
parentTxId?: string
) {
const debug = debugFn(ctx);
let commit: () => Promise<void>,
exec: (args: any) => Promise<any>,
nestedPrismaClient: Promise<ExtendedPrismaClient> = Promise.resolve(prisma);
if (!parentTxId) {
if (!("$transaction" in prisma)) {
// not expected at runtime - just hint for type checking
throw new Error(
"prismaLocalProxy: shouldn't be here, prisma.$transaction() missing"
);
}
let resolvePrismaTxClient: (value: ExtendedPrismaClient) => void,
rejectPrismaTxClient: (reason?: any) => void;
const prismaTxClient = new Promise<ExtendedPrismaClient>(
(resolve, reject) => {
resolvePrismaTxClient = resolve;
rejectPrismaTxClient = reject;
}
);
let resolveInteractiveTxn: (value: unknown) => void;
const resolveInteractiveTxnFn = new Promise((resolve) => {
resolveInteractiveTxn = resolve;
});
let txnException: unknown;
debug(
`transactionHandler: starting $transaction() with options ${JSON.stringify(
options
)}`
);
const tx = prisma
.$transaction((prisma: ExtendedPrismaClient) => {
debug(`$transaction start`);
resolvePrismaTxClient(prisma);
return new Promise((resolve, reject) => {
debug(`$transaction Promise`);
void resolveInteractiveTxnFn
.then((value: unknown) => {
debug(`$transaction Promise resolved`);
resolve(value);
})
.catch((reason: any) => {
debug(`$transaction Promise rejected`);
reject(reason);
});
}) as any;
}, options)
.catch((e) => {
debug(`transactionHandler: exception starting $transaction(): ${e}`);
txnException = e;
rejectPrismaTxClient(e);
});
const ensureNoException = (logInfo: string) => {
if (txnException) {
debug(
`transactionHandler (${logInfo}): throwing exception from $transaction() start: ${txnException}`
);
throw txnException;
}
};
commit = async () => {
debug(`COMMIT!`);
resolveInteractiveTxn(null);
ensureNoException("commit");
await tx;
debug(`transaction closed`);
};
exec = async (body: any) => {
debug(`exec!`);
ensureNoException("exec");
let prisma: Awaited<typeof prismaTxClient>;
try {
debug(`exec: awaiting prismaTxClient`);
prisma = await prismaTxClient;
debug(`exec: successfully awaited prismaTxClient`);
} catch (e) {
debug(`exec error awaiting prismaTxClient: ${e}`);
throw e;
}
return await execQuery(prisma, body);
};
nestedPrismaClient = prismaTxClient;
} else {
commit = async () => {
debug(`nested tx commit - no action taken`);
return Promise.resolve();
};
exec = async (body: any) => {
debug(`nested tx exec!`);
return await execQuery(prisma, body);
};
}
return {
commit,
exec,
nestedTransaction: async (nestedTxId: string) => {
return transactionHandler(
await nestedPrismaClient,
nestedTxId,
ctx,
undefined,
txid
);
},
};
}
async function execQuery(prisma: any, body: any) {
const debug = debugFn({
options: body.transactionOptions,
txId: body.transactionUUID,
parentTxId: body.parentTransactionUUID,
});
try {
const modelKey = body.model
? `${String(body.model).substring(0, 1).toLowerCase()}${String(
body.model
).substring(1)}`
: undefined;
let result: any;
if (modelKey) {
const model: any = prisma[modelKey as any];
if (!model) {
throw new Error(`prismaLocalProxy: model ${modelKey} not found`);
}
const fn = model[body.operation] as (
...args: any[]
) => Promise<any> | undefined;
if (!fn) {
throw new Error(
`prismaLocalProxy: ${model}.${body.operation} not found`
);
}
try {
result = await fn.bind(model)(body.args);
} catch (e) {
debug(`prismaLocalProxy: ${modelKey}.${body.operation} failed: ${e}`);
throw e;
}
} else {
const topLevelFn = prisma[body.operation] as unknown as (
...args: any[]
) => Promise<any>;
if (!topLevelFn) {
throw new Error(
`prismaLocalProxy: top level function ${body.operation} not found`
);
}
const args = body.args;
if (["$executeRaw", "$queryRaw"].includes(body.operation)) {
const argsTemplate = new Sql(args.strings, args.values);
try {
result = await topLevelFn.bind(prisma)(argsTemplate, ...args.values);
} catch (e) {
debug(`prismaLocalProxy: ${body.operation} failed: ${e}`);
throw e;
}
} else {
try {
result = await topLevelFn.bind(prisma)(...args);
} catch (e) {
debug(`prismaLocalProxy: ${body.operation} failed: ${e}`);
throw e;
}
}
}
sharedDebug({
model: body.model,
operation: body.operation,
txid: body.transactionUUID,
result:
result && Object.keys(result).length > 0
? "<object>"
: typeof result !== "object"
? result
: "<empty>",
});
return result;
} catch (e) {
debug(`prismaLocalProxy: execQuery failed: ${e}`);
throw e;
}
}
export async function proxy(
req: NextApiRequest,
res: NextApiResponse,
prisma: ExtendedPrismaClient,
defaultTransactionOptions?: TransactionOptions
) {
const ctx = {
options: req.body.transactionOptions,
txId: req.body.transactionUUID,
parentTxId: req.body.parentTransactionUUID,
};
const debug = debugFn(ctx);
try {
debug(
`prismaLocalProxy: ${JSON.stringify(req.body)}, handler count: ${
transactionQueue.size
}`
);
if (req.body.transactionUUID) {
let handler: TransactionHandler | undefined = transactionQueue.get(
req.body.transactionUUID
);
if (!handler) {
if (req.body.parentTransactionUUID) {
const parentHandler = transactionQueue.get(
req.body.parentTransactionUUID
);
if (!parentHandler) {
throw new Error(
`prismaLocalProxy: parent transaction ${req.body.parentTransactionUUID} not found`
);
}
handler = await parentHandler.nestedTransaction(
req.body.transactionUUID
);
} else {
handler = transactionHandler(prisma, req.body.transactionUUID, ctx, {
...defaultTransactionOptions,
...req.body.transactionOptions,
});
}
transactionQueue.set(req.body.transactionUUID, handler);
}
if (req.body.operation === "$commit") {
const result = await handler.commit();
transactionQueue.delete(req.body.transactionUUID);
res.json(serialize({ transactionCommitResult: result }));
} else if (req.body.operation === "$cleanup") {
transactionQueue.delete(req.body.transactionUUID);
res.json(serialize({ cleanup: true }));
} else if (req.body.operation === "$start") {
res.json(serialize({ started: true }));
} else {
const result = await handler.exec(req.body);
res.json(serialize(result));
}
} else {
const result = await execQuery(prisma, req.body);
res.json(serialize(result));
}
} catch (e) {
res.status(500);
res.json(serialize({ error: e }));
if (e && typeof e === "object") {
if (
"code" in e &&
["P2002", "P2003", "P2004", "P2028"].includes(`${e.code}`)
) {
// https://www.prisma.io/docs/reference/api-reference/error-reference:
// - P2002-P2004 are "unique constraint" errors
// - P2028 is Transaction API errors
// (e.g. "unable to start a transaction in the given time")
// eslint-disable-next-line no-console
console.warn(
`${new Date().toISOString()} prismaLocalProxy: Prisma error: ${
e.code
} ${e}`
);
} else if ("name" in e && e.name == "PrismaClientUnknownRequestError") {
// eslint-disable-next-line no-console
console.warn(
`${new Date().toISOString()} prismaLocalProxy: PrismaClientUnknownRequestError error: ${e}`
);
} else {
debug(`prismaLocalProxy.proxy: error: ${e}`);
throw e;
}
} else {
debug(`prismaLocalProxy.proxy: error: ${e}`);
throw e;
}
}
debug(`prismaLocalProxy.proxy: done`);
}
function debugFn(ctx: Context) {
return (msg: string) =>
sharedDebug(
`[${ctx.parentTxId ? `${ctx.parentTxId} -> ` : ""}${ctx.txId}] ${msg}`
);
}