-
Notifications
You must be signed in to change notification settings - Fork 0
feat: bootstrap package structure, exceptions, and store interface #2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
1c02199
feat: bootstrap package structure, exceptions, and store interface
claude 60a5432
fix: return (event_id, payload) tuples from dequeue_unacknowledged
claude 04e2ea2
docs: document PR review workflow in CLAUDE.md
claude f5a812e
fix: move dev tools to optional-dependencies group
claude 136cd43
docs: add ADR-002 for pluggable store interface, document ADR evaluat…
claude 7676df8
test: add unit tests for exceptions and InMemoryStore; add CI workflow
claude 15ff5bf
chore: add .gitignore and remove committed pycache files
claude c1ecddf
docs: add CI status badge to README
claude e029813
docs: add testing guide and strengthen test requirement in CLAUDE.md
claude File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| name: CI | ||
|
|
||
| on: | ||
| push: | ||
| pull_request: | ||
|
|
||
| jobs: | ||
| lint: | ||
| runs-on: ubuntu-latest | ||
| steps: | ||
| - uses: actions/checkout@v4 | ||
| - uses: actions/setup-python@v5 | ||
| with: | ||
| python-version: "3.11" | ||
| - name: Install dev dependencies | ||
| run: pip install -e .[dev] | ||
| - name: Lint with ruff | ||
| run: ruff check . | ||
| - name: Check formatting with black | ||
| run: black --check . | ||
|
|
||
| test: | ||
| runs-on: ubuntu-latest | ||
| steps: | ||
| - uses: actions/checkout@v4 | ||
| - uses: actions/setup-python@v5 | ||
| with: | ||
| python-version: "3.11" | ||
| - name: Install dev dependencies | ||
| run: pip install -e .[dev] | ||
| - name: Run tests | ||
| run: pytest |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| __pycache__/ | ||
| *.py[cod] | ||
| *.egg-info/ | ||
| dist/ | ||
| build/ | ||
| .pytest_cache/ | ||
| .ruff_cache/ | ||
| *.egg |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| # ADR-002 — Pluggable store interface via abstract base class | ||
|
|
||
| **Status**: Accepted | ||
| **Date**: 2026-06-09 | ||
| **Deciders**: fullstack-pilot team | ||
|
|
||
| --- | ||
|
|
||
| ## Context | ||
|
|
||
| ADR-001 establishes that a persistent store is required for two things: | ||
|
|
||
| 1. `last_successful_sync_at` — used by the reconciliation loop to compute the missed-event window after an outage. | ||
| 2. The webhook queue — at-least-once delivery buffer that survives a crash between reception and processing. | ||
|
|
||
| ADR-001 does not specify the implementation technology or how the rest of the engine should depend on the store. Two options were considered: | ||
|
|
||
| 1. **Concrete dependency** — engine components import and instantiate a specific backend directly (e.g. SQLite helper, Redis client). | ||
| 2. **Abstract interface** — engine components depend on a Python ABC; the concrete backend is injected at startup. | ||
|
|
||
| --- | ||
|
|
||
| ## Decision | ||
|
|
||
| We define `SyncStore` as a Python abstract base class (`abc.ABC`) in `src/sync_engine/store/base.py`. All engine components — webhook handler, reconciliation loop, processor — interact exclusively with this interface. No engine code imports a concrete backend. | ||
|
|
||
| The interface surface is intentionally minimal (six methods): | ||
|
|
||
| | Method | Purpose | | ||
| |---|---| | ||
| | `get_last_sync_at()` | Read the recovery timestamp | | ||
| | `set_last_sync_at(dt)` | Write it after a confirmed commit | | ||
| | `is_event_processed(event_id)` | Idempotency check before processing | | ||
| | `mark_event_processed(event_id)` | Acknowledge after commit | | ||
| | `enqueue_webhook(event_id, payload)` | Persist before processing begins | | ||
| | `dequeue_unacknowledged()` | Replay buffer on recovery | | ||
|
|
||
| `dequeue_unacknowledged` returns `list[tuple[str, dict]]` — event_id is always returned alongside the payload so callers can acknowledge without the payload embedding its own ID. | ||
|
|
||
| --- | ||
|
|
||
| ## Why not a concrete dependency | ||
|
|
||
| - **Test coupling**: any concrete backend (SQLite, Redis) requires setup, teardown, and I/O in tests. An in-memory implementation behind the same interface eliminates all of that. | ||
| - **Migration cost**: coupling engine logic to a specific backend turns a backend swap into a cross-cutting refactor. With an interface, only a new implementation file is needed. | ||
| - **Invariant enforcement**: the interface is the right place to document the commit-before-acknowledge invariants (see CLAUDE.md §Invariants). Concrete classes are not readable enough for this. | ||
|
|
||
| --- | ||
|
|
||
| ## Consequences | ||
|
|
||
| **Positive:** | ||
| - `InMemoryStore` (`store/memory.py`) satisfies the interface for all tests — no I/O, no fixtures, no external process. | ||
| - Production backends (SQLite, Redis, Postgres) are drop-in replacements — they implement the ABC and are injected at startup. | ||
| - Engine invariants (acknowledge-after-commit, last_sync_at write-only-after-success) are enforced at the call site by convention documented on the interface, not scattered across backends. | ||
|
|
||
| **Negative / accepted costs:** | ||
| - Dependency injection must be wired at startup — the concrete backend is not self-instantiated. | ||
| - Adding a new persistence operation requires updating the ABC and every implementation, not just one file. | ||
|
|
||
| --- | ||
|
|
||
| ## Rejected alternatives | ||
|
|
||
| | Alternative | Reason for rejection | | ||
| |---|---| | ||
| | Hardcoded SQLite backend | Tight coupling; tests require a real file; migration is cross-cutting | | ||
| | Dataclass / TypedDict (no ABC) | No enforcement of the interface contract; silent drift between implementations | | ||
| | Repository pattern with separate read/write interfaces | Over-engineering for current scope; a single interface covers all six operations cleanly | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| # Testing guide | ||
|
|
||
| ## Running tests | ||
|
|
||
| ```bash | ||
| pip install -e ".[dev]" | ||
| pytest # all tests | ||
| pytest -v # verbose | ||
| pytest tests/store/ # one subdirectory | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## Layout | ||
|
|
||
| Tests mirror the source tree under `tests/`: | ||
|
|
||
| ``` | ||
| tests/ | ||
| ├── test_exceptions.py | ||
| ├── store/ | ||
| │ └── test_memory_store.py | ||
| ├── webhook/ | ||
| │ └── test_handler.py # (upcoming) | ||
| ├── reconciliation/ | ||
| │ └── test_loop.py # (upcoming) | ||
| └── processor/ | ||
| └── test_processor.py # (upcoming) | ||
| ``` | ||
|
|
||
| Every new module in `src/sync_engine/<package>/` gets a matching test file | ||
| in `tests/<package>/`. No test file = the feature is not done. | ||
|
|
||
| --- | ||
|
|
||
| ## Naming | ||
|
|
||
| ``` | ||
| test_<what_is_tested>_<condition>_<expected_behavior> | ||
| ``` | ||
|
|
||
| One test per behavior, not per function. Examples: | ||
|
|
||
| ```python | ||
| def test_get_last_sync_at_before_any_write_returns_none(): ... | ||
| def test_dequeue_unacknowledged_excludes_processed_events(): ... | ||
| def test_webhook_signature_error_caught_as_sync_error(): ... | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## Fixtures | ||
|
|
||
| Define fixtures at the test-file level unless shared across multiple files, in | ||
| which case add them to a `conftest.py` in the relevant directory. | ||
|
|
||
| `InMemoryStore` is the canonical fixture for any test that touches the store: | ||
|
|
||
| ```python | ||
| import pytest | ||
| from sync_engine.store.memory import InMemoryStore | ||
|
|
||
| @pytest.fixture | ||
| def store() -> InMemoryStore: | ||
| return InMemoryStore() | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## Mocking rules | ||
|
|
||
| ### Webhook signature verification | ||
|
|
||
| Never depend on real secrets in tests. Patch the verification call: | ||
|
|
||
| ```python | ||
| from unittest.mock import patch | ||
|
|
||
| def test_valid_webhook_is_queued(store): | ||
| with patch("sync_engine.webhook.handler.verify_signature", return_value=True): | ||
| ... | ||
| ``` | ||
|
|
||
| ### REST API (reconciliation) | ||
|
|
||
| No network calls in CI. Patch `httpx.Client` or inject a fake transport: | ||
|
|
||
| ```python | ||
| import httpx | ||
|
|
||
| def test_reconciliation_fetches_since_last_sync(store): | ||
| def handler(request): | ||
| return httpx.Response(200, json={"items": []}) | ||
|
|
||
| transport = httpx.MockTransport(handler) | ||
| client = httpx.Client(transport=transport) | ||
| ... | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## What to test | ||
|
|
||
| For each new module, cover at minimum: | ||
|
|
||
| | Scenario | Example | | ||
| |---|---| | ||
| | Happy path | event processed end-to-end | | ||
| | Idempotency | same `event_id` processed twice, second is a no-op | | ||
| | Pre-condition violated | invalid signature → `WebhookSignatureError` raised | | ||
| | State after failure | crash mid-processing → event still in `dequeue_unacknowledged` | | ||
|
|
||
| --- | ||
|
|
||
| ## What not to test | ||
|
|
||
| - Internal implementation details (private methods, internal dict structure). | ||
| - The abstract `SyncStore` interface directly — test it through `InMemoryStore`. | ||
| - Framework behavior (FastAPI routing, httpx serialization). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| [build-system] | ||
| requires = ["hatchling"] | ||
| build-backend = "hatchling.build" | ||
|
|
||
| [project] | ||
| name = "sync-engine" | ||
| version = "0.1.0" | ||
| requires-python = ">=3.11" | ||
| dependencies = [ | ||
| "fastapi", | ||
| "httpx", | ||
| ] | ||
|
|
||
| [project.optional-dependencies] | ||
| dev = [ | ||
| "pytest", | ||
| "ruff", | ||
| "black", | ||
| ] | ||
|
|
||
| [tool.hatch.build.targets.wheel] | ||
| packages = ["src/sync_engine"] | ||
|
|
||
| [tool.pytest.ini_options] | ||
| testpaths = ["tests"] | ||
| pythonpath = ["src"] | ||
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| class SyncError(Exception): | ||
| """Base class for all sync-engine business exceptions.""" | ||
|
|
||
|
|
||
| class WebhookSignatureError(SyncError): | ||
| """Raised when a webhook payload fails HMAC signature verification.""" | ||
|
|
||
|
|
||
| class DuplicateEventError(SyncError): | ||
| """Raised when an event_id has already been processed (idempotency guard).""" | ||
|
|
||
|
|
||
| class ReconciliationError(SyncError): | ||
| """Raised when the REST reconciliation loop encounters an unrecoverable error.""" |
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| from abc import ABC, abstractmethod | ||
| from datetime import datetime | ||
|
|
||
|
|
||
| class SyncStore(ABC): | ||
| @abstractmethod | ||
| def get_last_sync_at(self) -> datetime | None: | ||
| """Return the timestamp of the last confirmed successful sync, or None.""" | ||
|
|
||
| @abstractmethod | ||
| def set_last_sync_at(self, dt: datetime) -> None: | ||
| """Persist dt as the last successful sync timestamp. | ||
|
|
||
| Must only be called after the sync has been fully committed — never | ||
| at the start of a cycle (see invariant #3 in CLAUDE.md). | ||
| """ | ||
|
|
||
| @abstractmethod | ||
| def is_event_processed(self, event_id: str) -> bool: | ||
| """Return True if event_id has already been committed (idempotency check).""" | ||
|
|
||
| @abstractmethod | ||
| def mark_event_processed(self, event_id: str) -> None: | ||
| """Record event_id as processed. Call only after the payload is committed.""" | ||
|
|
||
| @abstractmethod | ||
| def enqueue_webhook(self, event_id: str, payload: dict) -> None: | ||
| """Persist a webhook payload before processing begins (at-least-once delivery).""" | ||
|
|
||
| @abstractmethod | ||
| def dequeue_unacknowledged(self) -> list[tuple[str, dict]]: | ||
| """Return (event_id, payload) pairs for every queued webhook not yet marked processed.""" |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.