Skip to content

feat(server): analytics and limits as Effect service packages - #84

Merged
allisonmahmood merged 3 commits into
mainfrom
feat/analytics-limits
Aug 29, 2026
Merged

allisonmahmood merged 3 commits into
mainfrom
feat/analytics-limits

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

What changed

Analytics and the fixed-window rate limiter lived in apps/server as plain modules, but auth and patches will both need them once they port, so they had to move onto Effect first. This PR turns each into a service package and leaves the Fastify app consuming them through one runtime seam.

  • packages/analytics: an Analytics service whose track never fails; a PostHog layer over a PostHogClient service, with a finalizer that flushes and gives up after 3 s; a no-op layer; and a layer that picks between them by PATCHY_POSTHOG_API_KEY, read as a Redacted Effect Config. A test injects a broken backend by providing another PostHogClient layer; the flush bound is tested with TestClock.
  • packages/limits: a Limits service mirroring RateLimiter.consume (key, limit and window per call; remaining and a Retry-After back). In memory, fails closed at 10k tracked keys, window expiry and the cap tested through the service with TestClock. A Redis-backed store later is a layer swap.
  • apps/server: one ManagedRuntime built in start.ts, two adapters in runtime.ts (consume, track); analytics.ts, rate-limit.ts and their tests are gone, the emitter tests run against a recording layer, and the posthog* fields leave @patchy/config. CONTEXT.md for both packages, language-service rules promoted to error.

One semantic nuance worth knowing: the four per-minute limits now share one store (keys are prefixed by limit name), so the 10k fail-closed cap is across all of them rather than per limiter. That matches the RateLimiter shape the issue asked for and only matters under a flood.

Stacked on #83 (feat/sql-package); merge that first.

Closes #73

How it was verified

  • pnpm test passes locally (also pnpm lint, pnpm typecheck, pnpm format:check)
  • Added or updated tests covering this change
  • Smoke-ran the server with the new runtime: /healthz answers, a protected route is limited and 401s as before, SIGINT shuts down cleanly through the analytics finalizer.

Release impact

  • Breaking — requires action from anyone already running this
  • Not breaking — no action required

Environment variables and every wire response are unchanged; internal refactor.

Built by Claude Fable 5 via Claude Code.

@github-actions github-actions Bot added area:server Touches the server area area:ci CI, shared testing infrastructure, development scripts and tooling area:docs Touches the docs area size:l 501-1,000 changed lines labels Aug 29, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Code review — PR 84 / issue 73

Reviewed git diff feat/sql-package...HEAD (4f45d8d, a1d08a6) against #73. Two-axis review (Standards / Spec) plus separate passes on implementation method and YAGNI.

Standards

Checked: Effect namespace imports, one-file services with inline interfaces, Schema.TaggedError + cause, environment deps (yield*), ManagedRuntime / runPromise only at the start.ts / runtime.ts seam and the Fastify test harness, @effect/vitest + TestClock + fault layers, Config.redacted for the PostHog key, language-service whole-file rules promoted to error, glossary in each CONTEXT.md. UI consistency N/A.

Hard — namespace at a service boundary

.agents/skills/effect-service-conventions/SKILL.md → Imports and module namespaces (same rule in AGENTS.md): import the service module as a namespace (Limits.Limits, Limits.layer).

packages/limits/src/Limits.test.ts:

import { Limits, MAX_TRACKED_KEYS, layer } from "./Limits.js";
// ...
it.layer(layer)("Limits", (it) => {

layer is pulled off the module — the alias pattern the spec flags. Analytics tests already do import * as Analytics. Smallest fix: import * as Limits from "./Limits.js", then Limits.layer / Limits.Limits / Limits.MAX_TRACKED_KEYS.

Judgement — glossary / Mysterious Name

packages/limits/CONTEXT.md Window / Avoid: bucket. packages/limits/src/Limits.ts still uses that name (interface Bucket, const buckets = new Map...). Comments already say “windows”. Rename to Window / windows.

Judgement — Feature Envy

CONTEXT Shutdown flush is “the PostHog layer’s finalizer”. Construction is PostHogClient.make; the 3s flush lives on Analytics.make. Not a hard violation: putting the timeout on Analytics is what lets a substituted hanging PostHogClient still exercise the bound.

Not findings: runtime.ts runPromise/runFork and start.ts ManagedRuntime.make are the documented seam; testing.ts extra runtime is the unported Fastify clock, not fake DI; PostHogError.operation is the allowed multi-value discriminator; packages match #56 even with one production consumer today.

Spec

Done when: yes. No limiter or analytics implementation remains in apps/server/src. runtime.ts is the specified ManagedRuntime seam; app.ts only applies consumer policy (named keys, 1-minute windows, HTTP Retry-After) and emitters. analytics.ts / rate-limit.ts are gone. Remaining apps/server/src/analytics.test.ts is HTTP emitter coverage, not the old modules.

Checklist that landed: Retry-After + fail-closed tested on the service (packages/limits/src/Limits.test.ts); finalizer 3s flush tested with TestClock (packages/analytics/src/Analytics.test.ts); language-service warnings promoted to error in both package tsconfig.jsons; PATCHY_POSTHOG_API_KEY is Config.redacted; unset key selects layerNoop; consume({ key, limit, window }) → { allowed, remaining, retryAfterSeconds } is a layer-swappable shape. Emitters keep the same six event names and properties; the four per-minute limits still key IP vs token the same way, now as ${name}:${key}.

(a) Missing / partial

None that fail Done when. Spec asked for a thin Effect.runPromise seam for both services; consume uses runPromise, track uses runFork (apps/server/src/runtime.ts). That matches “never awaited / never fails a request,” not a gap.

(b) Not asked for

  • Shared 10k cap. Spec: “keeping today's semantics: fails closed at 10k tracked keys.” One Limits store + name:key prefixes makes the cap global, not per limiter. The PR body discloses it; CONTEXT.md documents it; it is still a behaviour change vs four independent 10k maps.
  • Closed AnalyticsEventName union in packages/analytics (spec only asked for a track interface; the closed list already lived in the server module being moved).
  • Extra PostHogClient service file — justified by “fault injection by a failing PostHog layer, not a mock.”

(c) Implemented but wrong / fragile

Spec: “the interface must allow a Redis-backed layer later with no consumer change” and per-call window. In-memory pruneFromFront (packages/limits/src/Limits.ts) assumes Map insertion order == expiry order. That holds only when every window length is equal (today’s Fastify callers all pass "1 minute"). Mixed windows can leave expired keys occupying the 10k cap until pruneAll. The Limits tests themselves already mix "1 second" and "1 minute" on one store.

Related weakening, not in the ticket’s wording but in “today’s semantics”: the old config rejected a non-http(s) PATCHY_POSTHOG_HOST at startup (httpUrlValue). PostHogClient.host is now Config.string with a default, so a typo host no longer fails Layer.orDie.

Implementation method

Sound, with one leftover cleverness in Limits that is heavier than a 10k in-memory store needs.

Splitting Analytics from PostHogClient is the old AnalyticsClient adapter, not a second analytics. Analytics owns domain policy (closed event names, instance distinct id, $process_person_profile: false, never-fail track, 3s finalizer). PostHogClient owns the SDK. Collapse the client and you cannot test never-fail / flush without mocking posthog-node. Keep it.

The ManagedRuntime seam is the right size: one runtime in start.ts, two adapters, marked for deletion when Fastify goes. runFork for track is the correct reading of “fire-and-forget”; Layer.orDie failing startup on a missing-but-malformed key is better than a silent no-op. testing.ts reconstructing Clock member-by-member is bulky and is the cost of Fastify still owning a mutable now for db/storage.

Limits.consume({ key, limit, window }) plus consumer-prefixed keys is the RateLimiter shape the ticket asked for. Four independent 10k maps were 4× flood capacity; one store is the honest memory bound. Dropping the doubly-linked expiration list is the real simplification — don’t bring it back. What to do instead: at this cap, scan expired entries. pruneFromFront as a queue is the part that overclaims.

Config selection is clean: Config.option(apiKey) → layerNoop vs layerPostHog + PostHogClient.layer. Capability owns PATCHY_POSTHOG_*; @patchy/config is out. Default is off.

Do not merge PostHog into Analytics. Do not add Redis until a replica exists.

YAGNI

Cut it. The insertion-order prune in packages/limits/src/Limits.ts (pruneFromFront + pruneAll + “hot path never walks live windows”) is performance theatre at 10k keys. Mixed windows already break “expire from the front.” Smallest model: expire the current key; full scan only at the cap. The file-level essay on Analytics restates CONTEXT.md — keep “track never fails” and “no visit events”; the restatement is optional.

Keep it. Redis-later is the good kind: one consume shape, no unused port, generic, or Redis type. PostHogClient as Context.Service is how this repo injects faults (broken / hanging layers). Seam wrappers are not casts (runFork vs runPromise). PATCHY_POSTHOG_HOST is live, not orphaned. Package tests vs server tests are two layers, not two harnesses.

Beautiful. Default-off in one expression:

export const layer = Layer.unwrap(
  Effect.map(Config.option(PostHogClient.apiKey), (key) =>
    Option.isNone(key) ? layerNoop : layerPostHog.pipe(Layer.provide(PostHogClient.layer))
  )
);

Closed event names, consumer-prefixed keys, shutdown TestClock 2999 millis then 1 millis. This is tagged services and unions, not wrapper-shaped TypeScript.

Verdict: mostly-lean, with the Map-as-queue prune the one thing that isn’t.


Standards: 1 hard finding, 2 judgement calls; worst is the namespace import in Limits.test.ts.
Spec: Done-when met; 1 semantic delta (shared 10k cap) and 1 fragile prune; worst is pruneFromFront vs mixed windows.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Went through the review. Pushed the follow-ups as one commit.

Fixed

  • Limits.test.ts imports the service module as a namespace (Limits.layer, Limits.Limits). Real finding, per the conventions spec.
  • pruneFromFront is gone. It assumed Map insertion order equals expiry order, which only holds when every window is the same length, and the store now takes a per-call window. New model is the smallest one: a key's own expired window is replaced on the spot; the whole store is scanned only when it is full (10k entries, cheap and rare). No queue, no linked list.
  • Bucket renamed to Window, matching the glossary's own Avoid entry.
  • PATCHY_POSTHOG_HOST must be an http(s) URL again (Config.schema with a string check), so a typo fails startup through Layer.orDie instead of every event quietly going nowhere. That restored a piece of today's semantics the port had dropped; covered by a test and the self-hosting guide says so again.

Not changing, with reasons

  • Shared 10k cap across the four limits: intended. The issue asks for the RateLimiter.consume shape (one store, per-call limit and window), and one store is the honest memory bound; four independent 10k maps were 4x flood capacity by accident, not design. Disclosed in the PR body and in packages/limits/CONTEXT.md.
  • 3 s flush living on Analytics.make rather than PostHogClient: deliberate. Keeping the bound above the client is what lets a substituted hanging PostHogClient layer exercise it under TestClock; the CONTEXT wording ("the PostHog layer's finalizer") describes layerPostHog, which is the Analytics layer.
  • PostHogClient as its own service, closed AnalyticsEventName union, the runFork vs runPromise split in the seam: the review itself concluded these are correct; leaving them.
  • The module comment at the top of Analytics.ts: it is the moved-over invariant text from the old module, kept per "preserve useful comments while moving code". Happy to trim if you would rather the CONTEXT be the only copy.

pnpm lint, pnpm typecheck, pnpm format:check and the full pnpm test (454) are green on the new head. Ready to merge once #83 lands.

Base automatically changed from feat/sql-package to main August 29, 2026 22:59
Analytics and the fixed-window rate limiter were modules in apps/server with
two consumers each once auth and patches exist, so they port first.

packages/analytics: the Analytics service (track never fails), a PostHog
layer over a PostHogClient service whose finalizer flushes and gives up
after 3 s, a no-op layer, and a layer that picks by PATCHY_POSTHOG_API_KEY
read as a Redacted Config. packages/limits: the Limits service mirroring
RateLimiter.consume (key, limit, window per call; remaining and a
Retry-After back), in memory, failing closed at 10k tracked keys.

The Fastify app consumes both through one ManagedRuntime built in start.ts;
the old modules, their tests and the posthog fields in @patchy/config are
gone. CONTEXT.md for each package; language-service rules at error.
Limits: drop the insertion-order prune, which only held when every window
was the same length; a key's own expired window is replaced on the spot and
the store is scanned end to end only when it is full. Rename Bucket to
Window to match the glossary; the test imports the service module as a
namespace.

Analytics: PATCHY_POSTHOG_HOST must again be an http(s) URL, failing
startup on a typo as the old config did.
@allisonmahmood
allisonmahmood merged commit 4b507f0 into main Aug 29, 2026
7 checks passed
@allisonmahmood
allisonmahmood deleted the feat/analytics-limits branch August 29, 2026 23:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci CI, shared testing infrastructure, development scripts and tooling area:docs Touches the docs area area:server Touches the server area size:l 501-1,000 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(server): analytics and limits as Effect service packages

1 participant