B2B Second Inventory Catalog Backend Architecture
Internal architecture of the bb phase 2 catalog — composition, data model, locking and invariants, job state machine, sweeps, error contract and file map.
B2B Second Inventory (bb) — Catalog Backend Documentation
1. Module Scope
Phase 2 owns, in the bb module:
- The bb catalog tables: categories, brands, brand series, tags, products, variants, option axes, option values and the product-tag and variant-option-value links
- The admin API for those tables, including bulk delete, bulk restore, reorder and bulk active
- The
bb_catalog_jobtable, its state machine, thebb_catalogqueue worker and its sweeps - The import and export handlers that run on that worker, and the daily cleanup of job files
- The product description sanitizer
- A change to the shared upload service that keeps bb job files off the shared upload routes
- A retail change: the never-dispatched sweep for retail product and catalog jobs (R1)
It does not own:
- Retail products, categories, brands, series or tags. bb has its own tables and never reads retail rows
- Stock, orders, pricing rules beyond the stored price pair, or any storefront endpoint
- The
role,admin_usersandpermissiontables (reused from phase 1)
The catalog admin modules are imported by BbAdminAggregateModule and the worker by BbModule. See section 12.
2. Composition
All paths are under apps/api/src/modules/bb/.
| Piece | File |
|---|---|
| Category controllers | admin/category/bb-category-admin.controller.ts, bb-category-bulk.controller.ts |
| Category services | bb-category-admin.service.ts (reads), bb-category-write.service.ts (writes), bb-category-bulk.service.ts, bb-category-lifecycle.ts (single-row delete/restore, shared with bulk) |
| Brand | admin/brand/bb-brand-admin.{controller,service}.ts, bb-brand-bulk.{controller,service}.ts, bb-brand-lifecycle.ts |
| Brand series | admin/brand-series/bb-brand-series-admin.{controller,service}.ts, bb-brand-series-bulk.{controller,service}.ts, bb-brand-series-lifecycle.ts |
| Tag | admin/tag/bb-tag-admin.{controller,service}.ts |
| Product | admin/product/bb-product-admin.controller.ts, bb-product-lifecycle.controller.ts, bb-product-bulk.controller.ts; bb-product-read.service.ts, bb-product-write.service.ts, bb-product-bulk.service.ts; bb-product-gallery.ts, bb-product-description-input.ts, bb-product-lifecycle.ts |
| Variant | admin/variant/bb-variant-admin.{controller,service}.ts, bb-variant-default.ts, bb-variant-values.ts |
| Option axes and values | admin/option/bb-option-admin.{controller,service}.ts, bb-option-value-admin.{controller,service}.ts, bb-option-shared.ts, bb-option.constants.ts |
| Job admin | admin/job/bb-job-{products,categories,brands,brand-series}.controller.ts, bb-job-admin.service.ts (writes), bb-job-read.service.ts (reads), bb-job-import-upload.config.ts, bb-job-permissions.ts |
| Job worker | jobs/bb-catalog-queue.processor.ts (runner and queue processor; two stub handler classes stay in the file for the runner's specs and are not wired), bb-catalog-job-state.ts, bb-catalog-job-enqueue.ts, bb-catalog-job-authority.service.ts, bb-catalog-job-handler.ts, bb-job-files.ts, bb-catalog-job.constants.ts, bb-catalog-export-filter.ts, bb-catalog-import-columns.ts, bb-catalog-worker.module.ts |
| Import handler | jobs/import/: bb-catalog-import.processor.ts (handler and runBbCatalogImport), bb-import-file.ts (CSV and XLSX reader), bb-zip-directory.ts, bb-import-cells.ts (cell parsers, header check, row messages), bb-import-rows.ts (per-entity parse and in-file duplicates), bb-import-row-loop.ts (savepoint loop), bb-import-taxonomy.writer.ts, bb-import-product.writer.ts, bb-import-description.ts, bb-import.constants.ts |
| Export handler | jobs/export/: bb-catalog-export.processor.ts, bb-export-rows.ts, bb-export-csv.ts |
| Job sweep | jobs/sweep/bb-catalog-sweep.{module,processor,scheduler}.ts, bb-job-file-cleanup.ts |
| Shared catalog helpers | catalog-shared/: bb-bulk.dto.ts, bb-bulk.util.ts, bb-bulk-runner.ts, bb-reorder.rules.ts, bb-catalog-lock.ts, bb-product-lock.ts, bb-catalog-db-errors.ts, bb-product-description.ts, bb-variant-combination.rules.ts, bb-variant-view.ts, bb-option-read.ts, bb-dto-transforms.ts, rules/bb-category-tree.rules.ts, rules/bb-product-create.rules.ts, rules/bb-referent.rules.ts |
| Permission catalog | packages/db/src/authorization/permission-catalog.ts |
| Error codes | apps/api/src/common/types/error-codes.ts |
| Queue and job names | packages/jobs/src/index.ts (QueueName.BB_CATALOG = "bb_catalog", BbCatalogJob, MaintenanceJob.SWEEP_STALLED_BB_CATALOG_JOBS) |
| Schema | packages/db/src/schema/bb/ (bb-category.ts, bb-brand.ts, bb-brand-series.ts, bb-tag.ts, bb-product.ts, bb-product-option.ts, bb-catalog-job.ts) |
| Migrations | packages/db/src/migrations/0061_bb_catalog.sql, 0062_bb_catalog_jobs.sql (down scripts in down/) |
Every controller applies JwtAuthGuard and RoleGuard, then IpThrottlerGuard per route and @Permissions(...).
Create routes apply IdempotentCreate with IdempotencyInterceptor. Scopes: bb.category.create, bb.brand.create, bb.brand_series.create, bb.tag.create, bb.product.create, bb.variant.create, bb.option.create, bb.option_value.create, bb.catalog_job.export.{product,category,brand,brand_series}.
The import route does not use the interceptor. It reads the Idempotency-Key header itself and stores the key on the job row.
Controller order matters. Literal paths (bulk/delete, reorder, deleted, tree, import-template) are declared before :publicId. The bulk controllers are listed before the item controllers in each module for the same reason.
3. Data Model
Migration 0061_bb_catalog.sql creates ten tables and widens one CHECK on bb_audit. Migration 0062_bb_catalog_jobs.sql creates bb_catalog_job.
| Table | Notes |
|---|---|
bb_category | Tree via parent_id; stored depth 0-6; soft delete; live sibling names unique |
bb_brand | Soft delete; live name unique |
bb_brand_series | Belongs to one brand; live name unique |
bb_tag | Soft delete; live name unique |
bb_product | Category (required), brand and series (optional); gallery jsonb; version; description is a branded type, so a raw string does not compile |
bb_product_variant | Price pair in paisa; partial unique indexes for the default variant and for live SKU |
bb_product_tag | Product-tag link |
bb_product_option | Axis per product |
bb_product_option_value | Value per axis |
bb_product_variant_option_value | Variant-to-value link |
bb_catalog_job | One row per import or export; also the database-side dead-letter record for the bb_catalog queue |
Foreign keys that reference a catalog parent use RESTRICT.
bb_audit.entity_type accepts nine more values: category, brand, brand_series, tag, product, variant, option, option_value, catalog_job. Phase 3 adds a tenth, inventory (stock backend). New audit verbs: move, set_tags, cancel, reorder, download.
bb_catalog_job
| Column | Meaning |
|---|---|
kind | import or export |
entity | category, brand, brand_series, product; phase 3 adds inventory (stock backend) |
status | queued, processing, completed, failed, cancelled |
lease_token | Set when a worker claims the job; NOT NULL exactly while processing (CHECK chk_bb_catalog_job_lease_token) |
attempts_made, processed_rows, failed_rows, total_rows | Counters; failed_rows keeps the true total while errors keeps at most 500 rows |
source_file_key, source_sha256, idempotency_key | Import only; unique per (requested_by_admin_id, entity, idempotency_key) where the key is not null |
result_file_key | Export only, set with completed in the same statement |
filters | { includeDeleted?, search? }; {} for imports |
requested_by_admin_id, requested_by_name, requested_by_role, requested_ip | Requester snapshot |
The table carries 19 CHECK constraints.
4. Runtime Rules and Domain Invariants
Soft delete and restore share one code path
Single delete, single restore and bulk delete/restore all call the same *InTx functions in each *-lifecycle.ts file. The caller owns the transaction.
Locking and lock order
- Every catalog write sets
lock_timeoutto 5,000 ms on its transaction. A lock timeout (55P03) becomes 409BB_CATALOG_BUSY. - Category writes take one advisory lock,
pg_advisory_xact_lock(4812101), so the whole tree is serialized. - Bulk and reorder lock the requested rows
FOR UPDATEin id order. - Every series path locks brand, then series. Series reorder takes the brand
FOR UPDATEand then the series rows. Series bulk delete and restore take the owning brandsFOR KEY SHAREin id order before the series rows, because a series locked before its brand would deadlock against a reorder. - A deadlock (
40P01) or a serialization failure (40001) on a classified write path is reported as 409BB_CATALOG_BUSY, never as a 500. Job submit and job cancel catch only the lock timeout, so a deadlock there still surfaces as a 500. - A brand created while a brand reorder runs keeps its own
displayOrder; there is no brand-scope lock (an accepted risk).
Optimistic version on products
bb_product.version is bumped by option and axis writes. Product update takes an optional version; option writes take a required productVersion.
Price cap
BB_VARIANT_MAX_PRICE_PAISA is 1_000_000_000_000 and is the @Max on every price field in the create-product variant item, the create-variant and the update-variant DTOs.
Description sanitizer
sanitizeBbProductDescription runs sanitize-html with a fixed allow-list, discards disallowed tags, rejects protocol-relative URLs and keeps img src only for configured image origins. It returns a branded type, so a raw string cannot reach the column.
Reorder
Reorder is all-or-nothing. Step 1 checks duplicate ids, missing or deleted rows and mixed parents. Step 2 checks the request equals the live sibling set.
Bulk runner
Each id runs in its own savepoint. A refusal (a BB_* HttpException below 500 other than BB_CATALOG_BUSY, or a classified constraint error) goes to failed[]. Anything else, including a lock timeout, rolls back the whole batch.
Retail never-dispatched sweep (R1)
The retail product and catalog sweeps now also fail a queued, never-started job whose outbox row has been dead for 24 hours. The product sweep picks rows with a MATERIALIZED CTE, because UPDATE ... WHERE id IN (SELECT ... LIMIT ... FOR UPDATE SKIP LOCKED) ignores LIMIT. Product: 500 rows per batch, 20 batches per tick. Catalog: one page of 500 per tick, with one getJob read per candidate.
5. Job State Machine
Every status write is one SQL statement in jobs/bb-catalog-job-state.ts, and every write after a claim is guarded by public_id, status = 'processing' and lease_token.
| Transition | Function | Rule |
|---|---|---|
| queued to processing (claim) | claimBbCatalogJob | Sets a new lease_token, started_at, attempts_made + 1. Also reclaims a processing row whose started_at is older than the lease cutoff |
| processing to queued (retry) | releaseBbCatalogJob | Keeps started_at, clears the token |
| processing to failed | failBbCatalogJob | Permanent, revoked or final transient failure |
| processing to completed | completeBbCatalogImport, completeBbCatalogExport | Called inside the handler's write transaction; a lost lease aborts it |
| queued or processing to cancelled | cancelBbCatalogJob | Returns null when already terminal |
| released retry to failed (BullMQ exhausted) | failBbCatalogJobAfterExhaustion | The listener backstop |
| processing past lease to failed | sweepStalledBbCatalogJobs | Code BB_JOB_LEASE_EXPIRED |
| queued, never started, outbox dead 24 h, to failed | sweepNeverDispatchedBbCatalogJobs | Code BB_JOB_NEVER_DISPATCHED |
| released retry untouched 2 h, to failed | sweepRetryAbandonedBbCatalogJobs | Code BB_JOB_RETRY_ABANDONED |
Constants
| Constant | Value |
|---|---|
| Lease TTL | 15 minutes |
isStalled for a queued row | 30 minutes since created_at |
| Never-dispatched window | 24 hours |
| Retry-abandoned window | 2 hours |
| Sweep batch size / max batches | 500 / 20 |
| Worker concurrency | 1 (a constant, not env) |
| Active jobs per admin | 2 |
| Import max rows / file size | 5,000 / 25 MiB |
| Export max rows | 50,000 |
last_error max length | 1,000 characters |
| Import limits: columns / XLSX uncompressed / zip entries | 50 / 100 MiB / 1,000 |
| Export batch size | 500 rows, with a lease check every 500 rows |
| Job-file cleanup: min age / deletions per run / entries scanned per directory pass | 24 hours / 500 / 5,000 |
| Job-file cleanup bucket | 20:15 UTC (02:00 Asia/Kathmandu) |
Runner behavior
One delivery does: claim, authority re-check, handler, outcome classification.
missingrow: logs[failure]and throws.terminalrow: logs[skip]and returns.lease_held: moves the BullMQ job to delayed until the lease expires plus 1 s, then throwsDelayedError.- Authority revoked: fails the job with
BB_JOB_AUTHORIZATION_REVOKEDand returns without retry. BbJobLeaseLostError: logs[skip], returns.BbJobPermanentError: fails the job with the handler's row errors;last_erroris the handler's own fixed sentence.- Any other error: on the last attempt the row is failed, otherwise released; the error is rethrown so BullMQ retries.
last_erroris a fixed sentence in both cases:BB_CATALOG_JOB_RETRYING_MESSAGEon release,BB_CATALOG_JOB_EXHAUSTED_MESSAGEon the final failure. The raw error text goes to the[failure]and[retry]log lines only. - The
failedworker event usesjob.isFailed()for finality, neverattemptsMade. When the listener backstop fails a released row it overwriteslast_errorwith the exhausted sentence, so a failed row never reads "will be retried".
Outbox and queue
Submit writes the job row, the outbox row (aggregateType: "bb_catalog_job", queue bb_catalog, dedupeKey: bb_catalog_job:<id>) and the audit row in one transaction. It never calls queue.add.
The bb_catalog queue is registered with env-configured default job options (BULL_QUEUE_BB_CATALOG_*) because outbox-relayed jobs carry no per-call attempts.
Sweeps
BbCatalogSweepScheduler adds one MAINTENANCE job every 5 minutes (timezone Asia/Kathmandu), with a minute-bucket job id so two instances enqueue one job. Under API_RUNTIME_PROFILE=fast the scheduler never fires.
BbCatalogSweepProcessor runs the three passes, a dead-letter monitor and, on one tick a day, the job-file cleanup. Each pass logs Swept N <pass> bb catalog job(s) with up to 50 ids and deletes the import source files of the jobs it failed. A step that throws logs [failure] and does not skip the next one.
The dead-letter monitor counts a failed job in the last hour only when the system failed it: errors is NULL (retries exhausted or an unexpected error), or the first error code is BB_JOB_LEASE_EXPIRED, BB_JOB_NEVER_DISPATCHED or BB_JOB_RETRY_ABANDONED. Bad rows, a bad file and a revoked permission are the requester's failures and never raise the alert. The threshold log fires when the count reaches BULL_QUEUE_BB_CATALOG_DEAD_LETTER_THRESHOLD, once for Redis and once for the database.
Job-file cleanup. The scheduler's job id is bb_catalog_sweep_<yyyyMMddHHmm> in UTC. The one bucket ending 2015 (20:15 UTC, 02:00 Asia/Kathmandu) also runs cleanupBbJobFiles. The id is shared by every instance, so it runs once a day, and it is missed if that tick is missed. It deletes, at most 500 files per run and only files older than 24 hours: export .part files whose job is not active, import sources whose job is terminal or gone, and export results whose job row is gone. It scans at most 5,000 directory entries per pass, checks every key against its pattern before the unlink, and logs one WARN summary line when it deleted anything. A completed export's result is never expired.
The sweep module is imported by MaintenanceWorkerModule, not by the job worker module, so it runs whether or not the worker is registered.
6. Job Files
- Imports are stored by multer at
<upload root>/uploads/bb-import/<uuid>.<csv or xlsx>; exports atuploads/bb-export/<jobPublicId>.csv. An export attempt writes<result key>.<lease token>.partand renames it into place once whole. - File keys are validated against the same pattern as the table CHECKs before any read or delete.
- The upload filter accepts
.csvand.xlsxwith one of five MIME types, before anything is written. Multer limits: 1 file, 2 fields, 4 KiB per field, 3 parts. A file over 25 MiB answers 400BB_JOB_FILE_TOO_LARGE(the wrapper rewrites multer's 413). Other multer limits answer 400VALIDATION_FAILED. - A submit that does not insert a new job (an idempotent replay, or any error) deletes the new upload.
- An import source file is deleted once its job is terminal. Every path deletes after the terminal write committed, never inside it, through
deleteBbJobFile, which never throws: the runner after a completed import, a permanent failure, a revoked permission or a final transient failure; the listener backstop; all three sweep passes (by the swept ids, including batches that committed before a later batch erred); and admin cancel, after its transaction. A worker still parsing a cancelled file loses its lease at the next check and writes nothing. The daily cleanup catches whatever a crash left behind. - Export results are kept. There is no result-expiry rule.
BB_JOB_RESULT_GONEis answered only when the file is already missing. A failed or cancelled export's leftover final file is not deleted by the cleanup either, because the cleanup only removes results whose job row is gone. - Export download resolves the stored key, checks the file exists (410
BB_JOB_RESULT_GONEif not), writes abb.catalog_job.downloadaudit row, then streams the file. A stream error before the headers sends a fixed 410; after them, the socket is destroyed.
Shared upload routes refuse bb job files
UploadService.enforceKeyOwnership normalizes the key once, then denies any key whose first segment is uploads and whose second starts with bb-, for every caller including superadmin. It checks both the served form and the ..-resolved form, and the caller serves only the returned normalized key. Denial answers 403 UPLOAD_FILE_ACCESS_DENIED.
Product video is a new upload type, product-video: .mp4, .webm, .mov with video/mp4, video/webm, video/quicktime.
7. Configuration
| Key | Effect |
|---|---|
BULL_QUEUE_BB_CATALOG_ATTEMPTS | Attempts per job. Default 3. The queue's default job options are read per queue from BULL_QUEUE_<QUEUE NAME>_*, because outbox-relayed jobs carry no per-call attempts |
BULL_QUEUE_BB_CATALOG_REMOVE_ON_FAIL_AGE_SEC | How long BullMQ keeps a failed job. Default 172800 (2 days), minimum 86400 |
BULL_QUEUE_BB_CATALOG_DEAD_LETTER_THRESHOLD | Failed-job count that triggers the dead-letter error log. Default 10, minimum 1 |
API_RUNTIME_PROFILE=fast | Skips ScheduleModule, so the sweep scheduler never runs |
APP_URL | With StorageManager.getPublicUrl("public/"), sets the origins an img src in a description may point at. The sanitizer module itself reads no env; the caller supplies the origins |
The three BULL_QUEUE_BB_CATALOG_* keys are declared with defaults in env.validation.ts and have no entry in apps/api/.env.example, so the defaults hold without an .env edit. The worker concurrency (1), the job caps and the cleanup timings are constants, not env. All cites in this table are under apps/api/src/.
8. Security and Operational Controls
- Every route needs a bb permission. The job routes need
BB_Catalog_*plus an entity code, and the worker re-checks both when it claims the job. - Job reads are scoped to the controller's entity, so another entity's job looks missing.
- A job whose filters include deleted rows can only be read, fetched or downloaded by a caller holding the entity's
RESTOREcode (403BB_JOB_INCLUDE_DELETED_FORBIDDEN). - Idempotency keys are always looked up with the requester's admin id. A replay with a different file answers 409
BB_JOB_IDEMPOTENCY_CONFLICT. - One admin's job submits are serialized by an advisory lock keyed on
bb_catalog_job_active:<adminId>, so two concurrent requests cannot both pass the 2-job cap. - Catalog audit rows record the actor, IP and a redacted diff. Bulk rows use summary
bulk; reorder rows usereorder. - A job row's
last_errornever carries raw error text, which can hold SQL, bound values or an absolute path. The bulk runner logs constraint names only. The raw text of a job failure goes to the[failure]and[retry]log lines.
9. Error Contract
Every BB_* code is a string in ErrorCodes and travels in the errorCode field of the response body.
Database errors are classified
classifyBbCatalogDbError maps 23505 unique violations, 23503 foreign-key violations and 23514 check violations on catalog constraints to a BB_* code, and 55P03 (lock timeout), 40P01 (deadlock) and 40001 (serialization failure) to BB_CATALOG_BUSY. Any other chk_bb_<table>_* check becomes BB_CATALOG_FIELD_INVALID; chk_bb_category_depth_within_cap becomes BB_CATEGORY_DEPTH_EXCEEDED.
Precedence on write paths
The order in which a write reports competing errors, read from the services. A request stops at the first failing step.
Create product
- DTO validation: 400
VALIDATION_FAILED - Gallery:
BB_PRODUCT_GALLERY_INVALID - Description:
BB_PRODUCT_DESCRIPTION_TOO_LONG, thenBB_PRODUCT_DESCRIPTION_EMPTY - Option values on a new variant:
BB_VARIANT_OPTION_VALUES_INVALID(a new product has no axes) - Inside the transaction, after the lock timeout is set: category, brand and series lookup,
BB_PRODUCT_REFERENT_NOT_FOUND(400) orBB_PRODUCT_REFERENT_DELETED(409), then tags (BB_TAG_NOT_FOUND) - Variant count, prices (
BB_VARIANT_PRICE_INVALID), SKUs repeated in the request, default election (400VALIDATION_FAILEDfor two defaults, 409BB_VARIANT_DEFAULT_INACTIVE), repeated label (BB_VARIANT_DUPLICATE_COMBINATION) - Database constraints through the classifier, for example
BB_VARIANT_SKU_TAKEN
Update product
- Gallery, then description, before any lock
- Product lock:
BB_PRODUCT_NOT_FOUND(404, also for a deleted product), thenBB_PRODUCT_VERSION_CONFLICTwhenversionwas sent - Referent lookup, only when a category, brand or series key was sent: not found (400) or deleted (409)
- Database constraints through the classifier
Variant update : product lock (404), variant lookup (BB_VARIANT_NOT_FOUND), BB_VARIANT_VERSION_CONFLICT, prices, then BB_VARIANT_DEFAULT_INACTIVE, then constraints. Variant create checks prices before it takes any lock, so a bad price answers before a missing product does. After the lock it checks the 100-variant limit, the option values, then the duplicate combination.
Option axis create : product lock (404) with productVersion (409), then BB_OPTION_LIMIT_EXCEEDED, then BB_OPTION_ADD_WOULD_DUPLICATE_VARIANTS, then constraints such as BB_OPTION_NAME_TAKEN.
Every classified path ends at the same place: a database error maps to a BB_* code, or to 409 BB_CATALOG_BUSY for a lock timeout, deadlock or serialization failure.
Job-level codes
These are written to a job's errors[] or last_error, not returned as an HTTP error: BB_JOB_AUTHORIZATION_REVOKED, BB_JOB_LEASE_EXPIRED, BB_JOB_NEVER_DISPATCHED, BB_JOB_RETRY_ABANDONED, and the row-level BB_IMPORT_ROW_* family.
The full list with status codes is in the API page.
10. Tests and Gates Recorded
The final gate report records these results (HEAD df0bf70 plus the barrier fixes that became 8bd7bcd and 4cac0cf). This page does not re-run them.
- Build of the db and jobs packages,
check-typesandcheck:ci(error codes, module size and shape, job ids, env orphans): pass. - Unit: 338 suites / 4,114 tests. Integration: 107 suites / 1,716 tests. End to end: 1 suite. Structure: 5 suites / 20 tests. Build: pass.
scripts/checks/bb-phase2.shagainst a live API: 64 pass, 0 fail, using a copy with the video MIME type set on the upload. The script as shipped failed 13 checks on this machine because curl sentapplication/octet-streamfor the.mp4; commit4cac0cfadds the type to the shipped script.- A real export and a real import ran end to end through the outbox, the dispatcher and the
bb_catalogworker. - A 5,000-row product import completed with 0 failed rows: handler time 15.9 s, wall time 17 to 19 s. Other requests stayed at 11 to 16 ms during the run.
- Real MAINTENANCE ticks ran for the stalled and never-dispatched passes.
- Migration down to
0061and back up on an empty database: schema dump identical. - Real MAINTENANCE ticks were run for the stalled, never-dispatched and retry-abandoned passes.
11. File Map
apps/api/src/modules/bb/
admin/
category/ brand/ brand-series/ tag/ product/ variant/ option/
job/ (controllers per entity, admin and read services, upload config, permissions)
catalog-shared/ (bulk, reorder, locks, db errors, sanitizer, rules/)
jobs/ (state machine, runner, enqueue, authority, files, constants)
jobs/import/ (reader, cell parsers, writers, import handler)
jobs/export/ (row readers, CSV escaping, export handler)
jobs/sweep/ (module, processor, scheduler, job-file cleanup)
shared/ (audit types and redaction widened for catalog entities)
packages/db/src/schema/bb/ (7 new schema files + index)
packages/db/src/migrations/ (0061, 0062, down/0061, down/0062, meta snapshots)
packages/jobs/src/index.ts (queue, job names, payload types)
packages/storage/src/upload-allowlist.ts (product-video)
scripts/checks/bb-phase2.sh12. Registration and Known Limits
Registration. BbAdminAggregateModule imports 13 leaf modules, flat on purpose, because the audit-completeness spec reads only its direct imports and Swagger derives its bb leaves from them: the 5 phase-1 leaves plus BbCategoryAdminModule, BbBrandAdminModule, BbBrandSeriesAdminModule, BbTagAdminModule, BbProductAdminModule, BbVariantAdminModule, BbOptionAdminModule and BbJobAdminModule. BbModule imports BbCatalogWorkerModule, which provides the queue processor, the runner, the authority service, both handlers and BbImportDescription.
Import handler. BbCatalogImportHandler calls runBbCatalogImport: read the file under every cap, check the header, parse every row, and refuse the whole file if any row has an error. Only then does it open one transaction, set the lock timeout, take the category tree lock (categories only), write each row inside its own savepoint, re-check the lease, and write completed in the same transaction. Parsing never happens inside the transaction. A row that fails inside its savepoint is collected, and the transaction rolls back at the end if any row failed.
Export handler. BbCatalogExportHandler reads in keyset batches of 500 on the pool, never in a transaction, appends to a per-attempt part file, re-checks the lease every 500 rows and again just before the rename, and writes completed and the result key in one statement. After a failure it removes the final file only when this attempt still holds the lease, or when the lease was lost at the completing write and the job is already cancelled or failed. A lease lost before the rename never touches the final file.
Known limits
- Part files and result files left by a crashed attempt wait for the daily cleanup, which removes only files older than 24 hours.
- The CSV reader is shared with other importers. It trims unguarded cell edges, drops cells beyond the header width, and turns a CR inside a quoted cell into LF.
- The import normalizes names to NFC. The API does not, so the same visible name written through the API and through an import can differ in its stored bytes.
- Job submit and cancel do not map a deadlock to
BB_CATALOG_BUSY. - Counts for an import (
processedRows) are written at completion only. A running import reads 0.
13. See Also
- Catalog API reference:
catalog-api - Catalog feature overview:
catalog-feature - Phase 1 backend:
backend
B2B Second Inventory Catalog Feature Overview
Phase 2 of the bb (B2B second inventory) area — a catalog of categories, brands, series, tags, products, variants and option axes, with bulk actions and import/export jobs, kept apart from the retail catalog.
B2B Second Inventory Catalog API Reference
Endpoint reference for the bb phase 2 admin catalog API — categories, brands, series, tags, products, variants, options, bulk actions and import/export jobs — with contracts and error codes.