chore(pockethost): rename PromiseAllocator to ResourceAllocator

This commit is contained in:
Ben Allfree 2024-06-07 03:08:24 -07:00
parent d34a2f62b5
commit c821258dea
4 changed files with 19 additions and 30 deletions

View File

@ -9,6 +9,7 @@
"czvf",
"daos",
"Darkmode",
"Deallocator",
"devcert",
"Dockerized",
"dockerode",

View File

@ -1,12 +1,13 @@
export type Deallocator = () => void
export type Allocator<T> = {
free: (item: T) => void
alloc: () => Promise<[T, () => void]>
alloc: () => [T, Deallocator]
}
export type PortReleaser = () => void
export function PromiseAllocator<T>(
export function ResourceAllocator<T>(
initialPoolSize: number,
initializer: () => Promise<T>,
initializer: () => T,
): Allocator<T> {
// Available queue to hold resolved items of type T
const available: T[] = []
@ -18,27 +19,17 @@ export function PromiseAllocator<T>(
// Pre-populate the available queue with initial items
for (let i = 0; i < initialPoolSize; i++) {
initializer().then((item) => {
available.push(item)
})
}
const alloc = async (): Promise<[T, PortReleaser]> => {
// If an item is available, return it along with the free function
if (available.length > 0) {
const item = available.pop()
if (item) {
return [item, () => free(item)]
}
}
// If no items are available, wait for a new initializer call and return it
const newItem = await initializer()
return [newItem, () => free(newItem)]
available.push(initializer())
}
return {
alloc,
alloc() {
if (available.length === 0) {
available.push(initializer())
}
const newItem = initializer()
return [newItem, () => free(newItem)]
},
free,
}
}

View File

@ -251,7 +251,8 @@ export const instanceService = mkSingleton(
Obtain empty port
*/
dbg(`Obtaining port`)
const [newPort, releasePort] = await PortService().alloc()
const [newPortPromise, releasePort] = PortService().alloc()
const newPort = await newPortPromise
shutdownManager.add(() => {
dbg(`shut down: releasing port`)
releasePort()

View File

@ -1,10 +1,6 @@
import getPort from 'get-port'
import {
INITIAL_PORT_POOL_SIZE,
PromiseAllocator,
mergeConfig,
mkSingleton,
} from '../../core'
import { INITIAL_PORT_POOL_SIZE, mergeConfig, mkSingleton } from '../../core'
import { ResourceAllocator } from '../common/ResourceAllocator'
export type Config = { maxPorts: number }
export const PortService = mkSingleton((config: Partial<Config> = {}) => {
@ -12,5 +8,5 @@ export const PortService = mkSingleton((config: Partial<Config> = {}) => {
{ maxPorts: INITIAL_PORT_POOL_SIZE() },
config,
)
return PromiseAllocator(maxPorts, getPort)
return ResourceAllocator(maxPorts, getPort)
})