-
Notifications
You must be signed in to change notification settings - Fork 0
feat: Add stream client to dotnet sdk #156
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
aholmis
wants to merge
8
commits into
main
Choose a base branch
from
POWER-5102-stream-sdk
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
2df6ae6
Add intial sdk code from stream
aholmis c5f27d6
Make stream client more in line with existing client - and add tests
aholmis 49f55ae
Refacoring and xml comments
aholmis e1251e2
Use correct name for stream example project
aholmis 16eeba2
Stop client after max retries, and include quantity in url
aholmis 7f56295
Throw exception after max attempts, plus comment improvements
aholmis 7286e4d
Use correct event type name in parsing
aholmis a64ec61
Remove grid owner id from url, update tests to fit
aholmis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
52 changes: 52 additions & 0 deletions
52
...allPower.Api.Client/HeimdallPower.Api.Client.Extensions/HeimdallStreamClientExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| using HeimdallPower.Api.Client.Stream; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.Options; | ||
|
|
||
| namespace HeimdallPower.Api.Client.Extensions; | ||
|
|
||
| /// <summary> | ||
| /// Extension methods for adding the Heimdall Power stream client to the service collection. | ||
| /// </summary> | ||
| public static class HeimdallStreamClientExtensions | ||
| { | ||
| /// <summary> | ||
| /// Registers <see cref="IHeimdallStreamClient"/> as a singleton, configured via <paramref name="configureOptions"/>. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// The stream connection reconnects with exponential backoff internally, handled by <see cref="HeimdallStreamClient"/>. | ||
| /// </remarks> | ||
| /// <param name="services">The service collection to add the client to.</param> | ||
| /// <param name="configureOptions">Callback used to set the <see cref="HeimdallStreamClientOptions"/>, such as client credentials and optional proxy settings.</param> | ||
| /// <returns>The same service collection, for chaining.</returns> | ||
| public static IServiceCollection AddHeimdallPowerStreamClient(this IServiceCollection services, Action<HeimdallStreamClientOptions> configureOptions) | ||
| { | ||
| const string clientName = "HeimdallPowerStream"; | ||
|
|
||
| services.Configure(configureOptions); | ||
|
|
||
| services.AddHttpClient(clientName) | ||
| .ConfigureHttpClient((_, client) => | ||
| { | ||
| client.BaseAddress = new Uri("https://stream-api.heimdallcloud.com"); | ||
| }) | ||
| .ConfigurePrimaryHttpMessageHandler(sp => | ||
| { | ||
| var options = sp.GetRequiredService<IOptions<HeimdallStreamClientOptions>>().Value; | ||
| return ProxyHandlerFactory.CreateHandler(options.Proxy) ?? new HttpClientHandler(); | ||
| }); | ||
|
|
||
| services.AddSingleton(sp => | ||
| { | ||
| var options = sp.GetRequiredService<IOptions<HeimdallStreamClientOptions>>().Value; | ||
| var httpClientFactory = sp.GetRequiredService<IHttpClientFactory>(); | ||
| var httpClient = httpClientFactory.CreateClient(clientName); | ||
| var proxyHandler = ProxyHandlerFactory.CreateHandler(options.Proxy); | ||
|
|
||
| return new HeimdallStreamClient(options.ClientId, options.ClientSecret, httpClient, options.ClientMetadata, proxyHandler, options.RetryPolicy); | ||
| }); | ||
|
|
||
| services.AddSingleton<IHeimdallStreamClient>(sp => sp.GetRequiredService<HeimdallStreamClient>()); | ||
|
|
||
| return services; | ||
| } | ||
| } |
35 changes: 35 additions & 0 deletions
35
...imdallPower.Api.Client/HeimdallPower.Api.Client.Extensions/HeimdallStreamClientOptions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| using HeimdallPower.Api.Client.Stream; | ||
|
|
||
| namespace HeimdallPower.Api.Client.Extensions; | ||
|
|
||
| /// <summary> | ||
| /// Options for configuring the Heimdall Power stream client. | ||
| /// </summary> | ||
| public class HeimdallStreamClientOptions | ||
| { | ||
| /// <summary> | ||
| /// The client ID for the Heimdall Power API. | ||
| /// </summary> | ||
| public required string ClientId { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// The client secret for the Heimdall Power API. | ||
| /// </summary> | ||
| public required string ClientSecret { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Additional metadata to include in the request headers. | ||
| /// </summary> | ||
| public Dictionary<string, string>? ClientMetadata { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Optional proxy configuration. When set, all HTTP requests (stream connection and token acquisition) | ||
| /// are routed through the specified proxy. | ||
| /// </summary> | ||
| public ProxyOptions? Proxy { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Optional configuration for the reconnect backoff behavior used when the stream connection drops. | ||
| /// </summary> | ||
| public StreamConnectionRetryPolicyOptions? RetryPolicy { get; set; } | ||
| } |
57 changes: 57 additions & 0 deletions
57
dotnet/HeimdallPower.Api.Client/HeimdallPower.Api.Client/AccessTokenHeaderRefresher.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| namespace HeimdallPower.Api.Client; | ||
|
|
||
| /// <summary> | ||
| /// Keeps an <see cref="HttpClient"/>'s auth and client headers fresh, coalescing concurrent | ||
| /// refresh attempts behind a single in-flight token request. | ||
| /// </summary> | ||
| internal sealed class AccessTokenHeaderRefresher( | ||
| IAccessTokenProvider accessTokenProvider, | ||
| HttpClient httpClient, | ||
| Dictionary<string, string>? clientMetadata = null) | ||
| { | ||
| private static readonly TimeSpan TokenExpirationBuffer = TimeSpan.FromMinutes(2); | ||
|
|
||
| private readonly SemaphoreSlim _tokenLock = new(1, 1); | ||
| private DateTimeOffset _tokenExpiresOn; | ||
|
|
||
| private bool IsTokenFresh => _tokenExpiresOn != default && DateTimeOffset.UtcNow.Add(TokenExpirationBuffer) <= _tokenExpiresOn; | ||
|
|
||
| /// <summary>Refreshes the token only if it is missing or within the expiration buffer.</summary> | ||
| public Task EnsureFreshTokenAsync(CancellationToken cancellationToken) => | ||
| IsTokenFresh ? Task.CompletedTask : RefreshAsync(force: false, cancellationToken); | ||
|
|
||
| /// <summary>Refreshes the token unconditionally, e.g. after the server rejects it as unauthorized.</summary> | ||
| public Task ForceRefreshAsync(CancellationToken cancellationToken) => RefreshAsync(force: true, cancellationToken); | ||
|
|
||
| private async Task RefreshAsync(bool force, CancellationToken cancellationToken) | ||
| { | ||
| await _tokenLock.WaitAsync(TimeSpan.FromSeconds(30), cancellationToken); | ||
| try | ||
| { | ||
| if (!force && IsTokenFresh) | ||
| return; // Another caller already refreshed while we were waiting. | ||
|
|
||
| await accessTokenProvider.AcquireTokenAsync(cancellationToken); | ||
| _tokenExpiresOn = accessTokenProvider.GetTokenExpiry(); | ||
|
|
||
| foreach (var header in accessTokenProvider.GetAccessHeaders()) | ||
| { | ||
| httpClient.DefaultRequestHeaders.Remove(header.Key); | ||
| httpClient.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value); | ||
| } | ||
|
|
||
| foreach (var header in ClientHeaders.Build(clientMetadata)) | ||
| { | ||
| if (header.Key.Equals("x-region", StringComparison.OrdinalIgnoreCase)) | ||
| continue; // x-region comes from the token, not client metadata | ||
|
|
||
| httpClient.DefaultRequestHeaders.Remove(header.Key); | ||
| httpClient.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value); | ||
| } | ||
| } | ||
| finally | ||
| { | ||
| _tokenLock.Release(); | ||
| } | ||
| } | ||
| } | ||
31 changes: 31 additions & 0 deletions
31
dotnet/HeimdallPower.Api.Client/HeimdallPower.Api.Client/ClientHeaders.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| using System.Reflection; | ||
|
|
||
| namespace HeimdallPower.Api.Client; | ||
|
|
||
| /// <summary> | ||
| /// Builds the x-client-name/x-client-version (plus any caller-supplied metadata) headers sent by every SDK client. | ||
| /// </summary> | ||
| internal static class ClientHeaders | ||
| { | ||
| private const string ClientName = "dotnet-sdk"; | ||
| private static readonly string AssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "0.0.0"; | ||
|
|
||
| public static Dictionary<string, string> Build(Dictionary<string, string>? clientMetadata) | ||
| { | ||
| var headers = new Dictionary<string, string> | ||
| { | ||
| { "x-client-name", ClientName }, | ||
| { "x-client-version", AssemblyVersion }, | ||
| }; | ||
|
|
||
| if (clientMetadata != null) | ||
| { | ||
| foreach (var kvp in clientMetadata) | ||
| { | ||
| headers[kvp.Key] = kvp.Value; // Overwrite defaults if present | ||
| } | ||
| } | ||
|
|
||
| return headers; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
15 changes: 15 additions & 0 deletions
15
dotnet/HeimdallPower.Api.Client/HeimdallPower.Api.Client/HeimdallApiEndpoints.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| namespace HeimdallPower.Api.Client; | ||
|
|
||
| /// <summary> | ||
| /// Endpoint/authority constants shared by every client (REST, streaming) in this SDK. | ||
| /// </summary> | ||
| internal static class HeimdallApiEndpoints | ||
| { | ||
| public const string ApiUrl = "https://external-api.heimdallcloud.com"; | ||
| public const string StreamUrl = "https://stream-api.heimdallcloud.com"; | ||
| private const string Policy = "B2C_1A_CLIENTCREDENTIALSFLOW"; | ||
| private const string Instance = "https://hpadb2cprod.b2clogin.com"; | ||
| private const string Domain = "hpadb2cprod.onmicrosoft.com"; | ||
| public const string Scope = $"https://{Domain}/dc5758ae-4eea-416e-9e61-812914d9a49a/.default"; | ||
| public const string Authority = $"{Instance}/tfp/{Domain}/{Policy}"; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
23 changes: 23 additions & 0 deletions
23
...r.Api.Client/HeimdallPower.Api.Client/Stream/CapacityMonitoring/Lines/HeimdallDlrEvent.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| namespace HeimdallPower.Api.Client.Stream.CapacityMonitoring.Lines; | ||
|
|
||
| /// <summary> | ||
| /// A Heimdall Dynamic Line Rating (DLR) reading for a span, as carried in <see cref="HeimdallEventEnvelope.Data"/> | ||
| /// when <see cref="HeimdallEventEnvelope.Metric"/> equals <see cref="EventName"/>. | ||
| /// </summary> | ||
| /// <param name="AtLineId">The ID of the line the span belongs to.</param> | ||
| /// <param name="AtSpanId">The ID of the span the reading applies to.</param> | ||
| /// <param name="Timestamp">The time the reading was taken.</param> | ||
| /// <param name="Value">The DLR value, in the unit specified by <see cref="HeimdallEventEnvelope.Unit"/>.</param> | ||
| /// <param name="IsFallback">Whether this is a fallback rating, used when a live DLR value is unavailable.</param> | ||
| public record HeimdallDlrEvent( | ||
| Guid AtLineId, | ||
| Guid AtSpanId, | ||
| DateTimeOffset Timestamp, | ||
| double Value, | ||
| bool IsFallback) | ||
| { | ||
| /// <summary> | ||
| /// The value of SSE 'event:' field for Heimdall DLR events. | ||
| /// </summary> | ||
| public const string EventName = "heimdall_dlr"; | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.