@dojocho/effect-ts 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DOJO.md +22 -0
- package/dojo.json +50 -0
- package/katas/001-hello-effect/SENSEI.md +72 -0
- package/katas/001-hello-effect/solution.test.ts +35 -0
- package/katas/001-hello-effect/solution.ts +16 -0
- package/katas/002-transform-with-map/SENSEI.md +72 -0
- package/katas/002-transform-with-map/solution.test.ts +33 -0
- package/katas/002-transform-with-map/solution.ts +16 -0
- package/katas/003-generator-pipelines/SENSEI.md +72 -0
- package/katas/003-generator-pipelines/solution.test.ts +40 -0
- package/katas/003-generator-pipelines/solution.ts +29 -0
- package/katas/004-flatmap-and-chaining/SENSEI.md +80 -0
- package/katas/004-flatmap-and-chaining/solution.test.ts +34 -0
- package/katas/004-flatmap-and-chaining/solution.ts +18 -0
- package/katas/005-pipe-composition/SENSEI.md +81 -0
- package/katas/005-pipe-composition/solution.test.ts +41 -0
- package/katas/005-pipe-composition/solution.ts +19 -0
- package/katas/006-handle-errors/SENSEI.md +86 -0
- package/katas/006-handle-errors/solution.test.ts +53 -0
- package/katas/006-handle-errors/solution.ts +30 -0
- package/katas/007-tagged-errors/SENSEI.md +79 -0
- package/katas/007-tagged-errors/solution.test.ts +82 -0
- package/katas/007-tagged-errors/solution.ts +37 -0
- package/katas/008-error-patterns/SENSEI.md +89 -0
- package/katas/008-error-patterns/solution.test.ts +41 -0
- package/katas/008-error-patterns/solution.ts +38 -0
- package/katas/009-option-type/SENSEI.md +96 -0
- package/katas/009-option-type/solution.test.ts +49 -0
- package/katas/009-option-type/solution.ts +26 -0
- package/katas/010-either-and-exit/SENSEI.md +86 -0
- package/katas/010-either-and-exit/solution.test.ts +33 -0
- package/katas/010-either-and-exit/solution.ts +17 -0
- package/katas/011-services-and-context/SENSEI.md +82 -0
- package/katas/011-services-and-context/solution.test.ts +23 -0
- package/katas/011-services-and-context/solution.ts +17 -0
- package/katas/012-layers/SENSEI.md +73 -0
- package/katas/012-layers/solution.test.ts +23 -0
- package/katas/012-layers/solution.ts +26 -0
- package/katas/013-testing-effects/SENSEI.md +88 -0
- package/katas/013-testing-effects/solution.test.ts +41 -0
- package/katas/013-testing-effects/solution.ts +20 -0
- package/katas/014-schema-basics/SENSEI.md +81 -0
- package/katas/014-schema-basics/solution.test.ts +35 -0
- package/katas/014-schema-basics/solution.ts +25 -0
- package/katas/015-domain-modeling/SENSEI.md +85 -0
- package/katas/015-domain-modeling/solution.test.ts +46 -0
- package/katas/015-domain-modeling/solution.ts +42 -0
- package/katas/016-retry-and-schedule/SENSEI.md +72 -0
- package/katas/016-retry-and-schedule/solution.test.ts +26 -0
- package/katas/016-retry-and-schedule/solution.ts +23 -0
- package/katas/017-parallel-effects/SENSEI.md +70 -0
- package/katas/017-parallel-effects/solution.test.ts +33 -0
- package/katas/017-parallel-effects/solution.ts +17 -0
- package/katas/018-race-and-timeout/SENSEI.md +75 -0
- package/katas/018-race-and-timeout/solution.test.ts +30 -0
- package/katas/018-race-and-timeout/solution.ts +27 -0
- package/katas/019-ref-and-state/SENSEI.md +72 -0
- package/katas/019-ref-and-state/solution.test.ts +29 -0
- package/katas/019-ref-and-state/solution.ts +16 -0
- package/katas/020-fibers/SENSEI.md +80 -0
- package/katas/020-fibers/solution.test.ts +23 -0
- package/katas/020-fibers/solution.ts +23 -0
- package/katas/021-acquire-release/SENSEI.md +57 -0
- package/katas/021-acquire-release/solution.test.ts +23 -0
- package/katas/021-acquire-release/solution.ts +22 -0
- package/katas/022-scoped-layers/SENSEI.md +52 -0
- package/katas/022-scoped-layers/solution.test.ts +35 -0
- package/katas/022-scoped-layers/solution.ts +19 -0
- package/katas/023-resource-patterns/SENSEI.md +52 -0
- package/katas/023-resource-patterns/solution.test.ts +20 -0
- package/katas/023-resource-patterns/solution.ts +13 -0
- package/katas/024-streams-basics/SENSEI.md +61 -0
- package/katas/024-streams-basics/solution.test.ts +30 -0
- package/katas/024-streams-basics/solution.ts +16 -0
- package/katas/025-stream-operations/SENSEI.md +59 -0
- package/katas/025-stream-operations/solution.test.ts +26 -0
- package/katas/025-stream-operations/solution.ts +17 -0
- package/katas/026-combining-streams/SENSEI.md +54 -0
- package/katas/026-combining-streams/solution.test.ts +20 -0
- package/katas/026-combining-streams/solution.ts +16 -0
- package/katas/027-data-pipelines/SENSEI.md +58 -0
- package/katas/027-data-pipelines/solution.test.ts +22 -0
- package/katas/027-data-pipelines/solution.ts +16 -0
- package/katas/028-logging-and-spans/SENSEI.md +58 -0
- package/katas/028-logging-and-spans/solution.test.ts +50 -0
- package/katas/028-logging-and-spans/solution.ts +20 -0
- package/katas/029-http-client/SENSEI.md +59 -0
- package/katas/029-http-client/solution.test.ts +49 -0
- package/katas/029-http-client/solution.ts +24 -0
- package/katas/030-capstone/SENSEI.md +63 -0
- package/katas/030-capstone/solution.test.ts +67 -0
- package/katas/030-capstone/solution.ts +55 -0
- package/katas/031-config-and-environment/SENSEI.md +77 -0
- package/katas/031-config-and-environment/solution.test.ts +38 -0
- package/katas/031-config-and-environment/solution.ts +11 -0
- package/katas/032-cause-and-defects/SENSEI.md +90 -0
- package/katas/032-cause-and-defects/solution.test.ts +50 -0
- package/katas/032-cause-and-defects/solution.ts +23 -0
- package/katas/033-pattern-matching/SENSEI.md +86 -0
- package/katas/033-pattern-matching/solution.test.ts +36 -0
- package/katas/033-pattern-matching/solution.ts +28 -0
- package/katas/034-deferred-and-coordination/SENSEI.md +85 -0
- package/katas/034-deferred-and-coordination/solution.test.ts +25 -0
- package/katas/034-deferred-and-coordination/solution.ts +24 -0
- package/katas/035-queue-and-backpressure/SENSEI.md +100 -0
- package/katas/035-queue-and-backpressure/solution.test.ts +25 -0
- package/katas/035-queue-and-backpressure/solution.ts +21 -0
- package/katas/036-schema-advanced/SENSEI.md +81 -0
- package/katas/036-schema-advanced/solution.test.ts +55 -0
- package/katas/036-schema-advanced/solution.ts +19 -0
- package/katas/037-cache-and-memoization/SENSEI.md +73 -0
- package/katas/037-cache-and-memoization/solution.test.ts +47 -0
- package/katas/037-cache-and-memoization/solution.ts +24 -0
- package/katas/038-metrics/SENSEI.md +91 -0
- package/katas/038-metrics/solution.test.ts +39 -0
- package/katas/038-metrics/solution.ts +23 -0
- package/katas/039-managed-runtime/SENSEI.md +75 -0
- package/katas/039-managed-runtime/solution.test.ts +29 -0
- package/katas/039-managed-runtime/solution.ts +19 -0
- package/katas/040-request-batching/SENSEI.md +87 -0
- package/katas/040-request-batching/solution.test.ts +56 -0
- package/katas/040-request-batching/solution.ts +32 -0
- package/package.json +22 -0
- package/skills/effect-patterns-building-apis/SKILL.md +2393 -0
- package/skills/effect-patterns-building-data-pipelines/SKILL.md +1876 -0
- package/skills/effect-patterns-concurrency/SKILL.md +2999 -0
- package/skills/effect-patterns-concurrency-getting-started/SKILL.md +351 -0
- package/skills/effect-patterns-core-concepts/SKILL.md +3199 -0
- package/skills/effect-patterns-domain-modeling/SKILL.md +1385 -0
- package/skills/effect-patterns-error-handling/SKILL.md +1212 -0
- package/skills/effect-patterns-error-handling-resilience/SKILL.md +179 -0
- package/skills/effect-patterns-error-management/SKILL.md +1668 -0
- package/skills/effect-patterns-getting-started/SKILL.md +237 -0
- package/skills/effect-patterns-making-http-requests/SKILL.md +1756 -0
- package/skills/effect-patterns-observability/SKILL.md +1586 -0
- package/skills/effect-patterns-platform/SKILL.md +1195 -0
- package/skills/effect-patterns-platform-getting-started/SKILL.md +179 -0
- package/skills/effect-patterns-project-setup--execution/SKILL.md +233 -0
- package/skills/effect-patterns-resource-management/SKILL.md +827 -0
- package/skills/effect-patterns-scheduling/SKILL.md +451 -0
- package/skills/effect-patterns-scheduling-periodic-tasks/SKILL.md +763 -0
- package/skills/effect-patterns-streams/SKILL.md +2052 -0
- package/skills/effect-patterns-streams-getting-started/SKILL.md +421 -0
- package/skills/effect-patterns-streams-sinks/SKILL.md +1181 -0
- package/skills/effect-patterns-testing/SKILL.md +1632 -0
- package/skills/effect-patterns-tooling-and-debugging/SKILL.md +1125 -0
- package/skills/effect-patterns-value-handling/SKILL.md +676 -0
- package/tsconfig.json +20 -0
- package/vitest.config.ts +3 -0
|
@@ -0,0 +1,827 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: effect-patterns-resource-management
|
|
3
|
+
description: Effect-TS patterns for Resource Management. Use when working with resource management in Effect-TS applications.
|
|
4
|
+
---
|
|
5
|
+
# Effect-TS Patterns: Resource Management
|
|
6
|
+
This skill provides 8 curated Effect-TS patterns for resource management.
|
|
7
|
+
Use this skill when working on tasks related to:
|
|
8
|
+
- resource management
|
|
9
|
+
- Best practices in Effect-TS applications
|
|
10
|
+
- Real-world patterns and solutions
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## 🟢 Beginner Patterns
|
|
15
|
+
|
|
16
|
+
### Safely Bracket Resource Usage with `acquireRelease`
|
|
17
|
+
|
|
18
|
+
**Rule:** Bracket the use of a resource between an `acquire` and a `release` effect.
|
|
19
|
+
|
|
20
|
+
**Good Example:**
|
|
21
|
+
|
|
22
|
+
```typescript
|
|
23
|
+
import { Effect, Console } from "effect";
|
|
24
|
+
|
|
25
|
+
// A mock resource that needs to be managed
|
|
26
|
+
const getDbConnection = Effect.sync(() => ({ id: Math.random() })).pipe(
|
|
27
|
+
Effect.tap(() => Effect.log("Connection Acquired"))
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
const closeDbConnection = (conn: {
|
|
31
|
+
id: number;
|
|
32
|
+
}): Effect.Effect<void, never, never> =>
|
|
33
|
+
Effect.log(`Connection ${conn.id} Released`);
|
|
34
|
+
|
|
35
|
+
// The program that uses the resource
|
|
36
|
+
const program = Effect.acquireRelease(
|
|
37
|
+
getDbConnection, // 1. acquire
|
|
38
|
+
(connection) => closeDbConnection(connection) // 2. cleanup
|
|
39
|
+
).pipe(
|
|
40
|
+
Effect.tap((connection) =>
|
|
41
|
+
Effect.log(`Using connection ${connection.id} to run query...`)
|
|
42
|
+
)
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
Effect.runPromise(Effect.scoped(program));
|
|
46
|
+
|
|
47
|
+
/*
|
|
48
|
+
Output:
|
|
49
|
+
Connection Acquired
|
|
50
|
+
Using connection 0.12345... to run query...
|
|
51
|
+
Connection 0.12345... Released
|
|
52
|
+
*/
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
**Explanation:**
|
|
56
|
+
By using `Effect.acquireRelease`, the `closeDbConnection` logic is guaranteed to run after the main logic completes. This creates a self-contained, leak-proof unit of work that can be safely composed into larger programs.
|
|
57
|
+
|
|
58
|
+
**Anti-Pattern:**
|
|
59
|
+
|
|
60
|
+
Using a standard `try...finally` block with `async/await`. While it handles success and failure cases, it is **not interruption-safe**. If the fiber executing the `Promise` is interrupted by Effect's structured concurrency, the `finally` block is not guaranteed to run, leading to resource leaks.
|
|
61
|
+
|
|
62
|
+
```typescript
|
|
63
|
+
// ANTI-PATTERN: Not interruption-safe
|
|
64
|
+
async function getUser() {
|
|
65
|
+
const connection = await getDbConnectionPromise(); // acquire
|
|
66
|
+
try {
|
|
67
|
+
return await useConnectionPromise(connection); // use
|
|
68
|
+
} finally {
|
|
69
|
+
// This block may not run if the fiber is interrupted!
|
|
70
|
+
await closeConnectionPromise(connection); // release
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
**Rationale:**
|
|
76
|
+
|
|
77
|
+
Wrap the acquisition, usage, and release of a resource within an `Effect.acquireRelease` call. This ensures the resource's cleanup logic is executed, regardless of whether the usage logic succeeds, fails, or is interrupted.
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
This pattern is the foundation of resource safety in Effect. It provides a composable and interruption-safe alternative to a standard `try...finally` block. The `release` effect is guaranteed to execute, preventing resource leaks which are common in complex asynchronous applications, especially those involving concurrency where tasks can be cancelled.
|
|
81
|
+
|
|
82
|
+
---
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
## 🟡 Intermediate Patterns
|
|
86
|
+
|
|
87
|
+
### Pool Resources for Reuse
|
|
88
|
+
|
|
89
|
+
**Rule:** Use Pool to manage expensive resources that can be reused across operations.
|
|
90
|
+
|
|
91
|
+
**Good Example:**
|
|
92
|
+
|
|
93
|
+
```typescript
|
|
94
|
+
import { Effect, Pool, Scope, Duration } from "effect"
|
|
95
|
+
|
|
96
|
+
// ============================================
|
|
97
|
+
// 1. Define a poolable resource
|
|
98
|
+
// ============================================
|
|
99
|
+
|
|
100
|
+
interface DatabaseConnection {
|
|
101
|
+
readonly id: number
|
|
102
|
+
readonly query: (sql: string) => Effect.Effect<unknown[]>
|
|
103
|
+
readonly close: () => Effect.Effect<void>
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
let connectionId = 0
|
|
107
|
+
|
|
108
|
+
const createConnection = Effect.gen(function* () {
|
|
109
|
+
const id = ++connectionId
|
|
110
|
+
yield* Effect.log(`Creating connection ${id}`)
|
|
111
|
+
|
|
112
|
+
// Simulate connection setup time
|
|
113
|
+
yield* Effect.sleep("100 millis")
|
|
114
|
+
|
|
115
|
+
const connection: DatabaseConnection = {
|
|
116
|
+
id,
|
|
117
|
+
query: (sql) => Effect.gen(function* () {
|
|
118
|
+
yield* Effect.log(`[Conn ${id}] Executing: ${sql}`)
|
|
119
|
+
return [{ result: "data" }]
|
|
120
|
+
}),
|
|
121
|
+
close: () => Effect.gen(function* () {
|
|
122
|
+
yield* Effect.log(`Closing connection ${id}`)
|
|
123
|
+
}),
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
return connection
|
|
127
|
+
})
|
|
128
|
+
|
|
129
|
+
// ============================================
|
|
130
|
+
// 2. Create a pool
|
|
131
|
+
// ============================================
|
|
132
|
+
|
|
133
|
+
const makeConnectionPool = Pool.make({
|
|
134
|
+
acquire: createConnection,
|
|
135
|
+
size: 5, // Maximum 5 connections
|
|
136
|
+
})
|
|
137
|
+
|
|
138
|
+
// ============================================
|
|
139
|
+
// 3. Use the pool
|
|
140
|
+
// ============================================
|
|
141
|
+
|
|
142
|
+
const runQuery = (pool: Pool.Pool<DatabaseConnection>, sql: string) =>
|
|
143
|
+
Effect.scoped(
|
|
144
|
+
Effect.gen(function* () {
|
|
145
|
+
// Get a connection from the pool
|
|
146
|
+
const connection = yield* pool.get
|
|
147
|
+
|
|
148
|
+
// Use it
|
|
149
|
+
const results = yield* connection.query(sql)
|
|
150
|
+
|
|
151
|
+
// Connection automatically returned to pool when scope ends
|
|
152
|
+
return results
|
|
153
|
+
})
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
// ============================================
|
|
157
|
+
// 4. Run multiple queries concurrently
|
|
158
|
+
// ============================================
|
|
159
|
+
|
|
160
|
+
const program = Effect.scoped(
|
|
161
|
+
Effect.gen(function* () {
|
|
162
|
+
const pool = yield* makeConnectionPool
|
|
163
|
+
|
|
164
|
+
yield* Effect.log("Starting concurrent queries...")
|
|
165
|
+
|
|
166
|
+
// Run 10 queries with only 5 connections
|
|
167
|
+
const queries = Array.from({ length: 10 }, (_, i) =>
|
|
168
|
+
runQuery(pool, `SELECT * FROM users WHERE id = ${i}`)
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
const results = yield* Effect.all(queries, { concurrency: "unbounded" })
|
|
172
|
+
|
|
173
|
+
yield* Effect.log(`Completed ${results.length} queries`)
|
|
174
|
+
return results
|
|
175
|
+
})
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
Effect.runPromise(program)
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
**Rationale:**
|
|
182
|
+
|
|
183
|
+
Use `Pool` to manage a collection of reusable resources. The pool handles acquisition, release, and lifecycle management automatically.
|
|
184
|
+
|
|
185
|
+
---
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
Creating resources is expensive:
|
|
189
|
+
|
|
190
|
+
1. **Database connections** - TCP handshake, authentication
|
|
191
|
+
2. **HTTP clients** - Connection setup, TLS negotiation
|
|
192
|
+
3. **Worker threads** - Spawn overhead
|
|
193
|
+
4. **File handles** - System calls
|
|
194
|
+
|
|
195
|
+
Pooling amortizes this cost across many operations.
|
|
196
|
+
|
|
197
|
+
---
|
|
198
|
+
|
|
199
|
+
---
|
|
200
|
+
|
|
201
|
+
### Create a Service Layer from a Managed Resource
|
|
202
|
+
|
|
203
|
+
**Rule:** Provide a managed resource to the application context using `Layer.scoped`.
|
|
204
|
+
|
|
205
|
+
**Good Example:**
|
|
206
|
+
|
|
207
|
+
```typescript
|
|
208
|
+
import { Effect, Console } from "effect";
|
|
209
|
+
|
|
210
|
+
// 1. Define the service interface
|
|
211
|
+
interface DatabaseService {
|
|
212
|
+
readonly query: (sql: string) => Effect.Effect<string[], never, never>;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// 2. Define the service implementation with scoped resource management
|
|
216
|
+
class Database extends Effect.Service<DatabaseService>()("Database", {
|
|
217
|
+
// The scoped property manages the resource lifecycle
|
|
218
|
+
scoped: Effect.gen(function* () {
|
|
219
|
+
const id = Math.floor(Math.random() * 1000);
|
|
220
|
+
|
|
221
|
+
// Acquire the connection
|
|
222
|
+
yield* Effect.log(`[Pool ${id}] Acquired`);
|
|
223
|
+
|
|
224
|
+
// Setup cleanup to run when scope closes
|
|
225
|
+
yield* Effect.addFinalizer(() => Effect.log(`[Pool ${id}] Released`));
|
|
226
|
+
|
|
227
|
+
// Return the service implementation
|
|
228
|
+
return {
|
|
229
|
+
query: (sql: string) =>
|
|
230
|
+
Effect.sync(() => [`Result for '${sql}' from pool ${id}`]),
|
|
231
|
+
};
|
|
232
|
+
}),
|
|
233
|
+
}) {}
|
|
234
|
+
|
|
235
|
+
// 3. Use the service in your program
|
|
236
|
+
const program = Effect.gen(function* () {
|
|
237
|
+
const db = yield* Database;
|
|
238
|
+
const users = yield* db.query("SELECT * FROM users");
|
|
239
|
+
yield* Effect.log(`Query successful: ${users[0]}`);
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
// 4. Run the program with scoped resource management
|
|
243
|
+
Effect.runPromise(
|
|
244
|
+
Effect.scoped(program).pipe(Effect.provide(Database.Default))
|
|
245
|
+
);
|
|
246
|
+
|
|
247
|
+
/*
|
|
248
|
+
Output:
|
|
249
|
+
[Pool 458] Acquired
|
|
250
|
+
Query successful: Result for 'SELECT * FROM users' from pool 458
|
|
251
|
+
[Pool 458] Released
|
|
252
|
+
*/
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
**Explanation:**
|
|
256
|
+
The `Effect.Service` helper creates the `Database` class, which acts as both the service definition and its context key (Tag). The `Database.Live` layer connects this service to a concrete, lifecycle-managed implementation. When `program` asks for the `Database` service, the Effect runtime uses the `Live` layer to run the `acquire` effect once, caches the resulting `DbPool`, and injects it. The `release` effect is automatically run when the program completes.
|
|
257
|
+
|
|
258
|
+
**Anti-Pattern:**
|
|
259
|
+
|
|
260
|
+
Creating and exporting a global singleton instance of a resource. This tightly couples your application to a specific implementation, makes testing difficult, and offers no guarantees about graceful shutdown.
|
|
261
|
+
|
|
262
|
+
```typescript
|
|
263
|
+
// ANTI-PATTERN: Global singleton
|
|
264
|
+
export const dbPool = makeDbPoolSync(); // Eagerly created, hard to test/mock
|
|
265
|
+
|
|
266
|
+
function someBusinessLogic() {
|
|
267
|
+
// This function has a hidden dependency on the global dbPool
|
|
268
|
+
return dbPool.query("SELECT * FROM products");
|
|
269
|
+
}
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
**Rationale:**
|
|
273
|
+
|
|
274
|
+
Define a service using `class MyService extends Effect.Service(...)`. Implement the service using the `scoped` property of the service class. This property should be a scoped `Effect` (typically from `Effect.acquireRelease`) that builds and releases the underlying resource.
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
This pattern is the key to building robust, testable, and leak-proof applications in Effect. It elevates a managed resource into a first-class service that can be used anywhere in your application. The `Effect.Service` helper simplifies defining the service's interface and context key. This approach decouples your business logic from the concrete implementation, as the logic only depends on the abstract service. The `Layer` declaratively handles the resource's entire lifecycle, ensuring it is acquired lazily, shared safely, and released automatically.
|
|
278
|
+
|
|
279
|
+
---
|
|
280
|
+
|
|
281
|
+
### Compose Resource Lifecycles with `Layer.merge`
|
|
282
|
+
|
|
283
|
+
**Rule:** Compose multiple scoped layers using `Layer.merge` or by providing one layer to another.
|
|
284
|
+
|
|
285
|
+
**Good Example:**
|
|
286
|
+
|
|
287
|
+
```typescript
|
|
288
|
+
import { Effect, Layer, Console } from "effect";
|
|
289
|
+
|
|
290
|
+
// --- Service 1: Database ---
|
|
291
|
+
interface DatabaseOps {
|
|
292
|
+
query: (sql: string) => Effect.Effect<string, never, never>;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
class Database extends Effect.Service<DatabaseOps>()("Database", {
|
|
296
|
+
sync: () => ({
|
|
297
|
+
query: (sql: string): Effect.Effect<string, never, never> =>
|
|
298
|
+
Effect.sync(() => `db says: ${sql}`),
|
|
299
|
+
}),
|
|
300
|
+
}) {}
|
|
301
|
+
|
|
302
|
+
// --- Service 2: API Client ---
|
|
303
|
+
interface ApiClientOps {
|
|
304
|
+
fetch: (path: string) => Effect.Effect<string, never, never>;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
class ApiClient extends Effect.Service<ApiClientOps>()("ApiClient", {
|
|
308
|
+
sync: () => ({
|
|
309
|
+
fetch: (path: string): Effect.Effect<string, never, never> =>
|
|
310
|
+
Effect.sync(() => `api says: ${path}`),
|
|
311
|
+
}),
|
|
312
|
+
}) {}
|
|
313
|
+
|
|
314
|
+
// --- Application Layer ---
|
|
315
|
+
// We merge the two independent layers into one.
|
|
316
|
+
const AppLayer = Layer.merge(Database.Default, ApiClient.Default);
|
|
317
|
+
|
|
318
|
+
// This program uses both services, unaware of their implementation details.
|
|
319
|
+
const program = Effect.gen(function* () {
|
|
320
|
+
const db = yield* Database;
|
|
321
|
+
const api = yield* ApiClient;
|
|
322
|
+
|
|
323
|
+
const dbResult = yield* db.query("SELECT *");
|
|
324
|
+
const apiResult = yield* api.fetch("/users");
|
|
325
|
+
|
|
326
|
+
yield* Effect.log(dbResult);
|
|
327
|
+
yield* Effect.log(apiResult);
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
// Provide the combined layer to the program.
|
|
331
|
+
Effect.runPromise(Effect.provide(program, AppLayer));
|
|
332
|
+
|
|
333
|
+
/*
|
|
334
|
+
Output (note the LIFO release order):
|
|
335
|
+
Database pool opened
|
|
336
|
+
API client session started
|
|
337
|
+
db says: SELECT *
|
|
338
|
+
api says: /users
|
|
339
|
+
API client session ended
|
|
340
|
+
Database pool closed
|
|
341
|
+
*/
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
**Explanation:**
|
|
345
|
+
We define two completely independent services, `Database` and `ApiClient`, each with its own resource lifecycle. By combining them with `Layer.merge`, we create a single `AppLayer`. When `program` runs, Effect acquires the resources for both layers. When `program` finishes, Effect closes the application's scope, releasing the resources in the reverse order they were acquired (`ApiClient` then `Database`), ensuring a clean and predictable shutdown.
|
|
346
|
+
|
|
347
|
+
**Anti-Pattern:**
|
|
348
|
+
|
|
349
|
+
A manual, imperative startup and shutdown script. This approach is brittle and error-prone. The developer is responsible for maintaining the correct order of initialization and, more importantly, the reverse order for shutdown. This becomes unmanageable as an application grows.
|
|
350
|
+
|
|
351
|
+
```typescript
|
|
352
|
+
// ANTI-PATTERN: Manual, brittle, and error-prone
|
|
353
|
+
async function main() {
|
|
354
|
+
const db = await initDb(); // acquire 1
|
|
355
|
+
const client = await initApiClient(); // acquire 2
|
|
356
|
+
|
|
357
|
+
try {
|
|
358
|
+
await doWork(db, client); // use
|
|
359
|
+
} finally {
|
|
360
|
+
// This order is easy to get wrong!
|
|
361
|
+
await client.close(); // release 2
|
|
362
|
+
await db.close(); // release 1
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
**Rationale:**
|
|
368
|
+
|
|
369
|
+
Combine multiple resource-managing `Layer`s into a single application layer using functions like `Layer.merge`. The Effect runtime will automatically build a dependency graph, acquire resources in the correct order, and release them in the reverse order.
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
This pattern is the ultimate payoff for defining services with `Layer`. It allows for true modularity. Each service can be defined in its own file, declaring its own resource requirements in its `Live` layer, completely unaware of other services.
|
|
373
|
+
|
|
374
|
+
When you assemble the final application layer, Effect analyzes the dependencies:
|
|
375
|
+
|
|
376
|
+
1. **Acquisition Order:** It ensures resources are acquired in the correct order. For example, a `Logger` layer might be initialized before a `Database` layer that uses it for logging.
|
|
377
|
+
2. **Release Order:** It guarantees that resources are released in the **exact reverse order** of their acquisition. This is critical for preventing shutdown errors, such as a `UserRepository` trying to log a final message after the `Logger` has already been shut down.
|
|
378
|
+
|
|
379
|
+
This automates one of the most complex and error-prone parts of application architecture.
|
|
380
|
+
|
|
381
|
+
---
|
|
382
|
+
|
|
383
|
+
### Handle Resource Timeouts
|
|
384
|
+
|
|
385
|
+
**Rule:** Always set timeouts on resource acquisition to prevent indefinite waits.
|
|
386
|
+
|
|
387
|
+
**Good Example:**
|
|
388
|
+
|
|
389
|
+
```typescript
|
|
390
|
+
import { Effect, Duration, Scope } from "effect"
|
|
391
|
+
|
|
392
|
+
// ============================================
|
|
393
|
+
// 1. Define a resource with slow acquisition
|
|
394
|
+
// ============================================
|
|
395
|
+
|
|
396
|
+
interface Connection {
|
|
397
|
+
readonly id: string
|
|
398
|
+
readonly query: (sql: string) => Effect.Effect<unknown>
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
const acquireConnection = Effect.gen(function* () {
|
|
402
|
+
yield* Effect.log("Attempting to connect...")
|
|
403
|
+
|
|
404
|
+
// Simulate slow connection
|
|
405
|
+
yield* Effect.sleep("2 seconds")
|
|
406
|
+
|
|
407
|
+
const connection: Connection = {
|
|
408
|
+
id: crypto.randomUUID(),
|
|
409
|
+
query: (sql) => Effect.succeed({ rows: [] }),
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
yield* Effect.log(`Connected: ${connection.id}`)
|
|
413
|
+
return connection
|
|
414
|
+
})
|
|
415
|
+
|
|
416
|
+
const releaseConnection = (conn: Connection) =>
|
|
417
|
+
Effect.log(`Released: ${conn.id}`)
|
|
418
|
+
|
|
419
|
+
// ============================================
|
|
420
|
+
// 2. Timeout on acquisition
|
|
421
|
+
// ============================================
|
|
422
|
+
|
|
423
|
+
const acquireWithTimeout = acquireConnection.pipe(
|
|
424
|
+
Effect.timeout("1 second"),
|
|
425
|
+
Effect.catchTag("TimeoutException", () =>
|
|
426
|
+
Effect.fail(new Error("Connection timeout - database unreachable"))
|
|
427
|
+
)
|
|
428
|
+
)
|
|
429
|
+
|
|
430
|
+
// ============================================
|
|
431
|
+
// 3. Timeout on usage
|
|
432
|
+
// ============================================
|
|
433
|
+
|
|
434
|
+
const queryWithTimeout = (conn: Connection, sql: string) =>
|
|
435
|
+
conn.query(sql).pipe(
|
|
436
|
+
Effect.timeout("5 seconds"),
|
|
437
|
+
Effect.catchTag("TimeoutException", () =>
|
|
438
|
+
Effect.fail(new Error(`Query timeout: ${sql}`))
|
|
439
|
+
)
|
|
440
|
+
)
|
|
441
|
+
|
|
442
|
+
// ============================================
|
|
443
|
+
// 4. Full resource lifecycle with timeouts
|
|
444
|
+
// ============================================
|
|
445
|
+
|
|
446
|
+
const useConnectionWithTimeouts = Effect.acquireRelease(
|
|
447
|
+
acquireWithTimeout,
|
|
448
|
+
releaseConnection
|
|
449
|
+
).pipe(
|
|
450
|
+
Effect.flatMap((conn) =>
|
|
451
|
+
Effect.gen(function* () {
|
|
452
|
+
yield* Effect.log("Running queries...")
|
|
453
|
+
|
|
454
|
+
// Each query has its own timeout
|
|
455
|
+
const result1 = yield* queryWithTimeout(conn, "SELECT 1")
|
|
456
|
+
const result2 = yield* queryWithTimeout(conn, "SELECT 2")
|
|
457
|
+
|
|
458
|
+
return [result1, result2]
|
|
459
|
+
})
|
|
460
|
+
),
|
|
461
|
+
Effect.scoped
|
|
462
|
+
)
|
|
463
|
+
|
|
464
|
+
// ============================================
|
|
465
|
+
// 5. Timeout on entire operation
|
|
466
|
+
// ============================================
|
|
467
|
+
|
|
468
|
+
const entireOperationWithTimeout = useConnectionWithTimeouts.pipe(
|
|
469
|
+
Effect.timeout("10 seconds"),
|
|
470
|
+
Effect.catchTag("TimeoutException", () =>
|
|
471
|
+
Effect.fail(new Error("Entire operation timed out"))
|
|
472
|
+
)
|
|
473
|
+
)
|
|
474
|
+
|
|
475
|
+
// ============================================
|
|
476
|
+
// 6. Run with different scenarios
|
|
477
|
+
// ============================================
|
|
478
|
+
|
|
479
|
+
const program = Effect.gen(function* () {
|
|
480
|
+
yield* Effect.log("=== Testing timeouts ===")
|
|
481
|
+
|
|
482
|
+
const result = yield* entireOperationWithTimeout.pipe(
|
|
483
|
+
Effect.catchAll((error) =>
|
|
484
|
+
Effect.gen(function* () {
|
|
485
|
+
yield* Effect.logError(`Failed: ${error.message}`)
|
|
486
|
+
return []
|
|
487
|
+
})
|
|
488
|
+
)
|
|
489
|
+
)
|
|
490
|
+
|
|
491
|
+
yield* Effect.log(`Result: ${JSON.stringify(result)}`)
|
|
492
|
+
})
|
|
493
|
+
|
|
494
|
+
Effect.runPromise(program)
|
|
495
|
+
```
|
|
496
|
+
|
|
497
|
+
**Rationale:**
|
|
498
|
+
|
|
499
|
+
Set timeouts on resource acquisition and usage to ensure your application doesn't hang waiting for unavailable resources.
|
|
500
|
+
|
|
501
|
+
---
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
Resources can become unavailable:
|
|
505
|
+
|
|
506
|
+
1. **Network partitions** - Can't reach database
|
|
507
|
+
2. **Pool exhaustion** - All connections in use
|
|
508
|
+
3. **Deadlocks** - Resources held indefinitely
|
|
509
|
+
4. **Slow operations** - Query takes too long
|
|
510
|
+
|
|
511
|
+
Timeouts provide a safety net.
|
|
512
|
+
|
|
513
|
+
---
|
|
514
|
+
|
|
515
|
+
---
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
## 🟠 Advanced Patterns
|
|
519
|
+
|
|
520
|
+
### Manually Manage Lifecycles with `Scope`
|
|
521
|
+
|
|
522
|
+
**Rule:** Use `Effect.scope` and `Scope.addFinalizer` for fine-grained control over resource cleanup.
|
|
523
|
+
|
|
524
|
+
**Good Example:**
|
|
525
|
+
|
|
526
|
+
```typescript
|
|
527
|
+
import { Effect, Console } from "effect";
|
|
528
|
+
|
|
529
|
+
// Mocking a complex file operation
|
|
530
|
+
const openFile = (path: string) =>
|
|
531
|
+
Effect.succeed({ path, handle: Math.random() }).pipe(
|
|
532
|
+
Effect.tap((f) => Effect.log(`Opened ${f.path}`))
|
|
533
|
+
);
|
|
534
|
+
const createTempFile = (path: string) =>
|
|
535
|
+
Effect.succeed({ path: `${path}.tmp`, handle: Math.random() }).pipe(
|
|
536
|
+
Effect.tap((f) => Effect.log(`Created temp file ${f.path}`))
|
|
537
|
+
);
|
|
538
|
+
const closeFile = (file: { path: string }) =>
|
|
539
|
+
Effect.sync(() => Effect.log(`Closed ${file.path}`));
|
|
540
|
+
const deleteFile = (file: { path: string }) =>
|
|
541
|
+
Effect.sync(() => Effect.log(`Deleted ${file.path}`));
|
|
542
|
+
|
|
543
|
+
// This program acquires two resources (a file and a temp file)
|
|
544
|
+
// and ensures both are cleaned up correctly using acquireRelease.
|
|
545
|
+
const program = Effect.gen(function* () {
|
|
546
|
+
const file = yield* Effect.acquireRelease(openFile("data.csv"), (f) =>
|
|
547
|
+
closeFile(f)
|
|
548
|
+
);
|
|
549
|
+
|
|
550
|
+
const tempFile = yield* Effect.acquireRelease(
|
|
551
|
+
createTempFile("data.csv"),
|
|
552
|
+
(f) => deleteFile(f)
|
|
553
|
+
);
|
|
554
|
+
|
|
555
|
+
yield* Effect.log("...writing data from temp file to main file...");
|
|
556
|
+
});
|
|
557
|
+
|
|
558
|
+
// Run the program with a scope
|
|
559
|
+
Effect.runPromise(Effect.scoped(program));
|
|
560
|
+
|
|
561
|
+
/*
|
|
562
|
+
Output (note the LIFO cleanup order):
|
|
563
|
+
Opened data.csv
|
|
564
|
+
Created temp file data.csv.tmp
|
|
565
|
+
...writing data from temp file to main file...
|
|
566
|
+
Deleted data.csv.tmp
|
|
567
|
+
Closed data.csv
|
|
568
|
+
*/
|
|
569
|
+
```
|
|
570
|
+
|
|
571
|
+
**Explanation:**
|
|
572
|
+
`Effect.scope` creates a new `Scope` and provides it to the `program`. Inside `program`, we access this `Scope` and use `addFinalizer` to register cleanup actions immediately after acquiring each resource. When `Effect.scope` finishes executing `program`, it closes the scope, which in turn executes all registered finalizers in the reverse order of their addition.
|
|
573
|
+
|
|
574
|
+
**Anti-Pattern:**
|
|
575
|
+
|
|
576
|
+
Attempting to manage multiple, interdependent resource cleanups using nested `try...finally` blocks. This leads to a "pyramid of doom," is difficult to read, and remains unsafe in the face of interruptions.
|
|
577
|
+
|
|
578
|
+
```typescript
|
|
579
|
+
// ANTI-PATTERN: Nested, unsafe, and hard to read
|
|
580
|
+
async function complexOperation() {
|
|
581
|
+
const file = await openFilePromise(); // acquire 1
|
|
582
|
+
try {
|
|
583
|
+
const tempFile = await createTempFilePromise(); // acquire 2
|
|
584
|
+
try {
|
|
585
|
+
await doWorkPromise(file, tempFile); // use
|
|
586
|
+
} finally {
|
|
587
|
+
// This block may not run on interruption!
|
|
588
|
+
await deleteFilePromise(tempFile); // release 2
|
|
589
|
+
}
|
|
590
|
+
} finally {
|
|
591
|
+
// This block may also not run on interruption!
|
|
592
|
+
await closeFilePromise(file); // release 1
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
```
|
|
596
|
+
|
|
597
|
+
**Rationale:**
|
|
598
|
+
|
|
599
|
+
For complex scenarios where a resource's lifecycle doesn't fit a simple `acquireRelease` pattern, use `Effect.scope` to create a boundary for finalizers. Inside this boundary, you can access the `Scope` service and manually register cleanup actions using `Scope.addFinalizer`.
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
While `Effect.acquireRelease` and `Layer.scoped` are sufficient for most use cases, sometimes you need more control. This pattern is essential when:
|
|
603
|
+
|
|
604
|
+
1. A single logical operation acquires multiple resources that need independent cleanup.
|
|
605
|
+
2. You are building a custom, complex `Layer` that orchestrates several dependent resources.
|
|
606
|
+
3. You need to understand the fundamental mechanism that powers all of Effect's resource management.
|
|
607
|
+
|
|
608
|
+
By interacting with `Scope` directly, you gain precise, imperative-style control over resource cleanup within Effect's declarative, functional framework. Finalizers added to a scope are guaranteed to run in Last-In-First-Out (LIFO) order when the scope is closed.
|
|
609
|
+
|
|
610
|
+
---
|
|
611
|
+
|
|
612
|
+
### Manage Hierarchical Resources
|
|
613
|
+
|
|
614
|
+
**Rule:** Use nested Scopes to manage resources with parent-child dependencies.
|
|
615
|
+
|
|
616
|
+
**Good Example:**
|
|
617
|
+
|
|
618
|
+
```typescript
|
|
619
|
+
import { Effect, Scope, Exit } from "effect"
|
|
620
|
+
|
|
621
|
+
// ============================================
|
|
622
|
+
// 1. Define hierarchical resources
|
|
623
|
+
// ============================================
|
|
624
|
+
|
|
625
|
+
interface Database {
|
|
626
|
+
readonly name: string
|
|
627
|
+
readonly createConnection: () => Effect.Effect<Connection, never, Scope.Scope>
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
interface Connection {
|
|
631
|
+
readonly id: string
|
|
632
|
+
readonly database: string
|
|
633
|
+
readonly beginTransaction: () => Effect.Effect<Transaction, never, Scope.Scope>
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
interface Transaction {
|
|
637
|
+
readonly id: string
|
|
638
|
+
readonly connectionId: string
|
|
639
|
+
readonly execute: (sql: string) => Effect.Effect<void>
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
// ============================================
|
|
643
|
+
// 2. Create resources with proper lifecycle
|
|
644
|
+
// ============================================
|
|
645
|
+
|
|
646
|
+
const makeDatabase = (name: string): Effect.Effect<Database, never, Scope.Scope> =>
|
|
647
|
+
Effect.acquireRelease(
|
|
648
|
+
Effect.gen(function* () {
|
|
649
|
+
yield* Effect.log(`Opening database: ${name}`)
|
|
650
|
+
|
|
651
|
+
const db: Database = {
|
|
652
|
+
name,
|
|
653
|
+
createConnection: () => makeConnection(name),
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
return db
|
|
657
|
+
}),
|
|
658
|
+
(db) => Effect.log(`Closing database: ${db.name}`)
|
|
659
|
+
)
|
|
660
|
+
|
|
661
|
+
const makeConnection = (dbName: string): Effect.Effect<Connection, never, Scope.Scope> =>
|
|
662
|
+
Effect.acquireRelease(
|
|
663
|
+
Effect.gen(function* () {
|
|
664
|
+
const id = `conn-${crypto.randomUUID().slice(0, 8)}`
|
|
665
|
+
yield* Effect.log(` Opening connection: ${id} to ${dbName}`)
|
|
666
|
+
|
|
667
|
+
const conn: Connection = {
|
|
668
|
+
id,
|
|
669
|
+
database: dbName,
|
|
670
|
+
beginTransaction: () => makeTransaction(id),
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
return conn
|
|
674
|
+
}),
|
|
675
|
+
(conn) => Effect.log(` Closing connection: ${conn.id}`)
|
|
676
|
+
)
|
|
677
|
+
|
|
678
|
+
const makeTransaction = (connId: string): Effect.Effect<Transaction, never, Scope.Scope> =>
|
|
679
|
+
Effect.acquireRelease(
|
|
680
|
+
Effect.gen(function* () {
|
|
681
|
+
const id = `tx-${crypto.randomUUID().slice(0, 8)}`
|
|
682
|
+
yield* Effect.log(` Beginning transaction: ${id}`)
|
|
683
|
+
|
|
684
|
+
const tx: Transaction = {
|
|
685
|
+
id,
|
|
686
|
+
connectionId: connId,
|
|
687
|
+
execute: (sql) => Effect.log(` [${id}] ${sql}`),
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
return tx
|
|
691
|
+
}),
|
|
692
|
+
(tx) => Effect.log(` Committing transaction: ${tx.id}`)
|
|
693
|
+
)
|
|
694
|
+
|
|
695
|
+
// ============================================
|
|
696
|
+
// 3. Use hierarchical resources
|
|
697
|
+
// ============================================
|
|
698
|
+
|
|
699
|
+
const program = Effect.scoped(
|
|
700
|
+
Effect.gen(function* () {
|
|
701
|
+
yield* Effect.log("=== Starting hierarchical resource demo ===\n")
|
|
702
|
+
|
|
703
|
+
// Level 1: Database
|
|
704
|
+
const db = yield* makeDatabase("myapp")
|
|
705
|
+
|
|
706
|
+
// Level 2: Connection (child of database)
|
|
707
|
+
const conn = yield* db.createConnection()
|
|
708
|
+
|
|
709
|
+
// Level 3: Transaction (child of connection)
|
|
710
|
+
const tx = yield* conn.beginTransaction()
|
|
711
|
+
|
|
712
|
+
// Use the transaction
|
|
713
|
+
yield* tx.execute("INSERT INTO users (name) VALUES ('Alice')")
|
|
714
|
+
yield* tx.execute("INSERT INTO users (name) VALUES ('Bob')")
|
|
715
|
+
|
|
716
|
+
yield* Effect.log("\n=== Work complete, releasing resources ===\n")
|
|
717
|
+
|
|
718
|
+
// Resources released in reverse order:
|
|
719
|
+
// 1. Transaction committed
|
|
720
|
+
// 2. Connection closed
|
|
721
|
+
// 3. Database closed
|
|
722
|
+
})
|
|
723
|
+
)
|
|
724
|
+
|
|
725
|
+
Effect.runPromise(program)
|
|
726
|
+
|
|
727
|
+
// ============================================
|
|
728
|
+
// 4. Multiple children at same level
|
|
729
|
+
// ============================================
|
|
730
|
+
|
|
731
|
+
const multipleConnections = Effect.scoped(
|
|
732
|
+
Effect.gen(function* () {
|
|
733
|
+
const db = yield* makeDatabase("myapp")
|
|
734
|
+
|
|
735
|
+
// Create multiple connections
|
|
736
|
+
const conn1 = yield* db.createConnection()
|
|
737
|
+
const conn2 = yield* db.createConnection()
|
|
738
|
+
|
|
739
|
+
// Each connection can have transactions
|
|
740
|
+
const tx1 = yield* conn1.beginTransaction()
|
|
741
|
+
const tx2 = yield* conn2.beginTransaction()
|
|
742
|
+
|
|
743
|
+
// Use both transactions
|
|
744
|
+
yield* Effect.all([
|
|
745
|
+
tx1.execute("UPDATE table1 SET x = 1"),
|
|
746
|
+
tx2.execute("UPDATE table2 SET y = 2"),
|
|
747
|
+
])
|
|
748
|
+
|
|
749
|
+
// All released in proper order
|
|
750
|
+
})
|
|
751
|
+
)
|
|
752
|
+
```
|
|
753
|
+
|
|
754
|
+
**Rationale:**
|
|
755
|
+
|
|
756
|
+
Use nested `Scope` to manage hierarchical resources where child resources depend on their parents and must be released first.
|
|
757
|
+
|
|
758
|
+
---
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
Resources often have dependencies:
|
|
762
|
+
|
|
763
|
+
1. **Database → Connections → Transactions** - Transaction needs connection
|
|
764
|
+
2. **Server → Routes → Handlers** - Handler needs server context
|
|
765
|
+
3. **File → Reader → Parser** - Parser needs reader
|
|
766
|
+
|
|
767
|
+
Release order matters: children before parents.
|
|
768
|
+
|
|
769
|
+
---
|
|
770
|
+
|
|
771
|
+
---
|
|
772
|
+
|
|
773
|
+
### Create a Managed Runtime for Scoped Resources
|
|
774
|
+
|
|
775
|
+
**Rule:** Create a managed runtime for scoped resources.
|
|
776
|
+
|
|
777
|
+
**Good Example:**
|
|
778
|
+
|
|
779
|
+
```typescript
|
|
780
|
+
import { Effect, Layer } from "effect";
|
|
781
|
+
|
|
782
|
+
class DatabasePool extends Effect.Service<DatabasePool>()("DbPool", {
|
|
783
|
+
effect: Effect.gen(function* () {
|
|
784
|
+
yield* Effect.log("Acquiring pool");
|
|
785
|
+
return {
|
|
786
|
+
query: () => Effect.succeed("result"),
|
|
787
|
+
};
|
|
788
|
+
}),
|
|
789
|
+
}) {}
|
|
790
|
+
|
|
791
|
+
// Create a program that uses the DatabasePool service
|
|
792
|
+
const program = Effect.gen(function* () {
|
|
793
|
+
const db = yield* DatabasePool;
|
|
794
|
+
yield* Effect.log("Using DB");
|
|
795
|
+
yield* db.query();
|
|
796
|
+
});
|
|
797
|
+
|
|
798
|
+
// Run the program with the service implementation
|
|
799
|
+
Effect.runPromise(
|
|
800
|
+
program.pipe(Effect.provide(DatabasePool.Default), Effect.scoped)
|
|
801
|
+
);
|
|
802
|
+
```
|
|
803
|
+
|
|
804
|
+
**Explanation:**
|
|
805
|
+
`Layer.launch` ensures that resources are acquired and released safely, even
|
|
806
|
+
in the event of errors or interruptions.
|
|
807
|
+
|
|
808
|
+
**Anti-Pattern:**
|
|
809
|
+
|
|
810
|
+
Do not use `Layer.toRuntime` with layers that contain scoped resources. This
|
|
811
|
+
will acquire the resource, but the runtime has no mechanism to release it,
|
|
812
|
+
leading to resource leaks.
|
|
813
|
+
|
|
814
|
+
**Rationale:**
|
|
815
|
+
|
|
816
|
+
For services that manage resources needing explicit cleanup (e.g., a database
|
|
817
|
+
connection), define them in a `Layer` using `Layer.scoped`. Then, use
|
|
818
|
+
`Layer.launch` to provide this layer to your application.
|
|
819
|
+
|
|
820
|
+
|
|
821
|
+
`Layer.launch` is designed for resource safety. It acquires all resources,
|
|
822
|
+
provides them to your effect, and—crucially—guarantees that all registered
|
|
823
|
+
finalizers are executed upon completion or interruption.
|
|
824
|
+
|
|
825
|
+
---
|
|
826
|
+
|
|
827
|
+
|