Repository navigation
Expand file tree
/
Copy pathEfCatalogAdmin.Pipelines.cs
More file actions
567 lines (514 loc) · 30.2 KB
/
Copy pathEfCatalogAdmin.Pipelines.cs
File metadata and controls
567 lines (514 loc) · 30.2 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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
using System.Text.Json.Nodes;
using Microsoft.EntityFrameworkCore;
using PythonScriptRunner.EntityFrameworkCore.Entities;
using PythonScriptRunner.EntityFrameworkCore.Infrastructure;
namespace PythonScriptRunner.EntityFrameworkCore.Catalog;
internal sealed partial class EfCatalogAdmin
{
public async Task<Page<PipelineSummary>> ListPipelinesAsync(CatalogQuery query, CancellationToken cancellationToken = default)
{
var (pageNumber, pageSize) = Paging(query);
if (query.UsedByPipeline is not null)
{
throw new ArgumentException("UsedByPipeline filters stages only.", nameof(query));
}
var db = await factory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
await using (db.ConfigureAwait(false))
{
var pipelines = db.Pipelines.AsNoTracking();
if (!string.IsNullOrWhiteSpace(query.Search))
{
var pattern = $"%{query.Search.Trim()}%";
pipelines = pipelines.Where(p => EF.Functions.ILike(p.Key, pattern) || EF.Functions.ILike(p.Name, pattern));
}
if (query.Status is { } status)
{
pipelines = pipelines.Where(p => p.Versions.Any(v => v.Status == status));
}
var total = await pipelines.CountAsync(cancellationToken).ConfigureAwait(false);
var items = await pipelines.OrderBy(p => p.Key)
.Skip((pageNumber - 1) * pageSize).Take(pageSize)
.Select(p => new PipelineSummary(
p.Key, p.Name, p.Description, p.LatestPublishedVersion,
p.Versions.Where(v => v.Status == VersionStatus.Draft).Select(v => (int?)v.Version).FirstOrDefault(),
p.UpdatedAt))
.ToListAsync(cancellationToken).ConfigureAwait(false);
return new Page<PipelineSummary>(items, pageNumber, pageSize, total);
}
}
public async Task<PipelineDetail?> GetPipelineAsync(string key, CancellationToken cancellationToken = default)
{
var db = await factory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
await using (db.ConfigureAwait(false))
{
var pipeline = await db.Pipelines.AsNoTracking().Include(p => p.Versions).SingleOrDefaultAsync(p => p.Key == key, cancellationToken).ConfigureAwait(false);
return pipeline is null ? null : ToPipelineDetail(pipeline);
}
}
public async Task<PipelineVersionDetail?> GetPipelineVersionAsync(string key, int version, CancellationToken cancellationToken = default)
{
var db = await factory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
await using (db.ConfigureAwait(false))
{
var row = await db.PipelineVersions.AsNoTracking().Include(v => v.Pipeline)
.SingleOrDefaultAsync(v => v.Pipeline.Key == key && v.Version == version, cancellationToken).ConfigureAwait(false);
return row is null
? null
: CatalogMapping.ToPipelineVersionDetail(row.Pipeline, row, await EfCatalog.LoadStepsAsync(db, row.Id, cancellationToken).ConfigureAwait(false));
}
}
public async Task<PipelineDraft?> GetPipelineDraftAsync(string key, CancellationToken cancellationToken = default)
{
var db = await factory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
await using (db.ConfigureAwait(false))
{
var row = await db.PipelineVersions.AsNoTracking().Include(v => v.Pipeline)
.SingleOrDefaultAsync(v => v.Pipeline.Key == key && v.Status == VersionStatus.Draft, cancellationToken).ConfigureAwait(false);
return row is null ? null : await ToPipelineDraftAsync(db, row, cancellationToken).ConfigureAwait(false);
}
}
public async Task<PipelineDraft> CreatePipelineAsync(NewCatalogItem pipeline, Actor actor, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(pipeline);
ArgumentNullException.ThrowIfNull(actor);
ValidateItem(pipeline);
var db = await factory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
await using (db.ConfigureAwait(false))
{
if (await db.Pipelines.AnyAsync(p => p.Key == pipeline.Key, cancellationToken).ConfigureAwait(false))
{
throw new PsrDomainException(PsrErrorCodes.PipelineKeyTaken, $"Pipeline '{pipeline.Key}' already exists.");
}
var now = time.GetUtcNow();
var row = new PipelineEntity
{
Id = Guid.CreateVersion7(now),
Key = pipeline.Key,
Name = pipeline.Name,
Description = pipeline.Description,
CreatedAt = now,
CreatedBy = actor.Subject,
UpdatedAt = now,
UpdatedBy = actor.Subject,
};
var draft = NewPipelineVersion(row, 1, actor, now);
row.Versions.Add(draft);
db.Pipelines.Add(row);
AuditLog.Add(db, new AuditEntry(actor, AuditActions.PipelineCreated, "Pipeline", row.Id, row.Key), now);
await SaveAsync(db, cancellationToken, unique: _ => new PsrDomainException(PsrErrorCodes.PipelineKeyTaken, $"Pipeline '{pipeline.Key}' already exists."))
.ConfigureAwait(false);
return new PipelineDraft(row.Key, 1, new PipelineDraftData(), draft.RowVersion, CatalogMapping.Authorship(draft));
}
}
public async Task<PipelineDetail> UpdatePipelineAsync(
string key, CatalogItemChanges changes, uint expectedRowVersion, Actor actor, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(changes);
return await ChangePipelineAsync(key, expectedRowVersion, actor, AuditActions.PipelineUpdated, (pipeline, details) =>
{
if (changes.Name is { } name && name != pipeline.Name)
{
ValidateName(name);
details["name"] = new JsonArray(pipeline.Name, name);
pipeline.Name = name;
}
if (changes.Description is { } description && description != pipeline.Description)
{
details["description"] = new JsonArray(pipeline.Description, description);
pipeline.Description = description;
}
}, cancellationToken).ConfigureAwait(false);
}
public async Task<PipelineDraft> CreatePipelineDraftFromAsync(string key, int fromVersion, Actor actor, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var db = await factory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
await using (db.ConfigureAwait(false))
{
var pipeline = await db.Pipelines.Include(p => p.Versions).ThenInclude(v => v.Steps)
.SingleOrDefaultAsync(p => p.Key == key, cancellationToken).ConfigureAwait(false)
?? throw new PipelineNotFoundException(key);
EnsureNoDraft(pipeline.Versions.Any(v => v.Status == VersionStatus.Draft), key);
var source = pipeline.Versions.SingleOrDefault(v => v.Version == fromVersion) ?? throw new VersionNotFoundException(key, fromVersion);
var now = time.GetUtcNow();
var draft = NewPipelineVersion(pipeline, pipeline.Versions.Max(v => v.Version) + 1, actor, now);
draft.InputFields = source.InputFields;
draft.Outputs = source.Outputs;
draft.Layout = source.Layout;
draft.Steps.AddRange(source.Steps.Select(s => new PipelineStepEntity
{
Id = Guid.CreateVersion7(now),
PipelineVersionId = draft.Id,
Order = s.Order,
Key = s.Key,
DisplayName = s.DisplayName,
StageVersionId = s.StageVersionId,
Bindings = s.Bindings,
}));
pipeline.Versions.Add(draft);
AuditLog.Add(db, new AuditEntry(actor, AuditActions.PipelineDraftCreated, "PipelineVersion", draft.Id, $"{key}@{draft.Version}",
new JsonObject { ["fromVersion"] = fromVersion }), now);
await SaveAsync(db, cancellationToken, unique: _ => DraftExists(key)).ConfigureAwait(false);
return await ToPipelineDraftAsync(db, draft, cancellationToken).ConfigureAwait(false);
}
}
public async Task<PipelineDraft> SavePipelineDraftAsync(
string key, int version, PipelineDraftData data, uint expectedRowVersion, Actor actor, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(data);
ArgumentNullException.ThrowIfNull(actor);
var db = await factory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
await using (db.ConfigureAwait(false))
{
var row = await LoadPipelineVersionAsync(db, key, version, cancellationToken).ConfigureAwait(false);
EnsureDraft(row.Status, key, version);
if (row.RowVersion != expectedRowVersion)
{
throw new ConcurrencyConflictException($"The draft {key}@{version} was changed by someone else.",
await ToPipelineDraftAsync(db, row, cancellationToken).ConfigureAwait(false));
}
var steps = await BuildStepsAsync(db, row.Id, data.Steps, cancellationToken).ConfigureAwait(false);
var now = time.GetUtcNow();
var transaction = await db.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
await using var rollback = transaction.ConfigureAwait(false);
await db.PipelineSteps.Where(s => s.PipelineVersionId == row.Id).ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
db.PipelineSteps.AddRange(steps);
row.InputFields = StoredJson.Fields(data.Inputs);
row.Outputs = StoredJson.Outputs(data.Outputs);
row.Layout = StoredJson.Node(data.Layout);
Touch(row, actor, now);
db.Entry(row).Property(v => v.RowVersion).OriginalValue = expectedRowVersion;
AuditLog.Add(db, new AuditEntry(actor, AuditActions.PipelineDraftSaved, "PipelineVersion", row.Id, $"{key}@{version}"), now);
await SaveAsync(db, cancellationToken, conflict: Current(() => GetPipelineDraftAsync(key, CancellationToken.None))).ConfigureAwait(false);
await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
return await ToPipelineDraftAsync(db, row, cancellationToken).ConfigureAwait(false);
}
}
public async Task DiscardPipelineDraftAsync(string key, int version, uint expectedRowVersion, Actor actor, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var db = await factory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
await using (db.ConfigureAwait(false))
{
var row = await LoadPipelineVersionAsync(db, key, version, cancellationToken).ConfigureAwait(false);
EnsureDraft(row.Status, key, version);
if (row.RowVersion != expectedRowVersion)
{
throw new ConcurrencyConflictException($"The draft {key}@{version} was changed by someone else.",
await ToPipelineDraftAsync(db, row, cancellationToken).ConfigureAwait(false));
}
var onlyVersion = !await db.PipelineVersions.AnyAsync(v => v.PipelineId == row.PipelineId && v.Id != row.Id, cancellationToken).ConfigureAwait(false);
db.Entry(row).Property(v => v.RowVersion).OriginalValue = expectedRowVersion;
db.PipelineVersions.Remove(row);
if (onlyVersion && !await db.Runs.AnyAsync(r => r.PipelineId == row.PipelineId, cancellationToken).ConfigureAwait(false))
{
// A pipeline without versions cannot get a new draft; discarding its first draft removes it.
db.Pipelines.Remove(row.Pipeline);
}
AuditLog.Add(db, new AuditEntry(actor, AuditActions.PipelineDraftDiscarded, "PipelineVersion", row.Id, $"{key}@{version}"), time.GetUtcNow());
await SaveAsync(db, cancellationToken, conflict: Current(() => GetPipelineDraftAsync(key, CancellationToken.None))).ConfigureAwait(false);
catalog.InvalidatePipeline(key);
}
}
public async Task<PipelinePublication> PublishPipelineAsync(
string key, int version, uint expectedRowVersion, Actor actor, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var db = await factory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
await using (db.ConfigureAwait(false))
{
var row = await LoadPipelineVersionAsync(db, key, version, cancellationToken).ConfigureAwait(false);
EnsureDraft(row.Status, key, version);
if (row.RowVersion != expectedRowVersion)
{
throw new ConcurrencyConflictException($"The draft {key}@{version} was changed by someone else.",
await ToPipelineDraftAsync(db, row, cancellationToken).ConfigureAwait(false));
}
var steps = await EfCatalog.LoadStepsAsync(db, row.Id, cancellationToken).ConfigureAwait(false);
var definition = CatalogMapping.ToPipeline(row.Pipeline, row, steps);
var report = await pipelineValidator.ValidateAsync(definition, cancellationToken).ConfigureAwait(false);
if (!report.IsValid)
{
throw new DefinitionInvalidException(PsrErrorCodes.PipelineInvalid, report);
}
List<ValidationIssue> warnings = [.. report.Warnings, .. await ScheduleWarningsAsync(db, row.PipelineId, definition, cancellationToken).ConfigureAwait(false)];
var now = time.GetUtcNow();
row.Status = VersionStatus.Published;
row.PublishedAt = now;
row.PublishedBy = actor.Subject;
Touch(row, actor, now);
row.Pipeline.LatestPublishedVersion = Math.Max(row.Pipeline.LatestPublishedVersion ?? 0, version);
Touch(row.Pipeline, actor, now);
db.Entry(row).Property(v => v.RowVersion).OriginalValue = expectedRowVersion;
AuditLog.Add(db, new AuditEntry(actor, AuditActions.PipelinePublished, "PipelineVersion", row.Id, $"{key}@{version}"), now);
await SaveAsync(db, cancellationToken, conflict: Current(() => GetPipelineDraftAsync(key, CancellationToken.None))).ConfigureAwait(false);
catalog.InvalidatePipeline(key);
return new PipelinePublication(CatalogMapping.ToPipelineVersionDetail(row.Pipeline, row, steps), warnings);
}
}
public async Task<PipelineVersionDetail> ArchivePipelineVersionAsync(string key, int version, Actor actor, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var db = await factory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
await using (db.ConfigureAwait(false))
{
var row = await LoadPipelineVersionAsync(db, key, version, cancellationToken).ConfigureAwait(false);
var steps = await EfCatalog.LoadStepsAsync(db, row.Id, cancellationToken).ConfigureAwait(false);
if (row.Status == VersionStatus.Archived)
{
return CatalogMapping.ToPipelineVersionDetail(row.Pipeline, row, steps);
}
if (row.Status != VersionStatus.Published)
{
throw new PsrDomainException(PsrErrorCodes.VersionImmutable, $"Only published versions can be archived; discard the draft {key}@{version} instead.");
}
var schedules = await db.Schedules.AsNoTracking()
.Where(s => s.PipelineId == row.PipelineId && s.IsEnabled && s.PinnedVersion == version)
.Select(s => s.Name)
.ToListAsync(cancellationToken).ConfigureAwait(false);
if (schedules.Count > 0)
{
throw new PsrDomainException(PsrErrorCodes.VersionScheduled,
$"Version {key}@{version} is pinned by enabled schedules: {string.Join(", ", schedules)}.");
}
var now = time.GetUtcNow();
row.Status = VersionStatus.Archived;
row.ArchivedAt = now;
row.ArchivedBy = actor.Subject;
Touch(row, actor, now);
if (row.Pipeline.LatestPublishedVersion == version)
{
row.Pipeline.LatestPublishedVersion = await db.PipelineVersions
.Where(v => v.PipelineId == row.PipelineId && v.Status == VersionStatus.Published && v.Id != row.Id)
.MaxAsync(v => (int?)v.Version, cancellationToken).ConfigureAwait(false);
Touch(row.Pipeline, actor, now);
}
AuditLog.Add(db, new AuditEntry(actor, AuditActions.PipelineVersionArchived, "PipelineVersion", row.Id, $"{key}@{version}"), now);
await SaveAsync(db, cancellationToken).ConfigureAwait(false);
catalog.InvalidatePipeline(key);
return CatalogMapping.ToPipelineVersionDetail(row.Pipeline, row, steps);
}
}
public async Task DeletePipelineAsync(string key, Actor actor, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var db = await factory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
await using (db.ConfigureAwait(false))
{
var pipeline = await db.Pipelines.SingleOrDefaultAsync(p => p.Key == key, cancellationToken).ConfigureAwait(false)
?? throw new PipelineNotFoundException(key);
if (await db.Runs.AnyAsync(r => r.PipelineId == pipeline.Id, cancellationToken).ConfigureAwait(false))
{
throw new PsrDomainException(PsrErrorCodes.DeleteNotAllowed, $"Pipeline '{key}' has runs in the retained history.");
}
db.Pipelines.Remove(pipeline);
AuditLog.Add(db, new AuditEntry(actor, AuditActions.PipelineDeleted, "Pipeline", pipeline.Id, key), time.GetUtcNow());
await SaveAsync(db, cancellationToken).ConfigureAwait(false);
catalog.InvalidatePipeline(key);
}
}
public async Task<PipelineDetail> UpdatePipelineSettingsAsync(
string key, PipelineSettings settings, uint expectedRowVersion, Actor actor, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(settings);
if (settings.MaxConcurrentRuns is < 1)
{
throw new ArgumentOutOfRangeException(nameof(settings), "MaxConcurrentRuns must be at least 1 (or null for no limit).");
}
return await ChangePipelineAsync(key, expectedRowVersion, actor, AuditActions.PipelineSettingsChanged, (pipeline, details) =>
{
if (pipeline.MaxConcurrentRuns != settings.MaxConcurrentRuns)
{
details["maxConcurrentRuns"] = new JsonArray(pipeline.MaxConcurrentRuns, settings.MaxConcurrentRuns);
pipeline.MaxConcurrentRuns = settings.MaxConcurrentRuns;
}
}, cancellationToken).ConfigureAwait(false);
}
public async Task<PipelineDetail> UpdatePipelineRetentionAsync(
string key, PipelineRetention retention, uint expectedRowVersion, Actor actor, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(retention);
CheckRetention(retention.ArtifactRetentionDays, options.Retention.Artifacts, "artifacts");
CheckRetention(retention.RunRetentionDays, options.Retention.Runs, "runs");
return await ChangePipelineAsync(key, expectedRowVersion, actor, AuditActions.PipelineSettingsChanged, (pipeline, details) =>
{
if (pipeline.ArtifactRetentionDays != retention.ArtifactRetentionDays)
{
details["artifactRetentionDays"] = new JsonArray(pipeline.ArtifactRetentionDays, retention.ArtifactRetentionDays);
pipeline.ArtifactRetentionDays = retention.ArtifactRetentionDays;
}
if (pipeline.RunRetentionDays != retention.RunRetentionDays)
{
details["runRetentionDays"] = new JsonArray(pipeline.RunRetentionDays, retention.RunRetentionDays);
pipeline.RunRetentionDays = retention.RunRetentionDays;
}
}, cancellationToken).ConfigureAwait(false);
}
public async Task<RunResult> TestPipelineDraftAsync(string key, object? inputs, Actor actor, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var pipeline = await PreparePipelineTestAsync(key, actor, cancellationToken).ConfigureAwait(false);
return await engine.RunPipelineAsync(pipeline, RunKind.PipelineTest, inputs, RunOptionsFor(actor), cancellationToken).ConfigureAwait(false);
}
public async Task<RunHandle> EnqueuePipelineDraftTestAsync(string key, object? inputs, Actor actor, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var pipeline = await LoadValidPipelineDraftAsync(key, cancellationToken).ConfigureAwait(false);
var bound = engine.BindInputs(pipeline.Definition.Inputs, inputs);
await WriteAuditAsync(new AuditEntry(actor, AuditActions.PipelineTested, "PipelineVersion", pipeline.VersionId, $"{key}@{pipeline.Definition.Version}"),
cancellationToken).ConfigureAwait(false);
return await lifecycle.CreateAsync(QueuedTest(RunKind.PipelineTest, actor, bound) with { Pipeline = pipeline.Definition }, cancellationToken)
.ConfigureAwait(false);
}
/// <summary>Loads and validates the draft, then audits the test.</summary>
private async Task<PipelineDefinition> PreparePipelineTestAsync(string key, Actor actor, CancellationToken cancellationToken)
{
var pipeline = await LoadValidPipelineDraftAsync(key, cancellationToken).ConfigureAwait(false);
await WriteAuditAsync(new AuditEntry(actor, AuditActions.PipelineTested, "PipelineVersion", pipeline.VersionId, $"{key}@{pipeline.Definition.Version}"),
cancellationToken).ConfigureAwait(false);
return pipeline.Definition;
}
/// <summary>The current draft of a pipeline; <c>PIPELINE_INVALID</c> when it does not validate.</summary>
private async Task<(PipelineDefinition Definition, Guid VersionId)> LoadValidPipelineDraftAsync(string key, CancellationToken cancellationToken)
{
PipelineDefinition pipeline;
Guid versionId;
var db = await factory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
await using (db.ConfigureAwait(false))
{
var row = await db.PipelineVersions.AsNoTracking().Include(v => v.Pipeline)
.SingleOrDefaultAsync(v => v.Pipeline.Key == key && v.Status == VersionStatus.Draft, cancellationToken).ConfigureAwait(false)
?? throw (await db.Pipelines.AnyAsync(p => p.Key == key, cancellationToken).ConfigureAwait(false)
? new PsrDomainException(PsrErrorCodes.VersionImmutable, $"Pipeline '{key}' has no draft; create one from a version first.")
: new PipelineNotFoundException(key));
pipeline = CatalogMapping.ToPipeline(row.Pipeline, row, await EfCatalog.LoadStepsAsync(db, row.Id, cancellationToken).ConfigureAwait(false));
versionId = row.Id;
}
var report = await pipelineValidator.ValidateAsync(pipeline, cancellationToken).ConfigureAwait(false);
if (!report.IsValid)
{
throw new DefinitionInvalidException(PsrErrorCodes.PipelineInvalid, report);
}
return (pipeline, versionId);
}
private async Task<PipelineDetail> ChangePipelineAsync(
string key, uint expectedRowVersion, Actor actor, string action, Action<PipelineEntity, JsonObject> change, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(actor);
var db = await factory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
await using (db.ConfigureAwait(false))
{
var pipeline = await db.Pipelines.Include(p => p.Versions).SingleOrDefaultAsync(p => p.Key == key, cancellationToken).ConfigureAwait(false)
?? throw new PipelineNotFoundException(key);
if (pipeline.RowVersion != expectedRowVersion)
{
throw new ConcurrencyConflictException($"Pipeline '{key}' was changed by someone else.", ToPipelineDetail(pipeline));
}
var details = new JsonObject();
change(pipeline, details);
var now = time.GetUtcNow();
Touch(pipeline, actor, now);
db.Entry(pipeline).Property(p => p.RowVersion).OriginalValue = expectedRowVersion;
AuditLog.Add(db, new AuditEntry(actor, action, "Pipeline", pipeline.Id, key, details), now);
await SaveAsync(db, cancellationToken, conflict: Current(() => GetPipelineAsync(key, CancellationToken.None))).ConfigureAwait(false);
catalog.InvalidatePipeline(key);
return ToPipelineDetail(pipeline);
}
}
/// <summary>Builds the step rows of a draft; every step must reference an existing stage version.</summary>
private static async Task<List<PipelineStepEntity>> BuildStepsAsync(
PsrDbContext db, Guid pipelineVersionId, IReadOnlyList<PipelineStepDefinition> steps, CancellationToken cancellationToken)
{
var issues = new List<ValidationIssue>();
foreach (var duplicate in steps.GroupBy(s => s.Key, StringComparer.Ordinal).Where(g => g.Count() > 1))
{
issues.Add(new ValidationIssue("PIPE_STEP_KEY", $"step key '{duplicate.Key}' is used more than once") { Step = duplicate.Key });
}
var keys = steps.Select(s => s.StageKey).Distinct().ToList();
var versions = await db.StageVersions.AsNoTracking()
.Where(v => keys.Contains(v.Stage.Key))
.Select(v => new { v.Id, v.Stage.Key, v.Version })
.ToListAsync(cancellationToken).ConfigureAwait(false);
var result = new List<PipelineStepEntity>();
for (var i = 0; i < steps.Count; i++)
{
var step = steps[i];
if (step.Key.Length is 0 or > 64 || !KeyPattern().IsMatch(step.Key))
{
issues.Add(new ValidationIssue("PIPE_STEP_KEY", $"step key '{step.Key}' must be a slug of up to 64 chars") { Step = step.Key });
}
var stageVersion = versions.FirstOrDefault(v => v.Key == step.StageKey && v.Version == step.StageVersion);
if (stageVersion is null)
{
issues.Add(new ValidationIssue("PIPE_STAGE_NOT_PUBLISHED", $"stage '{step.StageKey}@{step.StageVersion}' does not exist") { Step = step.Key });
continue;
}
result.Add(new PipelineStepEntity
{
Id = Guid.CreateVersion7(),
PipelineVersionId = pipelineVersionId,
Order = i + 1,
Key = step.Key,
DisplayName = step.DisplayName,
StageVersionId = stageVersion.Id,
Bindings = StoredJson.Bindings(step.Bindings),
});
}
return issues.Count > 0 ? throw new DefinitionInvalidException(PsrErrorCodes.PipelineInvalid, new ValidationReport(issues, [])) : result;
}
private static async Task<PipelineVersionEntity> LoadPipelineVersionAsync(PsrDbContext db, string key, int version, CancellationToken cancellationToken)
{
var row = await db.PipelineVersions.Include(v => v.Pipeline)
.SingleOrDefaultAsync(v => v.Pipeline.Key == key && v.Version == version, cancellationToken).ConfigureAwait(false);
if (row is not null)
{
return row;
}
return await db.Pipelines.AnyAsync(p => p.Key == key, cancellationToken).ConfigureAwait(false)
? throw new VersionNotFoundException(key, version)
: throw new PipelineNotFoundException(key);
}
private static async Task<PipelineDraft> ToPipelineDraftAsync(PsrDbContext db, PipelineVersionEntity row, CancellationToken cancellationToken)
{
var steps = await EfCatalog.LoadStepsAsync(db, row.Id, cancellationToken).ConfigureAwait(false);
var definition = CatalogMapping.ToPipeline(row.Pipeline, row, steps);
return new PipelineDraft(row.Pipeline.Key, row.Version, CatalogMapping.ToPipelineData(definition, row.Layout), row.RowVersion, CatalogMapping.Authorship(row));
}
private static PipelineDetail ToPipelineDetail(PipelineEntity pipeline) => new(
pipeline.Key,
pipeline.Name,
pipeline.Description,
pipeline.LatestPublishedVersion,
[.. pipeline.Versions.OrderByDescending(v => v.Version).Select(v => new VersionSummary(v.Version, v.Status, v.PublishedAt, v.UpdatedAt))],
new PipelineSettings(pipeline.MaxConcurrentRuns),
new PipelineRetention(pipeline.ArtifactRetentionDays, pipeline.RunRetentionDays),
pipeline.RowVersion,
CatalogMapping.Authorship(pipeline));
private static PipelineVersionEntity NewPipelineVersion(PipelineEntity pipeline, int version, Actor actor, DateTimeOffset now) => new()
{
Id = Guid.CreateVersion7(now),
PipelineId = pipeline.Id,
Pipeline = pipeline,
Version = version,
Status = VersionStatus.Draft,
InputFields = "[]",
Outputs = "[]",
CreatedAt = now,
CreatedBy = actor.Subject,
UpdatedAt = now,
UpdatedBy = actor.Subject,
};
private static void CheckRetention(int? days, TimeSpan global, string what)
{
if (days is < 1)
{
throw new ArgumentOutOfRangeException(nameof(days), $"The {what} retention must be at least 1 day.");
}
if (days is { } value && TimeSpan.FromDays(value) > global)
{
throw new PsrDomainException(PsrErrorCodes.RetentionExceedsGlobal,
$"The {what} retention ({value} days) exceeds the global retention ({global.TotalDays:0} days); pipelines can only shorten it.");
}
}
private static Func<Task<object?>> Current<T>(Func<Task<T>> load) => async () => await load().ConfigureAwait(false);
}