Skip to content

refactor(worker): move job handler data access into business services - #1101

Open
realcodesiman wants to merge 2 commits into
mainfrom
refactor/data-access-worker-jobs
Open

refactor(worker): move job handler data access into business services#1101
realcodesiman wants to merge 2 commits into
mainfrom
refactor/data-access-worker-jobs

Conversation

@realcodesiman

@realcodesiman realcodesiman commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Summary

Changes

  • New tag-channel and sequence-dispatch repositories, mac-partitions.ts DDL helpers, contactRepository.listForExportPage, fileRepository.updateForWorkspace, contactInboxRepository.{listByInboxPage,listContactIdsByIds}, integrationMessengerRepository.{findById,findByInboxId,listByWorkspace}.
  • broadcastService: listDueScheduled, listSendingAwaitingHandoff, findScheduledForPrepare, resolveTemplateIntegrationMessengerId, insertRecipients, promoteAfterPrepare (keeps the resumeCount = promotionEpoch CAS guard and returns the boolean the handler branches on), listSendableById, listPendingRecipients, markContactFailed.
  • userQuotaService.{reconcileUserSelfUsage,persistMacUsed,applyMonthlyBotMessagesReset} and workspaceUsageService.{loadReconcileCounts,upsertReconciled}: direct-assign semantics (never GREATEST), onConflictDoUpdate kept, self-path hset has no mac field, DB zeroing still precedes the Redis field write (AGENTS.md invariants 11 and 12).
  • triggerService, webhookService, tagService, conversationService, flowService, inboxService, zaloIntegrationService: trigger-engine and sync-tag reads/writes. tagService.{attachExistingToContactForTrigger,detachFromContactForTrigger} deliberately do not emit or bulk-enqueue; the worker keeps its own per-pair enqueue loops. hardDeleteSoftDeleted keeps the isNotNull(deletedAt) guard.
  • sequenceDispatchRepository.claim keeps the status='pending' predicate + affected-row check; deleteTerminalBatch keeps the CTE with the partition-pruning sd.workspaceId = rows.workspaceId join.
  • contactService.insertImportedContactBatch (body in contact/insert-imported-batch.ts, exposed as a normal class method) holds the import transaction verbatim.
  • 22 worker test files re-pointed to the service boundary; SQL-shape assertions relocated into business/database unit tests rather than dropped; new blocked-owner-guard and job-id regression tests. Restored the promoteAfterPrepare epoch-CAS WHERE-shape assertion and the upsertLabelMapping insert-ordering/createId/onConflictDoNothing assertions in this revision; de-tautologized the listSendingAwaitingHandoff/findScheduledForPrepare/insertRecipients tests to assert the actual where/row shape instead of just the mocked return value. Fixed sequence-dispatch-processor.test.ts, which mocked @chatbotx.io/database/schema narrowly while the service under test now imports the repositories barrel (which reaches the full schema graph) — it now mocks @chatbotx.io/database/repositories directly. Removed the dead, uncalled inboxService.findTeamById.

Notes for reviewers

Test plan

  • pnpm --filter @chatbotx.io/database check-types && test
  • pnpm --filter @chatbotx.io/business check-types && test (only the pre-existing questionnaire-service.test.ts failure remains — a bloomFilter mock gap in packages/analytics/src/services/mac-tracking.service.ts, also red on main, untouched by this PR)
  • pnpm --filter worker check-types && test (all 219 files green; no pre-existing failures observed in this scope)
  • pnpm --filter worker build
  • pnpm lint
  • Staging smoke: export + import a contact CSV; sync a tag to Messenger/Zalo; schedule and send a broadcast; run the quota reconcile cron once

🤖 Generated with Claude Code

@github-actions github-actions Bot added the improvement Refactor or performance improvement label Sep 6, 2026
Removes direct db usage from apps/worker/src/{default,schedule,trigger,
sequence-scheduler,webhook} per .agents/rules/data-access.md. Query
bodies, chunk sizes, orderings, onConflict targets and raw SQL are moved
verbatim; only signatures change.

- new tag-channel and sequence-dispatch repositories, mac-partitions
  DDL helpers, contactRepository.listForExportPage,
  fileRepository.updateForWorkspace
- broadcastService gains the prepare/send/reconcile reads and writes;
  promoteAfterPrepare keeps the resumeCount CAS guard
- userQuotaService.reconcileUserSelfUsage / persistMacUsed /
  applyMonthlyBotMessagesReset and workspaceUsageService.loadReconcileCounts
  / upsertReconciled keep the direct-assign (not GREATEST) semantics and
  the DB-before-Redis zeroing order
- triggerService / webhookService / tagService / conversationService /
  flowService / inboxService / zaloIntegrationService gain the trigger
  engine and sync-tag reads; the trigger-only tag helpers deliberately do
  not emit or bulk-enqueue
- contactService.insertImportedContactBatch (body in
  contact/insert-imported-batch.ts) holds the import transaction

isBlockedWorkspace call sites and retry semantics are unchanged.
Update sequence-dispatch, broadcast-prepare, and tag-channel tests to
match the repository/service-based data access introduced in the prior
refactor, remove an inline wrapper around persistMacUsed, and drop the
now-unused InboxService.findTeamById.
@realcodesiman
realcodesiman force-pushed the refactor/data-access-worker-jobs branch from 9d1337a to 3b41d79 Compare September 12, 2026 02:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

improvement Refactor or performance improvement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant