-
Notifications
You must be signed in to change notification settings - Fork 30
Refactor communication with AWS for KeyValueStore updates #1503
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
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c530401
Refactor communication with AWS for KeyValueStore updates
cotti 33c6613
Non-idempotent operations should only be performed once
cotti ac91937
Print compact JSON for CLI use
cotti 830bc72
Compact response from AWS CLI, fix arguments according to official docs
cotti 26fc473
Merge branch 'main' into fix/aws_cli_redirects
cotti 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
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
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
127 changes: 127 additions & 0 deletions
127
src/tooling/docs-assembler/Deploying/AwsCloudFrontKeyValueStoreProxy.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,127 @@ | ||
// Licensed to Elasticsearch B.V under one or more agreements. | ||
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. | ||
// See the LICENSE file in the project root for more information | ||
|
||
using System.IO.Abstractions; | ||
using System.Text.Json; | ||
using ConsoleAppFramework; | ||
using Documentation.Assembler.Deploying.Serialization; | ||
using Elastic.Documentation.Diagnostics; | ||
using Elastic.Documentation.Tooling.ExternalCommands; | ||
|
||
namespace Documentation.Assembler.Deploying; | ||
|
||
internal enum KvsOperation | ||
{ | ||
Puts, | ||
Deletes | ||
} | ||
|
||
public class AwsCloudFrontKeyValueStoreProxy(DiagnosticsCollector collector, IDirectoryInfo workingDirectory) : ExternalCommandExecutor(collector, workingDirectory) | ||
{ | ||
public void UpdateRedirects(string kvsName, IReadOnlyDictionary<string, string> sourcedRedirects) | ||
{ | ||
var (kvsArn, eTag) = DescribeKeyValueStore(kvsName); | ||
if (string.IsNullOrEmpty(kvsArn) || string.IsNullOrEmpty(eTag)) | ||
return; | ||
|
||
var existingRedirects = ListAllKeys(kvsArn); | ||
|
||
var toPut = sourcedRedirects | ||
.Select(kvp => new PutKeyRequestListItem { Key = kvp.Key, Value = kvp.Value }); | ||
var toDelete = existingRedirects | ||
.Except(sourcedRedirects.Keys) | ||
.Select(k => new DeleteKeyRequestListItem { Key = k }); | ||
|
||
eTag = ProcessBatchUpdates(kvsArn, eTag, toPut, KvsOperation.Puts); | ||
_ = ProcessBatchUpdates(kvsArn, eTag, toDelete, KvsOperation.Deletes); | ||
} | ||
|
||
private (string? Arn, string? ETag) DescribeKeyValueStore(string kvsName) | ||
{ | ||
ConsoleApp.Log("Describing KeyValueStore"); | ||
try | ||
{ | ||
var json = Capture("aws", "cloudfront", "describe-key-value-store", "--name", kvsName, "|", "jq", "-c"); | ||
var describeResponse = JsonSerializer.Deserialize<DescribeKeyValueStoreResponse>(json, AwsCloudFrontKeyValueStoreJsonContext.Default.DescribeKeyValueStoreResponse); | ||
if (describeResponse?.ETag is not null && describeResponse.KeyValueStore is { ARN.Length: > 0 }) | ||
return (describeResponse.KeyValueStore.ARN, describeResponse.ETag); | ||
|
||
Collector.EmitError("", "Could not deserialize the DescribeKeyValueStoreResponse"); | ||
return (null, null); | ||
} | ||
catch (Exception e) | ||
{ | ||
Collector.EmitError("", "An error occurred while describing the KeyValueStore", e); | ||
return (null, null); | ||
} | ||
} | ||
|
||
private HashSet<string> ListAllKeys(string kvsArn) | ||
{ | ||
ConsoleApp.Log("Acquiring existing redirects"); | ||
var allKeys = new HashSet<string>(); | ||
string[] baseArgs = ["cloudfront-keyvaluestore", "list-keys", "--kvs-arn", kvsArn]; | ||
string? nextToken = null; | ||
try | ||
{ | ||
do | ||
{ | ||
var json = Capture("aws", [.. baseArgs, .. nextToken is not null ? (string[])["--starting-token", nextToken] : [], "|", "jq", "-c"]); | ||
var response = JsonSerializer.Deserialize<ListKeysResponse>(json, AwsCloudFrontKeyValueStoreJsonContext.Default.ListKeysResponse); | ||
|
||
if (response?.Items != null) | ||
{ | ||
foreach (var item in response.Items) | ||
_ = allKeys.Add(item.Key); | ||
} | ||
|
||
nextToken = response?.NextToken; | ||
} while (!string.IsNullOrEmpty(nextToken)); | ||
} | ||
catch (Exception e) | ||
{ | ||
Collector.EmitError("", "An error occurred while acquiring existing redirects in the KeyValueStore", e); | ||
return []; | ||
} | ||
return allKeys; | ||
} | ||
|
||
|
||
private string ProcessBatchUpdates( | ||
string kvsArn, | ||
string eTag, | ||
IEnumerable<object> items, | ||
KvsOperation operation) | ||
{ | ||
const int batchSize = 50; | ||
ConsoleApp.Log($"Processing {items.Count()} items in batches of {batchSize} for {operation} update operation."); | ||
try | ||
{ | ||
foreach (var batch in items.Chunk(batchSize)) | ||
{ | ||
var payload = operation switch | ||
{ | ||
KvsOperation.Puts => JsonSerializer.Serialize(batch.Cast<PutKeyRequestListItem>().ToList(), | ||
AwsCloudFrontKeyValueStoreJsonContext.Default.ListPutKeyRequestListItem), | ||
KvsOperation.Deletes => JsonSerializer.Serialize(batch.Cast<DeleteKeyRequestListItem>().ToList(), | ||
AwsCloudFrontKeyValueStoreJsonContext.Default.ListDeleteKeyRequestListItem), | ||
_ => string.Empty | ||
}; | ||
var responseJson = Capture(false, 1, "aws", "cloudfront-keyvaluestore", "update-keys", "--kvs-arn", kvsArn, "--if-match", eTag, | ||
$"--{operation.ToString().ToLowerInvariant()}", "--payload", payload, "|", "jq", "-c"); | ||
var updateResponse = JsonSerializer.Deserialize<UpdateKeysResponse>(responseJson, AwsCloudFrontKeyValueStoreJsonContext.Default.UpdateKeysResponse); | ||
|
||
if (string.IsNullOrEmpty(updateResponse?.ETag)) | ||
throw new Exception("Failed to get new ETag after update operation."); | ||
|
||
eTag = updateResponse.ETag; | ||
} | ||
} | ||
catch (Exception e) | ||
{ | ||
Collector.EmitError("", $"An error occurred while performing a {operation} update to the KeyValueStore", e); | ||
} | ||
return eTag; | ||
} | ||
} |
37 changes: 37 additions & 0 deletions
37
src/tooling/docs-assembler/Deploying/Serialization/AwsCloudFrontKeyValueStoreModels.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,37 @@ | ||
// Licensed to Elasticsearch B.V under one or more agreements. | ||
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. | ||
// See the LICENSE file in the project root for more information | ||
|
||
using System.Text.Json.Serialization; | ||
|
||
namespace Documentation.Assembler.Deploying.Serialization; | ||
|
||
public record DescribeKeyValueStoreResponse([property: JsonPropertyName("ETag")] string ETag, [property: JsonPropertyName("KeyValueStore")] KeyValueStore KeyValueStore); | ||
public record KeyValueStore([property: JsonPropertyName("ARN")] string ARN); | ||
|
||
public record ListKeysResponse([property: JsonPropertyName("NextToken")] string? NextToken, [property: JsonPropertyName("Items")] List<KeyItem> Items); | ||
public record KeyItem([property: JsonPropertyName("Key")] string Key); | ||
|
||
public record UpdateKeysResponse([property: JsonPropertyName("ETag")] string ETag); | ||
|
||
public record PutKeyRequestListItem | ||
{ | ||
[JsonPropertyName("Key")] | ||
public required string Key { get; init; } | ||
[JsonPropertyName("Value")] | ||
public required string Value { get; init; } | ||
} | ||
|
||
public record DeleteKeyRequestListItem | ||
{ | ||
[JsonPropertyName("Key")] | ||
public required string Key { get; init; } | ||
} | ||
|
||
[JsonSourceGenerationOptions(WriteIndented = false, UseStringEnumConverter = true)] | ||
[JsonSerializable(typeof(DescribeKeyValueStoreResponse))] | ||
[JsonSerializable(typeof(ListKeysResponse))] | ||
[JsonSerializable(typeof(UpdateKeysResponse))] | ||
[JsonSerializable(typeof(List<PutKeyRequestListItem>))] | ||
[JsonSerializable(typeof(List<DeleteKeyRequestListItem>))] | ||
internal sealed partial class AwsCloudFrontKeyValueStoreJsonContext : JsonSerializerContext; |
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
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.