Skip to content

fix: pub/sub delivery + Redis auto-subscriber - #108

Merged
koistya merged 7 commits into
mainfrom
dev
Jan 20, 2026
Merged

koistya merged 7 commits into
mainfrom
dev

Conversation

@koistya

@koistya koistya commented Jan 19, 2026 •

Copy link
Copy Markdown
Member

Fixes #106

Summary

  • Fix local pub/sub delivery for memory adapter (messages now work across browser tabs)
  • Add Redis auto-subscriber via duplicate() for simplified setup
  • Handle excludeSelf universally at plugin layer

Problem

When @isak102 reported that messages weren't showing up between browser tabs in the chat example, the root cause was that the memory adapter wasn't delivering messages to local subscribers. Additionally, Redis setup required verbose boilerplate with two connections.

Solution

1. Local Delivery for Memory Adapter

The pubsub plugin now handles local delivery for adapters without broker ingestion:

// Plugin delivers locally for non-broker adapters
if (result.ok && typeof adapter.start !== "function") {
  await deliverLocally(envelope);
}

2. Redis Auto-Subscriber

redisPubSub(redis) now auto-creates a subscriber via duplicate():

// Before (verbose)
const publisher = createClient({ url: REDIS_URL });
const subscriber = createClient({ url: REDIS_URL });
await Promise.all([publisher.connect(), subscriber.connect()]);
const adapter = redisPubSub(publisher, { subscriber });

// After (simple)
const redis = createClient({ url: REDIS_URL });
await redis.connect();
const adapter = redisPubSub(redis); // Auto-creates subscriber
await router.pubsub.init();

Changes

  • @ws-kit/pubsub: Local delivery for non-broker adapters, excludeSelf filtering at plugin layer
  • @ws-kit/memory: Works correctly with local delivery
  • @ws-kit/redis: Auto-subscriber via duplicate(), fail-fast validation, connection leak fixes
  • @ws-kit/bun: Returns UNSUPPORTED for excludeSelf (Bun's native pub/sub limitation)
  • @ws-kit/core: Fixed client ID assignment order for pub/sub plugins

Adapter Capabilities

Adapter Local Delivery excludeSelf Broker
memory ✅ via plugin ✅ via plugin ❌
redis ✅ via broker ✅ via plugin ✅ auto-subscriber
bun ✅ native ❌ unsupported ✅ native

Test Plan

  • bun test packages/pubsub — local delivery tests (420+ lines)
  • bun test packages/redis — auto-subscriber, fail-fast, cleanup tests
  • bun test packages/memory — memory adapter tests
  • bun test packages/bun — Bun adapter tests
  • Manual: two browser tabs, same room, messages visible across tabs

- Add deliverLocally() call after adapter.publish() for adapters without start()
- Fix wire format: JSON.stringify envelope with proper shape stripping
- Strip internal excludeClientId from wire meta before serialization
- Handle JSON serialization errors gracefully (BigInt, circular refs)
- Fix lifecycle ordering: getOrCreateClientId() runs before handleInternalOpen()
- Update memory adapter to accept excludeSelf (plugin handles filtering)
- Add comprehensive local-delivery.test.ts with 12 test cases
- Update docs to reflect excludeSelf is now supported

Closes #106
The pubsub plugin now handles excludeSelf universally:
- Plugin adds excludeClientId to envelope.meta when excludeSelf is true
- deliverLocally() filters out the sender during fan-out
- Distributed adapters (Redis, Bun) pass envelope through to broker
- Consumer callback (deliverLocally) handles filtering on delivery

Changes:
- Remove excludeSelf rejection from Redis and Bun adapters
- Update plugin header to document excludeClientId filtering
- Update types.ts to remove "not yet implemented" comment
- Update docs (api-reference.md, ADR-019, pubsub README)
- Fix superficial test assertions to expect success
Bun's server.publish() broadcasts directly with no way to intercept delivery
or enumerate subscribers. This makes excludeSelf architecturally impossible.

Changes:
- Bun adapter returns UNSUPPORTED for excludeSelf with clear explanation
- Strip internal fields (excludeClientId) from wire message defensively
- Update Bun adapter docs to explain the limitation
- Update pubsub.md spec to document adapter-specific behavior
- Update api-reference.md with adapter support notes
- Update pubsub README with Bun limitation note
- Update context-methods.md spec with adapter support note
- Update ADR-030 with adapter support note
- Add regression test for Bun excludeSelf returning UNSUPPORTED
@codecov

codecov Bot commented Jan 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.62162% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.54%. Comparing base (a727c4c) to head (1c32e49).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
packages/redis/src/pubsub.ts 93.97% 5 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #108      +/-   ##
==========================================
+ Coverage   82.17%   82.54%   +0.37%     
==========================================
  Files          78       79       +1     
  Lines        6249     6399     +150     
==========================================
+ Hits         5135     5282     +147     
- Misses       1114     1117       +3     
Files with missing lines Coverage Δ
packages/bun/src/pubsub.ts 100.00% <100.00%> (ø)
packages/core/src/core/router.ts 99.79% <100.00%> (ø)
packages/memory/src/pubsub.ts 97.97% <100.00%> (-0.10%) ⬇️
packages/pubsub/src/plugin.ts 90.39% <100.00%> (+3.65%) ⬆️
packages/redis/src/pubsub.ts 93.75% <93.97%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

redisPubSub(redis) now auto-creates a subscriber connection via
duplicate() during router.pubsub.init(), eliminating the need to
manually create two connections.

### Changes
- Auto-duplicate subscriber when client supports duplicate()
- Fail-fast validation when subscriber === publisher
- start() conditional based on subscriber capability
- Fixed connection leak on init failure
- Fixed sync exception handling (separate decode vs callback errors)
- Export type: PubSubDriver → PubSubAdapter

### Docs
- Updated all examples to simplified pattern
- Aligned migration guide with unified adapter architecture
- Fixed missing imports in code snippets
@koistya koistya changed the title fix: local pub/sub delivery for memory adapter fix: pub/sub delivery + Redis auto-subscriber Jan 20, 2026
@koistya
koistya merged commit 16e8f8d into main Jan 20, 2026
9 checks passed
@koistya
koistya deleted the dev branch January 20, 2026 00:54
@github-actions github-actions Bot mentioned this pull request Jan 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

The example bun-zod-chat does not work

1 participant