-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathChangelogUploadService.cs
More file actions
254 lines (209 loc) · 8.16 KB
/
ChangelogUploadService.cs
File metadata and controls
254 lines (209 loc) · 8.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
// 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.RegularExpressions;
using Amazon.S3;
using Elastic.Changelog.Configuration;
using Elastic.Documentation.Configuration;
using Elastic.Documentation.Configuration.Changelog;
using Elastic.Documentation.Configuration.ReleaseNotes;
using Elastic.Documentation.Diagnostics;
using Elastic.Documentation.Integrations.S3;
using Elastic.Documentation.ReleaseNotes;
using Elastic.Documentation.Services;
using Microsoft.Extensions.Logging;
using Nullean.ScopedFileSystem;
namespace Elastic.Changelog.Uploading;
public enum ArtifactType { Changelog, Bundle }
public enum UploadTargetKind { S3, Elasticsearch }
public record ChangelogUploadArguments
{
public required ArtifactType ArtifactType { get; init; }
public required UploadTargetKind Target { get; init; }
public required string S3BucketName { get; init; }
public string? Config { get; init; }
public string? Directory { get; init; }
}
public partial class ChangelogUploadService(
ILoggerFactory logFactory,
IConfigurationContext? configurationContext = null,
ScopedFileSystem? fileSystem = null,
IAmazonS3? s3Client = null
) : IService
{
private readonly ILogger _logger = logFactory.CreateLogger<ChangelogUploadService>();
private readonly IFileSystem _fileSystem = fileSystem ?? FileSystemFactory.RealRead;
private readonly ChangelogConfigurationLoader? _configLoader = configurationContext != null
? new ChangelogConfigurationLoader(logFactory, configurationContext, fileSystem ?? FileSystemFactory.RealRead)
: null;
[GeneratedRegex(@"^[a-zA-Z0-9_-]+$")]
private static partial Regex ProductNameRegex();
private static readonly YamlDotNet.Serialization.IDeserializer EntryDeserializer =
ReleaseNotesSerialization.GetEntryDeserializer();
public async Task<bool> Upload(IDiagnosticsCollector collector, ChangelogUploadArguments args, Cancel ctx)
{
if (args.Target == UploadTargetKind.Elasticsearch)
{
_logger.LogWarning("Elasticsearch upload target is not yet implemented; skipping");
return true;
}
var directory = args.ArtifactType == ArtifactType.Bundle
? await ResolveBundleDirectory(collector, args, ctx)
: await ResolveChangelogDirectory(collector, args, ctx);
if (directory == null)
return false;
if (!_fileSystem.Directory.Exists(directory))
{
_logger.LogInformation("{ArtifactType} directory {Directory} does not exist; nothing to upload", args.ArtifactType, directory);
return true;
}
var targets = args.ArtifactType == ArtifactType.Bundle
? DiscoverBundleUploadTargets(collector, directory)
: DiscoverUploadTargets(collector, directory);
if (targets.Count == 0)
{
_logger.LogInformation("No {ArtifactType} files found to upload in {Directory}", args.ArtifactType, directory);
return true;
}
_logger.LogInformation("Found {Count} upload target(s) from {Directory}", targets.Count, directory);
using var defaultClient = s3Client == null ? new AmazonS3Client() : null;
var client = s3Client ?? defaultClient!;
var etagCalculator = new S3EtagCalculator(logFactory, _fileSystem);
var uploader = new S3IncrementalUploader(logFactory, client, _fileSystem, etagCalculator, args.S3BucketName);
var result = await uploader.Upload(targets, ctx);
_logger.LogInformation("Upload complete: {Uploaded} uploaded, {Skipped} skipped, {Failed} failed", result.Uploaded, result.Skipped, result.Failed);
if (result.Failed > 0)
collector.EmitError(string.Empty, $"{result.Failed} file(s) failed to upload");
return result.Failed == 0;
}
internal IReadOnlyList<UploadTarget> DiscoverUploadTargets(IDiagnosticsCollector collector, string changelogDir)
{
var rootDir = _fileSystem.DirectoryInfo.New(changelogDir);
var yamlFiles = _fileSystem.Directory.GetFiles(changelogDir, "*.yaml", SearchOption.TopDirectoryOnly)
.Concat(_fileSystem.Directory.GetFiles(changelogDir, "*.yml", SearchOption.TopDirectoryOnly))
.ToList();
var targets = new List<UploadTarget>();
foreach (var filePath in yamlFiles)
{
var fileInfo = _fileSystem.FileInfo.New(filePath);
if (SymlinkValidator.ValidateFileAccess(fileInfo, rootDir) is { } accessError)
{
collector.EmitWarning(filePath, $"Skipping: {accessError}");
continue;
}
var products = ReadProductsFromFragment(filePath);
if (products.Count == 0)
{
_logger.LogDebug("No products found in {File}, skipping", filePath);
continue;
}
var fileName = _fileSystem.Path.GetFileName(filePath);
foreach (var product in products)
{
if (!ProductNameRegex().IsMatch(product))
{
collector.EmitWarning(filePath, $"Skipping invalid product name \"{product}\" (must match [a-zA-Z0-9_-]+)");
continue;
}
var s3Key = $"{product}/changelogs/{fileName}";
targets.Add(new UploadTarget(filePath, s3Key));
}
}
return targets;
}
internal IReadOnlyList<UploadTarget> DiscoverBundleUploadTargets(IDiagnosticsCollector collector, string bundleDir)
{
var rootDir = _fileSystem.DirectoryInfo.New(bundleDir);
var yamlFiles = _fileSystem.Directory.GetFiles(bundleDir, "*.yaml", SearchOption.TopDirectoryOnly)
.Concat(_fileSystem.Directory.GetFiles(bundleDir, "*.yml", SearchOption.TopDirectoryOnly))
.ToList();
var targets = new List<UploadTarget>();
foreach (var filePath in yamlFiles)
{
var fileInfo = _fileSystem.FileInfo.New(filePath);
if (SymlinkValidator.ValidateFileAccess(fileInfo, rootDir) is { } accessError)
{
collector.EmitWarning(filePath, $"Skipping: {accessError}");
continue;
}
var products = ReadProductsFromBundle(filePath);
if (products.Count == 0)
{
_logger.LogDebug("No products found in bundle {File}, skipping", filePath);
continue;
}
var fileName = _fileSystem.Path.GetFileName(filePath);
foreach (var product in products)
{
if (!ProductNameRegex().IsMatch(product))
{
collector.EmitWarning(filePath, $"Skipping invalid product name \"{product}\" (must match [a-zA-Z0-9_-]+)");
continue;
}
var s3Key = $"{product}/bundles/{fileName}";
targets.Add(new UploadTarget(filePath, s3Key));
}
}
return targets;
}
private List<string> ReadProductsFromBundle(string filePath)
{
try
{
var content = _fileSystem.File.ReadAllText(filePath);
var bundle = ReleaseNotesSerialization.DeserializeBundle(content);
if (bundle?.Products == null)
return [];
return bundle.Products
.Select(p => p.ProductId)
.Where(p => !string.IsNullOrWhiteSpace(p))
.Distinct()
.ToList();
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Could not read products from bundle {File}", filePath);
return [];
}
}
private List<string> ReadProductsFromFragment(string filePath)
{
try
{
var content = _fileSystem.File.ReadAllText(filePath);
var normalized = ReleaseNotesSerialization.NormalizeYaml(content);
var entry = EntryDeserializer.Deserialize<ChangelogEntryDto>(normalized);
if (entry?.Products == null)
return [];
return entry.Products
.Select(p => p?.Product)
.Where(p => !string.IsNullOrWhiteSpace(p))
.Select(p => p!)
.ToList();
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Could not read products from {File}", filePath);
return [];
}
}
private async Task<string?> ResolveChangelogDirectory(IDiagnosticsCollector collector, ChangelogUploadArguments args, Cancel ctx)
{
if (!string.IsNullOrWhiteSpace(args.Directory))
return args.Directory;
if (_configLoader == null)
return "docs/changelog";
var config = await _configLoader.LoadChangelogConfiguration(collector, args.Config, ctx);
return config?.Bundle?.Directory ?? "docs/changelog";
}
private async Task<string?> ResolveBundleDirectory(IDiagnosticsCollector collector, ChangelogUploadArguments args, Cancel ctx)
{
if (!string.IsNullOrWhiteSpace(args.Directory))
return args.Directory;
if (_configLoader == null)
return "docs/releases";
var config = await _configLoader.LoadChangelogConfiguration(collector, args.Config, ctx);
return config?.Bundle?.OutputDirectory ?? config?.Bundle?.Directory ?? "docs/releases";
}
}