|
| 1 | +using System; |
| 2 | +using System.Threading; |
| 3 | +using System.Threading.Tasks; |
| 4 | +using Coder.Desktop.App.Models; |
| 5 | +using Coder.Desktop.CoderSdk.Coder; |
| 6 | +using Coder.Desktop.Vpn.Utilities; |
| 7 | +using Microsoft.Extensions.Logging; |
| 8 | + |
| 9 | +namespace Coder.Desktop.App.Services; |
| 10 | + |
| 11 | +public interface IHostnameSuffixGetter |
| 12 | +{ |
| 13 | + public event EventHandler<string> SuffixChanged; |
| 14 | + |
| 15 | + public string GetCachedSuffix(); |
| 16 | +} |
| 17 | + |
| 18 | +public class HostnameSuffixGetter : IHostnameSuffixGetter |
| 19 | +{ |
| 20 | + private const string DefaultSuffix = ".coder"; |
| 21 | + |
| 22 | + private readonly ICredentialManager _credentialManager; |
| 23 | + private readonly ICoderApiClientFactory _clientFactory; |
| 24 | + private readonly ILogger<HostnameSuffixGetter> _logger; |
| 25 | + |
| 26 | + // _lock protects all private (non-readonly) values |
| 27 | + private readonly RaiiSemaphoreSlim _lock = new(1, 1); |
| 28 | + private string _domainSuffix = DefaultSuffix; |
| 29 | + private bool _dirty = false; |
| 30 | + private bool _getInProgress = false; |
| 31 | + private CredentialModel _credentialModel = new() { State = CredentialState.Invalid }; |
| 32 | + |
| 33 | + public event EventHandler<string>? SuffixChanged; |
| 34 | + |
| 35 | + public HostnameSuffixGetter(ICredentialManager credentialManager, ICoderApiClientFactory apiClientFactory, |
| 36 | + ILogger<HostnameSuffixGetter> logger) |
| 37 | + { |
| 38 | + _credentialManager = credentialManager; |
| 39 | + _clientFactory = apiClientFactory; |
| 40 | + _logger = logger; |
| 41 | + credentialManager.CredentialsChanged += HandleCredentialsChanged; |
| 42 | + HandleCredentialsChanged(this, _credentialManager.GetCachedCredentials()); |
| 43 | + } |
| 44 | + |
| 45 | + ~HostnameSuffixGetter() |
| 46 | + { |
| 47 | + _credentialManager.CredentialsChanged -= HandleCredentialsChanged; |
| 48 | + } |
| 49 | + |
| 50 | + private void HandleCredentialsChanged(object? sender, CredentialModel credentials) |
| 51 | + { |
| 52 | + using var _ = _lock.Lock(); |
| 53 | + _logger.LogDebug("credentials updated with state {state}", credentials.State); |
| 54 | + _credentialModel = credentials; |
| 55 | + if (credentials.State != CredentialState.Valid) return; |
| 56 | + |
| 57 | + _dirty = true; |
| 58 | + if (!_getInProgress) |
| 59 | + { |
| 60 | + _getInProgress = true; |
| 61 | + Task.Run(Refresh).ContinueWith(MaybeRefreshAgain); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + private async Task Refresh() |
| 66 | + { |
| 67 | + _logger.LogDebug("refreshing domain suffix"); |
| 68 | + CredentialModel credentials; |
| 69 | + using (_ = await _lock.LockAsync()) |
| 70 | + { |
| 71 | + credentials = _credentialModel; |
| 72 | + if (credentials.State != CredentialState.Valid) |
| 73 | + { |
| 74 | + _logger.LogDebug("abandoning refresh because credentials are now invalid"); |
| 75 | + return; |
| 76 | + } |
| 77 | + |
| 78 | + _dirty = false; |
| 79 | + } |
| 80 | + |
| 81 | + var client = _clientFactory.Create(credentials); |
| 82 | + using var timeoutSrc = new CancellationTokenSource(TimeSpan.FromSeconds(10)); |
| 83 | + var connInfo = await client.GetAgentConnectionInfoGeneric(timeoutSrc.Token); |
| 84 | + |
| 85 | + // older versions of Coder might not set this |
| 86 | + var suffix = string.IsNullOrEmpty(connInfo.HostnameSuffix) |
| 87 | + ? DefaultSuffix |
| 88 | + // and, it doesn't include the leading dot. |
| 89 | + : "." + connInfo.HostnameSuffix; |
| 90 | + |
| 91 | + var changed = false; |
| 92 | + using (_ = await _lock.LockAsync(CancellationToken.None)) |
| 93 | + { |
| 94 | + if (_domainSuffix != suffix) changed = true; |
| 95 | + _domainSuffix = suffix; |
| 96 | + } |
| 97 | + |
| 98 | + if (changed) |
| 99 | + { |
| 100 | + _logger.LogInformation("got new domain suffix '{suffix}'", suffix); |
| 101 | + // grab a local copy of the EventHandler to avoid TOCTOU race on the `?.` null-check |
| 102 | + var del = SuffixChanged; |
| 103 | + del?.Invoke(this, suffix); |
| 104 | + } |
| 105 | + else |
| 106 | + { |
| 107 | + _logger.LogDebug("domain suffix unchanged '{suffix}'", suffix); |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + private async Task MaybeRefreshAgain(Task prev) |
| 112 | + { |
| 113 | + if (prev.IsFaulted) |
| 114 | + { |
| 115 | + _logger.LogError(prev.Exception, "failed to query domain suffix"); |
| 116 | + // back off here before retrying. We're just going to use a fixed, long |
| 117 | + // delay since this just affects UI stuff; we're not in a huge rush as |
| 118 | + // long as we eventually get the right value. |
| 119 | + await Task.Delay(TimeSpan.FromSeconds(10)); |
| 120 | + } |
| 121 | + |
| 122 | + using var l = await _lock.LockAsync(CancellationToken.None); |
| 123 | + if ((_dirty || prev.IsFaulted) && _credentialModel.State == CredentialState.Valid) |
| 124 | + { |
| 125 | + // we still have valid credentials and we're either dirty or the last Get failed. |
| 126 | + _logger.LogDebug("retrying domain suffix query"); |
| 127 | + _ = Task.Run(Refresh).ContinueWith(MaybeRefreshAgain); |
| 128 | + return; |
| 129 | + } |
| 130 | + |
| 131 | + // Getting here means either the credentials are not valid or we don't need to |
| 132 | + // refresh anyway. |
| 133 | + // The next time we get new, valid credentials, HandleCredentialsChanged will kick off |
| 134 | + // a new Refresh |
| 135 | + _getInProgress = false; |
| 136 | + return; |
| 137 | + } |
| 138 | + |
| 139 | + public string GetCachedSuffix() |
| 140 | + { |
| 141 | + using var _ = _lock.Lock(); |
| 142 | + return _domainSuffix; |
| 143 | + } |
| 144 | +} |
0 commit comments