### new Pool(options) Source: https://context7.com/nds-stack/bun-pool/llms.txt Instantiates a pool with a factory object and optional tuning parameters. The constructor immediately begins warming up `min` connections in the background and starts the idle-reaper interval. Throws `PoolError` synchronously if `min < 0`, `max < 1`, or `min > max`. ```APIDOC ## new Pool(options) — Create a connection pool ### Description Instantiates a pool with a factory object and optional tuning parameters. The constructor immediately begins warming up `min` connections in the background and starts the idle-reaper interval. Throws `PoolError` synchronously if `min < 0`, `max < 1`, or `min > max`. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **options** (object) - Required - Configuration options for the pool. * **min** (number) - Optional - Minimum number of connections to keep alive. * **max** (number) - Optional - Maximum number of concurrent connections. * **acquireTimeoutMs** (number) - Optional - Timeout in milliseconds to reject waiters when the pool is exhausted (default: 5000). * **idleTimeoutMs** (number) - Optional - Timeout in milliseconds to evict idle connections (default: 30000). * **factory** (object) - Required - An object with `create`, `destroy`, and optionally `validate` methods. * **create** (() => T) - Required - Function to create a new connection. * **destroy** ((conn: T) => void) - Required - Function to destroy a connection. * **validate** ((conn: T) => boolean) - Optional - Function to validate a connection's health on checkout. ### Request Example ```typescript import { Pool, PoolError } from "@nds-stack/bun-pool"; import { Database } from "bun:sqlite"; const pool = new Pool({ min: 2, max: 10, acquireTimeoutMs: 3000, idleTimeoutMs: 60_000, factory: { create: () => new Database("app.db"), destroy: (db) => db.close(), validate: (db) => db.raw?.open ?? false, }, }); // Invalid options throw PoolError synchronously try { new Pool({ min: 10, max: 5, factory: { create: () => "x", destroy: () => {} } }); } catch (err) { if (err instanceof PoolError) console.error(err.message); // "min cannot exceed max" } ``` ### Response #### Success Response (200) Returns a new `Pool` instance. #### Response Example None (synchronous constructor) ``` -------------------------------- ### Create a Bun Pool with Options Source: https://context7.com/nds-stack/bun-pool/llms.txt Instantiate a connection pool with a factory object and tuning parameters. The constructor pre-warms connections and starts the idle-reaper. Invalid options will throw a PoolError synchronously. ```typescript import { Pool, PoolError } from "@nds-stack/bun-pool"; import { Database } from "bun:sqlite"; const pool = new Pool({ min: 2, // keep at least 2 connections alive max: 10, // never exceed 10 concurrent connections acquireTimeoutMs: 3000, // reject waiters after 3 s (default: 5000) idleTimeoutMs: 60_000, // evict connections idle > 60 s (default: 30 000) factory: { create: () => new Database("app.db"), destroy: (db) => db.close(), validate: (db) => db.raw?.open ?? false, // health-check on every acquire }, }); // Invalid options throw PoolError synchronously try { new Pool({ min: 10, max: 5, factory: { create: () => "x", destroy: () => {} } }); } catch (err) { if (err instanceof PoolError) console.error(err.message); // "min cannot exceed max" } ``` -------------------------------- ### Using the Pool Source: https://github.com/nds-stack/bun-pool/blob/main/README.md Demonstrates how to acquire a connection from the pool, use it for operations, and release it back to the pool. ```APIDOC ## `pool.withPool(callback)` ### Description Acquires a connection from the pool, executes a callback function with the connection, and ensures the connection is released back to the pool. ### Parameters - **`callback`** (async (db: T) => any) - Required - An asynchronous function that receives a database connection (`db`) and performs operations. ### Usage Example ```typescript await pool.withPool(async (db) => { const result = await db.query("SELECT * FROM users"); // Process result }); ``` ``` -------------------------------- ### Initialize and Use Bun Pool Source: https://github.com/nds-stack/bun-pool/blob/main/README.md Instantiate a new connection pool with custom minimum and maximum connections, and a factory for creating, destroying, and validating connections. Use the pool to acquire and manage connections for database operations. ```typescript import { Pool } from "@nds-stack/bun-pool"; const pool = new Pool({ min: 2, max: 10, factory: { create: () => new Database("app.db"), destroy: (db) => db.close(), validate: (db) => db.raw?.open ?? false, }, }); await pool.withPool(async (db) => { const result = db.query("..."); }); ``` -------------------------------- ### pool.withPool(fn, timeoutMs?) Source: https://context7.com/nds-stack/bun-pool/llms.txt Acquires a connection, passes it to `fn`, awaits the result, and unconditionally releases the connection — equivalent to a try/finally around `acquire`/`release`. This is the preferred API for typical usage because it eliminates the risk of forgetting to call `release()`. ```APIDOC ## pool.withPool(fn, timeoutMs?) ### Description Acquires a connection, passes it to a provided function `fn`, awaits the result of `fn`, and then unconditionally releases the connection. This method ensures that the connection is always released, even if errors occur within `fn`, making it the preferred method for typical usage. ### Method `withPool(fn: (conn: T) => Promise | R, timeoutMs?: number): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **fn** ((conn: T) => Promise | R) - Required - An asynchronous or synchronous function that accepts a connection object and returns a value or a promise of a value. * **timeoutMs** (number) - Optional - Overrides the pool's `acquireTimeoutMs` for this specific call. ### Request Example ```typescript // Single query const user = await pool.withPool(async (db) => { return db.query("SELECT * FROM users WHERE id = ?").get(42); }); console.log(user); // { id: 42, name: "Alice", ... } // Transaction — same connection held for the full duration const inserted = await pool.withPool(async (db) => { db.run("BEGIN"); try { db.run("INSERT INTO orders (user_id, total) VALUES (?, ?)", [42, 99.99]); db.run("UPDATE inventory SET qty = qty - 1 WHERE sku = ?", ["ITEM-7"]); db.run("COMMIT"); return true; } catch (err) { db.run("ROLLBACK"); throw err; } }); console.log("transaction committed:", inserted); // true // Override acquire timeout per-call await pool.withPool(async (db) => { db.run("VACUUM"); }, 10_000); // wait up to 10 s for a free connection ``` ### Response #### Success Response (200) - **R** - The return value of the provided function `fn`. #### Response Example ```json { "example": "result_of_fn" } ``` #### Error Response - **PoolError** - Thrown if acquiring a connection times out or if an error occurs within the provided function `fn`. ``` -------------------------------- ### pool.acquire(timeoutMs?) Source: https://context7.com/nds-stack/bun-pool/llms.txt Returns the first available idle connection, creating a new one if the pool is below `max`, or queuing the caller until a connection is released. If `timeoutMs` is provided it overrides the pool-level `acquireTimeoutMs` for this single call. Rejects with `PoolError` on timeout or if the validated connection fails and no replacement can be made. ```APIDOC ## pool.acquire(timeoutMs?) ### Description Checks out a connection from the pool. Returns the first available idle connection, creating a new one if the pool is below `max`, or queuing the caller until a connection is released. If `timeoutMs` is provided it overrides the pool-level `acquireTimeoutMs` for this single call. Rejects with `PoolError` on timeout or if the validated connection fails and no replacement can be made. ### Method `acquire(timeoutMs?: number): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Manual acquire / release — caller is responsible for always calling release() const db = await pool.acquire(); // uses pool-level acquireTimeoutMs // const db = await pool.acquire(1000); // override: 1 s timeout for this call only try { const rows = db.query("SELECT * FROM users WHERE active = 1").all(); console.log(rows); } catch (err) { console.error("Query failed:", err); } finally { pool.release(db); // MUST be called even on error } ``` ### Response #### Success Response (200) - **conn** (T) - A connection object of type `T`. #### Response Example ```json { "example": "connection_object" } ``` #### Error Response - **PoolError** - Thrown on timeout or if a validated connection fails and no replacement can be made. ``` -------------------------------- ### Pool Constructor Source: https://github.com/nds-stack/bun-pool/blob/main/README.md Initializes a new connection pool with specified options. The pool manages a set of connections to a resource, ensuring efficient reuse and handling of connections. ```APIDOC ## `new Pool(options)` ### Description Creates a new connection pool. ### Parameters #### Options - **`min`** (number) - Optional - Minimum idle connections. Defaults to `0`. - **`max`** (number) - Optional - Maximum total connections. Defaults to `10`. - **`acquireTimeoutMs`** (number) - Optional - Timeout in milliseconds when all connections are busy. Defaults to `5000`. - **`idleTimeoutMs`** (number) - Optional - Timeout in milliseconds after which idle connections are closed. Defaults to `30000`. - **`factory`** (object) - Required - Factory object for managing connections. - **`factory.create`** (() => T) - Required - Function to create a new connection. - **`factory.destroy`** ((T) => void) - Required - Function to destroy a connection. - **`factory.validate`** ((T) => boolean) - Optional - Function to health check a connection on acquire. ``` -------------------------------- ### Scoped Connection Usage with Automatic Release Source: https://context7.com/nds-stack/bun-pool/llms.txt Use `pool.withPool` for acquiring a connection, passing it to a callback function, and ensuring it's always released afterward. This is the preferred method to avoid forgetting to call `release()`. ```typescript // Single query const user = await pool.withPool(async (db) => { return db.query("SELECT * FROM users WHERE id = ?").get(42); }); console.log(user); // { id: 42, name: "Alice", ... } // Transaction — same connection held for the full duration const inserted = await pool.withPool(async (db) => { db.run("BEGIN"); try { db.run("INSERT INTO orders (user_id, total) VALUES (?, ?)", [42, 99.99]); db.run("UPDATE inventory SET qty = qty - 1 WHERE sku = ?", ["ITEM-7"]); db.run("COMMIT"); return true; } catch (err) { db.run("ROLLBACK"); throw err; } }); console.log("transaction committed:", inserted); // true // Override acquire timeout per-call await pool.withPool(async (db) => { db.run("VACUUM"); }, 10_000); // wait up to 10 s for a free connection ``` -------------------------------- ### pool.release(conn) Source: https://context7.com/nds-stack/bun-pool/llms.txt Marks the connection as idle so it can be re-used by the next caller. If one or more callers are waiting (`pool.pending > 0`) the connection is handed off directly to the first waiter without going back to the idle list. ```APIDOC ## pool.release(conn) ### Description Returns a connection to the pool, marking it as idle for re-use. If other callers are waiting, the connection is handed off directly to the next waiter. ### Method `release(conn: T): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **conn** (T) - Required - The connection object to release. ### Request Example ```typescript const db = await pool.acquire(); try { db.run("INSERT INTO events (name) VALUES (?)", ["user.login"]); } finally { pool.release(db); // safe to call even if acquire() succeeded but usage threw } console.log("idle after release:", pool.available); // 1 ``` ### Response None #### Response Example None ``` -------------------------------- ### Monitoring Pool State Properties Source: https://context7.com/nds-stack/bun-pool/llms.txt Exposes read-only getters for live pool state: `size` (total connections), `available` (idle connections), `pending` (callers waiting), and `created` (cumulative connections). Useful for monitoring, logging, or adaptive back-pressure. ```typescript const pool = new Pool({ min: 0, max: 3, factory: { create: () => "conn", destroy: () => {} }, }); const c1 = await pool.acquire(); const c2 = await pool.acquire(); console.log(pool.size); // 2 — total connections in pool (idle + busy) console.log(pool.available); // 0 — idle connections ready to check out console.log(pool.pending); // 0 — callers waiting for a free connection console.log(pool.created); // 2 — cumulative connections ever created // Saturate the pool pool.acquire(); // queued — pool is full (max: 3 not yet reached) pool.acquire(); pool.acquire(); // this one will queue console.log(pool.pending); // 1 pool.release(c1); pool.release(c2); ``` -------------------------------- ### Pool State Properties Source: https://context7.com/nds-stack/bun-pool/llms.txt Read-only getters that expose the live state of the pool for monitoring and adaptive logic. ```APIDOC ## Pool State Properties ### Description Four read-only getters expose the live state of the pool for monitoring, logging, or adaptive back-pressure logic. ### Properties - **`size`** (number): Total number of connections currently in the pool (idle + busy). - **`available`** (number): Number of idle connections ready to be checked out. - **`pending`** (number): Number of callers currently waiting for a free connection. - **`created`** (number): Cumulative number of connections ever created by the pool. ### Usage Example ```typescript console.log(pool.size); console.log(pool.available); console.log(pool.pending); console.log(pool.created); ``` ``` -------------------------------- ### Graceful Shutdown with pool.drain() Source: https://context7.com/nds-stack/bun-pool/llms.txt Use `pool.drain()` to destroy all connections and stop the pool. Awaiting `drain()` ensures all destroy callbacks have settled before the process exits or the pool is garbage-collected. This is useful for graceful shutdown procedures. ```typescript import { Pool } from "@nds-stack/bun-pool"; import { Database } from "bun:sqlite"; const pool = new Pool({ min: 2, max: 5, factory: { create: () => new Database("app.db"), destroy: (db) => db.close(), }, }); // ... application lifetime ... // Graceful shutdown process.on("SIGTERM", async () => { console.log("Shutting down — draining pool..."); await pool.drain(); console.log("Pool drained. Exiting."); process.exit(0); }); ``` -------------------------------- ### Acquire and Release a Connection Manually Source: https://context7.com/nds-stack/bun-pool/llms.txt Check out a connection from the pool, use it, and then release it. The caller is responsible for always calling release(), even if errors occur during usage. An optional timeout can override the pool-level acquire timeout. ```typescript // Manual acquire / release — caller is responsible for always calling release() const db = await pool.acquire(); // uses pool-level acquireTimeoutMs // const db = await pool.acquire(1000); // override: 1 s timeout for this call only try { const rows = db.query("SELECT * FROM users WHERE active = 1").all(); console.log(rows); } catch (err) { console.error("Query failed:", err); } finally { pool.release(db); // MUST be called even on error } ``` ```typescript const db = await pool.acquire(); try { db.run("INSERT INTO events (name) VALUES (?)", ["user.login"]); } finally { pool.release(db); // safe to call even if acquire() succeeded but usage threw } console.log("idle after release:", pool.available); // 1 ``` -------------------------------- ### Handling Pool Errors with PoolError Source: https://context7.com/nds-stack/bun-pool/llms.txt Pool-level failures like invalid configuration or acquire timeouts throw `PoolError`, a subclass of `Error`. Use `instanceof PoolError` to distinguish these from application errors and handle them appropriately. ```typescript import { Pool, PoolError } from "@nds-stack/bun-pool"; const pool = new Pool({ min: 0, max: 1, acquireTimeoutMs: 50, factory: { create: () => "conn", destroy: () => {} }, }); const c = await pool.acquire(); // pool is now saturated try { await pool.acquire(10); // 10 ms custom timeout — will expire } catch (err) { if (err instanceof PoolError) { console.error(err.name); // "PoolError" console.error(err.message); // "Pool acquire timed out" } else { throw err; // re-throw unexpected errors } } finally { pool.release(c); await pool.drain(); } ``` -------------------------------- ### PoolError Class Source: https://context7.com/nds-stack/bun-pool/llms.txt A typed error class for pool-level failures, such as invalid configuration or acquire timeouts. ```APIDOC ## PoolError ### Description All pool-level failures (invalid configuration, acquire timeout) throw or reject with `PoolError` — a subclass of `Error` with `name === "PoolError"`. Use `instanceof` checks to distinguish pool errors from application errors. ### Usage ```typescript import { Pool, PoolError } from "@nds-stack/bun-pool"; try { await pool.acquire(10); // Example of a call that might time out } catch (err) { if (err instanceof PoolError) { console.error(err.name); // "PoolError" console.error(err.message); } else { throw err; // re-throw unexpected errors } } ``` ``` -------------------------------- ### pool.drain() Source: https://context7.com/nds-stack/bun-pool/llms.txt Destroys all connections in the pool and stops the idle-reaper interval. Awaiting this method ensures all destroy callbacks have settled. ```APIDOC ## pool.drain() ### Description Clears the idle-reaper interval, removes every connection from the pool (regardless of idle/busy state), and calls `factory.destroy()` on each one concurrently. Awaiting `drain()` ensures all destroy callbacks have settled before the process exits or the pool is garbage-collected. ### Method `pool.drain()` ### Parameters None ### Request Example ```typescript await pool.drain(); ``` ### Response None (This is a method that performs an action and does not return a value directly, but its completion indicates resources are cleaned up.) ### Error Handling Errors during the destruction of connections will be thrown. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.