SR-029 — Tenant Catalog Bulk Data Migration Spec
Metadata
| Field | Value |
|---|---|
| System Name | firebase-function → tenant-migration → tenant-migration-orchestrator |
| Document ID | SR-2026-MIG-001 |
| Author | Engineering Team |
| Status | Implemented (gaps noted inline) |
Traces back to BRD-028 — Tenant Catalog Bulk Data Migration.
Functional Requirements
Batch ingestion (firebase-function → tenant-migration)
FR-01 (Upload-triggered batch creation, BR-01): a tenant catalog bundle uploaded to the staging bucket with a migration_bundle transaction name fires storage_migration_upload_event.js’s onStorageUpload trigger, which publishes a storage-upload envelope to the batch-uploaded topic — there is no REST endpoint to start a batch upload; the admin UI’s upload flow is the only producer of this transaction name. See ADR-00045 for why batch creation is event-driven off the upload’s own completion rather than a synchronous client call.
FR-02 (Idempotent batch record creation, BR-01): tenant-migration’s MigrationBatchCreatedReceiver (message-receiver/migration-batch/migration-batch-created.receiver.ts) consumes the envelope via the generic withMessageReceiver, uses the envelope’s data.transaction_id directly as the batchId, and creates the migration_batches document via validateCreateUploadedMigrationBatchInput + batchRepo.create; a redelivery of the same envelope is a no-op since handle() returns early when a batch with that id already exists.
Verify pipeline (tenant-migration)
FR-03 (Non-blocking verify trigger, BR-02): POST /migration/verify/:batchId validates batch ownership via findOwnedBatch, enqueues an Agenda job (process_migration_verify), and returns 202 Accepted immediately.
FR-04 (Three-step verify, BR-02): VerifyService.doRunVerify runs EXTRACT → SCHEMA → COMPILE in sequence, recording each step’s outcome on the batch document.
FR-05 (Streamed extraction, BR-02): EXTRACT streams the staged archive to a local scratch file (SCRATCH_ROOT/<batchId>.zip) rather than buffering it in memory; the raw-archive upload to the primary bucket and the zip extraction into per-entity-type CSV buckets then run concurrently off that same local file.
FR-06 (Bundle-driven schema check, BR-02): SCHEMA checks only the entity types whose folder is actually present in the uploaded bundle, resolved via EntityVerifyProcessorFactory.getForBundle; a bundle with zero recognized entity-type folders is rejected.
FR-07 (Streamed compile output, BR-02): COMPILE parses, validates, and compiles each present entity type’s CSV rows into a validation summary plus one or more output files, written as line-delimited records via writeMigrationRecords rather than as a single in-memory JSON array — see ADR-00043.
FR-08 (Verify terminal states, BR-02): a successful verify marks the batch VERIFIED and removes the local scratch copy; a failed verify marks it VERIFICATION_FAILED, records which step/entity type/error caused it, and deliberately leaves the extracted CSVs on local disk until the batch is retried or deleted.
FR-09 (Entity-type coverage, BR-01): all 13 entity types the pipeline knows about — category hierarchy, warehouse/fulfillment locations, packaging definitions, and the 10 product-related types (base product, specification, variant, opening stock entry, volumetric, pricing, package mapping, image, publish, and opening-entry processing) — have a registered verify-time processor (migration.module.ts’s ENTITY_VERIFY_PROCESSORS factory), matching the orchestrator’s dispatch-side coverage one for one. (Several of this monorepo’s own module docs still describe base product records as lacking a verify-time processor — that claim is stale; see TD-00023.)
Execute pipeline (tenant-migration)
FR-10 (Non-blocking execute trigger, BR-03): POST /migration/execute/:batchId validates ownership and enqueues a second Agenda job (process_migration_execute), returning 202 Accepted immediately.
FR-11 (Fixed stage order, BR-03): import proceeds across four fixed, named stages in strict order — foundational, dependent, publish-gating, finalization — resolved per tenant from migration_order’s DEFAULT_ORDER, never a per-entity dependency graph walked record-by-record at publish time.
FR-12 (Wave barrier, BR-03): before publishing any entity type in a stage after the first, every entity type in the previous stage must finish (processed + failed >= queued for each) via waitForWave, polled on an interval up to a configured maximum wait; exceeding the wait marks the whole run EXECUTION_FAILED.
FR-13 (Cancellation mid-wave, BR-06): waitForWave checks the batch’s own status on every poll tick and stops the run immediately, without marking it failed, if the batch has been cancelled in the meantime.
FR-14 (Tiered, tagged publish, BR-03): each record is streamed one line at a time from its compiled file (readMigrationRecords) and published individually, tagged with a tier Pub/Sub attribute (tierForEntityType) and, for the one self-referencing entity type (category hierarchy), a per-batch-and-entity-type ordering key (requiresOrderedDelivery) so its records are never processed out of order.
Per-record dispatch (tenant-migration-orchestrator)
FR-15 (Pub/Sub-only worker, BR-01): dispatch has no inbound HTTP or gRPC surface — every unit of work starts from a Pub/Sub message tenant-migration published.
FR-16 (Per-entity-type outbound integration, BR-01): each record is routed to its target microservice’s REST API through a dedicated repository per entity type (EntityMigrationServiceFactory.getForType), never a single hardcoded call, so a new entity type doesn’t change the shared dispatch machinery. See ADR-00044 for why this dispatches via each target microservice’s own REST API rather than writing directly into its database.
FR-17 (Shared circuit breaker, BR-02): every outbound call is wrapped in a cockatiel-backed circuit breaker keyed by destination baseURL, so every entity type calling the same downstream service shares one breaker and failure count.
FR-18 (Defensive dependency gate, BR-03): checkDependenciesReady() checks that every dependsOn entity type has finished its own wave before dispatching a record; a not-ready message is always nacked and redelivered — a backstop to the execute-side wave barrier (FR-12), not a replacement for it.
FR-19 (Dead-letter retry state, BR-05): a record that exhausts delivery attempts is captured in migration_dead_letters with its full original message envelope, separate from migration_errors (audit-only, never drives retry); tenant-migration’s retryBatch republishes dead-lettered records verbatim.
FR-20 (Idempotent failure recording, BR-05): recordFailureOnce makes failure recording safe against duplicate delivery — a redelivered failure never double-counts against the batch’s failed counter.
Batch lifecycle & tenant isolation
FR-21 (Full batch lifecycle, BR-04, BR-05, BR-06): operations can list/get a tenant’s own batches, stream live status updates (SSE), delete a batch (including uploaded artifacts and local scratch state), cancel an in-flight verify/execute run, and retry only the failed records of an EXECUTION_FAILED batch.
FR-22 (Tenant-scoped resolution, BR-07): every batch-scoped operation resolves the batch by id and tenant together via findOwnedBatch; a batch belonging to another tenant 404s identically to a batch that doesn’t exist.
Non-Functional Requirements
NFR-01 (Non-blocking ingestion): neither verify nor execute ever runs synchronously inside the HTTP request/response cycle — both return 202 Accepted immediately and run as Agenda background jobs (FR-03, FR-10).
NFR-02 (No whole-file buffering): no step in the verify or execute path loads a whole uploaded or compiled file into process memory — the staged archive, each entity type’s compiled output, and the per-record publish read path all stream to/from disk (FR-05, FR-07, FR-14).
NFR-03 (Independently scalable dispatch concurrency): the orchestrator’s four tier-filtered Pub/Sub subscriptions each have their own maxMessages concurrency cap, so image-bearing records can run at much lower concurrency than lightweight ones without a code change to the shared dispatch worker. See ADR-00044 for why these caps, not horizontal replica scaling (not configured anywhere in this codebase today), are what actually bounds downstream request load.
NFR-04 (Tenant identity never trusted from request content): every batch read/write resolves tenant identity from the authenticated caller or the upload envelope’s own header, never from request-body content (FR-02, FR-22).
NFR-05 (Bounded wait, not an unbounded hang): a wave that never completes does not hang the execute job forever — waitForWave’s timeout surfaces as EXECUTION_FAILED rather than a silently stuck job (FR-12).
NFR-06 (No silent duplicate side effects): both batch creation (FR-02) and failure recording (FR-20) are idempotent against redelivery — a retried or duplicated message is never double-applied.
NFR-07 (No cross-format compatibility shim): (Gap — a batch verified before the current line-delimited compiled-output format was introduced carries an incompatible older format and must be re-verified before it can be executed; no shim exists to bridge the two, see TD-00023.)
Related Documents
- BRD-028 — Tenant Catalog Bulk Data Migration
- ADR-00043 — NDJSON Streaming and Wave-Barrier Execution for Tenant Catalog Migration
- ADR-00044 — REST API Dispatch and Tiered Concurrency Over Direct Database Writes for Migration Delivery
- ADR-00045 — Event-Driven Batch Creation From Storage-Upload Completion
- Architecture-00024 — Tenant Catalog Bulk Migration Component Topology and Data Flow
- TD-00023 — Tenant Catalog Bulk Migration Gaps
- tenant-migration
- tenant-migration-orchestrator
- firebase-function