Core operations for acquiring, releasing, and destroying pooled resources with optional priority support and automated resource management patterns.
Acquires a resource from the pool, optionally specifying priority for queuing.
/**
* Acquires a resource from the pool
* @param priority - Optional priority level (0 = highest priority)
* @returns Promise that resolves to an available resource
*/
acquire(priority?: number): Promise<any>;Usage Examples:
// Basic resource acquisition
const resource = await pool.acquire();
try {
// Use the resource
await resource.doWork();
} finally {
// Always release the resource
await pool.release(resource);
}
// High-priority acquisition
const urgentResource = await pool.acquire(0);
try {
await urgentResource.doUrgentWork();
} finally {
await pool.release(urgentResource);
}
// Handle acquisition timeout
try {
const resource = await pool.acquire();
// Use resource
} catch (error) {
if (error.name === 'TimeoutError') {
console.log('Pool acquisition timed out');
}
}Returns a resource to the pool for reuse by other consumers.
/**
* Returns a resource to the pool
* @param resource - The resource to return
* @returns Promise that resolves when the resource is returned
*/
release(resource: any): Promise<void>;Usage Examples:
// Standard release pattern
const resource = await pool.acquire();
try {
await resource.performOperation();
} finally {
await pool.release(resource);
}
// Conditional release with error handling
const resource = await pool.acquire();
try {
const result = await resource.riskyOperation();
await pool.release(resource);
return result;
} catch (error) {
// Destroy corrupted resource instead of releasing
await pool.destroy(resource);
throw error;
}Destroys a resource instead of returning it to the pool, useful for corrupted or invalid resources.
/**
* Destroys a resource instead of returning it to the pool
* @param resource - The resource to destroy
* @returns Promise that resolves when the resource is destroyed
*/
destroy(resource: any): Promise<void>;Usage Examples:
// Destroy corrupted resource
const resource = await pool.acquire();
try {
await resource.performOperation();
} catch (error) {
if (error.code === 'CONNECTION_LOST') {
// Don't return corrupted resource to pool
await pool.destroy(resource);
} else {
await pool.release(resource);
}
throw error;
}
// Proactive resource cleanup
const resource = await pool.acquire();
if (resource.needsRefresh()) {
await pool.destroy(resource); // Will create a new one
const freshResource = await pool.acquire();
// Use fresh resource
}Simplified resource usage pattern that automatically handles acquisition and release.
/**
* Executes a function with an acquired resource, automatically handling release/destroy
* @param fn - Function to execute with the resource
* @param priority - Optional priority for resource acquisition
* @returns Promise that resolves to the function's return value
*/
use(fn: (resource: any) => Promise<any>, priority?: number): Promise<any>;Usage Examples:
// Automatic resource management
const result = await pool.use(async (resource) => {
return await resource.performQuery('SELECT * FROM users');
});
// With priority
const urgentResult = await pool.use(async (resource) => {
return await resource.performUrgentTask();
}, 0);
// Error handling - resource is automatically destroyed on error
try {
const result = await pool.use(async (resource) => {
if (resource.isCorrupted()) {
throw new Error('Resource corrupted');
}
return await resource.doWork();
});
} catch (error) {
// Resource was automatically destroyed due to error
console.log('Operation failed:', error.message);
}
// Multiple operations with the same resource
const results = await pool.use(async (resource) => {
const data1 = await resource.query('SELECT * FROM table1');
const data2 = await resource.query('SELECT * FROM table2');
return { data1, data2 };
});Checks if a resource is currently borrowed from the pool.
/**
* Checks if a resource is currently borrowed from the pool
* @param resource - The resource to check
* @returns true if the resource is currently borrowed, false otherwise
*/
isBorrowedResource(resource: any): boolean;Usage Examples:
// Check resource ownership
const resource = await pool.acquire();
console.log(pool.isBorrowedResource(resource)); // true
await pool.release(resource);
console.log(pool.isBorrowedResource(resource)); // false
// Validate before operations
function safeOperation(resource) {
if (!pool.isBorrowedResource(resource)) {
throw new Error('Resource not borrowed from this pool');
}
return resource.doOperation();
}
// Resource tracking
const activeResources = new Set();
const resource = await pool.acquire();
if (pool.isBorrowedResource(resource)) {
activeResources.add(resource);
}When no resources are available, requests are queued by priority level.
Usage Examples:
// Create pool with priority support
const pool = genericPool.createPool(factory, {
max: 2,
priorityRange: 3 // 0=high, 1=medium, 2=low
});
// High priority request (processed first)
const highPriorityPromise = pool.acquire(0);
// Low priority request (processed last)
const lowPriorityPromise = pool.acquire(2);
// No priority specified (defaults to lowest priority)
const defaultPriorityPromise = pool.acquire();
// Priority with use() method
const result = await pool.use(async (resource) => {
return await resource.priorityTask();
}, 0); // High priorityWhen testOnBorrow or testOnReturn is enabled, validation is automatically performed.
Usage Examples:
// Pool with validation enabled
const pool = genericPool.createPool({
create: async () => new DatabaseConnection(),
destroy: async (conn) => conn.close(),
validate: async (conn) => conn.ping()
}, {
testOnBorrow: true,
testOnReturn: true
});
// Validation happens automatically
const resource = await pool.acquire(); // validate() called before return
try {
await resource.query('SELECT 1');
} finally {
await pool.release(resource); // validate() called before accepting back
}