feat(cli) --seed-ingestion-sources reads JSON manifest, upserts to Cosmos#69
Merged
Conversation
…smos Phase 2 § Scope item 3 (Wave 1). New CLI flag bootstraps the ingestion_sources Cosmos container from a checked-in JSON manifest, with idempotent read-merge-upsert semantics that preserve runtime fields populated by actual scraper runs (LastRunAt, LastSuccessAt, totalDocumentsDiscovered, totalRunFailures). What ships: - src/PinballWizard.Application/Sync/IIngestionSourceSeeder.cs + IngestionSourceSeeder.cs + IngestionSourceSeed.cs — Application-layer service taking a manifest path, upserting one row per entry. DTO intentionally omits runtime fields (defense-in-depth: even if a manifest accidentally carried them, only config fields would apply). - data/seeds/ingestion_sources.v1.json — 9 entries (stern, jjp, ap, spooky, pinballbrothers, barrelsoffun, multimorphic, cgc, opdb) with cadences from project_phase2_architecture_decisions.md. - src/PinballWizard.Cli/Program.cs — wires --seed-ingestion-sources flag with the same exit-code-2-when-Cosmos-not-configured pattern as --ensure-cosmos-containers. DI registration of IIngestionSourceSeeder is gated alongside AddCosmosPersistence so it cannot resolve without its repository. - .gitignore — adjusts data/ pattern to data/* with !data/seeds/ re-include so the seed manifest is tracked while runtime output (downloads, metadata, logs, snapshots, history) stays ignored. The comment block explains why the pattern is data/* not data/ (git cannot re-include children of an excluded parent directory). - tests/PinballWizard.Scraper.Tests/Sync/IngestionSourceSeederTests.cs — 8 tests: first-run inserts with zero runtime fields; re-run applies config and preserves runtime fields (load-bearing); duplicate ids throw and roll back; missing manifest throws FileNotFoundException; empty array returns zero counts; malformed JSON throws InvalidOperationException; pre-cancelled token throws OperationCanceledException without upserting; production manifest on disk deserializes and pins the 9 expected ids. Local review: 1 🔴 finding (fixed); 3⚠️ categories (2 sub-findings fixed, 3 deferred with justifications below). 🔴 — Fixed: data/seeds/ingestion_sources.v1.json originally used "chicagogaming" for both id and scraperImplKey, but the canonical CGC key throughout the codebase is "cgc" (ScraperManufacturerKey, OpdbMachineMapper normalization, ScraperOrchestrator.SourceAliases, existing --source cgc CLI filter). Manifest + test fixture both updated.⚠️ — Fixed: cancellation propagation test added (SeedAsync_PreCancelledToken_ThrowsOperationCanceledExceptionWithoutUpserting); terminal LogInformation summary added to the seeder for sibling consistency with OpdbSyncService.⚠️ — Deferred (with justifications): - Per-record try/catch on UpsertAsync failures: deferred. Sibling OpdbSyncService has the same shape; the manifest is 9 rows and the seeder is idempotent, so a transient mid-loop failure is recovered by re-run. Worth revisiting if the manifest grows substantially or if Phase 6 operability work warrants partial-success counters. - Total field naming nuance (means "manifest count" not "processed count"): deferred. The early-throw path doesn't return a result, so the distinction is academic; the field is documented inline. - ProductionManifest_DeserializesCleanlyAndContainsNineEntries doesn't follow the SeedAsync_<state>_<expectation> naming pattern: deferred. The subject is the on-disk file, not a method on the seeder; a Method_State_Expectation rename would obscure that. Full test run: 515 / 515 passing (was 507 pre-PR; +8 seeder tests). Build clean, zero warnings.
| Seed("jjp", "Jersey Jack", "jjp", "https://www.jerseyjackpinball.com/", true, "daily")); | ||
|
|
||
| _repo.GetByIdAsync(Arg.Any<string>(), "config", Arg.Any<CancellationToken>()) | ||
| .Returns((IngestionSource?)null); |
| Seed("stern", "Stern Pinball", "stern", "https://sternpinball.com/", true, "daily")); | ||
|
|
||
| _repo.GetByIdAsync(Arg.Any<string>(), "config", Arg.Any<CancellationToken>()) | ||
| .Returns((IngestionSource?)null); |
| return; | ||
| } | ||
|
|
||
| var manifestPath = Path.Combine("data", "seeds", "ingestion_sources.v1.json"); |
| e.Id == "stern" | ||
| && e.PartitionKey == "config" | ||
| && e.DisplayName == "Stern Pinball" | ||
| && e.Enabled == true |
| [Fact] | ||
| public async Task SeedAsync_MissingManifestFile_ThrowsFileNotFoundException() | ||
| { | ||
| var nonexistent = Path.Combine(Path.GetTempPath(), $"missing-{Guid.NewGuid():N}.json"); |
| public void ProductionManifest_DeserializesCleanlyAndContainsNineEntries() | ||
| { | ||
| var repoRoot = FindRepoRoot(); | ||
| var manifestPath = Path.Combine(repoRoot, "data", "seeds", "ingestion_sources.v1.json"); |
|
|
||
| private string WriteRawManifest(string json) | ||
| { | ||
| var path = Path.Combine(Path.GetTempPath(), $"seed-{Guid.NewGuid():N}.json"); |
| { | ||
| // Walk upward from the test assembly until we find the .slnx file. | ||
| var dir = new DirectoryInfo(AppContext.BaseDirectory); | ||
| while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "PinballWizard.slnx"))) |
| e.Id == "stern" | ||
| && e.PartitionKey == "config" | ||
| && e.DisplayName == "Stern Pinball" | ||
| && e.Enabled == true |
| [Fact] | ||
| public async Task SeedAsync_MissingManifestFile_ThrowsFileNotFoundException() | ||
| { | ||
| var nonexistent = Path.Combine(Path.GetTempPath(), $"missing-{Guid.NewGuid():N}.json"); |
| public void ProductionManifest_DeserializesCleanlyAndContainsNineEntries() | ||
| { | ||
| var repoRoot = FindRepoRoot(); | ||
| var manifestPath = Path.Combine(repoRoot, "data", "seeds", "ingestion_sources.v1.json"); |
|
|
||
| private string WriteRawManifest(string json) | ||
| { | ||
| var path = Path.Combine(Path.GetTempPath(), $"seed-{Guid.NewGuid():N}.json"); |
| { | ||
| // Walk upward from the test assembly until we find the .slnx file. | ||
| var dir = new DirectoryInfo(AppContext.BaseDirectory); | ||
| while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "PinballWizard.slnx"))) |
6 tasks
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
Closes
docs/build-spec.mdPhase 2 § Scope item 3 (Wave 1).New CLI flag bootstraps the
ingestion_sourcesCosmos container from a checked-in JSON manifest, with idempotent read-merge-upsert semantics that preserve runtime fields populated by actual scraper runs (LastRunAt,LastSuccessAt,totalDocumentsDiscovered,totalRunFailures). Re-running the seeder with no manifest changes produces no semantic diff; manifest config-field changes apply without disturbing telemetry.What ships
src/PinballWizard.Application/Sync/—IIngestionSourceSeederinterface +IngestionSourceSeedResultrecord +IngestionSourceSeedDTO +IngestionSourceSeederimplementation. Application-layer service depending only onIIngestionSourceRepositoryandIngestionSource. The DTO intentionally omits runtime fields (defense-in-depth: even an accidentally-populated manifest can't blow them away on re-seed).data/seeds/ingestion_sources.v1.json— 9 manufacturer entries (stern, jjp, ap, spooky, pinballbrothers, barrelsoffun, multimorphic, cgc, opdb) with cadences fromproject_phase2_architecture_decisions.md.src/PinballWizard.Cli/Program.cs— wires--seed-ingestion-sourceswith the exit-code-2-when-Cosmos-not-configured pattern matching--ensure-cosmos-containers. Seeder DI registration is gated alongsideAddCosmosPersistenceso the service cannot resolve without its repository..gitignore— adjusts thedata/rule todata/*plus!data/seeds//!data/seeds/**so the seed manifest is tracked while runtime output (downloads / metadata / logs / snapshots / history) stays ignored. The comment block explains why the pattern isdata/*notdata/(git cannot re-include children of an excluded parent directory).tests/PinballWizard.Scraper.Tests/Sync/IngestionSourceSeederTests.cs— 8 tests covering happy path, the load-bearing idempotency assertion (re-run preserves runtime fields), duplicate-id rejection, missing-file, empty-array, malformed-JSON, cancellation, and a production-manifest sanity check that pins the on-disk JSON deserializes cleanly with the expected 9 ids.Setup required after merge
pwsh ./start-apphost.ps1→ setConnectionStrings__cosmosfrom the dashboard →dotnet run --project src/PinballWizard.Cli -- --seed-ingestion-sourcesCosmos__AccountEndpoint+Cosmos__AccountResourceId(PowerShell, not Git-Bash) → run the same commandingestion_sourcescontainer has 9 documents matching the manifest (Cosmos Data Explorer oraz cosmosdb sql container show)Test Plan
dotnet test PinballWizard.slnx --nologo→ 515 / 515 passing (was 507 pre-PR; +8 new seeder tests)dotnet build PinballWizard.slnx --nologo→ clean, zero warnings underTreatWarningsAsErrorsProductionManifest_DeserializesCleanlyAndContainsNineEntriestest pins the on-disk JSON; manifest schema regressions fail at test time, not at runtime in productionLocal review
/local-reviewran against the diff:"chicagogaming"for bothidandscraperImplKey, but the canonical key throughout the codebase is"cgc"(ScraperManufacturerKey.ChicagoGaming,OpdbMachineMappernormalization,ScraperOrchestrator.SourceAliases, the existing--source cgcCLI filter). Manifest + test fixture both updated to"cgc"before push.SeedAsync_PreCancelledToken_*test for cancellation propagation; added a terminalLogInformationsummary in the seeder matching the sibling pattern inOpdbSyncServiceandScraperReconciliationService.UpsertAsyncfailures: siblingOpdbSyncServicehas the same shape; the manifest is 9 rows and the seeder is idempotent, so a transient mid-loop failure is recovered by re-run. Revisit if the manifest grows substantially or Phase 6 operability work warrants partial-success counters.Totalfield naming nuance ("manifest count" vs "processed count"): the early-throw path doesn't return a result, so the distinction is academic; documented inline.ProductionManifest_DeserializesCleanlyAndContainsNineEntriesdoesn't followSeedAsync_<state>_<expectation>: the test's subject is the on-disk file, not a method on the seeder; aMethod_State_Expectationrename would obscure that.7-item self-audit
IngestionSourceSeedDTO has 7 fields, all read by the seeder (verified by grep):Id,DisplayName,ScraperImplKey,BaseUrl,Enabled,Cadence,PolitenessOverrides. ✅OpdbSyncServiceandScraperReconciliationServiceper local-review category Enterprise quality bar: build hardening, CI/CD gates, security tooling, integration tests #4; sibling drift was the source of the 🔴 (CGC key) and onecatch { }— only catch iscatch (JsonException ex)at the deserialize call; rethrows asInvalidOperationExceptionwith context. Test cleanup catchesIOExceptiononly. ✅--seed-ingestion-sourcesparsed and dispatched inProgram.cs;IIngestionSourceSeederregistered in DI inside thecosmosWiredblock. Manual:dotnet run --project src/PinballWizard.Cli -- --helpshows the new flag in the output. ✅TotalDocumentsDiscovered = 1234,TotalRunFailures = 7, etc., and explicitly asserts each survives. Duplicate-ids test feeds duplicates. Cancellation test pre-cancels the token. ✅dotnet build PinballWizard.slnx --nologo→ 0 warnings underTreatWarningsAsErrors. ✅git log -1 --format='%an <%ae>'→Jim Keeley <94459922+jkeeley2073@users.noreply.github.com>✅Out of Scope
--dry-runpre-req) — Wave 2; a separate PR.🤖 Generated with Claude Code