apollographql / apollographql/graphql-subscriptions

Expose a way to wait for async iterator to subscribe

Open
#252 1 comment 1 reaction 0 assignees View on GitHub
Dominant language
TypeScript
Stars
1.6k
Forks
129
PR merge metrics
No merged PRs in 30d

Description

In the current implementation, `PubSubAsyncIterator` registers its subscriptions on the very first call to `next`, and goes on to wait for the first event **before resolving**. As such, a user of the iterator has no way of determining that the iterator has properly subscribed before it receives a first event.

**This is a problem because some events can be published in the time it takes the iterator to subscribe.**

Example use case: I have a subscription that returns a list of posts initially, then a new post every so often. Right now, I have no way of knowing when I can safely yield my list of initial posts without possibly missing posts that were created while my iterator was subscribing. The flow is:

1. create iterator
2. yield initial posts
3. yield next from iterator
1. iterator subscribes
2. yield next from iterator
4. yield rest from iterator

Between 2. and 3.i., if any new posts come in, they will be entirely missed by my subscription. However, I have no way of knowing when 3.i. occurs without also waiting for 3.ii., which might happen at any point in the future.

The flow I'm looking for is:

1. create iterator
2. iterator subscribes
3. yield initial posts
4. yield rest from iterator

I see two ways to fix this issue:
* Make `PubSubEngine.asyncIterator` async. Instead of `pubsub.asyncIterator`, it would be `await pubsub.asyncIterator`. To avoid breaking changes, it could be called something else (e.g. `PubSubEngine.subscribedAsyncIterator` or whatever).
* Expose a `subscribe: () => Promise` method on `PubSubAsyncIterator` that resolves when the async iterator has fully subscribed.

Contributor guide

Open the contributing guide

Research direction

Start by tracing PubSubAsyncIterator and the PubSubEngine.asyncIterator entry point, especially the first next call where subscriptions are registered. The issue's requested behavior is complete when callers can know that subscription setup has finished before yielding initial data, without missing events; the exact API choice remains open between an async factory and a subscribe method.

Written by the indexing model from the issue text.

Assessment

Tech stack
graphql, typescript
Domain
api, backend-api-design
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.