Skip to content

Commit

Permalink
Re-use Google Cloud Access Tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
drakon64 committed Dec 8, 2024
1 parent 430788e commit 46c07a4
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
23 changes: 19 additions & 4 deletions Clients/GoogleClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,19 @@ namespace Ktisis.Clients;

internal static class GoogleClient
{
private static async Task<AccessTokenResponse?> GetAccessToken()
private static AccessTokenResponse _accessToken = new()
{
AccessToken = "",
ExpiresIn = 0,
TokenType = "",
};

private static async Task<AccessTokenResponse> GetAccessToken()
{
// If the current installation access token expires in less than a minute, generate a new one
if (_accessToken.ExpiresAt.Subtract(DateTime.Now).Minutes >= 1)
return _accessToken;

var request = await Program.HttpClient.SendAsync(
new HttpRequestMessage
{
Expand All @@ -18,9 +29,13 @@ internal static class GoogleClient
}
);

return await request.Content.ReadFromJsonAsync<AccessTokenResponse>(
AccessTokenResponseSerializerContext.Default.AccessTokenResponse
);
_accessToken = (
await request.Content.ReadFromJsonAsync<AccessTokenResponse>(
AccessTokenResponseSerializerContext.Default.AccessTokenResponse
)
)!;

return _accessToken;
}

public static async Task CreateInstance(Instance instance, string project, string zone)
Expand Down
12 changes: 11 additions & 1 deletion Models/GoogleCloud/AccessTokenResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,18 @@ namespace Ktisis.Models.GoogleCloud;
internal class AccessTokenResponse
{
public required string AccessToken { get; init; }
public required ushort ExpiresIn { get; init; }

[JsonInclude]
public required ushort ExpiresIn { private get; init; }

public required string TokenType { get; init; }

public readonly DateTime ExpiresAt;

public AccessTokenResponse()
{
ExpiresAt = DateTime.Now + TimeSpan.FromSeconds(ExpiresIn);
}
}

[JsonSerializable(typeof(AccessTokenResponse))]
Expand Down

0 comments on commit 46c07a4

Please sign in to comment.