adapter_slash_lane.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. """Per-session handoff order for Slack slash commands.
  2. Bolt runs slash callbacks concurrently and a slash awaits its name lookups before the handoff, so
  3. a cold ``users.info`` on an earlier slash would let a later one reach the gateway first (two
  4. ``/queue`` land in the FIFO swapped). A slash reserves its session's slot before any lookup and
  5. hands over only after the slash ahead of it returned from ``handle_message``.
  6. """
  7. from __future__ import annotations
  8. import asyncio
  9. class SlashHandoffLanes:
  10. def __init__(self) -> None:
  11. # Session key -> future of the newest slash still on its way through handle_message.
  12. self.tails: dict[str, asyncio.Future[None]] = {}
  13. def reserve(self, key: str) -> tuple[asyncio.Future[None] | None, asyncio.Future[None]]:
  14. """Take the session's next slot; returns (slot ahead, this slot). Call before any await."""
  15. ahead = self.tails.get(key)
  16. self.tails[key] = handed_off = asyncio.get_running_loop().create_future()
  17. return ahead, handed_off
  18. def release(self, key: str | None, ahead: asyncio.Future | None, handed_off: asyncio.Future | None) -> None:
  19. """Open the slot once this slash is done. Cancelled while waiting: the slash behind it
  20. still waits for the one ahead, or it reaches the gateway before unfinished earlier work."""
  21. if ahead is not None and not ahead.done():
  22. ahead.add_done_callback(lambda _f: self._open(key, handed_off))
  23. else:
  24. self._open(key, handed_off)
  25. def _open(self, key: str | None, handed_off: asyncio.Future | None) -> None:
  26. if handed_off is None or handed_off.done():
  27. return
  28. handed_off.set_result(None)
  29. if self.tails.get(key) is handed_off:
  30. del self.tails[key]