pugio 0.2.2__py3-none-any.whl

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.
pugio/__init__.py ADDED
@@ -0,0 +1,12 @@
1
+ """Pugio — 수집·전송 (ETL 엔진).
2
+
3
+ 커넥터 수 대신 신뢰성 코어로 경쟁한다: 재개·멱등·인증 갱신이 기본값.
4
+ 구조: sources/ sinks/ auth/ validate/ runner.py cli.py (docs/02-architecture.md)
5
+ """
6
+
7
+ from importlib.metadata import PackageNotFoundError, version
8
+
9
+ try:
10
+ __version__ = version("pugio")
11
+ except PackageNotFoundError:
12
+ __version__ = "0.2.2"
pugio/auth/__init__.py ADDED
@@ -0,0 +1,137 @@
1
+ """인증 계층 (M2-D) — 만료는 에러가 아니라 갱신 트리거.
2
+
3
+ 계획 (docs/01-scope.md M2 Task 2.4):
4
+ - AuthProvider 프로토콜: 요청 헤더 공급 + refresh() 훅
5
+ - 구현체: static token / oauth2 client credentials(만료 전 선제 갱신)
6
+ - 러너 연동: 401 → AuthExpiredError → provider.refresh() → 같은 unit 재시도 (runner.py)
7
+ """
8
+
9
+ import os
10
+ from typing import Protocol
11
+
12
+ import httpx
13
+
14
+ from arsenal_core.errors import FatalError
15
+ from arsenal_core.ratelimit import Clock, SystemClock
16
+ from arsenal_core.spec.models import AuthSpec
17
+
18
+
19
+ class AuthProvider(Protocol):
20
+ def headers(self) -> dict[str, str]:
21
+ """현재 유효한 인증 헤더."""
22
+ ...
23
+
24
+ def refresh(self) -> None:
25
+ """자격 증명 갱신. AuthExpiredError 수신 시 러너가 호출한다."""
26
+ ...
27
+
28
+
29
+ class StaticTokenAuth:
30
+ """정적 토큰 — 환경변수에서 매번 읽는다 (회전 시 프로세스 재시작 없이 반영).
31
+
32
+ 갱신 불가: 만료된 정적 토큰은 사람이 시크릿을 교체해야 하므로 refresh()는
33
+ FatalError로 즉시 중단한다 (재시도해도 나아지지 않음).
34
+ """
35
+
36
+ def __init__(self, token_env: str) -> None:
37
+ self._env = token_env
38
+
39
+ def headers(self) -> dict[str, str]:
40
+ try:
41
+ token = os.environ[self._env]
42
+ except KeyError as e:
43
+ raise FatalError(f"static token env var {self._env!r} is not set") from e
44
+ return {"Authorization": f"Bearer {token}"}
45
+
46
+ def refresh(self) -> None:
47
+ raise FatalError("static token expired; rotate the secret")
48
+
49
+
50
+ class OAuth2ClientCredentials:
51
+ """client_credentials 그랜트 — expiry_buffer_s 전에 선제 재발급.
52
+
53
+ headers()는 토큰이 없거나 만료(버퍼 포함)에 가까우면 자동으로 재발급한다.
54
+ refresh()는 (버퍼와 무관하게) 즉시 강제 재발급 — 401 수신 시 러너가 호출.
55
+ Clock은 테스트에서 FakeClock으로 주입해 시간 경과를 결정론적으로 검증한다.
56
+ """
57
+
58
+ def __init__(
59
+ self,
60
+ spec: AuthSpec,
61
+ *,
62
+ client: httpx.Client,
63
+ clock: Clock | None = None,
64
+ ) -> None:
65
+ self._spec = spec
66
+ self._client = client
67
+ self._clock = clock or SystemClock()
68
+ self._token: str | None = None
69
+ self._expiry: float = 0.0
70
+
71
+ def headers(self) -> dict[str, str]:
72
+ now = self._clock.monotonic()
73
+ if self._token is None or now > self._expiry - self._spec.expiry_buffer_s:
74
+ self._fetch_token()
75
+ return {"Authorization": f"Bearer {self._token}"}
76
+
77
+ def refresh(self) -> None:
78
+ self._fetch_token()
79
+
80
+ def _fetch_token(self) -> None:
81
+ if self._spec.token_url is None:
82
+ raise FatalError("oauth2 auth requires token_url")
83
+ if self._spec.client_id_env is None or self._spec.client_secret_env is None:
84
+ raise FatalError("oauth2 auth requires client_id_env and client_secret_env")
85
+ try:
86
+ client_id = os.environ[self._spec.client_id_env]
87
+ client_secret = os.environ[self._spec.client_secret_env]
88
+ except KeyError as e:
89
+ raise FatalError(f"oauth2 credential env var missing: {e}") from e
90
+ resp = self._client.post(
91
+ self._spec.token_url,
92
+ data={
93
+ "grant_type": "client_credentials",
94
+ "client_id": client_id,
95
+ "client_secret": client_secret,
96
+ },
97
+ )
98
+ if resp.status_code >= 400:
99
+ # 토큰 엔드포인트 실패는 설정/자격증명 오류 — 재시도해도 나아지지 않는다.
100
+ # 본문(resp.text)은 신지 않는다: 토큰 엔드포인트가 요청 페이로드(클라이언트
101
+ # 시크릿 등)를 에코백할 수 있고, 이 메시지는 mark_failed로 state.db에
102
+ # 영속된다 — rest.py의 401 리다크션과 동일한 defense-in-depth 원칙
103
+ # (M2 최종 리뷰 FIX 6). 상태코드+token_url이면 갱신 실패를 진단하기 충분하다.
104
+ raise FatalError(f"token request to {self._spec.token_url} failed: {resp.status_code}")
105
+ body = resp.json()
106
+ try:
107
+ access_token = body["access_token"]
108
+ expires_in = body["expires_in"]
109
+ except KeyError as e:
110
+ raise FatalError(f"token response missing field: {e}") from e
111
+ # 토큰 엔드포인트는 외부 신뢰 경계 — access_token/expires_in의 타입까지
112
+ # 계약대로 왔는지 검증한다. 검증 없이 쓰면 문자열 expires_in은
113
+ # self._clock.monotonic() + expires_in에서 TypeError, null access_token은
114
+ # "Bearer None" 헤더로 조용히 새어나간다. 값 자체는 메시지에 담지 않는다.
115
+ if not isinstance(access_token, str) or not isinstance(expires_in, int | float):
116
+ raise FatalError("token endpoint returned malformed response (access_token/expires_in)")
117
+ self._token = access_token
118
+ self._expiry = self._clock.monotonic() + expires_in
119
+
120
+
121
+ def build_auth(
122
+ spec: AuthSpec | None,
123
+ client: httpx.Client,
124
+ *,
125
+ clock: Clock | None = None,
126
+ ) -> AuthProvider | None:
127
+ """spec.type으로 알맞은 AuthProvider를 만든다. spec이 None이면 None (인증 없음)."""
128
+ if spec is None:
129
+ return None
130
+ if spec.type == "static_token":
131
+ if spec.token_env is None:
132
+ raise FatalError("static_token auth requires token_env")
133
+ return StaticTokenAuth(spec.token_env)
134
+ return OAuth2ClientCredentials(spec, client=client, clock=clock)
135
+
136
+
137
+ __all__ = ["AuthProvider", "StaticTokenAuth", "OAuth2ClientCredentials", "build_auth"]
pugio/cli.py ADDED
@@ -0,0 +1,159 @@
1
+ """Pugio CLI. 재실행은 곧 재개다 — resume 플래그는 존재하지 않는다.
2
+
3
+ 구현: docs/plans/2026-07-08-m1-core-foundation.md Task 9
4
+ M2 확장: retry, dlq list/retry 서브커맨드 (docs/02-architecture.md "CLI 설계")
5
+ """
6
+
7
+ from pathlib import Path
8
+
9
+ import typer
10
+ from scorpio import assess_freshness
11
+
12
+ from arsenal_core.errors import ArsenalError
13
+ from arsenal_core.spec import load_pipeline
14
+ from arsenal_core.state import StateStore
15
+ from pugio.dlq import dlq_dir, read_reason, remove_dlq
16
+ from pugio.runner import run_pipeline
17
+
18
+ app = typer.Typer(help="Pugio — 수집·전송. 재실행은 곧 재개다.")
19
+ dlq_app = typer.Typer(help="dead-letter queue — 격리된 unit 조회·재시도")
20
+ app.add_typer(dlq_app, name="dlq")
21
+
22
+
23
+ @app.command()
24
+ def run(spec_path: Path) -> None:
25
+ """파이프라인 실행. 중단됐던 실행은 자동으로 이어서 한다."""
26
+ try:
27
+ spec = load_pipeline(spec_path)
28
+ report = run_pipeline(spec)
29
+ except ArsenalError as e:
30
+ typer.echo(f"error: {e}", err=True)
31
+ raise typer.Exit(1) from e
32
+ typer.echo(
33
+ f"done: fetched={report.fetched} written={report.written} "
34
+ f"skipped={report.skipped} quarantined={report.quarantined}"
35
+ )
36
+
37
+
38
+ @app.command()
39
+ def status(
40
+ spec_path: Path,
41
+ cost: bool = typer.Option(False, "--cost", help="누적 행·바이트·처리 시간·freshness 표시"),
42
+ max_age_seconds: float | None = typer.Option(
43
+ None,
44
+ "--max-age-seconds",
45
+ min=0.001,
46
+ help="freshness 경보 임계값; stale이면 alert를 출력한다",
47
+ ),
48
+ ) -> None:
49
+ """unit 상태 요약. ``--cost``로 P0 단위 지표의 누적값도 표시한다."""
50
+ try:
51
+ spec = load_pipeline(spec_path)
52
+ except ArsenalError as e:
53
+ typer.echo(f"error: {e}", err=True)
54
+ raise typer.Exit(1) from e
55
+ store = StateStore(Path(spec.state_dir) / f"{spec.name}.db")
56
+ try:
57
+ counts = store.counts(spec.name)
58
+ metrics = store.pipeline_metrics(spec.name) if cost else None
59
+ freshness = (
60
+ assess_freshness(
61
+ store.pipeline_metrics(spec.name).last_completed_at,
62
+ max_age_seconds=max_age_seconds,
63
+ )
64
+ if max_age_seconds is not None
65
+ else None
66
+ )
67
+ finally:
68
+ store.close()
69
+ if not counts:
70
+ typer.echo("no runs yet")
71
+ return
72
+ for state, n in sorted(counts.items()):
73
+ typer.echo(f"{state}: {n}")
74
+ if metrics is not None:
75
+ typer.echo(
76
+ f"cost: units={metrics.completed_units} rows={metrics.row_count} "
77
+ f"bytes={metrics.byte_count} duration_ms={metrics.duration_ms} "
78
+ f"last_completed_at={metrics.last_completed_at or 'none'}"
79
+ )
80
+ if freshness is not None:
81
+ typer.echo(
82
+ f"freshness: status={freshness.status} "
83
+ f"age_seconds={freshness.age_seconds if freshness.age_seconds is not None else 'none'} "
84
+ f"limit_seconds={freshness.max_age_seconds}"
85
+ )
86
+ if freshness.alert:
87
+ typer.echo(f"alert: freshness {freshness.message}", err=True)
88
+
89
+
90
+ @dlq_app.command("list")
91
+ def dlq_list(spec_path: Path) -> None:
92
+ """격리된 unit 목록 — 한 줄에 `{unit_id} {unit_key} {reason}`.
93
+
94
+ unit_id가 맨 앞의 복사-붙여넣기 가능한 식별자다: `dlq retry --unit`은
95
+ unit_id로 매칭하므로 (M2-E FIX 1), 사람이 읽기 좋은 unit_key만 보고
96
+ 복사하면 store.requeue()가 0행을 갱신하고도 조용히 성공하는 것처럼 보였다.
97
+ unit_key + reason은 읽기용으로 같은 줄에 덧붙인다.
98
+ """
99
+ try:
100
+ spec = load_pipeline(spec_path)
101
+ except ArsenalError as e:
102
+ typer.echo(f"error: {e}", err=True)
103
+ raise typer.Exit(1) from e
104
+ store = StateStore(Path(spec.state_dir) / f"{spec.name}.db")
105
+ try:
106
+ records = store.quarantined(spec.name)
107
+ finally:
108
+ store.close()
109
+ if not records:
110
+ typer.echo("no quarantined units")
111
+ return
112
+ for rec in records:
113
+ json_path = dlq_dir(spec.state_dir, spec.name) / f"{rec.unit_id}.json"
114
+ unit_key = rec.unit_id
115
+ if json_path.exists():
116
+ reason = read_reason(json_path)
117
+ unit_key = str(reason.get("unit_key", rec.unit_id))
118
+ typer.echo(f"{rec.unit_id} {unit_key} {rec.last_error}")
119
+
120
+
121
+ @dlq_app.command("retry")
122
+ def dlq_retry(spec_path: Path, unit: str = typer.Option(..., "--unit")) -> None:
123
+ """격리된 unit을 pending으로 되돌리고 DLQ 파일을 지운다. 다음 run이 재수집한다.
124
+
125
+ `--unit`은 `dlq list`가 첫 컬럼으로 찍는 unit_id를 받는다 (M2-E FIX 1).
126
+
127
+ M2-E FIX 2 (P0 스코프 락): REST cursor/link 페이지네이션은 프론티어 커서가
128
+ 앞으로만 전진해서, 격리된 과거 페이지의 unit_key(`cursor=<val>`)를 재실행이
129
+ 다시는 생성할 수 없다 — requeue해도 다음 run이 그 unit을 절대 재등록하지
130
+ 않으므로 영원히 고아가 된다. 이 경우엔 evidence(DLQ 파일)도 지우지 않고
131
+ 거부한다. offset/page/file/database/python은 unit_key가 결정적으로
132
+ 재생산되므로 그대로 재시도된다.
133
+ """
134
+ try:
135
+ spec = load_pipeline(spec_path)
136
+ except ArsenalError as e:
137
+ typer.echo(f"error: {e}", err=True)
138
+ raise typer.Exit(1) from e
139
+ if spec.source.type == "rest" and spec.source.pagination.mode in ("cursor", "link"):
140
+ typer.echo(
141
+ "error: dlq retry is not supported for cursor/link pagination in P0 "
142
+ "(forward-only cursor cannot regenerate a past page)",
143
+ err=True,
144
+ )
145
+ raise typer.Exit(1)
146
+ store = StateStore(Path(spec.state_dir) / f"{spec.name}.db")
147
+ try:
148
+ updated = store.requeue(unit)
149
+ finally:
150
+ store.close()
151
+ if updated == 0:
152
+ typer.echo(f"error: no quarantined unit with id {unit}", err=True)
153
+ raise typer.Exit(1)
154
+ remove_dlq(spec.state_dir, spec.name, unit)
155
+ typer.echo(f"requeued {unit}")
156
+
157
+
158
+ if __name__ == "__main__":
159
+ app()
pugio/dlq.py ADDED
@@ -0,0 +1,56 @@
1
+ """DLQ(dead-letter queue) 파일 저장소 — 격리된 unit의 batch + 사유를 evidence로 남긴다.
2
+
3
+ M2-E: DLQ 파일은 재적재 소스가 아니다 — retry는 실제 소스에서 다시 fetch한다
4
+ (docs/01-scope.md M2 Task 2.7~2.8). `.arsenal/dlq/{pipeline}/{unit_id}.parquet`
5
+ + `{unit_id}.json`(사유) 쌍으로 저장한다.
6
+ """
7
+
8
+ import json
9
+ from datetime import UTC, datetime
10
+ from pathlib import Path
11
+
12
+ import pyarrow as pa
13
+ import pyarrow.parquet as pq
14
+
15
+ from arsenal_core.state import UnitSpec
16
+ from pugio.validate.gate import Violation
17
+
18
+
19
+ def dlq_dir(state_dir: str | Path, pipeline: str) -> Path:
20
+ return Path(state_dir) / "dlq" / pipeline
21
+
22
+
23
+ def write_dlq(
24
+ state_dir: str | Path,
25
+ pipeline: str,
26
+ unit: UnitSpec,
27
+ batch: pa.RecordBatch,
28
+ violations: list[Violation],
29
+ ) -> Path:
30
+ """격리 batch를 parquet으로, 위반 사유를 같은 이름의 json으로 저장한다."""
31
+ d = dlq_dir(state_dir, pipeline)
32
+ d.mkdir(parents=True, exist_ok=True)
33
+ parquet_path = d / f"{unit.unit_id}.parquet"
34
+ pq.write_table(pa.Table.from_batches([batch]), parquet_path) # pyright: ignore[reportUnknownMemberType]
35
+ reason = {
36
+ "unit_id": unit.unit_id,
37
+ "unit_key": unit.unit_key,
38
+ "violations": [{"rule": v.rule, "field": v.field, "count": v.count} for v in violations],
39
+ "quarantined_at": datetime.now(UTC).isoformat(),
40
+ }
41
+ (d / f"{unit.unit_id}.json").write_text(
42
+ json.dumps(reason, ensure_ascii=False, indent=2), encoding="utf-8"
43
+ )
44
+ return parquet_path
45
+
46
+
47
+ def read_reason(json_path: Path) -> dict[str, object]:
48
+ return json.loads(json_path.read_text(encoding="utf-8"))
49
+
50
+
51
+ def remove_dlq(state_dir: str | Path, pipeline: str, unit_id: str) -> None:
52
+ """parquet + json 둘 다 삭제 — 없으면 조용히 넘어간다 (재호출 안전)."""
53
+ d = dlq_dir(state_dir, pipeline)
54
+ for suffix in (".parquet", ".json"):
55
+ path = d / f"{unit_id}{suffix}"
56
+ path.unlink(missing_ok=True)
pugio/py.typed ADDED
File without changes