2022-09-07 19:24:43 +03:00
|
|
|
import os
|
2020-06-05 15:03:18 +03:00
|
|
|
import subprocess
|
2022-09-07 19:24:43 +03:00
|
|
|
from typing import Optional
|
2020-06-05 15:03:18 +03:00
|
|
|
|
2022-09-07 19:24:43 +03:00
|
|
|
import ports
|
2020-06-05 15:03:18 +03:00
|
|
|
|
2022-09-07 19:24:43 +03:00
|
|
|
class NodeGraphQL:
|
2023-04-25 15:49:31 +03:00
|
|
|
def __init__(self, worker_id: str, script: str, env: dict[str, str] = {}, port: Optional[int] = None):
|
|
|
|
self.script = script
|
2022-09-07 19:24:43 +03:00
|
|
|
self.env = env
|
2023-04-25 15:49:31 +03:00
|
|
|
self.port = port if port else ports.find_free_port(worker_id)
|
2022-09-07 19:24:43 +03:00
|
|
|
self.proc: Optional[subprocess.Popen[bytes]] = None
|
2020-06-05 15:03:18 +03:00
|
|
|
|
|
|
|
def start(self):
|
2023-04-25 15:49:31 +03:00
|
|
|
self.proc = subprocess.Popen(['node', self.script], env={**os.environ, **self.env, 'PORT': str(self.port)})
|
2022-09-07 19:24:43 +03:00
|
|
|
try:
|
2023-02-03 17:07:48 +03:00
|
|
|
ports.wait_for_port(self.port, timeout = 30)
|
2022-09-07 19:24:43 +03:00
|
|
|
except:
|
|
|
|
self.proc.kill()
|
|
|
|
self.proc = None
|
|
|
|
raise
|
2020-06-05 15:03:18 +03:00
|
|
|
|
|
|
|
def stop(self):
|
2022-09-07 19:24:43 +03:00
|
|
|
if self.proc:
|
|
|
|
self.proc.terminate()
|
|
|
|
self.proc = None
|
|
|
|
|
|
|
|
@property
|
|
|
|
def url(self):
|
|
|
|
return f'http://localhost:{self.port}'
|