zio-reference
Use when writing ZIO Scala code — implementing services with ZLayer, handling typed errors vs defects, choosing concurrency primitives (Ref, Queue, Hub, STM, Semaphore), avoiding anti-patterns like blocking on ZIO threads, unsafe resource handling with ensuring, or overusing Task for business logic
- License 许可
- MIT
- 最近更新
- 2026-11-14
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- zio-reference
- license
- MIT
- description
- Use when writing ZIO Scala code — implementing services with ZLayer, handling typed errors vs defects, choosing concurrency primitives (Ref, Queue, Hub, STM, Semaphore), avoiding anti-patterns like blocking on ZIO threads, unsafe resource handling with ensuring, or overusing Task for business logic
- compatibility
- opencode,claude-code,copilot
02 资源文件 7
- 参考文档references/anti-patterns.md4.5 KB
- 参考文档references/concurrency-and-fiber.md3.2 KB
- 参考文档references/core-concepts.md2.2 KB
- 参考文档references/error-handling-deep-dive.md2.8 KB
- 参考文档references/idioms.md4.2 KB
- 参考文档references/minimal-working-patterns.md3.6 KB
- 参考文档references/when-to-use-what.md3.7 KB
03 SKILL.md 正文
ZIO Coding Reference
Core Concepts
- Typed Errors vs Defects:
Echannel = expected domain failures (compiler-checked). Defects = unexpected bugs captured inCause, not inE.
Deep dive: references/core-concepts.md
Coding Rules
Error Handling
Deep dive: references/error-handling-deep-dive.md
- Model domain errors as sealed trait ADTs:
sealed trait UserError; case class NotFound(id: UUID) extends UserError - Use
ZIO.fail(NotFound(id)), notZIO.fail(new Exception("not found")) orDieshifts unrecoverableThrowableto defect channel:ZIO.attempt(expr).orDierefineToOrDie[SpecificError]keeps one error type, defects the rest- Never swallow defects:
effect.tapDefect(c => ZIO.logErrorCause("Unexpected", c)), noteffect.catchAllDefect(_ => ZIO.unit) mapErrorunifies error hierarchies across layerscatchAllfor recovery,foldZIOto transform both paths- Low-level: broad errors (
IOException). High-level: refined domain ADTs or defects. - Use
Eitheronly when errors are unrelated, to avoid wideningEtoAny
Composition
- For-comprehensions for sequential composition:
for { user <- getUser(id); _ <- notify(user) } yield () *>(zipRight) /<*(zipLeft) when discarding one result:Console.printLine("Starting") *> runTask
Dependencies (Service Pattern)
- Trait defines interface (methods return
IO[E, A]withR = Any) - Case class implements trait, gets dependencies via constructor
- Companion object provides
ZLayer
Resources
- Always use
ZIO.acquireReleaseorZIO.acquireReleaseWithfor resource cleanup, neverensuring ZIO.scopedfor narrowest possible resource lifetime:ZIO.scoped { ZIO.acquireRelease(open)(r => ZIO.succeed(r.close())).flatMap(use) }
Concurrency
Deep dive: references/concurrency-and-fiber.md
- Prefer
foreachPar,zipPar,raceover manualfork/join - Always
joinorinterruptany manually forked fiber - Blocking I/O:
ZIO.attemptBlockingorZIO.attemptBlockingIO, neverZIO.attempt - Custom operators:
ZIO.uninterruptibleMask(restore => setup *> restore(task) *> cleanup) - Don't wrap monolithic loops in
ZIO.succeed: runtime can't interrupt inside them
Anti-Patterns (Never Do These)
Deep dive: references/anti-patterns.md
| Anti-Pattern | Correct |
|---|---|
Task[A] for business logic |
IO[DomainError, A] with sealed trait ADT |
val f = api(); ZIO.fromFuture(_ => f) |
ZIO.fromFuture(ec => api()(ec)) |
ZIO.succeed(while(true) { ... }) |
Recursive ZIO effect or .forever |
object Svc { def method(a: A): ZIO[Svc, E, B] = ZIO.serviceWithZIO(_.method(a)) } |
Call ZIO.serviceWithZIO[Svc](_.method(a)) directly at call sites |
Decision Guide: Which Abstraction?
Deep dive: references/when-to-use-what.md
| Need | Use | Not |
|---|---|---|
| Service wiring + lifecycle | ZLayer |
Manual instance passing |
| Single shared mutable state | Ref |
var, AtomicReference |
| Multi-variable atomic updates | STM / TRef |
Multiple Ref updates |
| Work distribution (one consumer per item) | Queue |
Hub |
| Broadcast (all consumers get every item) | Hub |
Queue |
| Retry with backoff / repeat on schedule | Schedule |
Manual recursion |
| One-shot synchronization between fibers | Promise |
Queue, Ref |
| Limit concurrent access | Semaphore |
Manual counting |
| Incremental / infinite data processing | ZStream |
ZIO returning List |
| Resource with finalization | Scope + acquireRelease |
ensuring |
| Low-level fiber control | Fiber + fork |
Default; prefer foreachPar/zipPar |
Key Patterns
More patterns: references/minimal-working-patterns.md | references/idioms.md
Service Pattern (Repository variant)
trait UserRepo { def findById(id: UUID): IO[RepoError, Option[User]] }
case class PostgresUserRepo(ds: DataSource) extends UserRepo {
def findById(id: UUID): IO[RepoError, Option[User]] =
ZIO.attemptBlocking(query(ds, id)).mapError(DbError(_))
}
object UserRepo {
val layer: ZLayer[DataSource, Nothing, UserRepo] = ZLayer.derive[PostgresUserRepo]
}
Background Worker
def startWorker(queue: Queue[Job]): ZIO[Any, Nothing, Fiber.Runtime[Nothing, Nothing]] =
queue.take.flatMap(job => process(job).ignoreLogged).forever.forkDaemon
Retry with Backoff
val policy = Schedule.exponential(1.second) && Schedule.recurs(5)
ZIO.attempt(unstableCall()).retry(policy)
Parallel with Limit
ZIO.foreachPar(urls)(fetch).withParallelism(10)
HTTP Route (ZIO HTTP)
val route: Route[UserRepo, Nothing] =
Method.GET / "users" / uuid("id") -> handler { (id: UUID, req: Request) =>
ZIO.serviceWithZIO[UserRepo](_.findById(id)).map {
case Some(user) => Response.json(user.toJson)
case None => Response.notFound
}.orDie
}
04 同仓库更多 Skills
wiki-builder
Create and maintain a local Markdown research wiki (sources with provenance, compiled concept/source pages, index, maintenance log) driven by a per-wiki config. Use when the user wants to start a wiki or knowledge base, ingest sources into one, or query and update it; use wiki-page-writer for a single code deep-dive page.
refactoring-guru
Diagnose a named code smell and apply the smallest behavior-preserving refactoring, with verification before and after and an explicit stop condition. Use for structural refactors (extract, move, consolidate, change ownership), not for feature or bug work; for readability cleanup of recent changes use code-simplification.
legacy-seams
When changing untested legacy code, pin the observed results with characterization tests and open the smallest seam that substitutes only the blocking dependency, separate from any later logic change. Use when a clock, random source, I/O, global, or hidden constructor blocks a test or a safe edit. Use test-driven-development for a new behavior or a bug, refactoring-guru for one named structural refactor after the seam exists, and code-refactoring-tech-debt to choose which legacy to replace.
idea-refine
Refine a raw idea into a one-page brief (problem statement, recommended direction, assumptions to validate, MVP scope, not-doing list) through divergent then convergent thinking. Use when an idea is still vague or you want options and a stress test before committing; use interview-me when the goal itself is unclear and spec-driven-development once the direction is chosen.
code-review-and-quality
Review rubric and approval standard for any change before merge, including code written by you, another agent, or a human: five axes (correctness, readability, architecture, security, performance), change sizing, structural remedies, severity labels, and feedback technique. Use to judge whether a change is fit to merge; use code-review to run a PR or diff review end to end.
code-perfection
Smell and style gate for code you write or change. Bans known code smells (long method, large class, primitive obsession, long parameter list, data clumps, duplicate code, dead code, feature envy, shotgun surgery, flag arguments, message chains) and enforces behavior-preserving structure. On Scala files, enforces worxbend style. Use while implementing, reviewing a diff for smells, or when a smell or style violation is suspected. Routine construction stays with code-complete. SOLID and DRY stay with clean-code-guard. One named structural refactor stays with refactoring-guru.