Skip to content

refactor(payments): Removed payments from clickhouse - #43

Merged
SteakFisher merged 1 commit into
mainfrom
refactor/payments
May 18, 2026
Merged

refactor(payments): Removed payments from clickhouse#43
SteakFisher merged 1 commit into
mainfrom
refactor/payments

Conversation

@SteakFisher

@SteakFisher SteakFisher commented May 18, 2026

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • Refactor

    • Consolidated event type system to focus on core usage tracking categories.
    • Reorganized payment processing into a dedicated handling system.
    • Updated database schema and query support to reflect simplified architecture.
  • Improvements

    • Enhanced event query result availability for improved data retrieval.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 18, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR removes PAYMENT as a supported event type across the event system, storage adapters, and query infrastructure. Payment persistence moves from adapter-specific handlers to a unified PostgreSQL database helper, while HTTP routes are updated to call the new consolidated function.

Changes

Remove Payment Event Support

Layer / File(s) Summary
Event type system
src/interface/event/Event.ts
PAYMENT is removed from EventKind, EventDataMap, and SqlRecord unions; PaymentEventData type and PaymentEvent interface are deleted.
Storage adapter routing cleanup
src/factory/EventStorageAdapterFactory.ts, src/storage/adapter/clickhouse/ClickHouseAdapter.ts, src/storage/adapter/postgres/postgres.ts
PAYMENT case is removed from adapter dispatch switches in factory and add() methods; handler imports are cleaned up.
Handler consolidation to Postgres db helper
src/storage/db/postgres/helpers/payments.ts, src/storage/adapter/clickhouse/handlers/index.ts, src/storage/adapter/postgres/handlers/index.ts
New handleAddPayment helper is added to the db layer with creditAmount validation and ISO timestamp insertion; old adapter-specific handlers are removed; barrel exports are updated.
Query and schema system update
src/storage/adapter/clickhouse/schema.ts, src/storage/adapter/clickhouse/handlers/queryEvents.ts, src/storage/adapter/common/queryEventsBase.ts, src/storage/adapter/postgres/handlers/queryEvents.ts
ClickHouse payment_events table creation is removed from migrations; event type/table type unions are narrowed to BASIC_USAGE and AI_TOKEN_USAGE; query field registries no longer define payment event columns.
HTTP route integration update
src/routes/http/createdCheckout.ts
storePaymentEvent now calls the new consolidated handleAddPayment(userId, creditAmount, apiKeyId, mode) helper instead of constructing a Payment event and dispatching through adapters.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • ScrawnDotDev/Scrawn#40: Refactors the event type system where this PR narrows EventKind/tables by removing PAYMENT entirely.
  • ScrawnDotDev/Scrawn#41: Both PRs remove PAYMENT from storage adapter dispatch and handler exports across ClickHouse and Postgres adapters.
  • ScrawnDotDev/Scrawn#37: Touches the PAYMENT event pipeline in EventStorageAdapterFactory and createdCheckout that this PR removes entirely.

Poem

🐰 Off goes the Payment, no more events to store,
Consolidated helpers make the code so pure,
Type system slimmed down to two kinds so bright,
Adapters now simpler—a cleaner code flight! ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Title check ⚠️ Warning The title states payments were removed from ClickHouse, but the changeset removes PAYMENT event type system-wide from multiple storage adapters, builders, and type definitions across the entire codebase. Revise the title to reflect the broader scope: consider 'refactor(payments): Remove PAYMENT event type system-wide' or similar to accurately represent the comprehensive removal across all storage adapters and type systems.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/payments

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/routes/http/createdCheckout.ts (1)

140-146: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Make session update, user update, and payment insert atomic.

This flow can commit sessions.processed=true and user updates before payment insert succeeds. If insert fails, retries can be ignored and the payment event is permanently lost. Wrap all three writes in a single transaction and only mark processed when payment persistence succeeds.

As per coding guidelines, "Use Drizzle ORM with transactions; validate all inputs before DB operations; handle unique constraint violations explicitly".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/routes/http/createdCheckout.ts` around lines 140 - 146, Wrap the three DB
writes (update usersTable.last_billed_timestamp, update sessionsTable.processed,
and the call to storePaymentEvent) in a Drizzle ORM transaction so they succeed
or roll back together: start a transaction, validate inputs (userId,
checkout_session_id, payment_id, creditAmount, apiKeyId) before any DB calls,
call storePaymentEvent inside the transaction (or perform its inserts/updates
via the transaction-bound DB instance), and only set sessionsTable.processed =
true after the payment insert succeeds; additionally catch and explicitly handle
unique constraint violations from the payment insert (treat as idempotent or
return existing) and ensure builder.setUser/builder.setPaymentContext are used
with the same validated values inside the transactional flow to keep state
consistent.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/storage/db/postgres/helpers/payments.ts`:
- Around line 12-21: The current guard for creditAmount in payments.ts allows
zero even though the error message and contract require a positive finite
number; update the conditional that currently checks `creditAmount < 0` to
`creditAmount <= 0` so zero is rejected, keeping the existing type and
Number.isFinite checks intact, and ensure the thrown StorageError.invalidData
message remains accurate for values <= 0.
- Around line 44-49: Replace the fragile shape-check on the caught error with a
concrete type guard by using instanceof StorageError (remove the `(e as any)`
cast and the `"type" in e` shape checks) so existing StorageError instances are
not re-wrapped as insertFailed; update the catch block in the helper where `e`
is inspected (the postgresql payments helper) to import/ reference StorageError
and perform `if (e instanceof StorageError) { ... }` and handle other errors
separately.

---

Outside diff comments:
In `@src/routes/http/createdCheckout.ts`:
- Around line 140-146: Wrap the three DB writes (update
usersTable.last_billed_timestamp, update sessionsTable.processed, and the call
to storePaymentEvent) in a Drizzle ORM transaction so they succeed or roll back
together: start a transaction, validate inputs (userId, checkout_session_id,
payment_id, creditAmount, apiKeyId) before any DB calls, call storePaymentEvent
inside the transaction (or perform its inserts/updates via the transaction-bound
DB instance), and only set sessionsTable.processed = true after the payment
insert succeeds; additionally catch and explicitly handle unique constraint
violations from the payment insert (treat as idempotent or return existing) and
ensure builder.setUser/builder.setPaymentContext are used with the same
validated values inside the transactional flow to keep state consistent.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: e800c643-467e-49c5-a8b6-c482259edb03

📥 Commits

Reviewing files that changed from the base of the PR and between 3893828 and a09a7f6.

📒 Files selected for processing (15)
  • src/events/Payment.ts
  • src/factory/EventStorageAdapterFactory.ts
  • src/interface/event/Event.ts
  • src/routes/http/createdCheckout.ts
  • src/storage/adapter/clickhouse/ClickHouseAdapter.ts
  • src/storage/adapter/clickhouse/handlers/addPayment.ts
  • src/storage/adapter/clickhouse/handlers/index.ts
  • src/storage/adapter/clickhouse/handlers/queryEvents.ts
  • src/storage/adapter/clickhouse/schema.ts
  • src/storage/adapter/common/queryEventsBase.ts
  • src/storage/adapter/postgres/handlers/addPayment.ts
  • src/storage/adapter/postgres/handlers/index.ts
  • src/storage/adapter/postgres/handlers/queryEvents.ts
  • src/storage/adapter/postgres/postgres.ts
  • src/storage/db/postgres/helpers/payments.ts
💤 Files with no reviewable changes (8)
  • src/storage/adapter/clickhouse/handlers/index.ts
  • src/events/Payment.ts
  • src/storage/adapter/clickhouse/handlers/addPayment.ts
  • src/storage/adapter/clickhouse/schema.ts
  • src/storage/adapter/postgres/handlers/index.ts
  • src/storage/adapter/clickhouse/ClickHouseAdapter.ts
  • src/storage/adapter/postgres/postgres.ts
  • src/storage/adapter/postgres/handlers/addPayment.ts

Comment thread src/storage/db/postgres/helpers/payments.ts
Comment thread src/storage/db/postgres/helpers/payments.ts
@SteakFisher
SteakFisher merged commit 1456410 into main May 18, 2026
3 checks passed
@SteakFisher
SteakFisher deleted the refactor/payments branch May 22, 2026 13:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant