import { createRequire as createRequireShim } from 'module'; const require = createRequireShim(import.meta.url);
import {
  setupLogger
} from "./chunk-CPJKSHSV.js";
import {
  ProcessorServiceImpl,
  configureEndpoints,
  errorString,
  freezeGlobalConfig,
  require_cjs,
  require_lib3 as require_lib,
  require_lib4 as require_lib2
} from "./chunk-GZFHBYA2.js";
import "./chunk-I5YHR3CE.js";
import "./chunk-MV6JXS2P.js";
import {
  __toESM
} from "./chunk-KVSDPGUI.js";

// src/service-worker.ts
var import_nice_grpc = __toESM(require_lib(), 1);
var import_nice_grpc_error_details = __toESM(require_lib2(), 1);
import { threadId } from "worker_threads";
import { Piscina } from "piscina";
var import_rxjs = __toESM(require_cjs(), 1);
var started = false;
var unhandled;
process.on("uncaughtException", (err) => {
  console.error("Uncaught Exception, please checking if await is properly used", err);
  unhandled = err;
}).on("unhandledRejection", (reason, p) => {
  if (reason?.message.startsWith('invalid ENS name (disallowed character: "*"')) {
    return;
  }
  console.error("Unhandled Rejection, please checking if await is properly", reason);
  unhandled = reason;
}).on("exit", () => {
  console.info("Worker thread exiting, threadId:", threadId);
});
var service;
var loader = async (options) => {
  if (options.target) {
    const m = await import(options.target);
    console.debug("Module loaded, path:", options.target, "module:", m);
    return m;
  }
};
var emptyCallContext = {};
async function start(request, options) {
  if (started) {
    return {};
  }
  freezeGlobalConfig();
  try {
    service = new ProcessorServiceImpl(() => loader(options), options);
  } catch (e) {
    throw new import_nice_grpc.ServerError(import_nice_grpc.Status.INVALID_ARGUMENT, "Failed to load processor: " + errorString(e));
  }
  await service.start(request, emptyCallContext);
  started = true;
  return {};
}
async function service_worker_default({
  processId,
  request: firstRequest,
  workerPort
}) {
  const { startRequest, configRequest, options } = Piscina.workerData;
  if (!started) {
    const logLevel = process.env["LOG_LEVEL"]?.toUpperCase();
    setupLogger(options.logFormat === "json", logLevel === "debug" ? true : options.debug, threadId);
    configureEndpoints(options);
    if (startRequest) {
      await start(startRequest, options);
      console.debug("worker", threadId, " started, template instance:", startRequest.templateInstances?.length);
    }
    if (configRequest) {
      await service?.getConfig(configRequest, emptyCallContext);
      console.debug("worker", threadId, " configured");
    }
  }
  if (unhandled) {
    const err = unhandled;
    unhandled = void 0;
    console.error("Unhandled exception/rejection in previous request:", err);
    throw new import_nice_grpc_error_details.RichServerError(
      import_nice_grpc.Status.UNAVAILABLE,
      "Unhandled exception/rejection in previous request: " + errorString(err),
      [
        import_nice_grpc_error_details.DebugInfo.fromPartial({
          detail: err.message,
          stackEntries: err.stack?.split("\n")
        })
      ]
    );
  }
  const timeout = (options.workerTimeout || 0) * 1e3;
  const enablePartition = options.enablePartition || false;
  await new Promise((resolve, reject) => {
    const subject = new import_rxjs.Subject();
    let timeoutId = void 0;
    subject.subscribe((resp) => {
      console.debug("Worker", threadId, "send response:", resp.result ? "result" : "dbResult");
      workerPort.postMessage(resp);
      if (resp.result) {
        if (timeoutId) clearTimeout(timeoutId);
        resolve();
        workerPort.close();
      }
    });
    workerPort.on("message", (msg) => {
      const request = msg;
      console.debug("Worker", threadId, "received request:", request.start ? "start" : "dbResult");
      service?.handleRequest(request, firstRequest.binding, subject);
      if (enablePartition && request.start && timeout > 0) {
        timeoutId = setTimeout(async () => {
          reject(new import_nice_grpc_error_details.RichServerError(import_nice_grpc.Status.DEADLINE_EXCEEDED, "Worker timeout exceeded"));
        }, timeout);
      }
    });
    console.debug("Worker", threadId, "handle request: binding");
    service?.handleRequest(firstRequest, firstRequest.binding, subject);
    if (!enablePartition && timeout > 0) {
      timeoutId = setTimeout(() => {
        reject(new import_nice_grpc_error_details.RichServerError(import_nice_grpc.Status.DEADLINE_EXCEEDED, "Worker timeout exceeded"));
      }, timeout);
    }
  });
}
import("node:process").then((p) => p.stdout.write(""));
export {
  service_worker_default as default
};
//# sourceMappingURL=service-worker.js.map