File size: 804 Bytes
4acc19f
 
 
 
f3abb0d
4acc19f
f3abb0d
 
 
 
 
 
 
 
 
 
 
4acc19f
 
 
 
f3abb0d
 
4acc19f
 
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
import * as os from 'os';

// Auto-scale concurrency limit: e.g., 10 Prisma queries per CPU core
const cpuCores = os.cpus().length;
const concurrencyLimit = cpuCores * 10;

// Dynamic import for ESM-only p-limit package
let prismaConcurrencyLimit: <T>(fn: () => Promise<T>) => Promise<T>;

// Initialize p-limit with dynamic import
const initPLimit = (async () => {
  const pLimit = (await import('p-limit')).default;
  prismaConcurrencyLimit = pLimit(concurrencyLimit);
  console.log(
    `[safePrismaCall] Limiting Prisma concurrency to ${concurrencyLimit} (based on ${cpuCores} CPU cores)`,
  );
})();

export async function safePrismaCall<T = any>(
  fn: () => Promise<T>,
): Promise<T> {
  // Ensure p-limit is initialized before first use
  await initPLimit;
  return prismaConcurrencyLimit(fn);
}