matiasanaya/go-graphql-subscription-example

Qn: about subscription

bsr203 opened this issue · 5 comments

Hi @matiasanaya

thank you for the PR to support subscription and this example. I have couple of questions

  1. Can you please explain why there are two select statements inside and functions of each?
  2. What is the lifetime of a subscriber? Does it terminate with a ctx.Done() call from the framework when a websocket connection is terminated?

thanks,
bsr.
cc @pavelnikolov

Hi @bsr203, can you please clarify question 1? Are you referring to this and this select statements?

Re: lifetime of a subscriber, the framework cancels the context when the web socket connection is terminated or if the client sends a stop command. When that happens this code triggers a remove of the subscriber from the list and prevents further updates. If you are interested in how the framework works you can check out this file which manages all of the websocket events.

I hope this helps :)

Hi @matiasanaya
I can't believe I forgot to link the code :-) .I mean the two select statements in this go routine. Yup, you guessed it right :-)
Though I been using go a while, I haven't tried much of concurrency patterns. I wonder when the first

select {
	case <-s.stop:
		unsubscribe <- id
		return
	default:
}

select is needed as unsubscribe is also handled in the second when s.stop is received!

thanks again for your help.
Cheers

If/when the subscriptions PR gets merged I’d like to add some more examples.

@bsr203 in select statements If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. So my understanding is that in the second select there'd be a random choosing between "unsubscribing" and "event sending" if the context has been canceled and the events channel is free. I want to force an unsubscribe in that case and thus I've added the first select. This first select guarantees that at most one event is sent to the client after the context has been canceled.

Also note that I'm no expert but I've seen this pattern elsewhere. Check this stackoverflow answer for more details.

I hope this helps :)

@matiasanaya Thank you for taking the time to explain the code. I will spend time on the SO answer as other answers claims the accepted one wont work. I Need to learn the fundamentals and try out. Thanks agin for your time and help. Cheers. bsr.