resources
This skill should be used when the user asks about "Effect resources", "acquireRelease", "Scope", "finalizers", "resource cleanup", "Effect.addFinalizer", "Effect.ensuring", "scoped effects", "resource lifecycle", "bracket pattern", "safe resource handling", "database connections", "file handles", or needs to understand how Effect guarantees resource cleanup.
What this skill does
# Resource Management in Effect
## Overview
Effect provides structured resource management that **guarantees cleanup** even when errors occur or the effect is interrupted. This is essential for:
- Database connections
- File handles
- Network sockets
- Locks and semaphores
- Any resource requiring cleanup
## Core Concept: Scope
A `Scope` is a context that tracks resources and ensures their cleanup:
```typescript
Effect<A, E, R | Scope>;
// ^^^^^ Indicates resource needs cleanup
```
## Basic Resource Acquisition
### Effect.acquireRelease
The fundamental pattern for safe resource management:
```typescript
import { Effect } from "effect";
const managedFile = Effect.acquireRelease(
Effect.sync(() => fs.openSync("file.txt", "r")),
(fd) => Effect.sync(() => fs.closeSync(fd)),
);
```
### Using the Resource
```typescript
const program = Effect.gen(function* () {
const fd = yield* managedFile;
const content = yield* Effect.sync(() => fs.readFileSync(fd, "utf-8"));
return content;
});
// Run with automatic scope management
const result = yield * Effect.scoped(program);
```
## Effect.scoped
Converts a scoped effect into a regular effect by managing the scope:
```typescript
const runnable = Effect.scoped(program);
```
The scope closes when the scoped block completes, triggering all finalizers.
## acquireUseRelease Pattern
For simpler cases, combine acquire/use/release in one call:
```typescript
const readFile = (path: string) =>
Effect.acquireUseRelease(
Effect.sync(() => fs.openSync(path, "r")),
(fd) => Effect.sync(() => fs.readFileSync(fd, "utf-8")),
(fd) => Effect.sync(() => fs.closeSync(fd)),
);
```
## Finalizers
### Effect.addFinalizer
Add cleanup logic to the current scope:
```typescript
const program = Effect.gen(function* () {
yield* Effect.addFinalizer(() => Effect.log("Cleanup running!"));
// ... do work ...
return result;
});
```
### Effect.ensuring
Run cleanup after effect completes (success or failure):
```typescript
const withCleanup = someEffect.pipe(Effect.ensuring(Effect.log("Always runs after effect")));
```
### Effect.onExit
Run different cleanup based on exit status:
```typescript
const withExitHandler = someEffect.pipe(
Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.log("Succeeded!") : Effect.log("Failed or interrupted"))),
);
```
## Multiple Resources
### Sequential Acquisition
```typescript
const program = Effect.gen(function* () {
const db = yield* acquireDbConnection;
const cache = yield* acquireRedisConnection;
});
const result = yield * Effect.scoped(program);
```
### Parallel Acquisition
```typescript
const program = Effect.gen(function* () {
const [db, cache] = yield* Effect.all([acquireDbConnection, acquireRedisConnection]);
});
```
## Resource Patterns
### Database Connection Pool
```typescript
const DbPool = Effect.acquireRelease(
Effect.promise(() =>
createPool({
host: "localhost",
database: "mydb",
max: 10,
}),
),
(pool) => Effect.promise(() => pool.end()),
);
const query = (sql: string) =>
Effect.gen(function* () {
const pool = yield* DbPool;
return yield* Effect.tryPromise(() => pool.query(sql));
});
```
### File Handle
```typescript
const withFile = <A>(path: string, use: (handle: FileHandle) => Effect.Effect<A>) =>
Effect.acquireUseRelease(
Effect.promise(() => fs.promises.open(path)),
use,
(handle) => Effect.promise(() => handle.close()),
);
```
### Lock/Mutex
```typescript
const withLock = <A>(lock: Lock, effect: Effect.Effect<A>) =>
Effect.acquireUseRelease(
lock.acquire,
() => effect,
() => lock.release,
);
```
## Layered Resources
Use `Layer.scoped` for service-level resources:
```typescript
const DatabaseLive = Layer.scoped(
Database,
Effect.gen(function* () {
const pool = yield* Effect.acquireRelease(createPool(), (pool) => Effect.promise(() => pool.end()));
return {
query: (sql) => Effect.tryPromise(() => pool.query(sql)),
};
}),
);
```
## Error Handling in Cleanup
Finalizers should not fail, but if they do:
```typescript
const safeRelease = (resource: Resource) =>
Effect.sync(() => resource.close()).pipe(Effect.catchAll((error) => Effect.logError("Cleanup failed", error)));
const managed = Effect.acquireRelease(acquire, safeRelease);
```
## Interruption Safety
Resources are cleaned up even on interruption:
```typescript
const program = Effect.gen(function* () {
const resource = yield* acquireResource;
yield* Effect.sleep("1 hour");
});
const result = yield * program.pipe(Effect.scoped, Effect.timeout("1 second"));
```
## Best Practices
1. **Use acquireRelease for paired operations** - Guarantees cleanup
2. **Keep finalizers simple and infallible** - Log errors instead of throwing
3. **Use Effect.scoped at appropriate boundaries** - Not too wide, not too narrow
4. **Clean up in reverse acquisition order** - Effect handles this automatically
5. **Use Layer.scoped for service-level resources** - Lifecycle tied to layer
## Additional Resources
For comprehensive resource management documentation, consult `${CLAUDE_PLUGIN_ROOT}/references/llms-full.txt`.
Search for these sections:
- "Introduction" (Resource Management) for core concepts
- "Scope" for detailed scope mechanics
- "Managing Layers" for Layer.scoped patterns
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.