@dbcube/core 3.0.3 → 3.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -12,21 +12,25 @@ declare class Engine {
12
12
  private arguments;
13
13
  private binary;
14
14
  private timeout;
15
- private connectionId;
16
- private isConnected;
15
+ private childProcess;
16
+ private pendingRequests;
17
+ private requestCounter;
18
+ private isProcessStarting;
17
19
  constructor(name: string, timeout?: number);
18
- private generateConnectionId;
19
20
  initializeBinary(): Promise<void>;
20
21
  setArguments(): any[];
21
22
  setConfig(name: string): {
22
23
  [x: string]: any;
23
24
  } | null;
24
25
  getConfig(): any;
25
- ensurePersistentConnection(): Promise<void>;
26
+ private ensureProcess;
27
+ private setupProcessHandlers;
28
+ private processBuffer;
29
+ private handleProcessClose;
30
+ private handleProcessError;
26
31
  run(binary: string, args: string[]): Promise<ResponseEngine>;
27
- private executeWithPersistentConnection;
28
- private createProcess;
29
- disconnect(): Promise<ResponseEngine>;
32
+ close(): Promise<void>;
33
+ isProcessAlive(): boolean;
30
34
  }
31
35
 
32
36
  interface SystemInfo {
package/dist/index.d.ts CHANGED
@@ -12,21 +12,25 @@ declare class Engine {
12
12
  private arguments;
13
13
  private binary;
14
14
  private timeout;
15
- private connectionId;
16
- private isConnected;
15
+ private childProcess;
16
+ private pendingRequests;
17
+ private requestCounter;
18
+ private isProcessStarting;
17
19
  constructor(name: string, timeout?: number);
18
- private generateConnectionId;
19
20
  initializeBinary(): Promise<void>;
20
21
  setArguments(): any[];
21
22
  setConfig(name: string): {
22
23
  [x: string]: any;
23
24
  } | null;
24
25
  getConfig(): any;
25
- ensurePersistentConnection(): Promise<void>;
26
+ private ensureProcess;
27
+ private setupProcessHandlers;
28
+ private processBuffer;
29
+ private handleProcessClose;
30
+ private handleProcessError;
26
31
  run(binary: string, args: string[]): Promise<ResponseEngine>;
27
- private executeWithPersistentConnection;
28
- private createProcess;
29
- disconnect(): Promise<ResponseEngine>;
32
+ close(): Promise<void>;
33
+ isProcessAlive(): boolean;
30
34
  }
31
35
 
32
36
  interface SystemInfo {
package/dist/index.js CHANGED
@@ -556,17 +556,15 @@ var Engine = class {
556
556
  arguments;
557
557
  binary = null;
558
558
  timeout;
559
- connectionId;
560
- isConnected = false;
559
+ childProcess = null;
560
+ pendingRequests = /* @__PURE__ */ new Map();
561
+ requestCounter = 0;
562
+ isProcessStarting = false;
561
563
  constructor(name, timeout = 3e4) {
562
564
  this.name = name;
563
565
  this.config = this.setConfig(name);
564
566
  this.arguments = this.setArguments();
565
567
  this.timeout = timeout;
566
- this.connectionId = this.generateConnectionId();
567
- }
568
- generateConnectionId() {
569
- return `${this.name}_${this.config.type}_${this.config.config.DATABASE}_${this.config.config.HOST || "localhost"}`;
570
568
  }
571
569
  async initializeBinary() {
572
570
  if (!this.binary) {
@@ -584,7 +582,9 @@ var Engine = class {
584
582
  "--database",
585
583
  this.config.config.DATABASE + ".db",
586
584
  "--motor",
587
- this.config.type
585
+ this.config.type,
586
+ "--persistent"
587
+ // Agregar flag para modo persistente si el binario lo soporta
588
588
  ];
589
589
  } else {
590
590
  args = [
@@ -603,7 +603,9 @@ var Engine = class {
603
603
  "--password",
604
604
  this.config.config.PASSWORD,
605
605
  "--motor",
606
- this.config.type
606
+ this.config.type,
607
+ "--persistent"
608
+ // Agregar flag para modo persistente si el binario lo soporta
607
609
  ];
608
610
  }
609
611
  return args;
@@ -633,139 +635,151 @@ var Engine = class {
633
635
  getConfig() {
634
636
  return this.config;
635
637
  }
636
- async ensurePersistentConnection() {
637
- if (!this.isConnected) {
638
- console.log("\u{1F50C} Creating persistent connection...");
639
- const response = await this.createProcess("query_engine", [
640
- "--action",
641
- "connect"
642
- ]);
643
- if (response.status === 200) {
644
- this.isConnected = true;
645
- console.log("\u2705 Persistent connection established");
646
- } else {
647
- throw new Error(`Failed to create persistent connection: ${response.message}`);
638
+ async ensureProcess(binary) {
639
+ if (this.childProcess && !this.childProcess.killed) {
640
+ return;
641
+ }
642
+ if (this.isProcessStarting) {
643
+ return new Promise((resolve5) => {
644
+ const checkProcess = () => {
645
+ if (!this.isProcessStarting) {
646
+ resolve5();
647
+ } else {
648
+ setTimeout(checkProcess, 10);
649
+ }
650
+ };
651
+ checkProcess();
652
+ });
653
+ }
654
+ this.isProcessStarting = true;
655
+ try {
656
+ await this.initializeBinary();
657
+ if (!this.binary) {
658
+ throw new Error("Binary not initialized");
648
659
  }
660
+ this.childProcess = spawn(this.binary[binary], this.arguments, {
661
+ stdio: ["pipe", "pipe", "pipe"]
662
+ });
663
+ this.setupProcessHandlers();
664
+ } finally {
665
+ this.isProcessStarting = false;
649
666
  }
650
667
  }
651
- async run(binary, args) {
652
- const actionIndex = args.indexOf("--action");
653
- const isExecuteAction = actionIndex !== -1 && args[actionIndex + 1] === "execute";
654
- if (isExecuteAction) {
655
- await this.ensurePersistentConnection();
656
- return this.executeWithPersistentConnection(args);
657
- } else {
658
- return this.createProcess(binary, args);
668
+ setupProcessHandlers() {
669
+ if (!this.childProcess) return;
670
+ let stdoutBuffer = "";
671
+ let stderrBuffer = "";
672
+ this.childProcess.stdout?.on("data", (data) => {
673
+ stdoutBuffer += data.toString();
674
+ this.processBuffer(stdoutBuffer, "stdout");
675
+ });
676
+ this.childProcess.stderr?.on("data", (data) => {
677
+ stderrBuffer += data.toString();
678
+ this.processBuffer(stderrBuffer, "stderr");
679
+ });
680
+ this.childProcess.on("close", (code) => {
681
+ this.handleProcessClose(code);
682
+ });
683
+ this.childProcess.on("error", (error) => {
684
+ this.handleProcessError(error);
685
+ });
686
+ this.childProcess.unref();
687
+ }
688
+ processBuffer(buffer, source) {
689
+ const responsePattern = /PROCESS_RESPONSE:(\{[^}]*\})/g;
690
+ let match;
691
+ while ((match = responsePattern.exec(buffer)) !== null) {
692
+ try {
693
+ const response = JSON.parse(match[1]);
694
+ const requestId = response.requestId || "unknown";
695
+ const pendingRequest = this.pendingRequests.get(requestId);
696
+ if (pendingRequest) {
697
+ clearTimeout(pendingRequest.timeoutId);
698
+ this.pendingRequests.delete(requestId);
699
+ pendingRequest.resolve({
700
+ status: response.status,
701
+ message: response.message,
702
+ data: response.data
703
+ });
704
+ }
705
+ } catch (error) {
706
+ console.error("Failed to parse response JSON:", error);
707
+ }
659
708
  }
660
709
  }
661
- async executeWithPersistentConnection(args) {
662
- return this.createProcess("query_engine", args);
710
+ handleProcessClose(code) {
711
+ this.childProcess = null;
712
+ for (const [requestId, request] of this.pendingRequests) {
713
+ clearTimeout(request.timeoutId);
714
+ request.reject(new Error(`Process closed with code ${code}`));
715
+ }
716
+ this.pendingRequests.clear();
663
717
  }
664
- async createProcess(binary, args) {
665
- await this.initializeBinary();
666
- if (!this.binary) {
667
- throw new Error("Binary not initialized");
718
+ handleProcessError(error) {
719
+ this.childProcess = null;
720
+ for (const [requestId, request] of this.pendingRequests) {
721
+ clearTimeout(request.timeoutId);
722
+ request.reject(error);
723
+ }
724
+ this.pendingRequests.clear();
725
+ }
726
+ async run(binary, args) {
727
+ await this.ensureProcess(binary);
728
+ if (!this.childProcess) {
729
+ throw new Error("Failed to start process");
668
730
  }
669
731
  return new Promise((resolve5, reject) => {
670
- const child = spawn(this.binary[binary], [...this.arguments, ...args]);
671
- let stdoutBuffer = "";
672
- let stderrBuffer = "";
673
- let isResolved = false;
732
+ const requestId = `req_${++this.requestCounter}_${Date.now()}`;
674
733
  const timeoutId = setTimeout(() => {
675
- if (!isResolved) {
676
- isResolved = true;
677
- child.kill();
678
- reject(new Error("Process timeout"));
734
+ const request = this.pendingRequests.get(requestId);
735
+ if (request) {
736
+ this.pendingRequests.delete(requestId);
737
+ reject(new Error("Request timeout"));
679
738
  }
680
739
  }, this.timeout);
681
- const resolveOnce = (response) => {
682
- if (!isResolved) {
683
- isResolved = true;
684
- clearTimeout(timeoutId);
685
- resolve5(response);
686
- }
687
- };
688
- child.stdout.on("data", (data) => {
689
- stdoutBuffer += data.toString();
690
- const match = stdoutBuffer.match(/PROCESS_RESPONSE:(\{.*\})/);
691
- if (match) {
692
- try {
693
- const response = JSON.parse(match[1]);
694
- resolveOnce({
695
- status: response.status,
696
- message: response.message,
697
- data: response.data
698
- });
699
- } catch (error) {
700
- resolveOnce({
701
- status: 500,
702
- message: "Failed to parse response JSON",
703
- data: null
704
- });
705
- }
706
- }
740
+ this.pendingRequests.set(requestId, {
741
+ resolve: resolve5,
742
+ reject,
743
+ timeoutId,
744
+ requestId
707
745
  });
708
- child.stderr.on("data", (data) => {
709
- stderrBuffer += data.toString();
710
- const match = stderrBuffer.match(/PROCESS_RESPONSE:(\{.*\})/);
711
- if (match) {
712
- try {
713
- const response = JSON.parse(match[1]);
714
- resolveOnce({
715
- status: response.status,
716
- message: response.message,
717
- data: response.data
718
- });
719
- } catch (error) {
720
- resolveOnce({
721
- status: 500,
722
- message: "Failed to parse response JSON",
723
- data: null
724
- });
725
- }
726
- }
727
- });
728
- child.on("close", (code) => {
729
- clearTimeout(timeoutId);
730
- if (!isResolved) {
731
- resolveOnce({
732
- status: code === 0 ? 200 : 500,
733
- message: code === 0 ? "Process completed" : `Process exited with code ${code}`,
734
- data: null
735
- });
736
- }
737
- });
738
- child.on("error", (error) => {
746
+ const command = {
747
+ requestId,
748
+ args
749
+ };
750
+ try {
751
+ this.childProcess.stdin?.write(JSON.stringify(command) + "\n");
752
+ } catch (error) {
739
753
  clearTimeout(timeoutId);
740
- if (!isResolved) {
741
- resolveOnce({
742
- status: 500,
743
- message: `Process error: ${error.message}`,
744
- data: null
745
- });
746
- }
747
- });
748
- child.unref();
754
+ this.pendingRequests.delete(requestId);
755
+ reject(error);
756
+ }
749
757
  });
750
758
  }
751
- async disconnect() {
752
- if (this.isConnected) {
753
- console.log("\u{1F50C} Disconnecting persistent connection...");
754
- const response = await this.createProcess("query_engine", [
755
- "--action",
756
- "disconnect"
757
- ]);
758
- if (response.status === 200) {
759
- this.isConnected = false;
760
- console.log("\u2705 Persistent connection closed");
761
- }
762
- return response;
759
+ // Método para cerrar el proceso manualmente
760
+ async close() {
761
+ if (this.childProcess && !this.childProcess.killed) {
762
+ return new Promise((resolve5) => {
763
+ this.childProcess.once("close", () => {
764
+ resolve5();
765
+ });
766
+ this.childProcess.stdin?.end();
767
+ setTimeout(() => {
768
+ if (this.childProcess && !this.childProcess.killed) {
769
+ this.childProcess.kill("SIGTERM");
770
+ setTimeout(() => {
771
+ if (this.childProcess && !this.childProcess.killed) {
772
+ this.childProcess.kill("SIGKILL");
773
+ }
774
+ }, 2e3);
775
+ }
776
+ }, 5e3);
777
+ });
763
778
  }
764
- return {
765
- status: 200,
766
- message: "No persistent connection to disconnect",
767
- data: null
768
- };
779
+ }
780
+ // Verificar si el proceso está activo
781
+ isProcessAlive() {
782
+ return this.childProcess !== null && !this.childProcess.killed;
769
783
  }
770
784
  };
771
785