acquire

suspend fun acquire(leaf: GroupId, reservation: Long = defaultReservation): SlotOutcome

Suspend until fair share grants leaf a slot, and answer SlotOutcome.Granted with its lease, or SlotOutcome.Refused when no lease can end at leaf as the tree stands now. The caller holds a granted slot until it calls complete or cancel.

Cancelling the caller while it waits, or after its grant was made but before it resumed, frees the slot: the lease is cancelled with nothing charged.

Parameters

reservation

the cost the caller expects the work to take. The slot is picked at the engine's default whatever it is. Below the default, the lease holds reservation: the rest is handed back at the grant with LocalHeddle.shrink. Above it, the lease holds reservation when the engine can extend it that far; otherwise it holds the default, and the rest arrives as an overrun at complete.

Throws

when reservation is not in 1..LocalHeddle.MAX_RESERVATION, before anything waits.

the pool's failure, when it fails while the caller is queued: whatever the engine threw, or an IllegalStateException for an answer the engine's contract rules out (see Failures, above).

Samples

val farm = Topology("farm", listOf(Topology.Lane("web", Weight.of(3)), Topology.Lane("mobile")))
val web = farm.groupId("web")
val mobile = farm.groupId("mobile")
val (heddle, booted) = LocalHeddle.fromTopology(farm, LocalPolicy(defaultReservation = 3L), epoch = 0L)
check(booted.refusals.isEmpty())
// Two agents, and one unit of cost is one minute on an agent. The pool owns the engine now.
val pool = FairSharePool(heddle, slots = 2, TimeSource.Monotonic, costUnit = 1.minutes)

// Waits until fair share grants web a slot: at once, on an idle farm.
val build = pool.acquire(web)
check(build is SlotOutcome.Granted)
// The build took five minutes against the default estimate of three: two are overrun.
check(pool.complete(build.lease.id, actualCost = 5L) == LeaseOutcome.Done(charged = 5L, overrun = 2L, unrecorded = 0L))

// A name the farm does not declare is refused, never left waiting.
check(pool.acquire(GroupId("nightly")) is SlotOutcome.Refused)

val next = pool.acquire(mobile)
check(next is SlotOutcome.Granted)
pool.cancel(next.lease.id)