"use strict";const path=require("node:path"),OKDB=require(path.join(__dirname,"okdb.js"));let db=null,worker=null,stopping=!1;function send(e){try{"function"==typeof process.send&&process.send(e)}catch{}}async function gracefulShutdown(e){if(stopping)return;stopping=!0;const s=setTimeout(()=>process.exit(e),3e3);"function"==typeof s.unref&&s.unref();try{await(worker?.stop?.())}catch{}try{await(db?.close?.())}catch{}process.exit(e)}function startStatsReporter(e){const s=require("node:os");let t=process.cpuUsage(),n=Date.now();const r=()=>{const r=Date.now(),o=process.cpuUsage(),a=1e3*(r-n),c=o.user-t.user+(o.system-t.system),p=a>0?Math.min(100,Math.round(c/(a*(s.cpus().length||1))*100)):0;t=o,n=r;const u=process.memoryUsage();e({type:"stats",stats:{rss:u.rss,heapUsed:u.heapUsed,heapTotal:u.heapTotal,external:u.external,cpuPct:p,cpuWindowMs:Math.round(a/1e3)||null}})},o=Math.max(1e3,Number(process.env.OKDB_STATS_INTERVAL_MS)||5e3),a=setInterval(r,o);a.unref&&a.unref(),r()}const{loadHandler:loadHandler}=require("./okdb-queue-load-handler.js");async function main(){const e=process.env.OKDB_QUEUE_DB_PATH,s=process.env.OKDB_QUEUE_ENV_NAME||"default",t=process.env.OKDB_QUEUE_TYPE,n=process.env.OKDB_QUEUE_MODULE,r=process.env.OKDB_QUEUE_EXPORT||"default",o=JSON.parse(process.env.OKDB_QUEUE_WORKER_OPTIONS||"{}");if(!e)throw new Error("Missing OKDB_QUEUE_DB_PATH");if(!t)throw new Error("Missing OKDB_QUEUE_TYPE");if(!n)throw new Error("Missing OKDB_QUEUE_MODULE");process.on("disconnect",()=>gracefulShutdown(0));const a=setInterval(()=>{1===process.ppid&&gracefulShutdown(0)},2e3);"function"==typeof a.unref&&a.unref(),db=new OKDB(e,{runtimeDeclarations:!1,compaction:"passive",engines:!1,asyncProcessors:!1,http:!1,envs:[s]}),await db.open();const c=db.env(s);if(!c?.queue)throw new Error(`Queue environment not available: ${s}`);const p=loadHandler(n,r);worker=c.queue.process(t,p,o),process.on("message",e=>{e&&"object"==typeof e&&"stop"===e.type&&gracefulShutdown(0)}),process.on("SIGINT",()=>gracefulShutdown(0)),process.on("SIGTERM",()=>gracefulShutdown(0)),send({type:"ready",pid:process.pid,envName:s,queueType:t}),startStatsReporter(send)}main().catch(async e=>{send({type:"error",error:{message:e?.message||String(e),stack:e?.stack||null,code:e?.code||null}});try{await(worker?.stop?.())}catch{}try{await(db?.close?.())}catch{}process.exit(1)});