arsenal-core 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.
- arsenal_core/__init__.py +15 -0
- arsenal_core/errors.py +35 -0
- arsenal_core/identity.py +18 -0
- arsenal_core/io/__init__.py +8 -0
- arsenal_core/py.typed +0 -0
- arsenal_core/ratelimit.py +58 -0
- arsenal_core/retry.py +46 -0
- arsenal_core/schema.py +81 -0
- arsenal_core/spec/__init__.py +43 -0
- arsenal_core/spec/loader.py +67 -0
- arsenal_core/spec/models.py +260 -0
- arsenal_core/state/__init__.py +19 -0
- arsenal_core/state/store.py +362 -0
- arsenal_core-0.2.2.dist-info/METADATA +53 -0
- arsenal_core-0.2.2.dist-info/RECORD +16 -0
- arsenal_core-0.2.2.dist-info/WHEEL +4 -0
arsenal_core/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""arsenal-core — DE Arsenal 공통 신뢰성 코어.
|
|
2
|
+
|
|
3
|
+
모든 도구(pugio, gladius, …)의 유일한 공통 의존성.
|
|
4
|
+
구조: docs/02-architecture.md 참조.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
__version__ = version("arsenal-core")
|
|
11
|
+
except PackageNotFoundError:
|
|
12
|
+
__version__ = "0.2.2"
|
|
13
|
+
from arsenal_core.schema import SchemaChange, SchemaDiff, compare_schema_snapshots
|
|
14
|
+
|
|
15
|
+
__all__ = ["SchemaChange", "SchemaDiff", "compare_schema_snapshots"]
|
arsenal_core/errors.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""에러 분류 체계 — 커넥터가 분류하고, 러너는 타입만 보고 행동한다.
|
|
2
|
+
|
|
3
|
+
설계: docs/02-architecture.md "에러 분류 체계"
|
|
4
|
+
구현: docs/plans/2026-07-08-m1-core-foundation.md Task 1
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ArsenalError(Exception):
|
|
9
|
+
"""모든 Arsenal 예외의 루트."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class FatalError(ArsenalError):
|
|
13
|
+
"""재시도 무의미: 설정 오류, 4xx(401/429 제외), 계약 위반. 즉시 중단."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class RetryableError(ArsenalError):
|
|
17
|
+
"""일시적 실패: 네트워크, 5xx, 429, lock 충돌. backoff 재시도."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class AuthExpiredError(RetryableError):
|
|
21
|
+
"""인증 만료. 에러가 아니라 갱신 트리거 (M2에서 refresh hook 연결)."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def classify_http_status(status: int) -> type[ArsenalError] | None:
|
|
25
|
+
"""HTTP 상태 코드를 예외 타입으로 분류. 2xx/3xx는 None.
|
|
26
|
+
|
|
27
|
+
401→AuthExpired, 429/5xx→Retryable, 그 외 4xx→Fatal.
|
|
28
|
+
"""
|
|
29
|
+
if status < 400:
|
|
30
|
+
return None
|
|
31
|
+
if status == 401:
|
|
32
|
+
return AuthExpiredError
|
|
33
|
+
if status == 429 or status >= 500:
|
|
34
|
+
return RetryableError
|
|
35
|
+
return FatalError
|
arsenal_core/identity.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""결정적 Unit ID — 멱등성의 근거. 같은 unit은 언제 실행해도 같은 ID.
|
|
2
|
+
|
|
3
|
+
설계: docs/02-architecture.md "결정적 ID"
|
|
4
|
+
구현: docs/plans/2026-07-08-m1-core-foundation.md Task 2
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import hashlib
|
|
8
|
+
|
|
9
|
+
_ID_LEN = 16
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def unit_id(pipeline: str, source: str, unit_key: str) -> str:
|
|
13
|
+
"""sha256("{pipeline}\\x1f{source}\\x1f{unit_key}") 앞 16 hex.
|
|
14
|
+
|
|
15
|
+
\\x1f 구분자로 경계 모호성 제거. 결정성·충돌 저항은 hypothesis로 검증.
|
|
16
|
+
"""
|
|
17
|
+
raw = f"{pipeline}\x1f{source}\x1f{unit_key}"
|
|
18
|
+
return hashlib.sha256(raw.encode()).hexdigest()[:_ID_LEN]
|
arsenal_core/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""토큰 버킷 rate limiter — REST 소스가 rps 상한을 지키도록 acquire()로 스로틀한다.
|
|
2
|
+
|
|
3
|
+
설계: docs/02-architecture.md M2 rate_limit. penalize()는 429 Retry-After를
|
|
4
|
+
흡수해 다음 acquire()가 그만큼 더 기다리게 만든다 (with_retry의 재시도 루프와
|
|
5
|
+
맞물려 "실패 → 벌점 → 다음 시도 전 대기"를 구현한다).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import time
|
|
9
|
+
from typing import Protocol
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Clock(Protocol):
|
|
13
|
+
def monotonic(self) -> float: ...
|
|
14
|
+
def sleep(self, seconds: float) -> None: ...
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class SystemClock:
|
|
18
|
+
"""실제 time.monotonic()/time.sleep()을 쓰는 Clock 구현체 — 다른 패키지(pugio.auth
|
|
19
|
+
등)도 재선언 없이 import해 쓸 수 있도록 공개 이름으로 export한다."""
|
|
20
|
+
|
|
21
|
+
def monotonic(self) -> float:
|
|
22
|
+
return time.monotonic()
|
|
23
|
+
|
|
24
|
+
def sleep(self, seconds: float) -> None:
|
|
25
|
+
time.sleep(seconds)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# 하위 호환: 기존 내부 전용 이름으로 참조하던 코드(및 다른 패키지의 재선언부)가
|
|
29
|
+
# 있을 수 있어 별칭을 유지한다.
|
|
30
|
+
_MonotonicClock = SystemClock
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class TokenBucket:
|
|
34
|
+
"""rps 상한 토큰 버킷. penalize()로 429 Retry-After를 흡수한다."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, rps: float, *, clock: Clock | None = None, burst: int = 1) -> None:
|
|
37
|
+
self._interval = 1.0 / rps
|
|
38
|
+
self._clock = clock or _MonotonicClock()
|
|
39
|
+
self._burst = float(burst)
|
|
40
|
+
self._tokens = float(burst)
|
|
41
|
+
self._last = self._clock.monotonic()
|
|
42
|
+
self._penalty_until = 0.0
|
|
43
|
+
|
|
44
|
+
def acquire(self) -> None:
|
|
45
|
+
now = self._clock.monotonic()
|
|
46
|
+
if now < self._penalty_until:
|
|
47
|
+
self._clock.sleep(self._penalty_until - now)
|
|
48
|
+
now = self._clock.monotonic()
|
|
49
|
+
self._tokens = min(self._burst, self._tokens + (now - self._last) / self._interval)
|
|
50
|
+
self._last = now
|
|
51
|
+
if self._tokens < 1.0:
|
|
52
|
+
self._clock.sleep((1.0 - self._tokens) * self._interval)
|
|
53
|
+
self._tokens = self._burst
|
|
54
|
+
self._last = self._clock.monotonic()
|
|
55
|
+
self._tokens -= 1.0
|
|
56
|
+
|
|
57
|
+
def penalize(self, seconds: float) -> None:
|
|
58
|
+
self._penalty_until = self._clock.monotonic() + seconds
|
arsenal_core/retry.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Retryable만 재시도하는 backoff 래퍼. 엔진은 빌린다 — tenacity 사용.
|
|
2
|
+
|
|
3
|
+
구현: docs/plans/2026-07-08-m1-core-foundation.md Task 5
|
|
4
|
+
FatalError는 즉시 전파, RetryableError만 exponential backoff + jitter.
|
|
5
|
+
|
|
6
|
+
M2-D: AuthExpiredError는 RetryableError의 서브클래스지만 여기서는 재시도 대상에서
|
|
7
|
+
제외한다. 401을 blind하게 backoff 재시도해봐야 provider.refresh()가 호출되지
|
|
8
|
+
않는 한 계속 401만 받는다 — 갱신 없는 재시도는 의미가 없다. AuthExpiredError는
|
|
9
|
+
즉시 전파시켜 runner.py가 "refresh() 후 한 번 더 시도"를 명시적으로 수행하게
|
|
10
|
+
한다 (러너 쪽 갱신 루프, docs/02-architecture.md M2-D).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from collections.abc import Callable
|
|
14
|
+
from typing import TypeVar
|
|
15
|
+
|
|
16
|
+
from tenacity import (
|
|
17
|
+
retry,
|
|
18
|
+
retry_if_exception_type,
|
|
19
|
+
retry_if_not_exception_type,
|
|
20
|
+
stop_after_attempt,
|
|
21
|
+
wait_exponential_jitter,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
from arsenal_core.errors import AuthExpiredError, RetryableError
|
|
25
|
+
|
|
26
|
+
T = TypeVar("T")
|
|
27
|
+
|
|
28
|
+
DEFAULT_MAX_ATTEMPTS = 5
|
|
29
|
+
DEFAULT_BASE_WAIT = 1.0 # seconds
|
|
30
|
+
MAX_WAIT = 60.0 # seconds
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def with_retry(
|
|
34
|
+
fn: Callable[[], T],
|
|
35
|
+
*,
|
|
36
|
+
max_attempts: int = DEFAULT_MAX_ATTEMPTS,
|
|
37
|
+
base_wait: float = DEFAULT_BASE_WAIT,
|
|
38
|
+
) -> T:
|
|
39
|
+
wrapped = retry(
|
|
40
|
+
retry=retry_if_exception_type(RetryableError)
|
|
41
|
+
& retry_if_not_exception_type(AuthExpiredError),
|
|
42
|
+
stop=stop_after_attempt(max_attempts),
|
|
43
|
+
wait=wait_exponential_jitter(initial=base_wait, max=MAX_WAIT),
|
|
44
|
+
reraise=True,
|
|
45
|
+
)(fn)
|
|
46
|
+
return wrapped()
|
arsenal_core/schema.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Schema snapshot comparison primitives shared by collection components."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Any, cast
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class SchemaChange:
|
|
10
|
+
"""One field-level schema change."""
|
|
11
|
+
|
|
12
|
+
field: str
|
|
13
|
+
before: dict[str, Any] | None
|
|
14
|
+
after: dict[str, Any] | None
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class SchemaDiff:
|
|
19
|
+
"""Added, removed, and modified fields between two snapshots."""
|
|
20
|
+
|
|
21
|
+
added: tuple[SchemaChange, ...]
|
|
22
|
+
removed: tuple[SchemaChange, ...]
|
|
23
|
+
changed: tuple[SchemaChange, ...]
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def has_changes(self) -> bool:
|
|
27
|
+
return bool(self.added or self.removed or self.changed)
|
|
28
|
+
|
|
29
|
+
def summary(self) -> str:
|
|
30
|
+
"""Return a compact, stable message suitable for logs and state."""
|
|
31
|
+
parts: list[str] = []
|
|
32
|
+
if self.added:
|
|
33
|
+
parts.append("added=" + ",".join(change.field for change in self.added))
|
|
34
|
+
if self.removed:
|
|
35
|
+
parts.append("removed=" + ",".join(change.field for change in self.removed))
|
|
36
|
+
if self.changed:
|
|
37
|
+
parts.append("changed=" + ",".join(change.field for change in self.changed))
|
|
38
|
+
return "; ".join(parts)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def compare_schema_snapshots(previous: str, current: str) -> SchemaDiff:
|
|
42
|
+
"""Compare snapshots produced by the runner's deterministic JSON encoder.
|
|
43
|
+
|
|
44
|
+
Snapshot entries are intentionally treated as opaque dictionaries except for
|
|
45
|
+
their ``name`` key. This lets future snapshot metadata be added without
|
|
46
|
+
changing the comparison algorithm, while still detecting type/nullability
|
|
47
|
+
changes in today's format.
|
|
48
|
+
"""
|
|
49
|
+
previous_fields = _fields(previous)
|
|
50
|
+
current_fields = _fields(current)
|
|
51
|
+
added: list[SchemaChange] = []
|
|
52
|
+
removed: list[SchemaChange] = []
|
|
53
|
+
changed: list[SchemaChange] = []
|
|
54
|
+
|
|
55
|
+
for name in sorted(current_fields.keys() - previous_fields.keys()):
|
|
56
|
+
added.append(SchemaChange(name, None, current_fields[name]))
|
|
57
|
+
for name in sorted(previous_fields.keys() - current_fields.keys()):
|
|
58
|
+
removed.append(SchemaChange(name, previous_fields[name], None))
|
|
59
|
+
for name in sorted(current_fields.keys() & previous_fields.keys()):
|
|
60
|
+
before = previous_fields[name]
|
|
61
|
+
after = current_fields[name]
|
|
62
|
+
if before != after:
|
|
63
|
+
changed.append(SchemaChange(name, before, after))
|
|
64
|
+
|
|
65
|
+
return SchemaDiff(tuple(added), tuple(removed), tuple(changed))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _fields(snapshot: str) -> dict[str, dict[str, Any]]:
|
|
69
|
+
raw = cast(object, json.loads(snapshot))
|
|
70
|
+
if not isinstance(raw, list):
|
|
71
|
+
raise ValueError("schema snapshot must be a JSON list")
|
|
72
|
+
entries = cast(list[object], raw)
|
|
73
|
+
fields: dict[str, dict[str, Any]] = {}
|
|
74
|
+
for raw_entry in entries:
|
|
75
|
+
if not isinstance(raw_entry, dict):
|
|
76
|
+
raise ValueError("schema snapshot entries must contain a string name")
|
|
77
|
+
entry = cast(dict[str, Any], raw_entry)
|
|
78
|
+
if not isinstance(entry.get("name"), str):
|
|
79
|
+
raise ValueError("schema snapshot entries must contain a string name")
|
|
80
|
+
fields[entry["name"]] = entry
|
|
81
|
+
return fields
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
from arsenal_core.spec.loader import load_pipeline
|
|
2
|
+
from arsenal_core.spec.models import (
|
|
3
|
+
AuthSpec,
|
|
4
|
+
ContractColumnSpec,
|
|
5
|
+
ContractSpec,
|
|
6
|
+
DatabaseSourceSpec,
|
|
7
|
+
DuckDBSinkSpec,
|
|
8
|
+
FileSourceSpec,
|
|
9
|
+
PaginationSpec,
|
|
10
|
+
ParquetSinkSpec,
|
|
11
|
+
PipelineSpec,
|
|
12
|
+
PostgresSinkSpec,
|
|
13
|
+
PythonSourceSpec,
|
|
14
|
+
RateLimitSpec,
|
|
15
|
+
RestSourceSpec,
|
|
16
|
+
SinkSpec,
|
|
17
|
+
SourceSpec,
|
|
18
|
+
SplitSpec,
|
|
19
|
+
ValidateRule,
|
|
20
|
+
ValidateSpec,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"AuthSpec",
|
|
25
|
+
"ContractColumnSpec",
|
|
26
|
+
"ContractSpec",
|
|
27
|
+
"DatabaseSourceSpec",
|
|
28
|
+
"DuckDBSinkSpec",
|
|
29
|
+
"FileSourceSpec",
|
|
30
|
+
"PaginationSpec",
|
|
31
|
+
"ParquetSinkSpec",
|
|
32
|
+
"PipelineSpec",
|
|
33
|
+
"PostgresSinkSpec",
|
|
34
|
+
"PythonSourceSpec",
|
|
35
|
+
"RateLimitSpec",
|
|
36
|
+
"RestSourceSpec",
|
|
37
|
+
"SinkSpec",
|
|
38
|
+
"SourceSpec",
|
|
39
|
+
"SplitSpec",
|
|
40
|
+
"ValidateRule",
|
|
41
|
+
"ValidateSpec",
|
|
42
|
+
"load_pipeline",
|
|
43
|
+
]
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""YAML → 검증된 PipelineSpec. 에러 메시지 품질이 곧 UX.
|
|
2
|
+
|
|
3
|
+
구현: docs/plans/2026-07-08-m1-core-foundation.md Task 4
|
|
4
|
+
- ${VAR} 환경변수 치환 (비밀은 YAML에 두지 않는다)
|
|
5
|
+
- 검증 실패 시 필드 경로가 담긴 FatalError
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
import yaml
|
|
13
|
+
from pydantic import ValidationError
|
|
14
|
+
|
|
15
|
+
from arsenal_core.errors import FatalError
|
|
16
|
+
from arsenal_core.spec.models import PipelineSpec
|
|
17
|
+
|
|
18
|
+
_ENV_PATTERN = re.compile(r"\$\{(\w+)\}")
|
|
19
|
+
|
|
20
|
+
# discriminated union 필드 → 허용된 태그 값. Pydantic은 이런 필드의 에러 loc에
|
|
21
|
+
# 태그를 끼워 넣는다(예: ("source","rest","url")) — 사용자에게는 YAML 그대로의
|
|
22
|
+
# 경로(source.url)가 더 읽기 쉽고, M1 에러 메시지와도 하위 호환된다.
|
|
23
|
+
_UNION_TAGS: dict[str, frozenset[str]] = {
|
|
24
|
+
"source": frozenset({"rest", "file", "database", "python", "dlt"}),
|
|
25
|
+
"sink": frozenset({"parquet", "duckdb", "postgres"}),
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _substitute_env(text: str) -> str:
|
|
30
|
+
def repl(m: re.Match[str]) -> str:
|
|
31
|
+
value = os.environ.get(m.group(1))
|
|
32
|
+
if value is None:
|
|
33
|
+
raise FatalError(f"environment variable not set: {m.group(1)}")
|
|
34
|
+
return value
|
|
35
|
+
|
|
36
|
+
return _ENV_PATTERN.sub(repl, text)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _clean_loc(loc: tuple[int | str, ...]) -> tuple[int | str, ...]:
|
|
40
|
+
"""discriminated union의 태그 세그먼트를 제거한다 (source.rest.url → source.url)."""
|
|
41
|
+
cleaned: list[int | str] = []
|
|
42
|
+
for i, part in enumerate(loc):
|
|
43
|
+
prev = loc[i - 1] if i > 0 else None
|
|
44
|
+
allowed = _UNION_TAGS.get(str(prev)) if isinstance(prev, str) else None
|
|
45
|
+
if allowed is not None and isinstance(part, str) and part in allowed:
|
|
46
|
+
continue
|
|
47
|
+
cleaned.append(part)
|
|
48
|
+
return tuple(cleaned)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def load_pipeline(path: Path) -> PipelineSpec:
|
|
52
|
+
try:
|
|
53
|
+
text = path.read_text(encoding="utf-8")
|
|
54
|
+
except FileNotFoundError as e:
|
|
55
|
+
raise FatalError(f"spec file not found: {path}") from e
|
|
56
|
+
except OSError as e:
|
|
57
|
+
raise FatalError(f"cannot read spec file {path}: {e}") from e
|
|
58
|
+
|
|
59
|
+
raw = yaml.safe_load(_substitute_env(text))
|
|
60
|
+
try:
|
|
61
|
+
return PipelineSpec.model_validate(raw)
|
|
62
|
+
except ValidationError as e:
|
|
63
|
+
lines = [
|
|
64
|
+
f"{'.'.join(str(p) for p in _clean_loc(err['loc']))}: {err['msg']}"
|
|
65
|
+
for err in e.errors()
|
|
66
|
+
]
|
|
67
|
+
raise FatalError(f"invalid pipeline spec {path}:\n " + "\n ".join(lines)) from e
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
"""파이프라인 YAML의 Pydantic 모델. 선언이 인터페이스다 — extra는 거부.
|
|
2
|
+
|
|
3
|
+
YAML 전체 형태: docs/02-architecture.md "파이프라인 YAML 스펙"
|
|
4
|
+
SourceSpec은 discriminated union(rest/file/database/python/dlt)이다. 기존 이름
|
|
5
|
+
`SourceSpec`은 union 별칭으로 유지해 M1 코드의 import가 깨지지 않게 한다 — 단,
|
|
6
|
+
`SourceSpec(type="rest", ...)` 같은 직접 생성자 호출은 더 이상 불가하다
|
|
7
|
+
(Annotated[Union[...], ...]는 호출 불가). REST 소스를 직접 만들 때는
|
|
8
|
+
`RestSourceSpec`을 사용한다 (M1의 REST 필드를 그대로 옮긴 것 — 필드 호환).
|
|
9
|
+
필드 확장 계획: M2에서 pagination.mode(page/cursor), sink.type(duckdb/postgres),
|
|
10
|
+
auth, validate 블록 추가. P1 필드는 이름을 미리 예약해 하위 호환을 지킨다.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Annotated, Any, Literal
|
|
15
|
+
|
|
16
|
+
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class _Frozen(BaseModel):
|
|
20
|
+
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class PaginationSpec(_Frozen):
|
|
24
|
+
mode: Literal["offset", "page", "cursor", "link"]
|
|
25
|
+
param: str = "offset"
|
|
26
|
+
size_param: str = "limit"
|
|
27
|
+
size: int = 100
|
|
28
|
+
start_page: int = 1 # "page" 모드의 시작 페이지 번호
|
|
29
|
+
cursor_param: str | None = None # "cursor" 모드: 커서를 실어 보낼 요청 파라미터명
|
|
30
|
+
cursor_path: str | None = None # "cursor" 모드: 응답에서 다음 커서를 읽을 dot-path
|
|
31
|
+
record_path: str | None = None # envelope 내 레코드 배열의 dot-path (None=응답 자체가 배열)
|
|
32
|
+
|
|
33
|
+
@model_validator(mode="after")
|
|
34
|
+
def _cursor_fields_required(self) -> "PaginationSpec":
|
|
35
|
+
if self.mode == "cursor" and not (self.cursor_param and self.cursor_path):
|
|
36
|
+
raise ValueError("cursor mode requires cursor_param and cursor_path")
|
|
37
|
+
return self
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class RateLimitSpec(_Frozen):
|
|
41
|
+
rps: float = Field(gt=0) # M2: 토큰 버킷 + 429 적응 감속. 0/음수는 TokenBucket의
|
|
42
|
+
# 1.0/rps 계산에서 ZeroDivisionError/역방향 스로틀로 이어져 여기서 차단한다.
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class AuthSpec(_Frozen):
|
|
46
|
+
"""REST 소스 인증 (M2). static_token은 헤더에 그대로, oauth2는 client_credentials
|
|
47
|
+
흐름으로 토큰을 획득/갱신한다 (구현은 M2-D 이후, 여기는 모델만)."""
|
|
48
|
+
|
|
49
|
+
type: Literal["static_token", "oauth2_client_credentials"]
|
|
50
|
+
token_env: str | None = None
|
|
51
|
+
token_url: str | None = None
|
|
52
|
+
client_id_env: str | None = None
|
|
53
|
+
client_secret_env: str | None = None
|
|
54
|
+
expiry_buffer_s: int = 60
|
|
55
|
+
|
|
56
|
+
@model_validator(mode="after")
|
|
57
|
+
def _required_fields_for_type(self) -> "AuthSpec":
|
|
58
|
+
if self.type == "static_token" and not self.token_env:
|
|
59
|
+
raise ValueError("static_token auth requires token_env")
|
|
60
|
+
if self.type == "oauth2_client_credentials":
|
|
61
|
+
missing = [
|
|
62
|
+
name
|
|
63
|
+
for name, value in (
|
|
64
|
+
("token_url", self.token_url),
|
|
65
|
+
("client_id_env", self.client_id_env),
|
|
66
|
+
("client_secret_env", self.client_secret_env),
|
|
67
|
+
)
|
|
68
|
+
if not value
|
|
69
|
+
]
|
|
70
|
+
if missing:
|
|
71
|
+
raise ValueError(f"oauth2_client_credentials auth requires {', '.join(missing)}")
|
|
72
|
+
return self
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class RestSourceSpec(_Frozen):
|
|
76
|
+
"""REST API 소스 — M1 SourceSpec의 필드를 그대로 옮긴 것 (하위 호환)."""
|
|
77
|
+
|
|
78
|
+
type: Literal["rest"]
|
|
79
|
+
url: str
|
|
80
|
+
headers: dict[str, str] = {}
|
|
81
|
+
pagination: PaginationSpec
|
|
82
|
+
rate_limit: RateLimitSpec | None = None
|
|
83
|
+
encoding: str = "utf-8" # M2: euc-kr 등 비UTF-8 처리
|
|
84
|
+
auth: AuthSpec | None = None
|
|
85
|
+
# M2-H: Notion 검색(`POST /v1/search`)처럼 페이지네이션 파라미터를 쿼리가 아니라
|
|
86
|
+
# JSON 바디로 실어야 하는 API가 있다 — GET이 기본값이라 기존 스펙은 영향받지 않는다.
|
|
87
|
+
method: Literal["GET", "POST"] = "GET"
|
|
88
|
+
body: dict[str, Any] | None = None # method="POST"일 때 요청에 실을 정적 JSON 바디
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class FileSourceSpec(_Frozen):
|
|
92
|
+
"""로컬 파일 소스 (M2 Task 2.11) — csv/jsonl/excel to Arrow."""
|
|
93
|
+
|
|
94
|
+
type: Literal["file"]
|
|
95
|
+
path: str # 글롭 (예: "./raw/**/*.csv")
|
|
96
|
+
format: Literal["auto", "csv", "jsonl", "excel"] = "auto"
|
|
97
|
+
encoding: str = "utf-8"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class SplitSpec(_Frozen):
|
|
101
|
+
key: str # 단조 증가 키 (PK/serial/타임스탬프)
|
|
102
|
+
chunk: int = Field(default=100_000, gt=0) # 0/음수는 무한 루프로 이어져 검증 단계에서 차단
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class DatabaseSourceSpec(_Frozen):
|
|
106
|
+
"""운영 DB 소스 (M2 Task 2.12 / M2-G).
|
|
107
|
+
|
|
108
|
+
dialect="sqlite"는 Python 표준 sqlite3 드라이버. dialect="postgres"/"mysql"은
|
|
109
|
+
DuckDB scanner(ATTACH, docs/09 수 1)로 구현된다.
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
type: Literal["database"]
|
|
113
|
+
dialect: Literal["postgres", "mysql", "sqlite"]
|
|
114
|
+
dsn_env: str # DSN은 환경변수로만 (비밀 원칙)
|
|
115
|
+
table: str
|
|
116
|
+
split: SplitSpec
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class PythonSourceSpec(_Frozen):
|
|
120
|
+
"""커스텀 Python 소스 탈출구 (M2 Task 2.13). P1 dlt 래퍼의 기반 메커니즘."""
|
|
121
|
+
|
|
122
|
+
type: Literal["python"]
|
|
123
|
+
target: str # "pkg.module:ClassName" — Source 프로토콜 구현체
|
|
124
|
+
options: dict[str, Any] = {} # 생성자 첫 인자로 전달
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class DltSourceSpec(_Frozen):
|
|
128
|
+
"""Optional dlt source adapter (target is a user-owned source function)."""
|
|
129
|
+
|
|
130
|
+
type: Literal["dlt"]
|
|
131
|
+
target: str # "package.module:source_function"
|
|
132
|
+
options: dict[str, Any] = {}
|
|
133
|
+
resources: list[str] | None = None
|
|
134
|
+
batch_size: int = Field(default=10_000, gt=0)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
SourceSpec = Annotated[
|
|
138
|
+
RestSourceSpec | FileSourceSpec | DatabaseSourceSpec | PythonSourceSpec | DltSourceSpec,
|
|
139
|
+
Field(discriminator="type"),
|
|
140
|
+
]
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class ParquetSinkSpec(_Frozen):
|
|
144
|
+
type: Literal["parquet"]
|
|
145
|
+
# str로 보관 — Path로 파싱하면 "s3://bucket/x" 같은 URI 스킴이 "s3:/bucket/x"로
|
|
146
|
+
# 정규화되어 훼손된다 (P1 httpfs/S3 싱크가 이 필드를 그대로 쓴다). sink/엔진이
|
|
147
|
+
# 파일시스템 연산이 필요한 지점에서 Path(...)로 감싸 해석한다.
|
|
148
|
+
path: str
|
|
149
|
+
|
|
150
|
+
@field_validator("path", mode="before")
|
|
151
|
+
@classmethod
|
|
152
|
+
def _coerce_path_to_str(cls, v: object) -> object:
|
|
153
|
+
if isinstance(v, Path):
|
|
154
|
+
return str(v)
|
|
155
|
+
return v
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _merge_key_non_empty(v: list[str]) -> list[str]:
|
|
159
|
+
"""merge_key가 비어 있으면 DELETE/ON CONFLICT의 매치 조건이 없어 전체 테이블을
|
|
160
|
+
지우거나(duckdb) 제약을 만들 수 없다(postgres) — 생성 시점에 차단한다 (M2-F FIX 4)."""
|
|
161
|
+
if len(v) < 1:
|
|
162
|
+
raise ValueError("merge_key must have at least one column")
|
|
163
|
+
return v
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class DuckDBSinkSpec(_Frozen):
|
|
167
|
+
"""DuckDB 파일 싱크 (M2) — temp 테이블 → MERGE로 멱등 upsert."""
|
|
168
|
+
|
|
169
|
+
type: Literal["duckdb"]
|
|
170
|
+
path: str
|
|
171
|
+
table: str
|
|
172
|
+
merge_key: list[str]
|
|
173
|
+
|
|
174
|
+
@field_validator("merge_key")
|
|
175
|
+
@classmethod
|
|
176
|
+
def _merge_key_non_empty(cls, v: list[str]) -> list[str]:
|
|
177
|
+
return _merge_key_non_empty(v)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
class PostgresSinkSpec(_Frozen):
|
|
181
|
+
"""Postgres 싱크 (M2) — merge_key 기준 upsert."""
|
|
182
|
+
|
|
183
|
+
type: Literal["postgres"]
|
|
184
|
+
dsn_env: str
|
|
185
|
+
table: str
|
|
186
|
+
merge_key: list[str]
|
|
187
|
+
|
|
188
|
+
@field_validator("merge_key")
|
|
189
|
+
@classmethod
|
|
190
|
+
def _merge_key_non_empty(cls, v: list[str]) -> list[str]:
|
|
191
|
+
return _merge_key_non_empty(v)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
SinkSpec = Annotated[
|
|
195
|
+
ParquetSinkSpec | DuckDBSinkSpec | PostgresSinkSpec,
|
|
196
|
+
Field(discriminator="type"),
|
|
197
|
+
]
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
class ValidateRule(_Frozen):
|
|
201
|
+
field: str
|
|
202
|
+
not_null: bool = False
|
|
203
|
+
unique: bool = False
|
|
204
|
+
min: float | None = None
|
|
205
|
+
max: float | None = None
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
class ValidateSpec(_Frozen):
|
|
209
|
+
rules: list[ValidateRule]
|
|
210
|
+
on_violation: Literal["block", "quarantine", "warn"] = "quarantine"
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
class ContractColumnSpec(_Frozen):
|
|
214
|
+
name: str
|
|
215
|
+
type: str = Field(description="Arrow type string, for example int64 or string")
|
|
216
|
+
nullable: bool = True
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
class ContractSpec(_Frozen):
|
|
220
|
+
columns: list[ContractColumnSpec] = Field(min_length=1)
|
|
221
|
+
allow_extra: bool = False
|
|
222
|
+
on_violation: Literal["block", "quarantine", "warn"] = "block"
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
class PipelineSpec(_Frozen):
|
|
226
|
+
model_config = ConfigDict(frozen=True, extra="forbid", populate_by_name=True)
|
|
227
|
+
|
|
228
|
+
name: str
|
|
229
|
+
# str로 보관 — ParquetSinkSpec.path와 같은 규약. Path 기본값은 JSON 스키마
|
|
230
|
+
# 직렬화가 호스트의 경로 flavour에 묶여, Windows에서 생성한 산출물이
|
|
231
|
+
# Linux/macOS 것과 달라진다(생성 문서 `--check` CI 게이트가 깨진다).
|
|
232
|
+
# 파일시스템 연산이 필요한 지점에서 Path(...)로 감싸 해석한다.
|
|
233
|
+
state_dir: str = ".arsenal"
|
|
234
|
+
source: SourceSpec
|
|
235
|
+
sink: SinkSpec
|
|
236
|
+
validation: ValidateSpec | None = Field(default=None, alias="validate")
|
|
237
|
+
contract: ContractSpec | None = None
|
|
238
|
+
schema_drift: Literal["allow", "warn", "block"] = Field(
|
|
239
|
+
default="allow",
|
|
240
|
+
description="Policy when the observed source schema differs from the last snapshot.",
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
@field_validator("state_dir", mode="before")
|
|
244
|
+
@classmethod
|
|
245
|
+
def _coerce_state_dir_to_str(cls, v: object) -> object:
|
|
246
|
+
if isinstance(v, Path):
|
|
247
|
+
return str(v)
|
|
248
|
+
return v
|
|
249
|
+
|
|
250
|
+
@field_validator("name")
|
|
251
|
+
@classmethod
|
|
252
|
+
def _name_is_path_safe(cls, v: str) -> str:
|
|
253
|
+
"""name은 `state_dir/{name}.db`와 `dlq/{name}/`에 그대로 꽂힌다 (M2-E FIX 8) —
|
|
254
|
+
경로 구분자나 `..`가 섞이면 상태 DB/DLQ 경로를 다른 디렉터리로 탈출시킬 수
|
|
255
|
+
있어 여기서 차단한다."""
|
|
256
|
+
if "/" in v or "\\" in v or ".." in v:
|
|
257
|
+
raise ValueError(
|
|
258
|
+
f"pipeline name must not contain '/', '\\\\', or '..' (path-safety): {v!r}"
|
|
259
|
+
)
|
|
260
|
+
return v
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from arsenal_core.state.store import (
|
|
2
|
+
SOURCE_EXHAUSTED,
|
|
3
|
+
LineageRecord,
|
|
4
|
+
PipelineMetrics,
|
|
5
|
+
StateStore,
|
|
6
|
+
UnitMetrics,
|
|
7
|
+
UnitRecord,
|
|
8
|
+
UnitSpec,
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"SOURCE_EXHAUSTED",
|
|
13
|
+
"PipelineMetrics",
|
|
14
|
+
"LineageRecord",
|
|
15
|
+
"StateStore",
|
|
16
|
+
"UnitMetrics",
|
|
17
|
+
"UnitRecord",
|
|
18
|
+
"UnitSpec",
|
|
19
|
+
]
|
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
"""SQLite(WAL) 영속 상태 저장소. 상태는 절대 메모리에만 두지 않는다.
|
|
2
|
+
|
|
3
|
+
핵심 불변식: "sink 쓰기 성공 → done 마킹" 순서 (docs/02-architecture.md).
|
|
4
|
+
단위 지표(row_count/byte_count/duration_ms)는 비용 가시성의 원료 — P0부터 기록 (docs/07).
|
|
5
|
+
구현: docs/plans/2026-07-08-m1-core-foundation.md Task 3
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import sqlite3
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from datetime import UTC, datetime
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from arsenal_core.identity import unit_id as make_unit_id
|
|
16
|
+
|
|
17
|
+
# cursor/link 트래버설이 next_cursor=None에 도달해 "완료"됐음을 나타내는 예약 센티널.
|
|
18
|
+
# cursors 테이블(schema 불변)에 실제 커서/URL 값처럼 저장된다 — NUL 바이트 프리픽스라
|
|
19
|
+
# 실제 커서 값이나 URL과 절대 충돌하지 않는다. M2-B: 재실행 무한루프 수정.
|
|
20
|
+
SOURCE_EXHAUSTED = "\x00__ARSENAL_SOURCE_EXHAUSTED__"
|
|
21
|
+
|
|
22
|
+
_SCHEMA = """
|
|
23
|
+
CREATE TABLE IF NOT EXISTS units (
|
|
24
|
+
unit_id TEXT PRIMARY KEY,
|
|
25
|
+
pipeline TEXT NOT NULL,
|
|
26
|
+
unit_key TEXT NOT NULL,
|
|
27
|
+
payload TEXT NOT NULL,
|
|
28
|
+
status TEXT NOT NULL, -- pending | running | done | failed | quarantined
|
|
29
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
30
|
+
last_error TEXT,
|
|
31
|
+
row_count INTEGER,
|
|
32
|
+
byte_count INTEGER,
|
|
33
|
+
duration_ms INTEGER,
|
|
34
|
+
created_at TEXT NOT NULL, -- ISO8601 UTC
|
|
35
|
+
updated_at TEXT NOT NULL
|
|
36
|
+
);
|
|
37
|
+
CREATE INDEX IF NOT EXISTS idx_units_pipeline_status ON units(pipeline, status);
|
|
38
|
+
CREATE TABLE IF NOT EXISTS cursors (
|
|
39
|
+
pipeline TEXT NOT NULL, source TEXT NOT NULL,
|
|
40
|
+
cursor TEXT NOT NULL, updated_at TEXT NOT NULL,
|
|
41
|
+
PRIMARY KEY (pipeline, source)
|
|
42
|
+
);
|
|
43
|
+
CREATE TABLE IF NOT EXISTS schema_snapshots (
|
|
44
|
+
pipeline TEXT NOT NULL,
|
|
45
|
+
captured_at TEXT NOT NULL,
|
|
46
|
+
schema_json TEXT NOT NULL
|
|
47
|
+
);
|
|
48
|
+
CREATE TABLE IF NOT EXISTS lineage (
|
|
49
|
+
pipeline TEXT PRIMARY KEY,
|
|
50
|
+
source_type TEXT NOT NULL,
|
|
51
|
+
source_ref TEXT NOT NULL,
|
|
52
|
+
sink_type TEXT NOT NULL,
|
|
53
|
+
sink_ref TEXT NOT NULL,
|
|
54
|
+
updated_at TEXT NOT NULL
|
|
55
|
+
);
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _now() -> str:
|
|
60
|
+
return datetime.now(UTC).isoformat()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class UnitSpec:
|
|
65
|
+
"""수집·처리의 최소 단위. 결정적 ID를 가진다."""
|
|
66
|
+
|
|
67
|
+
unit_id: str
|
|
68
|
+
pipeline: str
|
|
69
|
+
unit_key: str # 사람이 읽는 키 (예: "offset=200")
|
|
70
|
+
payload: dict[str, Any] # 요청 재구성에 필요한 파라미터
|
|
71
|
+
|
|
72
|
+
@classmethod
|
|
73
|
+
def create(
|
|
74
|
+
cls, *, pipeline: str, source: str, unit_key: str, payload: dict[str, Any]
|
|
75
|
+
) -> "UnitSpec":
|
|
76
|
+
"""identity.unit_id로 결정적 ID를 만들어 생성한다."""
|
|
77
|
+
return cls(
|
|
78
|
+
unit_id=make_unit_id(pipeline, source, unit_key),
|
|
79
|
+
pipeline=pipeline,
|
|
80
|
+
unit_key=unit_key,
|
|
81
|
+
payload=payload,
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass(frozen=True)
|
|
86
|
+
class UnitRecord:
|
|
87
|
+
unit_id: str
|
|
88
|
+
status: str
|
|
89
|
+
attempts: int
|
|
90
|
+
last_error: str | None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass(frozen=True)
|
|
94
|
+
class UnitMetrics:
|
|
95
|
+
row_count: int | None
|
|
96
|
+
byte_count: int | None
|
|
97
|
+
duration_ms: int | None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
@dataclass(frozen=True)
|
|
101
|
+
class PipelineMetrics:
|
|
102
|
+
"""Cumulative completed-unit metrics used by Scorpio/status reporting."""
|
|
103
|
+
|
|
104
|
+
completed_units: int
|
|
105
|
+
row_count: int
|
|
106
|
+
byte_count: int
|
|
107
|
+
duration_ms: int
|
|
108
|
+
last_completed_at: str | None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@dataclass(frozen=True)
|
|
112
|
+
class LineageRecord:
|
|
113
|
+
pipeline: str
|
|
114
|
+
source_type: str
|
|
115
|
+
source_ref: str
|
|
116
|
+
sink_type: str
|
|
117
|
+
sink_ref: str
|
|
118
|
+
updated_at: str
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class StateStore:
|
|
122
|
+
"""unit 상태·커서·스키마 스냅샷의 영속 저장소.
|
|
123
|
+
|
|
124
|
+
상태 전이: pending → running → done | failed | quarantined
|
|
125
|
+
(재시도는 with_retry가 mark_failed 이전에 in-process로 수행한다 — 이 저장소는
|
|
126
|
+
running → pending으로 되돌리는 전이를 갖지 않는다.)
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
def __init__(self, db_path: Path) -> None:
|
|
130
|
+
db_path.parent.mkdir(parents=True, exist_ok=True)
|
|
131
|
+
self._conn = sqlite3.connect(db_path)
|
|
132
|
+
self._conn.execute("PRAGMA journal_mode=WAL")
|
|
133
|
+
self._conn.executescript(_SCHEMA)
|
|
134
|
+
|
|
135
|
+
def register(self, unit: UnitSpec) -> None:
|
|
136
|
+
"""INSERT OR IGNORE — 두 번 등록해도 안전 (멱등)."""
|
|
137
|
+
self._conn.execute(
|
|
138
|
+
"INSERT OR IGNORE INTO units "
|
|
139
|
+
"(unit_id, pipeline, unit_key, payload, status, created_at, updated_at) "
|
|
140
|
+
"VALUES (?, ?, ?, ?, 'pending', ?, ?)",
|
|
141
|
+
(unit.unit_id, unit.pipeline, unit.unit_key, json.dumps(unit.payload), _now(), _now()),
|
|
142
|
+
)
|
|
143
|
+
self._conn.commit()
|
|
144
|
+
|
|
145
|
+
def _set_status(self, uid: str, status: str, error: str | None = None) -> None:
|
|
146
|
+
bump = 1 if status == "failed" else 0
|
|
147
|
+
self._conn.execute(
|
|
148
|
+
"UPDATE units SET status=?, last_error=?, attempts=attempts+?, updated_at=? "
|
|
149
|
+
"WHERE unit_id=?",
|
|
150
|
+
(status, error, bump, _now(), uid),
|
|
151
|
+
)
|
|
152
|
+
self._conn.commit()
|
|
153
|
+
|
|
154
|
+
def mark_running(self, uid: str) -> None:
|
|
155
|
+
self._set_status(uid, "running")
|
|
156
|
+
|
|
157
|
+
def mark_done(
|
|
158
|
+
self,
|
|
159
|
+
uid: str,
|
|
160
|
+
*,
|
|
161
|
+
row_count: int | None = None,
|
|
162
|
+
byte_count: int | None = None,
|
|
163
|
+
duration_ms: int | None = None,
|
|
164
|
+
) -> None:
|
|
165
|
+
self._conn.execute(
|
|
166
|
+
"UPDATE units SET status='done', row_count=?, byte_count=?, duration_ms=?, "
|
|
167
|
+
"updated_at=? WHERE unit_id=?",
|
|
168
|
+
(row_count, byte_count, duration_ms, _now(), uid),
|
|
169
|
+
)
|
|
170
|
+
self._conn.commit()
|
|
171
|
+
|
|
172
|
+
def mark_done_and_advance_cursor(
|
|
173
|
+
self,
|
|
174
|
+
uid: str,
|
|
175
|
+
*,
|
|
176
|
+
pipeline: str,
|
|
177
|
+
source: str,
|
|
178
|
+
cursor: str,
|
|
179
|
+
row_count: int | None = None,
|
|
180
|
+
byte_count: int | None = None,
|
|
181
|
+
duration_ms: int | None = None,
|
|
182
|
+
) -> None:
|
|
183
|
+
"""mark_done + set_cursor를 한 커넥션·한 커밋으로 묶는다 (M2 최종 리뷰 FIX 1).
|
|
184
|
+
|
|
185
|
+
두 문장을 별개 트랜잭션(mark_done() 다음 set_cursor())으로 실행하면, 그
|
|
186
|
+
사이에 크래시가 나면 unit은 done인데 커서는 그 unit을 만들어낸 이전 값에
|
|
187
|
+
멈춘 상태로 남는다. 재실행 시 그 스테일 커서로 seed된 RestSource가 이미
|
|
188
|
+
done인 그 unit을 다시 내고, runner의 is_done 스킵 경로는 fetch()를 부르지
|
|
189
|
+
않으니 커서가 영원히 전진하지 못해 무한루프가 된다 — cursor/link 모드의
|
|
190
|
+
모든 중간 페이지에 영향을 준다(마지막 페이지의 SOURCE_EXHAUSTED 센티널만
|
|
191
|
+
고쳤던 이전 수정으로는 부족했다). 두 UPDATE/INSERT를 커밋 하나로 묶어,
|
|
192
|
+
크래시가 나면 "둘 다 반영" 또는 "둘 다 미반영"만 관측되게 한다 — 이 둘
|
|
193
|
+
사이의 상태는 존재하지 않는다.
|
|
194
|
+
"""
|
|
195
|
+
self._conn.execute(
|
|
196
|
+
"UPDATE units SET status='done', row_count=?, byte_count=?, duration_ms=?, "
|
|
197
|
+
"updated_at=? WHERE unit_id=?",
|
|
198
|
+
(row_count, byte_count, duration_ms, _now(), uid),
|
|
199
|
+
)
|
|
200
|
+
self._conn.execute(
|
|
201
|
+
"INSERT INTO cursors (pipeline, source, cursor, updated_at) VALUES (?,?,?,?) "
|
|
202
|
+
"ON CONFLICT(pipeline, source) DO UPDATE SET cursor=excluded.cursor, "
|
|
203
|
+
"updated_at=excluded.updated_at",
|
|
204
|
+
(pipeline, source, cursor, _now()),
|
|
205
|
+
)
|
|
206
|
+
self._conn.commit()
|
|
207
|
+
|
|
208
|
+
def mark_failed(self, uid: str, error: str) -> None:
|
|
209
|
+
"""attempts를 1 올리고 last_error 기록."""
|
|
210
|
+
self._set_status(uid, "failed", error)
|
|
211
|
+
|
|
212
|
+
def mark_quarantined(self, uid: str, reason: str) -> None:
|
|
213
|
+
"""검증 위반으로 격리. _set_status를 재사용하지 않는 이유: quarantine은
|
|
214
|
+
재시도 실패가 아니라서 attempts를 올리면 안 된다 (M2-E)."""
|
|
215
|
+
self._conn.execute(
|
|
216
|
+
"UPDATE units SET status='quarantined', last_error=?, updated_at=? WHERE unit_id=?",
|
|
217
|
+
(reason, _now(), uid),
|
|
218
|
+
)
|
|
219
|
+
self._conn.commit()
|
|
220
|
+
|
|
221
|
+
def quarantined(self, pipeline: str) -> list[UnitRecord]:
|
|
222
|
+
"""`pugio dlq list`의 데이터 — 격리된 unit만."""
|
|
223
|
+
rows = self._conn.execute(
|
|
224
|
+
"SELECT unit_id, status, attempts, last_error FROM units "
|
|
225
|
+
"WHERE pipeline=? AND status='quarantined'",
|
|
226
|
+
(pipeline,),
|
|
227
|
+
).fetchall()
|
|
228
|
+
return [UnitRecord(*r) for r in rows]
|
|
229
|
+
|
|
230
|
+
def requeue(self, uid: str) -> int:
|
|
231
|
+
"""`pugio dlq retry` — 격리를 풀고 pending으로 되돌려 다음 run이 재수집하게 한다.
|
|
232
|
+
|
|
233
|
+
반환값은 실제로 갱신된 행 수 (0 또는 1) — 존재하지 않는 unit_id를 넘기면
|
|
234
|
+
조용히 0건 갱신되고도 성공한 것처럼 보이는 걸 막으려고 CLI가 이 값을 확인한다
|
|
235
|
+
(M2-E FIX 1: unit_key/unit_id 혼동으로 인한 silent no-op false success).
|
|
236
|
+
"""
|
|
237
|
+
cur = self._conn.execute(
|
|
238
|
+
"UPDATE units SET status='pending', last_error=NULL, updated_at=? WHERE unit_id=?",
|
|
239
|
+
(_now(), uid),
|
|
240
|
+
)
|
|
241
|
+
self._conn.commit()
|
|
242
|
+
return cur.rowcount
|
|
243
|
+
|
|
244
|
+
def status(self, uid: str) -> str | None:
|
|
245
|
+
row = self._conn.execute("SELECT status FROM units WHERE unit_id=?", (uid,)).fetchone()
|
|
246
|
+
return row[0] if row else None
|
|
247
|
+
|
|
248
|
+
def is_done(self, uid: str) -> bool:
|
|
249
|
+
return self.status(uid) == "done"
|
|
250
|
+
|
|
251
|
+
def get(self, uid: str) -> UnitRecord:
|
|
252
|
+
row = self._conn.execute(
|
|
253
|
+
"SELECT unit_id, status, attempts, last_error FROM units WHERE unit_id=?", (uid,)
|
|
254
|
+
).fetchone()
|
|
255
|
+
if row is None:
|
|
256
|
+
raise KeyError(uid)
|
|
257
|
+
return UnitRecord(*row)
|
|
258
|
+
|
|
259
|
+
def metrics(self, uid: str) -> UnitMetrics:
|
|
260
|
+
row = self._conn.execute(
|
|
261
|
+
"SELECT row_count, byte_count, duration_ms FROM units WHERE unit_id=?", (uid,)
|
|
262
|
+
).fetchone()
|
|
263
|
+
if row is None:
|
|
264
|
+
raise KeyError(uid)
|
|
265
|
+
return UnitMetrics(*row)
|
|
266
|
+
|
|
267
|
+
def get_cursor(self, pipeline: str, source: str) -> str | None:
|
|
268
|
+
"""cursor/link 모드 재개용 — 없으면 None (첫 실행)."""
|
|
269
|
+
row = self._conn.execute(
|
|
270
|
+
"SELECT cursor FROM cursors WHERE pipeline=? AND source=?", (pipeline, source)
|
|
271
|
+
).fetchone()
|
|
272
|
+
return row[0] if row else None
|
|
273
|
+
|
|
274
|
+
def set_cursor(self, pipeline: str, source: str, cursor: str) -> None:
|
|
275
|
+
"""upsert — 같은 (pipeline, source)는 최신 커서로 덮어쓴다."""
|
|
276
|
+
self._conn.execute(
|
|
277
|
+
"INSERT INTO cursors (pipeline, source, cursor, updated_at) VALUES (?,?,?,?) "
|
|
278
|
+
"ON CONFLICT(pipeline, source) DO UPDATE SET cursor=excluded.cursor, "
|
|
279
|
+
"updated_at=excluded.updated_at",
|
|
280
|
+
(pipeline, source, cursor, _now()),
|
|
281
|
+
)
|
|
282
|
+
self._conn.commit()
|
|
283
|
+
|
|
284
|
+
def last_schema(self, pipeline: str) -> str | None:
|
|
285
|
+
"""이 pipeline의 가장 최근 스키마 스냅샷 — 없으면 None (첫 실행)."""
|
|
286
|
+
row = self._conn.execute(
|
|
287
|
+
"SELECT schema_json FROM schema_snapshots WHERE pipeline=? "
|
|
288
|
+
"ORDER BY captured_at DESC, rowid DESC LIMIT 1",
|
|
289
|
+
(pipeline,),
|
|
290
|
+
).fetchone()
|
|
291
|
+
return row[0] if row else None
|
|
292
|
+
|
|
293
|
+
def snapshot_schema(self, pipeline: str, schema_json: str) -> None:
|
|
294
|
+
"""가장 최근 스냅샷과 다를 때만 append — 스키마가 안 바뀌었으면 no-op.
|
|
295
|
+
|
|
296
|
+
스키마 변경 이력만 남기려는 것 — 매 run마다 동일한 schema_json을 계속
|
|
297
|
+
쌓으면 감사 이력이 노이즈로 뒤덮인다 (탐지/정책은 P1, 여기는 기록만).
|
|
298
|
+
"""
|
|
299
|
+
if self.last_schema(pipeline) == schema_json:
|
|
300
|
+
return
|
|
301
|
+
self._conn.execute(
|
|
302
|
+
"INSERT INTO schema_snapshots (pipeline, captured_at, schema_json) VALUES (?, ?, ?)",
|
|
303
|
+
(pipeline, _now(), schema_json),
|
|
304
|
+
)
|
|
305
|
+
self._conn.commit()
|
|
306
|
+
|
|
307
|
+
def counts(self, pipeline: str) -> dict[str, int]:
|
|
308
|
+
"""status → 개수. `pugio status`의 데이터."""
|
|
309
|
+
rows = self._conn.execute(
|
|
310
|
+
"SELECT status, count(*) FROM units WHERE pipeline=? GROUP BY status", (pipeline,)
|
|
311
|
+
).fetchall()
|
|
312
|
+
return dict(rows)
|
|
313
|
+
|
|
314
|
+
def pipeline_metrics(self, pipeline: str) -> PipelineMetrics:
|
|
315
|
+
"""Return cumulative rows/bytes/time and freshness for completed units."""
|
|
316
|
+
row = self._conn.execute(
|
|
317
|
+
"SELECT count(*), COALESCE(sum(row_count), 0), COALESCE(sum(byte_count), 0), "
|
|
318
|
+
"COALESCE(sum(duration_ms), 0), max(updated_at) FROM units "
|
|
319
|
+
"WHERE pipeline=? AND status='done'",
|
|
320
|
+
(pipeline,),
|
|
321
|
+
).fetchone()
|
|
322
|
+
if row is None: # pragma: no cover - aggregate queries always return one row
|
|
323
|
+
return PipelineMetrics(0, 0, 0, 0, None)
|
|
324
|
+
return PipelineMetrics(
|
|
325
|
+
completed_units=int(row[0]),
|
|
326
|
+
row_count=int(row[1]),
|
|
327
|
+
byte_count=int(row[2]),
|
|
328
|
+
duration_ms=int(row[3]),
|
|
329
|
+
last_completed_at=row[4],
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
def record_lineage(
|
|
333
|
+
self,
|
|
334
|
+
pipeline: str,
|
|
335
|
+
*,
|
|
336
|
+
source_type: str,
|
|
337
|
+
source_ref: str,
|
|
338
|
+
sink_type: str,
|
|
339
|
+
sink_ref: str,
|
|
340
|
+
) -> None:
|
|
341
|
+
"""Upsert the latest source-to-sink edge observed by a pipeline run."""
|
|
342
|
+
self._conn.execute(
|
|
343
|
+
"INSERT INTO lineage "
|
|
344
|
+
"(pipeline, source_type, source_ref, sink_type, sink_ref, updated_at) "
|
|
345
|
+
"VALUES (?, ?, ?, ?, ?, ?) "
|
|
346
|
+
"ON CONFLICT(pipeline) DO UPDATE SET source_type=excluded.source_type, "
|
|
347
|
+
"source_ref=excluded.source_ref, sink_type=excluded.sink_type, "
|
|
348
|
+
"sink_ref=excluded.sink_ref, updated_at=excluded.updated_at",
|
|
349
|
+
(pipeline, source_type, source_ref, sink_type, sink_ref, _now()),
|
|
350
|
+
)
|
|
351
|
+
self._conn.commit()
|
|
352
|
+
|
|
353
|
+
def lineage(self, pipeline: str) -> LineageRecord | None:
|
|
354
|
+
row = self._conn.execute(
|
|
355
|
+
"SELECT pipeline, source_type, source_ref, sink_type, sink_ref, updated_at "
|
|
356
|
+
"FROM lineage WHERE pipeline=?",
|
|
357
|
+
(pipeline,),
|
|
358
|
+
).fetchone()
|
|
359
|
+
return LineageRecord(*row) if row else None
|
|
360
|
+
|
|
361
|
+
def close(self) -> None:
|
|
362
|
+
self._conn.close()
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: arsenal-core
|
|
3
|
+
Version: 0.2.2
|
|
4
|
+
Summary: Shared reliability core for DE Arsenal tools — state, identity, errors, spec, retry
|
|
5
|
+
Project-URL: Homepage, https://github.com/KooEric/de-arsenal
|
|
6
|
+
Project-URL: Repository, https://github.com/KooEric/de-arsenal
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
Classifier: Intended Audience :: Developers
|
|
9
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
15
|
+
Requires-Python: >=3.11
|
|
16
|
+
Requires-Dist: pydantic>=2.7
|
|
17
|
+
Requires-Dist: pyyaml>=6
|
|
18
|
+
Requires-Dist: tenacity>=8.3
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# arsenal-core
|
|
22
|
+
|
|
23
|
+
DE Arsenal(Pugio·Gladius·Arsenal)이 공유하는 신뢰성 코어 라이브러리 —
|
|
24
|
+
파이프라인/변환 스펙 로더(Pydantic), 결정적 Unit ID, `StateStore`(SQLite
|
|
25
|
+
기반 unit 상태 기록), 에러 분류 체계(`RetryableError`/`AuthExpiredError`/
|
|
26
|
+
`FatalError`), backoff 재시도 래퍼. 그 자체로는 CLI가 없는 라이브러리 패키지다
|
|
27
|
+
— Pugio/Gladius가 이 위에서 "재개·멱등·에러 분류가 기본값"을 구현한다.
|
|
28
|
+
|
|
29
|
+
## 사용 예
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
|
|
34
|
+
from arsenal_core.state import UnitSpec, StateStore
|
|
35
|
+
from arsenal_core.errors import RetryableError, FatalError
|
|
36
|
+
|
|
37
|
+
# 결정적 unit_id: 같은 (pipeline, source, unit_key) → 항상 같은 id → 재실행 시 중복 방지
|
|
38
|
+
unit = UnitSpec.create(
|
|
39
|
+
pipeline="github-issues", source="issues", unit_key="page=1", payload={}
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
store = StateStore(Path("./state/github-issues.db"))
|
|
43
|
+
store.register(unit)
|
|
44
|
+
... # fetch → write
|
|
45
|
+
store.mark_done(unit.unit_id, row_count=100, byte_count=8192)
|
|
46
|
+
store.close()
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## 문서
|
|
50
|
+
|
|
51
|
+
- [docs/02-architecture.md](../../docs/02-architecture.md) — 공통 코어·상태 모델·멱등 전략
|
|
52
|
+
- [docs/08-limits.md](../../docs/08-limits.md) — 정직한 한계선
|
|
53
|
+
- [저장소 루트 README](../../README.md)
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
arsenal_core/__init__.py,sha256=5PpfqXctJUhHNLTHzAsIc2WrTlb17CzbBkzORBeuuTY,485
|
|
2
|
+
arsenal_core/errors.py,sha256=0O6irFuq8EcwDzL9bD-ncCjwMW-i1WG5-OIM2SDMpwE,1084
|
|
3
|
+
arsenal_core/identity.py,sha256=gWd1Ca67XPO8--PT4xJklKmOPEGN443klzOnm8ZzzSw,585
|
|
4
|
+
arsenal_core/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
arsenal_core/ratelimit.py,sha256=7I3UnGQox0Gy6jmUEfdexmpmaVknkiL_RS79Ml_0LjI,2152
|
|
6
|
+
arsenal_core/retry.py,sha256=zfOw_7lMx7LiatPxl04CuAbt-9smxQH_yQMeO-GaeGc,1535
|
|
7
|
+
arsenal_core/schema.py,sha256=zTxW1SaZTMZ5G3Kzxjofx7yfbPrh4UdY3kY2I7L7Rb4,3054
|
|
8
|
+
arsenal_core/io/__init__.py,sha256=wxJmKGWCtFRwfB-n3yRBBLs9U5pISduwoLZBXLUZy90,432
|
|
9
|
+
arsenal_core/spec/__init__.py,sha256=s_roNmgVHJBInH2ebVXJdRKMofNfGbqqrFduIOA4rNU,850
|
|
10
|
+
arsenal_core/spec/loader.py,sha256=KZti1lIFR2QuHe705fmzgFzjvpKPU7b5KUtZ5q9MFmw,2434
|
|
11
|
+
arsenal_core/spec/models.py,sha256=x4ZPLA0Qel_tauONdTLhM9fI3p63jPlXVkezjOTty3E,9724
|
|
12
|
+
arsenal_core/state/__init__.py,sha256=vK9WQiS2jcv7bPTDY9XL7zWwJR15i4XAMxGwhlrnxKU,320
|
|
13
|
+
arsenal_core/state/store.py,sha256=QHHZ-a5FL8RgzwogBGEgU4RVUJIFXy5Jt_2L_K_iAuA,14002
|
|
14
|
+
arsenal_core-0.2.2.dist-info/METADATA,sha256=wz_3LdvPiWQTt6FhtSq-TvWkRQDxaT4UhcE_feMBcyw,2097
|
|
15
|
+
arsenal_core-0.2.2.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
16
|
+
arsenal_core-0.2.2.dist-info/RECORD,,
|