Skip to content

feat: post view counts and daily visitor counting - #17

Merged
deckyfx merged 3 commits into
mainfrom
feat/view-visitor-counts
Jul 1, 2026
Merged

deckyfx merged 3 commits into
mainfrom
feat/view-visitor-counts

Conversation

@deckyfx

@deckyfx deckyfx commented Jun 30, 2026 •

Copy link
Copy Markdown
Owner

Roadmap milestone: post view counts + daily visitor counting. Counter + debounce model (no rollup job), counting anonymous traffic by an opaque, client-owned visitor id (a localStorage uuid sent as x-visitor-id) — never an IP.

Why a client-owned id (not a server cookie)

A server-minted cookie races across a first-load request burst: parallel cookieless requests each mint a different id, so a reloading visitor gets counted twice on day one (and a long-lived cookie would also need Secure). The client owning one stable id sidesteps both — every request carries the same id from the first moment. (Both were CodeRabbit CLI findings; this is the fix.)

db (migration 0006)

  • assets.view_count (+ nonneg check); post_views(visitor_id, asset_id) dedup ledger (PK + asset index, cascade); daily_visitors(day, visitor_id) PK.
  • recordView is the crux: one INSERT … ON CONFLICT DO UPDATE … WHERE counted_at <= cutoff RETURNING decides whether to count, bumping view_count only when newly inserted or a full session window has elapsed — so refreshes don't inflate it. recordVisit is insert-on-conflict-do-nothing.

core

stats-service: 30-min view debounce, UTC-day visitor buckets, getStats() = { posts, visitorsToday }. Wired into Core; viewCount flows onto the asset DTO automatically.

api

A group-level derive reads + validates x-visitor-id (throwaway per-request id for non-web clients). POST /assets/:id/view (404 if absent, else { counted }), POST /stats/visit (idempotent per day), GET /stats.

web

The Eden client owns a stable localStorage visitor id and sends it on every request. lib/stats hooks: useSiteStats, useRecordVisit (once per load → refreshes site-stats), useRecordView (once per post → refetches the asset only when it counted). Root layout records a visit; the footer counter + home odometer show live numbers; the post detail records a view and shows the count. Removes the localStorage demo counter and the static POST_COUNT.

Tests

stats-service unit; real-Postgres stats-repository integration (debounce + view_count bump, window elapse, daily-unique idempotency, totals); API routes incl. x-visitor-id attribution + fallback.

All green: typecheck (incl. web) · 197 tests · lint:boundaries. Ships migration 0006 (deploys run bun run migrate). CLI pre-review applied (4: inclusive debounce cutoff, post-mutation cache refresh, and the cookie-race + Secure issues resolved by the client-owned-id redesign).

Roadmap

Next: auth + superadmin (gates all writes, incl. the deferred tag-category endpoint).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added server-backed site stats and traffic counters (post views, daily unique visitors) with live counters on the home page.
    • Post pages now display view totals, and the visitor counter is driven by server data (no longer local-only).
    • Requests now include a stable anonymous visitor ID to power accurate counting.
  • Bug Fixes
    • Prevent repeated view/visit counting from inflating totals by throttling views per visitor+asset and recording daily visits idempotently.

Counter + debounce model (no rollup job), counting anonymous traffic by an
opaque, client-owned visitor id (a localStorage uuid sent as `x-visitor-id`) —
never an IP. The client owns the id so a server-minted cookie can't race across
a first-load request burst and count one human several times.

db — migration 0006: assets.view_count (+ nonneg check); post_views(visitor_id,
asset_id) dedup ledger (PK + asset index, cascade); daily_visitors(day,
visitor_id) PK. stats-repository: recordView upserts the dedup row and bumps
view_count only when newly inserted or last-counted at/older than the session
cutoff (a single INSERT ... ON CONFLICT DO UPDATE ... WHERE ... RETURNING decides
whether to count, so refreshes don't inflate it); recordVisit is insert-on-
conflict-do-nothing; visitorCount(day) and postCount() read the totals.

core — stats-service: 30-min view debounce window, today()-bucketed visits,
getStats() = { posts, visitorsToday }. Wired into Core; Asset now carries
viewCount, so it flows through serializeAsset/AssetDto unchanged.

api — a group-level derive reads + validates the `x-visitor-id` header (throwaway
per-request id for non-web clients). POST /assets/:id/view (404 if absent, else
{ counted }), POST /stats/visit (idempotent per day), GET /stats.

web — the Eden client owns a stable localStorage visitor id and sends it on every
request. lib/stats hooks: useSiteStats, useRecordVisit (once per load, then
refreshes site-stats), useRecordView (once per post, refetches the asset only
when it counted). Root layout records a visit; footer visitor counter + home
odometer show live numbers; post detail records a view and shows the count.
Drops the localStorage demo counter and the static POST_COUNT.

Tests: stats-service unit; stats-repository integration (real Postgres: view
debounce + view_count bump, window elapse, daily-unique idempotency, totals); API
routes incl. x-visitor-id attribution + fallback.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jun 30, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@deckyfx, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 48 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 365aa8f1-4e17-4bca-a8f0-503d6eb7d4eb

📥 Commits

Reviewing files that changed from the base of the PR and between 173299d and e2e216b.

📒 Files selected for processing (1)
  • apps/api/src/server.ts
📝 Walkthrough

Walkthrough

This PR adds database-backed traffic counters for post views and daily unique visitors. It introduces new schema, repository, and core service support, new API endpoints, browser visitor-id handling, and frontend hooks/UI updates to record and display counts.

Changes

Traffic counter feature

Layer / File(s) Summary
Database schema and migration
packages/db/drizzle/0006_view_visitor_counts.sql, packages/db/drizzle/meta/0006_snapshot.json, packages/db/drizzle/meta/_journal.json, packages/db/src/schema.ts
Adds daily_visitors, post_views, and assets.view_count, with matching schema exports, constraints, and generated migration metadata.
Stats repository
packages/db/src/repositories/stats-repository.ts, packages/db/src/index.ts, packages/db/test/stats-repository.test.ts
Implements throttled view recording, idempotent daily visit recording, and aggregate count queries, then exports and tests the repository behavior.
Core stats service and wiring
packages/core/src/services/stats-service.ts, packages/core/src/core.ts, packages/core/src/index.ts, packages/core/test/stats-service.test.ts, packages/core/test/asset-service.test.ts, packages/core/test/upload-finalize.integration.test.ts, packages/core/test/upload-service.test.ts
Adds the core stats service contract and factory, wires it into Core, re-exports it, and updates test fixtures to include viewCount.
API routes and visitor-id handling
apps/api/src/server.ts, apps/api/test/server.test.ts
Validates x-visitor-id, derives request context from it, adds traffic-counter routes, and covers them with server tests.
Frontend visitor-id, hooks, and UI
apps/web/src/lib/api.ts, apps/web/src/lib/stats.ts, apps/web/src/components/visitor-counter.tsx, apps/web/src/routes/__root.tsx, apps/web/src/routes/home.tsx, apps/web/src/routes/post-detail.tsx
Adds browser visitor-id persistence and header injection, stats hooks, and UI updates for recording visits/views and rendering live counters.

Sequence Diagram(s)

sequenceDiagram
  participant Browser
  participant ApiClient
  participant Server
  participant StatsService
  participant StatsRepository
  Browser->>ApiClient: load app / view post
  ApiClient->>Server: request with x-visitor-id
  Server->>StatsService: recordVisit(visitorId) / recordView(visitorId, assetId)
  StatsService->>StatsRepository: persist counter data
  StatsRepository-->>Server: counted / totals
  Server-->>ApiClient: JSON response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • deckyfx/bunbooru#6: Both PRs modify apps/api/src/server.ts’s /api/v1 routing and request-context wiring.

Poem

I’m a rabbit with a tally and a grin,
Counting views and visits coming in.
Hop to the page, the numbers bloom,
One little header brightens the room. 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 78.26% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the PR’s main change: adding post view counts and daily visitor counting.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/view-visitor-counts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@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: 4

🤖 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 `@apps/api/src/server.ts`:
- Around line 156-164: The visitor ID derivation in server.ts is synthesizing a
random ID when the x-visitor-id header is missing or invalid, which causes
counter routes to treat each request as a unique visitor. Update the .derive
logic to keep visitorId nullable instead of falling back to crypto.randomUUID(),
and then adjust the counter-writing handlers such as the POST /stats/visit and
POST /assets/:id/view paths to reject or no-op when visitorId is absent/invalid
so refreshes are not counted as new visits.

In `@apps/web/src/lib/api.ts`:
- Around line 25-29: The visitor ID helper can throw when accessing
localStorage, which causes the API client header callback to fail and blocks all
requests. Update visitorId() to safely read/write VISITOR_KEY inside a
try/catch, and if storage is unavailable or throws, fall back to generating and
returning an in-memory crypto.randomUUID() value without calling localStorage.
Keep the fix localized to visitorId() so the header callback can always return a
valid x-visitor-id.

In `@apps/web/src/lib/stats.ts`:
- Around line 27-37: The visit/view hooks in useRecordVisit and the matching
view hook mark their fired sentinel before the POST succeeds, so a transient
failure permanently suppresses retries for that mount. Update the logic to clear
or defer the fired flag in the promise rejection path (or only set it after a
successful response) and keep the invalidateQueries refresh on success, so
failed requests can retry safely while still deduping by mount.

In `@packages/db/src/repositories/stats-repository.ts`:
- Around line 35-49: The current upsert logic in stats-repository is
implementing a fixed-window throttle in the countedAt path, not a debounce.
Update StatsRepository’s postViews conflict handling so it tracks a separate
“last seen”/refresh timestamp (or equivalent) and only counts after a true quiet
period, rather than re-counting whenever lte(postViews.countedAt, cutoff)
becomes true. Add a regression test for the 0m / 10m / 20m / 31m sequence to
verify refreshes inside the debounce window do not inflate counts.
🪄 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: ef951838-f9be-4172-acf1-e1b3fd058630

📥 Commits

Reviewing files that changed from the base of the PR and between 4f1aa4a and b46e07e.

📒 Files selected for processing (22)
  • apps/api/src/server.ts
  • apps/api/test/server.test.ts
  • apps/web/src/components/visitor-counter.tsx
  • apps/web/src/lib/api.ts
  • apps/web/src/lib/stats.ts
  • apps/web/src/routes/__root.tsx
  • apps/web/src/routes/home.tsx
  • apps/web/src/routes/post-detail.tsx
  • packages/core/src/core.ts
  • packages/core/src/index.ts
  • packages/core/src/services/stats-service.ts
  • packages/core/test/asset-service.test.ts
  • packages/core/test/stats-service.test.ts
  • packages/core/test/upload-finalize.integration.test.ts
  • packages/core/test/upload-service.test.ts
  • packages/db/drizzle/0006_view_visitor_counts.sql
  • packages/db/drizzle/meta/0006_snapshot.json
  • packages/db/drizzle/meta/_journal.json
  • packages/db/src/index.ts
  • packages/db/src/repositories/stats-repository.ts
  • packages/db/src/schema.ts
  • packages/db/test/stats-repository.test.ts

Comment thread apps/api/src/server.ts Resolved
Comment thread apps/web/src/lib/api.ts Resolved
Comment thread apps/web/src/lib/stats.ts Resolved
- Visitor id (Major): the API no longer synthesizes a throwaway id for a
  header-less request — that would count every such request as a fresh
  visitor/view and defeat dedup. `visitorId` is nullable; POST /assets/:id/view
  and POST /stats/visit return 400 when it's absent/invalid. The web always
  sends a stable one.
- localStorage guard (Major): the web's x-visitor-id header callback wraps
  localStorage access in try/catch with an in-memory uuid fallback, so a storage
  failure (private mode, disabled, quota) can't reject and fail every request.
- Dropped writes (Major): useRecordVisit/useRecordView reset their "fired"
  sentinel on a failed POST so a transient error doesn't permanently lose the
  visit/view; a retry on the next mount is safe (endpoints are deduped).
- Throttle terminology (Major): recordView is a fixed-window throttle (≤1 count
  per window since the last counted view), not an idle-reset debounce — the
  intended behaviour for a view counter (an idle-reset would under-count an
  engaged reader). Renamed the docs/const accordingly and added a regression
  test proving intermediate hits don't extend the window.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@deckyfx

deckyfx commented Jun 30, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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.

🧹 Nitpick comments (1)
apps/api/src/server.ts (1)

326-348: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Stale comment terminology: "debounced" vs. actual fixed-window throttling.

The comment at Lines 327-328 describes recordView as "debounced to once per visitor-session," but the PR's own follow-up commit clarifies that recordView implements fixed-window throttling, not idle-reset debouncing. Worth aligning this comment's wording with that clarification to avoid confusing future readers about the actual dedup semantics.

🤖 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 `@apps/api/src/server.ts` around lines 326 - 348, Update the traffic counter
comment in server.ts to match the actual dedup behavior of recordView; the
current wording in the POST /assets/:id/view route says “debounced to once per
visitor-session,” but the implementation is fixed-window throttling. Adjust the
comment near the .post("/assets/:id/view", ...) handler so it describes
throttling/window-based dedup semantics and stays consistent with
core.statsService.recordView.
🤖 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.

Nitpick comments:
In `@apps/api/src/server.ts`:
- Around line 326-348: Update the traffic counter comment in server.ts to match
the actual dedup behavior of recordView; the current wording in the POST
/assets/:id/view route says “debounced to once per visitor-session,” but the
implementation is fixed-window throttling. Adjust the comment near the
.post("/assets/:id/view", ...) handler so it describes throttling/window-based
dedup semantics and stays consistent with core.statsService.recordView.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 5ae24d66-b8a5-41db-9312-c9b04f3b0053

📥 Commits

Reviewing files that changed from the base of the PR and between b46e07e and 173299d.

📒 Files selected for processing (7)
  • apps/api/src/server.ts
  • apps/api/test/server.test.ts
  • apps/web/src/lib/api.ts
  • apps/web/src/lib/stats.ts
  • packages/core/src/services/stats-service.ts
  • packages/db/src/repositories/stats-repository.ts
  • packages/db/test/stats-repository.test.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • apps/web/src/lib/api.ts
  • packages/core/src/services/stats-service.ts
  • packages/db/test/stats-repository.test.ts
  • apps/web/src/lib/stats.ts
  • packages/db/src/repositories/stats-repository.ts

CodeRabbit nitpick: the POST /assets/:id/view comment still said "debounced";
the implementation is a fixed-window throttle (per the rename in 173299d). Match
the wording so the dedup semantics aren't misdescribed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@deckyfx

deckyfx commented Jun 30, 2026

Copy link
Copy Markdown
Owner Author

Addressed the nitpick (POST /assets/:id/view comment terminology): fixed in e2e216b — the route comment now says "throttled to at most once per window per visitor" instead of "debounced", matching core.statsService.recordView (a fixed-window throttle, not an idle-reset debounce). That was the only remaining item from the review.

@deckyfx
deckyfx merged commit 60b197a into main Jul 1, 2026
2 checks passed
@deckyfx
deckyfx deleted the feat/view-visitor-counts branch August 1, 2026 15:45
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