[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,91 +2,169 @@
|
||||
id: wiki-2026-0508-effect-ts
|
||||
title: Effect TS
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-C7A07F]
|
||||
aliases: [Effect, Effect-TS, effect.ts]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
verification_status: applied
|
||||
tags: [typescript, functional-programming, effect, error-handling]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - Effect TS"
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: TypeScript
|
||||
framework: Effect
|
||||
---
|
||||
|
||||
# [[Effect TS]]
|
||||
# Effect TS
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> Effect TS는 타입이 풍부한(type-rich) TypeScript 애플리케이션을 구축하기 위해 널리 사용되는 인기 있는 프레임워크입니다 [1]. 이 프레임워크는 주로 구조적으로 동일해 보이는 타입들을 명확히 구분하기 위한 브랜디드 타입(Branded Types) 유틸리티를 제공합니다 [1, 2]. 또한, 예상되는 에러와 예상치 못한 에러를 구분하거나 `_tag` 속성을 통해 메타데이터를 관리하는 등 타입 시스템을 활용한 다양한 패턴의 기반을 제공합니다 [3, 4].
|
||||
## 매 한 줄
|
||||
> **"매 TypeScript 의 functional effect system — error · concurrency · resource 매 type-level encoding"**. 매 ZIO (Scala) inspired library 의 TS port. 2026 시점 v3.x stable, Discord · Vercel · Stripe internal services 가 production 채택.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **브랜디드 타입(Branded Types) 도구 제공**: Effect TS는 TypeScript 커뮤니티에서 널리 쓰이는 대표적인 브랜디드 타입 라이브러리 중 하나입니다 [2]. 타입 내에서 브랜드 역할을 하는 제네릭 타입인 `Brand.Brand`와 타입 브랜드 식별 함수를 반환하는 제네릭 함수 `Brand.nominal`을 제공하여 사용자가 브랜디드 타입을 쉽게 생성할 수 있도록 지원합니다 [1].
|
||||
* **정교한 타입 브랜드 단언 함수(`Brand.refined`)**: Effect TS는 제약 조건을 검증하기 위해 `Brand.refined`라는 함수를 별도로 제공합니다 [1, 5]. 이 함수는 값이 제약 조건을 충족하는지 확인하는 함수와, 제약 조건과 일치하지 않을 경우 에러를 던지는 함수라는 두 가지 매개변수를 활용하여 안전한 타입 단언(assertion)을 수행합니다 [5].
|
||||
* **에러 처리 및 메타데이터 컨벤션 모델링**: Effect TS는 시스템의 '예상되는 에러(Expected Errors)'와 '예상치 못한 에러(Defects)'를 명확히 구분하는 아키텍처적 접근법을 제시합니다 [3]. 이와 더불어 내부 로직이나 디버깅, 관측 도구에서 사용되는 데이터를 다른 응답 객체와 시각적으로 구분하기 위해 `_tag`와 같은 속성(메타데이터)을 사용하는 훌륭한 컨벤션을 제공합니다 [4, 6].
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
|
||||
### 매 Effect<A, E, R>
|
||||
- `A`: success value type
|
||||
- `E`: error type (typed errors, no exceptions)
|
||||
- `R`: required services (DI context)
|
||||
- 매 lazy description — execution은 `Effect.runPromise` 시점.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** Branded Types, TypeScript
|
||||
- **Projects/Contexts:** Type-rich TypeScript Applications
|
||||
- **Contradictions/Notes:** 소스에 관련 정보가 부족합니다.
|
||||
### 매 핵심 primitives
|
||||
- `Effect.succeed` / `Effect.fail` / `Effect.sync` / `Effect.tryPromise`
|
||||
- `Effect.gen` (generator-based do-notation)
|
||||
- `Effect.all` (parallel), `Effect.forEach` (concurrency control)
|
||||
- `Layer` (DI composition), `Context.Tag` (service identity)
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-18*
|
||||
### 매 응용
|
||||
1. API gateway error contracts (`HttpClient` typed errors).
|
||||
2. Database transactional pipelines (`Effect.scoped` + `Layer`).
|
||||
3. Streaming ETL (`Stream` module).
|
||||
|
||||
---
|
||||
## 💻 패턴
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### Effect.gen do-notation
|
||||
```ts
|
||||
import { Effect } from "effect"
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
const getUser = (id: string) =>
|
||||
Effect.gen(function* () {
|
||||
const db = yield* DatabaseService
|
||||
const user = yield* db.findUser(id)
|
||||
if (!user) return yield* Effect.fail(new UserNotFound({ id }))
|
||||
return user
|
||||
})
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Typed errors (Data.TaggedError)
|
||||
```ts
|
||||
import { Data } from "effect"
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
class UserNotFound extends Data.TaggedError("UserNotFound")<{
|
||||
id: string
|
||||
}> {}
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
class DbConnectionError extends Data.TaggedError("DbConnectionError")<{
|
||||
cause: unknown
|
||||
}> {}
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Layer composition
|
||||
```ts
|
||||
import { Effect, Layer, Context } from "effect"
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
class DatabaseService extends Context.Tag("DatabaseService")<
|
||||
DatabaseService,
|
||||
{ findUser: (id: string) => Effect.Effect<User | null, DbConnectionError> }
|
||||
>() {}
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
const DatabaseLive = Layer.succeed(DatabaseService, {
|
||||
findUser: (id) =>
|
||||
Effect.tryPromise({
|
||||
try: () => pgClient.query("SELECT * FROM users WHERE id=$1", [id]),
|
||||
catch: (cause) => new DbConnectionError({ cause }),
|
||||
}),
|
||||
})
|
||||
```
|
||||
|
||||
### Concurrent execution
|
||||
```ts
|
||||
const fetchAll = Effect.forEach(
|
||||
["a", "b", "c"],
|
||||
(id) => getUser(id),
|
||||
{ concurrency: 5 }
|
||||
)
|
||||
```
|
||||
|
||||
### Retry + timeout
|
||||
```ts
|
||||
import { Schedule, Duration } from "effect"
|
||||
|
||||
const robust = getUser("123").pipe(
|
||||
Effect.retry(Schedule.exponential(Duration.millis(100)).pipe(
|
||||
Schedule.compose(Schedule.recurs(3))
|
||||
)),
|
||||
Effect.timeout(Duration.seconds(5))
|
||||
)
|
||||
```
|
||||
|
||||
### Resource scoping
|
||||
```ts
|
||||
const program = Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const file = yield* Effect.acquireRelease(
|
||||
openFile("data.txt"),
|
||||
(f) => closeFile(f)
|
||||
)
|
||||
return yield* readContent(file)
|
||||
})
|
||||
)
|
||||
```
|
||||
|
||||
### Schema validation
|
||||
```ts
|
||||
import { Schema } from "effect"
|
||||
|
||||
const User = Schema.Struct({
|
||||
id: Schema.String,
|
||||
age: Schema.Number.pipe(Schema.int(), Schema.nonNegative()),
|
||||
})
|
||||
|
||||
const parse = Schema.decodeUnknown(User)
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 단순 CRUD app | plain async/await + zod |
|
||||
| 복잡한 error taxonomy | Effect (typed errors) |
|
||||
| Concurrency-heavy pipeline | Effect (Schedule + Stream) |
|
||||
| Team unfamiliar with FP | neverthrow / fp-ts 시작 |
|
||||
|
||||
**기본값**: greenfield TS backend with complex error contracts → Effect 채택. 매 learning curve 높음 — team buy-in 매 우선.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Functional Programming]] · [[TypeScript 타입 시스템 및 인터페이스 설계]]
|
||||
- 변형: [[Result Type]] · [[neverthrow]]
|
||||
- 응용: [[견고한 도메인 모델 및 API 계약 설계]] · [[API 응답 및 에러 핸들링 아키텍처]]
|
||||
- Adjacent: [[Zod 런타임 유효성 검사 통합]] · [[ts-brand]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: TS backend with strict error typing, dependency injection at type level, retry/circuit-breaker policies.
|
||||
**언제 X**: 매 simple script · prototype · React component logic — overhead 매 큼.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Effect.runSync everywhere**: 매 sync execution 강제 — async benefit 상실.
|
||||
- **Fail with strings**: typed `TaggedError` 의 사용해야 매 discriminated handling 가능.
|
||||
- **Layer.merge spaghetti**: 매 dependency graph 의 명시적 organize.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (effect.website official docs · Effect 3.x release notes 2025).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Effect 3.x patterns, Layer/Schema/typed errors |
|
||||
|
||||
Reference in New Issue
Block a user