Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

effect-patterns-resource-management

БесплатноБез исполняемых скриптовНе проверен

Effect-TS patterns for Resource Management. Use when working with resource management in Effect-TS applications.

PaulJPhilpот PaulJPhilp★ 807 звёзд на GitHub

Об этом скилле

Effect-TS Patterns: Resource Management

This skill provides 8 curated Effect-TS patterns for resource management. Use this skill when working on tasks related to:

  • resource management
  • Best practices in Effect-TS applications
  • Real-world patterns and solutions

🟢 Beginner Patterns

Safely Bracket Resource Usage with acquireRelease

Rule: Bracket the use of a resource between an acquire and a release effect.

Good Example:

import { Effect, Console } from "effect";

// A mock resource that needs to be managed
const getDbConnection = Effect.sync(() => ({ id: Math.random() })).pipe(
  Effect.tap(() => Effect.log("Connection Acquired"))
);

const closeDbConnection = (conn: {
  id: number;
}): Effect.Effect<void, never, never> =>
  Effect.log(`Connection ${conn.id} Released`);

// The program that uses the resource
const program = Effect.acquireRelease(
  getDbConnection, // 1. acquire
  (connection) => closeDbConnection(connection) // 2. cleanup
).pipe(
  Effect.tap((connection) =>
    Effect.log(`Using connection ${connection.id} to run query...`)
  )
);

Effect.runPromise(Effect.scoped(program));

/*
Output:
Connection Acquired
Using connection 0.12345... to run query...
Connection 0.12345... Released
*/

Explanation: 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.

Anti-Pattern:

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.

// ANTI-PATTERN: Not interruption-safe
async function getUser() {
  const connection = await getDbConnectionPromise(); // acquire
  try {
    return await useConnectionPromise(connection); // use
  } finally {
    // This block may not run if the fiber is interrupted!
    await closeConnectionPromise(connection); // release
  }
}

Rationale:

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.

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.


🟡 Intermediate Patterns

Pool Resources for Reuse

Rule: Use Pool to manage expensive resources that can be reused across operations.

Good Example:

import { Effect, Pool, Scope, Duration } from "effect"

// ============================================
// 1. Define a poolable resource
// ============================================

interface DatabaseConnection {
  readonly id: number
  readonly query: (sql: string) => Effect.Effect<unknown[]>
  readonly close: () => Effect.Effect<void>
}

let connectionId = 0

const createConnection = Effect.gen(function* () {
  const id = ++connectionId
  yield* Effect.log(`Creating connection ${id}`)
  
  // Simulate connection setup time
  yield* Effect.sleep("100 millis")
  
  const connection: DatabaseConnection = {
    id,
    query: (sql) => Effect.gen(function* () {
      yield* Effect.log(`[Conn ${id}] Executing: ${sql}`)
      return [{ result: "data" }]
    }),
    close: () => Effect.gen(function* () {
      yield* Effect.log(`Closing connection ${id}`)
    }),
  }
  
  return connection
})

// ============================================
// 2. Create a pool
// ============================================

const makeConnectionPool = Pool.make({
  acquire: createConnection,
  size: 5,  // Maximum 5 connections
})

// ============================================
// 3. Use the pool
// ============================================

const runQuery = (pool: Pool.Pool<DatabaseConnection>, sql: string) =>
  Effect.scoped(
    Effect.gen(function* () {
      // Get a connection from the pool
      const connection = yield* pool.get
      
      // Use it
      const results = yield* connection.query(sql)
      
      // Connection automatically returned to pool when scope ends
      return results
    })
  )

// ============================================
// 4. Run multiple queries concurrently
// ============================================

const program = Effect.scoped(
  Effect.gen(function* () {
    const pool = yield* makeConnectionPool
    
    yield* Effect.log("Starting concurrent queries...")
    
    // Run 10 queries with only 5 connections
    const queries = Array.from({ length: 10 }, (_, i) =>
Полный SKILL.md на GitHub

Установить effect-patterns-resource-management в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл effect-patterns-resource-management?

Effect-TS patterns for Resource Management. Use when working with resource management in Effect-TS applications.

Как установить скилл effect-patterns-resource-management?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл effect-patterns-resource-management запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить effect-patterns-resource-management с