procd 1.1.4__tar.gz → 1.2.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: procd
3
- Version: 1.1.4
3
+ Version: 1.2.0
4
4
  Summary: The Native Stack Runner. Orchestration Without Containers.
5
5
  Keywords:
6
6
  Author: alpine
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "procd"
7
- version = "1.1.4"
7
+ version = "1.2.0"
8
8
  description = "The Native Stack Runner. Orchestration Without Containers."
9
9
  readme = "README_PYPI.md"
10
10
  license = "MIT"
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "procd"
7
- version = "1.1.4"
7
+ version = "1.2.0"
8
8
  description = "The Native Stack Runner. Orchestration Without Containers."
9
9
  readme = "README_PYPI.md"
10
10
  license = "MIT"
@@ -352,32 +352,36 @@ def _do_run(name: str, conf: "Config", runtime_env: "dict[str, str] | None" = No
352
352
 
353
353
 
354
354
  def _do_up(name: str, conf: "Config") -> None:
355
- """@up の実装。サービスをバックグラウンドで起動し ready まで待機する。"""
356
- from . import process
355
+ """@up の実装。サービスを常駐ホスト経由でバックグラウンド起動し ready まで待機する。"""
356
+ from . import ipc, process
357
357
 
358
358
  if name not in conf.services:
359
359
  raise ValueError(f"@up: unknown service: {name}")
360
360
  if process.is_running(name):
361
361
  _console.print(f"[dim][{name}] already running[/dim]")
362
362
  return
363
- svc = conf.services[name]
364
363
  _console.print(f"[dim]starting {name}...[/dim]")
365
- process.start(name, svc, detach=True, project_dir=conf.project_dir)
366
- result = process.wait_ready(name, svc, project_dir=conf.project_dir)
367
- if result is None:
364
+ try:
365
+ r = ipc.up(conf, [name])[name]
366
+ except ipc.HostError as e:
367
+ raise RuntimeError(f"@up: {e}") from e
368
+ if not r["started"]:
369
+ _console.print(f"[dim][{name}] already running[/dim]")
370
+ return
371
+ if r["ready"] is None:
368
372
  raise RuntimeError(f"@up: {name} exited immediately")
369
- if not result:
373
+ if not r["ready"]:
370
374
  raise RuntimeError(f"@up: {name} timed out waiting for ready")
371
- _console.print(f"[dim][{name}] ready (pid {process.read_pid(name)})[/dim]")
375
+ _console.print(f"[dim][{name}] ready (pid {r['pid']})[/dim]")
372
376
 
373
377
 
374
378
  def _do_down(name: str, conf: "Config") -> None:
375
379
  """@down の実装。サービスを停止する。"""
376
- from . import process
380
+ from . import ipc
377
381
 
378
382
  if name not in conf.services:
379
383
  raise ValueError(f"@down: unknown service: {name}")
380
- if process.stop(name):
384
+ if ipc.down(conf, [name])[name]:
381
385
  _console.print(f"[dim]stopped {name}[/dim]")
382
386
  else:
383
387
  _console.print(f"[dim][{name}] was not running[/dim]")
@@ -19,6 +19,7 @@ from rich.panel import Panel
19
19
  from . import builtin
20
20
  from . import config as cfg
21
21
  from . import download as dl_mod
22
+ from . import ipc
22
23
  from . import process
23
24
  from ._expand import expand as _expand
24
25
  from .supervisor import Supervisor
@@ -199,40 +200,9 @@ def cmd_up(args: argparse.Namespace) -> None:
199
200
  return
200
201
 
201
202
  if args.detach:
202
- # detach: 従来通り _logger サブプロセスで JSONL に書き続ける
203
- procs: list[tuple[str, subprocess.Popen]] = []
204
- for i, name in enumerate(targets):
205
- if process.is_running(name):
206
- print(f"[{name}] already running (pid {process.read_pid(name)})")
207
- continue
208
- svc = conf.services[name]
209
- color = process.COLORS[i % len(process.COLORS)]
210
- print(f"{color}[{name}]{process.RESET} Starting...")
211
- proc = process.start(name, svc, detach=True, project_dir=conf.project_dir, verbose=args.verbose)
212
- procs.append((name, proc))
213
- if not procs:
214
- return
215
- for i, (name, _) in enumerate(procs):
216
- svc = conf.services[name]
217
- color = process.COLORS[i % len(process.COLORS)]
218
- result = process.wait_ready(name, svc, project_dir=conf.project_dir)
219
- if result is None:
220
- process.clear_pid(name)
221
- print(f"{color}[{name}]{process.RESET} Process exited immediately. Last log:", file=sys.stderr)
222
- tail = process.tail_log(name)
223
- if tail:
224
- for line in tail.splitlines():
225
- print(f" {line}", file=sys.stderr)
226
- sys.exit(1)
227
- elif result:
228
- print(f"{color}[{name}]{process.RESET} Ready (pid {process.read_pid(name)})")
229
- else:
230
- print(f"{color}[{name}]{process.RESET} Timed out waiting for ready. Last log:", file=sys.stderr)
231
- tail = process.tail_log(name)
232
- if tail:
233
- for line in tail.splitlines():
234
- print(f" {line}", file=sys.stderr)
235
- sys.exit(1)
203
+ _, failed = _start_in_host(conf, targets, verbose=args.verbose)
204
+ if failed:
205
+ sys.exit(1)
236
206
  return
237
207
 
238
208
  # フォアグラウンド: Supervisor が in-process でストリームを管理する
@@ -296,54 +266,70 @@ def cmd_up(args: argparse.Namespace) -> None:
296
266
  shutdown()
297
267
 
298
268
 
269
+ def _start_in_host(conf: cfg.Config, targets: list[str], *, verbose: bool = False) -> tuple[list[str], bool]:
270
+ """常駐ホスト経由でサービスを起動し、ready まで待つ。(今回起動した名前, 失敗があったか) を返す。"""
271
+ index = {n: i for i, n in enumerate(conf.services)}
272
+
273
+ def _color(name: str) -> str:
274
+ return process.COLORS[index[name] % len(process.COLORS)]
275
+
276
+ to_start = []
277
+ for name in targets:
278
+ if process.is_running(name):
279
+ print(f"[{name}] already running (pid {process.read_pid(name)})")
280
+ else:
281
+ to_start.append(name)
282
+ if not to_start:
283
+ return [], False
284
+ for name in to_start:
285
+ print(f"{_color(name)}[{name}]{process.RESET} Starting...")
286
+
287
+ try:
288
+ results = ipc.up(conf, to_start)
289
+ except ipc.HostError as e:
290
+ _err_console.print(f"[bold red]Error:[/bold red] {e}")
291
+ sys.exit(1)
292
+
293
+ started: list[str] = []
294
+ failed = False
295
+ for name in to_start:
296
+ r = results[name]
297
+ color = _color(name)
298
+ if not r["started"]:
299
+ print(f"[{name}] already running (pid {r['pid']})")
300
+ continue
301
+ started.append(name)
302
+ if verbose and r.get("cmd"):
303
+ print(f" cmd: {r['cmd']}")
304
+ if r["ready"]:
305
+ print(f"{color}[{name}]{process.RESET} Ready (pid {r['pid']})")
306
+ continue
307
+ reason = "Process exited immediately" if r["ready"] is None else "Timed out waiting for ready"
308
+ print(f"{color}[{name}]{process.RESET} {reason}. Last log:", file=sys.stderr)
309
+ tail = process.tail_log(name)
310
+ if tail:
311
+ for line in tail.splitlines():
312
+ print(f" {line}", file=sys.stderr)
313
+ failed = True
314
+ return started, failed
315
+
316
+
299
317
  def _up_follow(args: argparse.Namespace, conf: cfg.Config, targets: list[str]) -> None:
300
318
  """detach 起動してから jsonl ログをフォローし、終了時にそのサービスも停止する。"""
301
319
  jsonl = process.jsonl_path()
302
320
  log_start_pos = jsonl.stat().st_size if jsonl.exists() else 0
303
321
 
304
- started_names: list[str] = []
305
- for i, name in enumerate(targets):
306
- if process.is_running(name):
307
- print(f"[{name}] already running (pid {process.read_pid(name)})")
308
- continue
309
- svc = conf.services[name]
310
- color = process.COLORS[i % len(process.COLORS)]
311
- print(f"{color}[{name}]{process.RESET} Starting...")
312
- process.start(name, svc, detach=True, project_dir=conf.project_dir, verbose=args.verbose)
313
- started_names.append(name)
322
+ started_names, failed = _start_in_host(conf, targets, verbose=args.verbose)
314
323
 
315
324
  def _shutdown_started() -> None:
316
325
  if not started_names:
317
326
  return
318
327
  print("\nStopping services...")
328
+ stopped = ipc.down(conf, started_names)
319
329
  for name in reversed(started_names):
320
- if process.stop(name):
330
+ if stopped.get(name):
321
331
  print(f" Stopped {name}")
322
332
 
323
- failed = False
324
- for name in started_names:
325
- svc = conf.services[name]
326
- i = list(conf.services.keys()).index(name)
327
- color = process.COLORS[i % len(process.COLORS)]
328
- result = process.wait_ready(name, svc, project_dir=conf.project_dir)
329
- if result is None:
330
- process.clear_pid(name)
331
- print(f"{color}[{name}]{process.RESET} Process exited immediately. Last log:", file=sys.stderr)
332
- tail = process.tail_log(name)
333
- if tail:
334
- for line in tail.splitlines():
335
- print(f" {line}", file=sys.stderr)
336
- failed = True
337
- elif result:
338
- print(f"{color}[{name}]{process.RESET} Ready (pid {process.read_pid(name)})")
339
- else:
340
- print(f"{color}[{name}]{process.RESET} Timed out waiting for ready. Last log:", file=sys.stderr)
341
- tail = process.tail_log(name)
342
- if tail:
343
- for line in tail.splitlines():
344
- print(f" {line}", file=sys.stderr)
345
- failed = True
346
-
347
333
  if failed:
348
334
  # 起動失敗時はログを無限追尾せず、起動済み分を止めて終了する
349
335
  _shutdown_started()
@@ -367,7 +353,7 @@ def _up_follow(args: argparse.Namespace, conf: cfg.Config, targets: list[str]) -
367
353
  return f"{color}[{s}]{process.RESET}{ts} {entry.get('m','')}"
368
354
 
369
355
  try:
370
- with open(jsonl, encoding="utf-8") as f:
356
+ with open(jsonl, encoding="utf-8", errors="replace") as f:
371
357
  f.seek(log_start_pos)
372
358
  while True:
373
359
  line = f.readline()
@@ -376,6 +362,8 @@ def _up_follow(args: argparse.Namespace, conf: cfg.Config, targets: list[str]) -
376
362
  entry = json.loads(line)
377
363
  except json.JSONDecodeError:
378
364
  continue
365
+ if not isinstance(entry, dict):
366
+ continue
379
367
  print(_fmt(entry))
380
368
  sys.stdout.flush()
381
369
  else:
@@ -400,8 +388,9 @@ def cmd_down(args: argparse.Namespace) -> None:
400
388
  if targets is None:
401
389
  _no_default_group(conf)
402
390
  return
391
+ stopped = ipc.down(conf, targets)
403
392
  for name in reversed(targets):
404
- if process.stop(name):
393
+ if stopped.get(name):
405
394
  print(f"Stopped {name}")
406
395
  else:
407
396
  print(f"{name} was not running")
@@ -416,14 +405,17 @@ def cmd_restart(args: argparse.Namespace) -> None:
416
405
  if targets is None:
417
406
  _no_default_group(conf)
418
407
  return
419
- for name in reversed(targets):
420
- process.stop(name)
408
+ ipc.down(conf, targets)
409
+ try:
410
+ results = ipc.up(conf, targets, verbose=args.verbose)
411
+ except ipc.HostError as e:
412
+ _err_console.print(f"[bold red]Error:[/bold red] {e}")
413
+ sys.exit(1)
421
414
  for i, name in enumerate(targets):
422
- svc = conf.services[name]
423
415
  color = process.COLORS[i % len(process.COLORS)]
424
- process.start(name, svc, detach=True, project_dir=conf.project_dir, verbose=args.verbose)
425
- if process.wait_ready(name, svc, project_dir=conf.project_dir):
426
- print(f"{color}[{name}]{process.RESET} Restarted (pid {process.read_pid(name)})")
416
+ r = results[name]
417
+ if r.get("ready"):
418
+ print(f"{color}[{name}]{process.RESET} Restarted (pid {r['pid']})")
427
419
  else:
428
420
  print(f"{color}[{name}]{process.RESET} Timed out waiting for ready", file=sys.stderr)
429
421
 
@@ -453,9 +445,10 @@ def cmd_logs(args: argparse.Namespace) -> None:
453
445
 
454
446
  def _parse(line: str) -> dict | None:
455
447
  try:
456
- return json.loads(line)
448
+ entry = json.loads(line)
457
449
  except json.JSONDecodeError:
458
450
  return None
451
+ return entry if isinstance(entry, dict) else None
459
452
 
460
453
  def _fmt(entry: dict) -> str:
461
454
  s = entry.get("s", "?")
@@ -468,7 +461,7 @@ def cmd_logs(args: argparse.Namespace) -> None:
468
461
  _err_console.print("[yellow]no logs found — run 'procd up -d' first[/yellow]")
469
462
  return
470
463
  try:
471
- with open(jsonl, encoding="utf-8") as f:
464
+ with open(jsonl, encoding="utf-8", errors="replace") as f:
472
465
  f.seek(0, 2) # 末尾からフォロー
473
466
  while True:
474
467
  line = f.readline()
@@ -485,7 +478,7 @@ def cmd_logs(args: argparse.Namespace) -> None:
485
478
  if not jsonl.exists():
486
479
  return
487
480
  n = args.lines
488
- with open(jsonl, encoding="utf-8") as f:
481
+ with open(jsonl, encoding="utf-8", errors="replace") as f:
489
482
  entries = [e for line in f if (e := _parse(line)) and (filter_names is None or e.get("s") in filter_names)]
490
483
  for entry in entries[-n:]:
491
484
  print(_fmt(entry))
@@ -133,6 +133,8 @@ class Config:
133
133
  global_env: dict[str, str] = field(default_factory=dict)
134
134
  alias_vars: dict[str, str] = field(default_factory=dict)
135
135
  project_dir: Path = field(default_factory=Path.cwd)
136
+ # load() で読み込んだ procd.toml の絶対パス。常駐ホスト(ipc / host)の識別と設定の再読み込みに使う
137
+ config_path: Path | None = None
136
138
 
137
139
 
138
140
  def _build_merged_env(
@@ -155,6 +157,7 @@ def load(path: Path = Path("procd.toml")) -> Config:
155
157
 
156
158
  config = Config()
157
159
  config.project_dir = path.resolve().parent
160
+ config.config_path = path.resolve()
158
161
 
159
162
  settings = data.get("settings", {})
160
163
  def _resolve_dir(key: str, default: str) -> Path: