|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import itertools |
| 5 | +import logging |
| 6 | + |
| 7 | +from temporalio.worker import ( |
| 8 | + CustomSlotSupplier, |
| 9 | + SlotMarkUsedContext, |
| 10 | + SlotPermit, |
| 11 | + SlotReleaseContext, |
| 12 | + SlotReserveContext, |
| 13 | +) |
| 14 | + |
| 15 | +from custom_worker_tuner.downstream import Downstream |
| 16 | + |
| 17 | +logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | +# A single global counter so every slot grant gets a unique short ID we |
| 20 | +# can grep for. itertools.count is atomic under CPython's GIL. |
| 21 | +_slot_id_gen = itertools.count(1) |
| 22 | + |
| 23 | + |
| 24 | +class _Permit(SlotPermit): |
| 25 | + """SlotPermit subclass that just carries a sequential id for logs.""" |
| 26 | + |
| 27 | + def __init__(self, slot_id: int) -> None: |
| 28 | + super().__init__() |
| 29 | + self.slot_id = slot_id |
| 30 | + |
| 31 | + |
| 32 | +class DownstreamAwareSupplier(CustomSlotSupplier): |
| 33 | + def __init__(self, downstream: Downstream, poll_interval_ms: int = 100) -> None: |
| 34 | + self.downstream = downstream |
| 35 | + self.poll_interval_ms = poll_interval_ms |
| 36 | + logger.info( |
| 37 | + "DownstreamAwareSupplier ready: downstream=%s poll_interval_ms=%d", |
| 38 | + downstream.name, |
| 39 | + poll_interval_ms, |
| 40 | + ) |
| 41 | + |
| 42 | + async def reserve_slot(self, ctx: SlotReserveContext) -> SlotPermit: |
| 43 | + """block downstream until it has capacity to get incremented and then grant a slot.""" |
| 44 | + slot_id = next(_slot_id_gen) |
| 45 | + while not self.downstream.increment(): |
| 46 | + await asyncio.sleep(self.poll_interval_ms / 1000.0) |
| 47 | + self._log("reserve", slot_id, "ready to poll") |
| 48 | + return _Permit(slot_id) |
| 49 | + |
| 50 | + def try_reserve_slot(self, ctx: SlotReserveContext) -> SlotPermit | None: |
| 51 | + """Eager path: can i run this activity right now?""" |
| 52 | + if self.downstream.increment(): |
| 53 | + slot_id = next(_slot_id_gen) |
| 54 | + self._log("reserve", slot_id, "eager dispatch") |
| 55 | + return _Permit(slot_id) |
| 56 | + return None |
| 57 | + |
| 58 | + def mark_slot_used(self, ctx: SlotMarkUsedContext) -> None: |
| 59 | + """A task arrived for a reserved slot""" |
| 60 | + slot_id = getattr(ctx.permit, "slot_id", "?") |
| 61 | + self._log("used", slot_id, "activity running") |
| 62 | + |
| 63 | + def release_slot(self, ctx: SlotReleaseContext) -> None: |
| 64 | + """Return the slot to the downstream.""" |
| 65 | + slot_id = getattr(ctx.permit, "slot_id", "?") |
| 66 | + # ctx.slot_info is None when the poll timed out — the slot was |
| 67 | + # reserved but no task ever arrived. Surface it so it's not |
| 68 | + # confused with a normal completion. |
| 69 | + detail = "no task arrived" if ctx.slot_info is None else "activity done" |
| 70 | + self.downstream.decrement() |
| 71 | + self._log("release", slot_id, detail) |
| 72 | + |
| 73 | + # ----- internals ----- |
| 74 | + |
| 75 | + def _log(self, event: str, slot_id, note: str) -> None: |
| 76 | + """Emit one line in the column format:: |
| 77 | +
|
| 78 | + EVENT SLOT COUNT NOTE |
| 79 | + reserve #209 10/10 |
| 80 | + wait #210 10/10 full |
| 81 | + """ |
| 82 | + count = f"{self.downstream.currently_connected}/{self.downstream.allowed_connections}" |
| 83 | + logger.info(f"{event:<8} #{slot_id!s:<4} {count:>5} {note}") |
0 commit comments