outbound_ids.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /**
  2. * Bounded FIFO set of outbound message IDs.
  3. *
  4. * Used by the WhatsApp bridge to distinguish "echo of our own /send" from
  5. * "owner-typed message on the linked device" when forwarding `fromMe`
  6. * inbound events back to the Python adapter.
  7. *
  8. * Eviction drops the oldest insertion-order entry when the cap is exceeded.
  9. * Re-remembering an existing id is a no-op for ordering (not LRU refresh).
  10. *
  11. * Heuristic limitation (intentional, documented for future debugging):
  12. * the set is in-memory only. On bridge restart it is empty, so for the
  13. * brief window between restart and the first new outbound, any in-flight
  14. * delivery receipts of pre-restart sends would be classified as
  15. * owner-typed. The TTL on owner-driven plugin actions (e.g. handover
  16. * sliding TTL) bounds blast radius; persisting would not be worth the
  17. * extra complexity / disk churn.
  18. */
  19. export function createOutboundIdTracker(maxSize = 512) {
  20. if (!Number.isInteger(maxSize) || maxSize < 1) {
  21. throw new RangeError('createOutboundIdTracker: maxSize must be a positive integer');
  22. }
  23. const ids = new Set();
  24. function remember(id) {
  25. if (!id) return;
  26. ids.add(id);
  27. while (ids.size > maxSize) {
  28. // Set iteration order is insertion order, so values().next() is the
  29. // oldest entry — drop it to keep memory flat under sustained sending.
  30. ids.delete(ids.values().next().value);
  31. }
  32. }
  33. function has(id) {
  34. return Boolean(id) && ids.has(id);
  35. }
  36. function size() {
  37. return ids.size;
  38. }
  39. return { remember, has, size };
  40. }