@@ -123,6 +123,15 @@ internal class ZitiContextImpl(internal val id: Identity, enabled: Boolean) : Zi
123123 }
124124 }
125125
126+ launch {
127+ accessToken.filterNotNull().collect { token ->
128+ controller.setAccessToken(token)
129+ channels.forEach { (_, channel) ->
130+ channel.updateToken(token)
131+ }
132+ }
133+ }
134+
126135 start()
127136 }
128137
@@ -360,22 +369,30 @@ internal class ZitiContextImpl(internal val id: Identity, enabled: Boolean) : Zi
360369 }
361370
362371 private fun maintainApiSession (authenticator : ZitiAuthenticator ) = async {
372+ var retries = 5
363373 while (true ) {
364- val token = accessToken.value
365-
366- if (token == null ) break
367-
374+ val token = accessToken.value ? : break
368375 val now = OffsetDateTime .now()
369- var delay = token.expiration.toEpochSecond() - now.toEpochSecond() - 10
370- if (delay < 0 ) {
371- delay = 0
376+ if (token.expiration.isBefore(now)) break
377+
378+ if (retries == 0 ) {
379+ w{" stopping refresh after 5 consecutive failed attempts" }
380+ break
372381 }
373382
383+ val delay = (token.expiration.toEpochSecond() - now.toEpochSecond()) * 2 / 3
384+
374385 d(" [${name()} ] sleeping for $delay seconds" )
375386 delay(delay.toDuration(DurationUnit .SECONDS ))
376387 d(" [${name()} ] refreshing access token" )
377- val newToken = authenticator.refresh()
378- accessToken.value = newToken
388+ runCatching {
389+ val newToken = authenticator.refresh()
390+ accessToken.value = newToken
391+ retries = 5
392+ }.onFailure {
393+ retries--
394+ w{ " failed to refresh access token: ${it.message} " }
395+ }
379396 }
380397 }
381398
0 commit comments