Repository navigation
feat: post view counts and daily visitor counting - #17
Conversation
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>
|
Warning Review limit reached
Next review available in: 48 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughThis 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. ChangesTraffic counter feature
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (22)
apps/api/src/server.tsapps/api/test/server.test.tsapps/web/src/components/visitor-counter.tsxapps/web/src/lib/api.tsapps/web/src/lib/stats.tsapps/web/src/routes/__root.tsxapps/web/src/routes/home.tsxapps/web/src/routes/post-detail.tsxpackages/core/src/core.tspackages/core/src/index.tspackages/core/src/services/stats-service.tspackages/core/test/asset-service.test.tspackages/core/test/stats-service.test.tspackages/core/test/upload-finalize.integration.test.tspackages/core/test/upload-service.test.tspackages/db/drizzle/0006_view_visitor_counts.sqlpackages/db/drizzle/meta/0006_snapshot.jsonpackages/db/drizzle/meta/_journal.jsonpackages/db/src/index.tspackages/db/src/repositories/stats-repository.tspackages/db/src/schema.tspackages/db/test/stats-repository.test.ts
- 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>
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
🧹 Nitpick comments (1)
apps/api/src/server.ts (1)
326-348: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueStale comment terminology: "debounced" vs. actual fixed-window throttling.
The comment at Lines 327-328 describes
recordViewas "debounced to once per visitor-session," but the PR's own follow-up commit clarifies thatrecordViewimplements 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
📒 Files selected for processing (7)
apps/api/src/server.tsapps/api/test/server.test.tsapps/web/src/lib/api.tsapps/web/src/lib/stats.tspackages/core/src/services/stats-service.tspackages/db/src/repositories/stats-repository.tspackages/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>
|
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 |
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.recordViewis the crux: oneINSERT … ON CONFLICT DO UPDATE … WHERE counted_at <= cutoff RETURNINGdecides whether to count, bumpingview_countonly when newly inserted or a full session window has elapsed — so refreshes don't inflate it.recordVisitis insert-on-conflict-do-nothing.core
stats-service: 30-min view debounce, UTC-day visitor buckets,getStats() = { posts, visitorsToday }. Wired intoCore;viewCountflows 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/statshooks: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 staticPOST_COUNT.Tests
stats-service unit; real-Postgres stats-repository integration (debounce +
view_countbump, window elapse, daily-unique idempotency, totals); API routes incl.x-visitor-idattribution + fallback.All green:
typecheck(incl. web) · 197 tests ·lint:boundaries. Ships migration0006(deploys runbun run migrate). CLI pre-review applied (4: inclusive debounce cutoff, post-mutation cache refresh, and the cookie-race +Secureissues 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