@@ -114,7 +114,7 @@ func NewClient(apiKey string, options ...Option) *Client {
114114 }
115115 if c .config .useRealtime {
116116 // Poll until we get the environment once
117- go c .pollEnvironment (c .ctxLocalEval , false )
117+ go c .pollThenStartRealtime (c .ctxLocalEval )
118118 }
119119
120120 }
@@ -380,6 +380,40 @@ func (c *Client) pollEnvironment(ctx context.Context, pollForever bool) {
380380 }
381381}
382382
383+ func (c * Client ) pollThenStartRealtime (ctx context.Context ) {
384+ b := newBackoff ()
385+ update := func () {
386+ c .log .Debug ("polling environment" )
387+ ctx , cancel := context .WithTimeout (ctx , c .config .envRefreshInterval )
388+ defer cancel ()
389+ err := c .UpdateEnvironment (ctx )
390+ if err != nil {
391+ c .log .Error ("failed to update environment" , "error" , err )
392+ b .wait (ctx )
393+ }
394+ }
395+ update ()
396+ defer func () {
397+ c .log .Info ("initial polling stopped" )
398+ }()
399+ for {
400+ select {
401+ case <- ctx .Done ():
402+ return
403+ default :
404+ // If environment was fetched, start realtime and finish
405+ if env , ok := c .environment .Load ().(* environments.EnvironmentModel ); ok {
406+ streamURL := c .config .realtimeBaseUrl + "sse/environments/" + env .APIKey + "/stream"
407+ c .log .Debug ("environment initialised, starting realtime updates" )
408+ c .realtime = newRealtime (c , ctx , streamURL , env .UpdatedAt )
409+ go c .realtime .start ()
410+ return
411+ }
412+ update ()
413+ }
414+ }
415+ }
416+
383417func (c * Client ) UpdateEnvironment (ctx context.Context ) error {
384418 var env environments.EnvironmentModel
385419 resp , err := c .client .NewRequest ().
@@ -412,14 +446,7 @@ func (c *Client) UpdateEnvironment(ctx context.Context) error {
412446 c .identitiesWithOverrides .Store (identitiesWithOverrides )
413447
414448 c .log .Info ("environment updated" , "environment" , env .APIKey )
415- c .once .Do (func () {
416- if c .config .useRealtime && c .realtime == nil {
417- streamURL := c .config .realtimeBaseUrl + "sse/environments/" + env .APIKey + "/stream"
418- c .realtime = newRealtime (c , c .ctxLocalEval , streamURL , env .UpdatedAt )
419- c .log .Debug ("environment initialised, starting realtime updates" )
420- go c .realtime .start ()
421- }
422- })
449+
423450 return nil
424451}
425452
0 commit comments