Skip to content

Effect idioms audit: adopt Effect v4 patterns across effect-jsonapi #649

Open

Description

@thomasfosterau

1. Goal

Go beyond call-site lint fixes: look at what Effect can do for effect-jsonapi as a whole (data modelling, errors, services and layers, resources, concurrency, streams, platform, observability, testing) and adopt it, including public API changes where they're worth it.

2. Scope and constraints

  • docs/CONTRIBUTING.md § Effect: Effect v4 idioms and modules throughout; exceptions are non-Effect APIs adapted at the edge and hot paths where measured performance needs plain code. Absence is Option; JSON:API wire shapes keep their native optionals and null, spelled from their schemas. Exports are one PascalCase module per file, re-exported as a namespace.
  • docs/architecture.md: every module derives from one resource definition; a new query family goes in both the flat and the nested struct in Query.schema.
  • The JSON:API v1.1 wire format and the documented filter grammar (docs/filter-grammar.md, e.g. F-NULL-1) must not change without an explicit decision.
  • vp run docgen executes every @example against dist/: changed APIs need complete, runnable examples.
  • Public API changes are allowed. Each needs a changeset; pre-1.0 a breaking change is a minor, never major, with migration notes in the changeset text (and in the consumer migration guide, Migration guide: 0.21 → 0.22 (breaking changes for website, gardeneria, preferenceflow, in-the-dark) #620, when the consuming apps are affected).
  • Lint-level issues listed in §6 are handled separately.

3. Effect version

Catalog and installed: effect@4.1.4 (@effect/vitest 4.1.4), matching the catalogue; the published peer floor is ^4.1.0, so anything adopted must exist in 4.1.0 or the floor rises (a breaking change, checked by typecheck:floor).

v3 → v4 traps that matter here:

  • Non-core modules are plain subpaths (effect/http, effect/http-api, effect/sql, effect/cli, effect/process, effect/encoding, effect/crypto, effect/persistence, effect/testing, …), not effect/unstable/*; every one is @stability unstable, as are some core exports (check the JSDoc @stability before calling one settled).
  • Not present in v4: Either (→ Result), Context.Tag / Effect.Service (→ Context.Service), Effect.catchAll (→ catch), catchAllCause (→ catchCause), catchSome (→ catchFilter), Effect.either (→ result), Effect.fork / forkDaemon (→ forkChild / forkDetach), Effect.async (→ callback), Schema.decodeUnknown (→ decodeUnknownEffect), FiberRef / Effect.locally (→ References.* / provideService), Runtime<R> (→ ManagedRuntime / runForkWith), effect/FastCheck (→ Effect's own Arbitrary), TestClock in core (→ effect/testing).
  • Semantics: Option and Result are no longer Effects (Effect.fromOption / fromResult); layers are memoised across Effect.provide calls (Layer.fresh or { local: true } to opt out); Context.Service has no auto-generated Default layer; defects take precedence over typed errors in mixed causes; Equal.equals is structural by default (Equal.byReference opts out); forked fibers keep the process alive.
  • Sources for every rename: Effect-TS/effect main MIGRATION.md and migration/*.md, effect.website /docs/v4/**, and the installed node_modules/effect (AGENTS.md, ai-docs/, dist/*.d.ts).

4. Candidates found in this repository

A starting point, not the full audit. Format: site → current shape → pattern → benefit → API impact.

Errors

  • src/Lid.ts:63 UnknownLidError extends Error, thrown from resolveRef (:212) → a Schema.TaggedError and a Result- or Effect-returning resolver, so Atomic handlers recover with catchTag rather than instanceof in Effect.try. Benefit: typed channel, serialisable. API: yes.
  • src/internal/filter.ts:78-97, 684, 736 throw InvalidFilter from the literal encoder and operator check → Result-returning encoders. Benefit: no exceptions as control flow inside encoding. API: no (internal).
  • src/Registry.ts:205, 213 checkFamily throws UnknownFamily / FamilyMismatch → decide: a Result-returning check (typed) or a documented construction-time defect. API: maybe.
  • src/internal/conformance/semantics.ts:127, 156 throw DomainMismatch → Result. API: no.
  • orDie / die audit: Assemble.ts:1347, Idempotency.ts:511 (digest), Idempotency.ts:876 (request.text body read: an I/O failure, maybe a 400 rather than a defect), Middleware.ts:1234, 1276, ServerErrors.ts:559, 631, internal/conformance/core.ts:1093, 1278, 1321. API: maybe.
  • src/Client.ts:477-478 and src/Registry.ts:59, 345 type effects as Effect<unknown, unknown, unknown> → precise error unions where the shape is known. API: maybe.

Services, layers and storage

  • src/Idempotency.ts:680 Store is a plain interface passed to layer(store) (:866); memoryStore() (:721) keeps entries in a MutableHashMap with no expiry → a Context.Service Store with layerMemory on SynchronizedRef (atomic claim) and a TTL read through Clock; optionally a KeyValueStore-backed layer (effect/persistence, unstable) via toSchemaStore. Benefit: atomic claim/record, expiry, swappable stores without threading values. API: yes.
  • src/Lid.ts:205-219 make() returns a mutable map closed over a MutableHashMap: keep (synchronous, per request) unless the resolver becomes effectful. API: no.

Effect.fn and tracing

  • 7 Effect.fn / 6 Effect.fnUntraced sites against roughly 60 (x) => Effect.gen(...) wrappers, concentrated in src/internal/conformance/spec.ts (26), profile.ts (11), relationships.ts (7), sort.ts (5), pagination.ts (4), plus Handlers.ts (2) and Atomic.ts (2) → Effect.fn("Conformance.rule") etc. Benefit: spans per rule and handler. API: no.

Concurrency and batching

  • src/Handlers.ts:1147-1166 builds include batches by type by hand, then Effect.forEach(batches, load, { concurrency }); src/ResourceHandlers.ts:949-1048 loadRefs with a hard-coded concurrency of 6 → Request + RequestResolver.makeGrouped (grouped by type) with Effect.request and a per-request cache. Benefit: dedupe and batching across the whole include tree, not per level. API: maybe (loader signature).
  • Module-level WeakMap memo caches keyed by schema identity (ApiError.ts:239, Resource.ts:2756, 2817, internal/sparse.ts:171, Middleware.ts:1025, internal/wireNames.ts:206): hand-written get/set memoisation on the hot path → Function.memoize (a private WeakMap by object identity, same cost) where the key is the single argument; keep the rest, recorded with the reason. API: no.

Data modelling

  • src/internal/wireNames.ts:71 runs a decode with Effect.runSyncExitWith(noServices) → Schema.decodeUnknownExit / decodeUnknownResult, with no runtime call in library code. API: no.

Streams

  • src/Client.ts:1465-1538 offers page-window arithmetic but no paginated fetch → an additive Client helper on Stream.paginate that follows links.next. API: yes (additive).

Style

  • Tacit src/internal/json.ts:35 (flow() and src/internal/conformance/profile.ts:490 (Effect.map(Arr.of)) → explicit lambdas. API: no.

Observability

  • src/ServerErrors.ts:639 logs an unhandled defect with a bracketed string prefix → Effect.annotateLogs + Cause.pretty, and consider an ErrorReporter hook (unstable) so applications can route defects to their tracker. API: maybe (additive).

5. Full checklist

1. Data modelling

  • Schema.Class / TaggedClass / Struct / TaggedStruct for every type that crosses a boundary (replaces an interface plus a hand validator)
  • Decode at the boundary: Schema.decodeUnknownEffect / decodeUnknownResult / decodeUnknownOption, decodeUnknownSync only at edges (replaces JSON.parse(x) as T, as casts, isFoo guards)
  • Transformations: Schema.decodeTo + SchemaGetter; built-ins NumberFromString, DateTimeUtcFromString, fromJsonString, URLFromString, Uint8ArrayFromBase64, OptionFromNullOr / OptionFromOptionalKey (replaces parseInt, new Date(str), null/undefined shuffles)
  • Unions: Schema.Union, TaggedUnion, toTaggedUnion(tag), Literals, Enum (replaces string unions duplicated as arrays)
  • Checks: .check(Schema.isMinLength, isPattern, isInt, isBetween, …), Schema.makeFilter, Schema.refine (replaces scattered if (…) throw)
  • Brands: Schema.brand, Brand.nominal / Brand.check, Schema.fromBrand (replaces bare string ids and hand-rolled __brand casts)
  • Defaults: withConstructorDefault, withDecodingDefault(Key), optionalKey vs optional (replaces ?? default in every consumer)
  • Derivation: toJsonSchemaDocument, toStandardSchemaV1, Arbitrary.schema, toEquivalence, toFormatter, toCodecJson, toDifferJsonPatch, toIso (replaces a second representation kept by hand)
  • Built-in schemas (NonEmptyString, Trimmed, Int, Natural, Port, Redacted, DateTimeUtc, Duration, BigDecimal, Json, DomainName, SemVer, TimeZone, Uint8Array, Defect()) over re-declared regexes
  • Data.TaggedEnum + Data.taggedEnum<T>() ($is, $match), Data.TaggedClass for internal ADTs (replaces { kind } unions + switch)
  • Equal.equals / Hash / Equal.byReference (replaces JSON.stringify equality, hand deep-equal; v4 is structural by default)
  • Option for public absence (fromNullishOr, getOrElse, match, liftThrowable) (replaces T | null | undefined returns; wire and framework edges keep native nulls)
  • Result for pure synchronous fallible code (replaces Either, hand-rolled { ok } objects, throwing parsers)
  • Struct.pick / omit / evolve / renameKeys, Tuple (replaces spread-and-delete)

2. Errors

  • Schema.TaggedError<Self>()(tag, { …, cause: Schema.Defect() }) for expected failures, Data.TaggedError for in-process-only ones (replaces throw new Error, extends Error, string codes, Effect.fail("…"))
  • Reason errors: one tagged error with a tagged reason; Effect.catchReason / catchReasons / unwrapReason (replaces an exploding error union)
  • Effect.catchTag / catchTags / catch / catchIf / catchFilter / mapError / tapErrorTag / Effect.result / Effect.option (replaces _tag checks and instanceof)
  • Errors vs defects: audit every orDie / Effect.die; die only on the proven-impossible; catchDefect only at edges (v4: defects win in mixed causes)
  • Cause.pretty / squash / findError / hasInterruptsOnly, Exit.match at reporting edges (replaces String(err))
  • Effect.try / Effect.tryPromise({ try: (signal) => … }) / Effect.callback / Effect.promise, once per non-Effect API (replaces try/catch in generators and new Promise)
  • Retries: Effect.retry(Schedule.exponential(…).pipe(Schedule.jittered, Schedule.upTo(…))), Effect.retry({ times, while }), HttpClient.retryTransient (replaces loops with sleeps)
  • ExecutionPlan.make + Effect.withExecutionPlan (unstable) for fallback providers
  • ErrorReporter + Effect.withErrorReporting (unstable) for error tracking hooks

3. Services and layers

  • class X extends Context.Service<X, Shape>()("pkg/X") { static readonly layer = Layer.effect(X, …) }; v4 has no auto-generated Default layer (replaces singletons, Context.Tag / GenericTag, factories passed by hand)
  • Resolve dependencies when the layer is built, so methods have R = never
  • Context.Reference<T>(id, { defaultValue }) for settings with a default (replaces module let toggles)
  • Composition: Layer.provide / provideMerge / mergeAll / unwrap / effectDiscard / fresh / launch, LayerMap.Service (unstable); v4 memoises layers across Effect.provide
  • Test doubles: Layer.mock, layerTest / layerMemory siblings (replaces vi.mock)
  • Effect.fn("Mod.fn") for reusable effectful functions, Effect.fnUntraced for hot internals (replaces (x) => Effect.gen(…))
  • Scopes: Effect.acquireRelease / acquireUseRelease / addFinalizer / scoped / ensuring / onExit / acquireDisposable (replaces try/finally)
  • RcMap, RcRef, ScopedRef, Resource, LayerRef for shared, lazily created resources
  • Edges: ManagedRuntime, NodeRuntime.runMain, FiberSet.makeRuntimePromise, Effect.runForkWith; Effect.run* in one edge file (replaces runPromise(… Effect.provide(layer)) per call)

5. Concurrency and resources

  • Effect.all / Effect.forEach with explicit concurrency, discard, mode: "result"; Effect.partition / validate (replaces Promise.all / allSettled)
  • Fibers: forkChild / forkScoped / forkDetach / forkIn, FiberSet / FiberMap / FiberHandle (replaces void promise, setInterval jobs)
  • Semaphore, PartitionedSemaphore, Latch (replaces "isRunning" flags, p-limit)
  • Queue, PubSub, Deferred (replaces EventEmitter, resolve-later promises)
  • Ref, SynchronizedRef, SubscriptionRef, Effect.tx + TxRef (replaces mutable closures and module-level Map state)
  • Pool.make / makeWithTTL (replaces hand-rolled pools)
  • Cache.make, ScopedCache, Effect.cached / cachedWithTTL, PersistedCache (replaces Map memos with manual expiry)
  • Request + RequestResolver.make / makeGrouped / batchN / withCache, Effect.request (replaces N+1 loops and hand batching)
  • Effect.timeout / timeoutOption / timeoutOrElse / race / raceFirst, Effect.abortSignal (replaces Promise.race, AbortController plumbing)
  • RateLimiter / CircuitBreaker (effect/persistence, unstable), HttpClient.withRateLimiter

6. Streams

  • Sources: Stream.fromIterable / fromAsyncIterable / fromReadableStream / fromEventListener / callback / paginate / fromQueue / fromPubSub
  • Operators: mapEffect(f, { concurrency }), grouped, groupedWithin, rechunk, buffer, throttle, debounce, splitLines, decodeText / encodeText, retry, timeout, haltWhen
  • Sinks and running: Sink.fold / forEach / collect, runCollect / runForEach / runDrain / toReadableStream / toAsyncIterable
  • Codecs: Stream.pipeThroughChannel with effect/encoding Ndjson / Sse / Csv / SchemaBinary (unstable)
  • Replace for await / getReader() loops and manual batching with setTimeout flushes

8. Platform

  • HTTP client (effect/http): HttpClient, FetchHttpClient.layer, HttpClientRequest.*, filterStatusOk, retryTransient, HttpClientResponse.schemaJson / matchStatus (replaces fetch)
  • HTTP server: HttpRouter, HttpServerResponse, HttpMiddleware; effect/http-api (HttpApi*, HttpApiClient, OpenApi, HttpApiTest)
  • FS/OS: FileSystem, Path, effect/process ChildProcess + ChildProcessSpawner, NodeServices.layer (replaces node:fs, node:path, child_process)
  • Storage: effect/persistence KeyValueStore (layerMemory, layerFileSystem, toSchemaStore), PersistedQueue (unstable)
  • Encoding/crypto (unstable): effect/encoding (Base64, Hex, Csv, Xml, Zip, …), effect/crypto (Digest, Mac, SecureRandom, …), effect/jose (replaces btoa, Buffer, hand-rolled hex, crypto.subtle)
  • Library code depends on abstract services; applications supply @effect/platform-node / -browser layers

9. Observability

  • Tracing: Effect.fn spans, Effect.withSpan, annotateCurrentSpan, Layer.withSpan, Effect.linkSpans
  • Logging: Effect.log*, annotateLogs, withLogSpan, Logger.*, References.MinimumLogLevel, Console (replaces console.*)
  • Metrics: Metric.counter / gauge / histogram / summary / frequency / timer, Effect.track* (replaces counters in module variables)

10. Collections and utilities

  • Array (groupBy, partition, dedupe, sortBy, chunksOf, head, findFirst, filterMap, getSomes; makeBy / range never return empty) (replaces lodash, arr[0]!)
  • Record (map, filter, collect, get, toEntries), Struct, Tuple, Iterable
  • HashMap / HashSet / Chunk / MutableHashMap / Trie / HashRing where structural keys or persistence matter (native Map is fine otherwise)
  • Match.type / Match.value with tag, tags(Exhaustive), exhaustive, discriminatorsExhaustive; $match (replaces non-exhaustive switch)
  • Predicate (isString, isObject, hasProperty, isTagged, isNotNullish, and / or / not) (replaces own isRecord helpers)
  • Order (mapInput, Struct, combine, flip) and Equivalence (replaces (a, b) => a.x - b.x); BigDecimal, ByteSize, SemVer, JsonPointer, JsonPatch, TextDiff, Glob, Str case helpers
  • Function.dual + Pipeable for exported helpers (additive API)
  • Optic (Lens, Prism, Iso, Schema.toIso) for deep immutable updates

11. Testing

  • @effect/vitest: it.effect / it.live / it.effect.each / it.effect.prop / it.layer / layer(L) / it.flakyTest (replaces Effect.runPromise inside it)
  • TestClock / TestConsole from effect/testing (replaces vi.useFakeTimers, real sleeps)
  • Arbitrary.schema(S) for property tests (effect/FastCheck is gone from v4)
  • In-memory layers and HttpApiTest / RpcTest instead of vi.mock

12. Newer modules (all @stability unstable)

  • effect/http / effect/http-api (in use): check new helpers (HttpApiTest, HttpClient.retryTransient in the conformance runner) against the hand-written equivalents
  • effect/persistence KeyValueStore / PersistedCache for the idempotency store
  • effect/crypto Digest + effect/encoding Hex (tracked in Use effect/crypto Digest and Record helpers instead of hand-rolled code #646)
  • Not applicable: effect/sql, effect/rpc, effect/ai, effect/cli, effect/cluster, effect/workflow, effect/reactivity (a library over HttpApi; storage stays behind seams).

Dropped as not applicable: §4 Configuration (the library takes explicit options and reads no environment; a layerConfig is only worth it if a consumer asks) and §7 Time (no clock reads today; requestTimeout already uses Duration; the idempotency TTL above is the one new time use).

Anti-patterns to grep for (pattern → replacement; run against src/ excluding comments and @example blocks):

async function / await / .then( inside Effect code      → Effect.gen / Effect.fn; Effect.tryPromise at the edge
try { … } catch around yield* or Effect.run*            → Effect.try / catchTag / catch; Exit/Cause at edges
\bthrow new\b in src/ (library code)                    → Schema.TaggedError + return yield* / Effect.fail; Effect.die for bugs
class \w+Error extends Error                            → Schema.TaggedError / Data.TaggedError
Effect.fail\("|Effect.fail\(new Error                   → tagged error with fields
: .*\| null\b|return null;|return undefined;           → Option (keep at wire/framework edges)
\bas [A-Z]\w*\b after JSON.parse / .json() / decode     → Schema.decodeUnknown*
JSON.parse\(                                            → Schema.fromJsonString(S) / decodeUnknownEffect
for (.*retry|attempt) / while.*attempt / 2 \*\* attempt → Effect.retry(Schedule…) / HttpClient.retryTransient
setTimeout|setInterval|new Promise\(\s*\(?res          → Effect.sleep / Schedule / Effect.callback / Deferred
Date\.now\(\)|new Date\(\)|Math\.random\(\)             → Clock / DateTime.now / Random (crypto: SecureRandom)
Promise\.all\(|Promise\.allSettled\(                    → Effect.all / forEach with { concurrency }
Promise\.race\(                                         → Effect.timeout / Effect.race
process\.env\.|import\.meta\.env                        → Config + ConfigProvider (fromEnv / fromEnvRecord)
apiKey: string|token: string|password: string           → Redacted
^let \w+ = |^const \w+ = new (Map|Set)\( at module top  → Ref / service state / Cache (and "sideEffects": false)
export const \w+ = new \w+Client\(                      → Context.Service + Layer
functions taking (deps, …) / ctx: { db, http }          → yield* Service in layer construction
Effect.runPromise|runSync|runFork outside one edge file → ManagedRuntime / NodeRuntime.runMain / it.effect
=> Effect.gen\(function\*                               → Effect.fn("name") / fnUntraced
Effect\.(map|flatMap|tap)\(\w+\)  / flow\(               → explicit lambdas (avoid tacit style)
yield\* Option\.|yield\* Result\. in Effect.gen          → Effect.fromOption / Effect.fromResult (v4: no longer Effects)
repeated Effect.provide(layer) per call                  → compose once; layers memoise across provides
catchAll|catchAllCause|either\(|fork\(|forkDaemon|Effect\.Tag|Effect\.Service|Context\.Tag|GenericTag|FiberRef|Effect\.locally|Either\.  → v4 names
\.orDie\b / Effect\.orDie in library modules            → keep typed errors; die only on proven-impossible
switch \((\w+)\.(_tag|type|kind)\)                       → Match.tags(Exhaustive) / $match / Match.exhaustive
typeof \w+ === "(string|object)"|isRecord|isObject\(    → Predicate / Schema
fetch\(|axios                                           → HttpClient + HttpClientResponse.schemaJson
node:fs|node:path|child_process in library src          → FileSystem / Path / effect/process
btoa|atob|Buffer\.from\(.*(base64|hex)                  → effect/encoding Base64 / Hex
console\.(log|error|warn)                               → Effect.log* / Logger
\bany\b in error position / Effect<.*, unknown          → precise tagged unions
for await \(|\.getReader\(\)                            → Stream.fromAsyncIterable / fromReadableStream
lodash|ramda|date-fns|dayjs|p-limit|p-retry|lru-cache   → Array/Record/Order, DateTime, Semaphore, Schedule, Cache

6. Related issues

Covered separately (don't duplicate here):

7. Instructions for the assigned session

  • Audit every module against §5, not only the candidates in §4. Record each finding in the PR description as adopt, defer or reject, with a one-line reason.
  • Read the installed node_modules/effect (AGENTS.md, ai-docs/, .d.ts) and the effect.website v4 docs / Effect-TS/effect main (MIGRATION.md, migration/*.md) rather than guessing APIs. Effect-TS/effect-smol is archived; ignore it.
  • Make the changes in one PR (the repository's one-PR-per-change rule), in reviewable commits by area. Keep behaviour unless a change is an intended improvement, and call each one out in the PR.
  • Benchmark before and after any hot path touched (no bench task exists: measure with a focused script and report the numbers in the PR).
  • Run the full gates (vp run ci, vp run docgen) and the pre-commit Fallow audit; say in the PR body which couldn't run.
  • Update docs/CONTRIBUTING.md and AGENTS.md (and package AGENTS.md files) if a convention changes, e.g. a new service or error pattern becomes the house style.
  • File follow-up issues for anything deferred.

8. Acceptance criteria

  • Every §5 checklist item is marked adopted, not applicable, or deferred (with a follow-up issue)
  • vp run ci and the repository's other gates are green; any that couldn't run are named in the PR body
  • Changesets present for every published-package change, at the right level, with migration notes
  • No new lint allowances (no new warn entries, scoped overrides or inline disables without a recorded reason)

Generated by Claude Code

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions