-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathMachineApiService.cs
More file actions
2647 lines (2393 loc) · 105 KB
/
MachineApiService.cs
File metadata and controls
2647 lines (2393 loc) · 105 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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hangfire;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using Newtonsoft.Json;
using Serval.Client;
using SIL.Converters.Usj;
using SIL.ObjectModel;
using SIL.Scripture;
using SIL.XForge.Configuration;
using SIL.XForge.DataAccess;
using SIL.XForge.EventMetrics;
using SIL.XForge.Models;
using SIL.XForge.Realtime;
using SIL.XForge.Realtime.Json0;
using SIL.XForge.Realtime.RichText;
using SIL.XForge.Scripture.Models;
using SIL.XForge.Services;
using SIL.XForge.Utils;
using Chapter = SIL.XForge.Scripture.Models.Chapter;
using TextInfo = SIL.XForge.Scripture.Models.TextInfo;
// Disable notice "The logging message template should not vary between calls to..."
#pragma warning disable CA2254
namespace SIL.XForge.Scripture.Services;
/// <summary>
/// The Machine API service for use with <see cref="Controllers.MachineApiController"/>.
/// </summary>
public class MachineApiService(
IBackgroundJobClient backgroundJobClient,
IDeltaUsxMapper deltaUsxMapper,
IEventMetricService eventMetricService,
IExceptionHandler exceptionHandler,
IHttpRequestAccessor httpRequestAccessor,
IHubContext<NotificationHub, INotifier> hubContext,
ILogger<MachineApiService> logger,
IMachineProjectService machineProjectService,
IParatextService paratextService,
IPreTranslationService preTranslationService,
IRepository<SFProjectSecret> projectSecrets,
ISFProjectRights projectRights,
ISFProjectService projectService,
IRealtimeService realtimeService,
IOptions<ServalOptions> servalOptions,
ISyncService syncService,
ITranslationEnginesClient translationEnginesClient,
ITranslationEngineTypesClient translationEngineTypesClient,
IRepository<UserSecret> userSecrets
) : IMachineApiService
{
/// <summary>
/// The Faulted build state.
/// </summary>
/// <remarks>
/// NOTE: Serval returns states in TitleCase, while the frontend requires uppercase.
/// </remarks>
internal const string BuildStateFaulted = "FAULTED";
/// <summary>
/// The Queued build state.
/// </summary>
/// <remarks>
/// SF returns this state while the files are being uploaded to Serval.
/// </remarks>
internal const string BuildStateQueued = "QUEUED";
/// <summary>
/// The Finishing build state.
/// </summary>
/// <remarks>
/// SF returns this state while the webhook is running and the drafts are being downloaded to SF.
/// </remarks>
internal const string BuildStateFinishing = "FINISHING";
/// <summary>
/// The Completed build state.
/// </summary>
/// <remarks>
/// Serval returns this state when the build is completed.
/// </remarks>
internal const string BuildStateCompleted = "COMPLETED";
private static readonly IEqualityComparer<IList<string>> _listStringComparer = SequenceEqualityComparer.Create(
EqualityComparer<string>.Default
);
private static readonly IEqualityComparer<IList<ProjectScriptureRange>> _listProjectScriptureRangeComparer =
SequenceEqualityComparer.Create(EqualityComparer<ProjectScriptureRange>.Default);
public async Task<DraftApplyResult> ApplyPreTranslationToProjectAsync(
string curUserId,
string sfProjectId,
string scriptureRange,
string targetProjectId,
DateTime timestamp,
CancellationToken cancellationToken
)
{
// Ensure that the user has permission to access the draft project
SFProject project = await EnsureProjectPermissionAsync(
curUserId,
sfProjectId,
isServalAdmin: false,
cancellationToken
);
// Retrieve the user secret
Attempt<UserSecret> attempt = await userSecrets.TryGetAsync(curUserId, cancellationToken);
if (!attempt.TryResult(out UserSecret userSecret))
{
throw new DataNotFoundException("The user does not exist.");
}
// Connect to the realtime server
await using IConnection connection = await realtimeService.ConnectAsync(curUserId);
// Retrieve the chapter deltas
var result = new DraftApplyResult();
IDocument<SFProject> targetProjectDoc;
List<int> createdBooks = [];
Dictionary<int, List<int>> createdChapters = [];
List<(ChapterDelta chapterDelta, int bookNum)> chapterDeltas = [];
try
{
// Load the target project
targetProjectDoc = await connection.FetchAsync<SFProject>(targetProjectId);
if (!targetProjectDoc.IsLoaded)
{
throw new DataNotFoundException("The project does not exist");
}
// Get the draft project versification
ScrVers versification =
paratextService.GetParatextSettings(userSecret, project.ParatextId)?.Versification
?? VerseRef.defaultVersification;
// Get the target project versification
ScrVers targetVersification =
paratextService.GetParatextSettings(userSecret, targetProjectDoc.Data.ParatextId)?.Versification
?? VerseRef.defaultVersification;
// Parse the scripture range
ScriptureRangeParser scriptureRangeParser = new ScriptureRangeParser(versification);
Dictionary<string, List<int>> booksAndChapters = scriptureRangeParser.GetChapters(scriptureRange);
// Get the drafts for the scripture range
foreach ((string book, List<int> bookChapters) in booksAndChapters)
{
await hubContext.NotifyDraftApplyProgress(
sfProjectId,
new DraftApplyState { State = $"Retrieving draft for {book}." }
);
int bookNum = Canon.BookIdToNumber(book);
// Warn if the last chapter is different (this will affect chapter creation
int lastChapter = versification.GetLastChapter(bookNum);
int targetLastChapter = targetVersification.GetLastChapter(bookNum);
if (lastChapter != targetLastChapter)
{
string message =
$"The draft project ({project.ShortName.Sanitize()}) versification for {book} has {lastChapter} chapters,"
+ $" while the target project ({targetProjectDoc.Data.ShortName.Sanitize()}) has {targetLastChapter} chapters.";
logger.LogWarning(message);
result.Log += $"{message}\n";
await hubContext.NotifyDraftApplyProgress(sfProjectId, new DraftApplyState { State = message });
}
// Ensure that if chapters is blank, it contains every chapter in the book.
// ScriptureRangeParser will return no chapters, meaning all chapters,
// if the scripture range just specifies a book without chapter numbers.
List<int> chapters = bookChapters;
if (chapters.Count == 0)
{
chapters = [.. Enumerable.Range(1, lastChapter)];
}
// Store the USJ for each chapter, so if we download form Serval we only do it once per book
List<Usj> chapterUsj = [];
foreach (int chapterNum in chapters.Where(c => c > 0))
{
// See if we have a draft locally
string id = TextDocument.GetDocId(sfProjectId, bookNum, chapterNum, TextDocument.Draft);
IDocument<TextDocument> textDocument = await connection.FetchAsync<TextDocument>(id);
IUsj usj;
if (textDocument.IsLoaded)
{
// Retrieve the snapshot if it exists, or use the latest available if none
Snapshot<TextDocument> snapshot = await connection.FetchSnapshotAsync<TextDocument>(
id,
timestamp
);
usj = snapshot.Data ?? textDocument.Data;
}
else
{
// We do not have a draft locally, so we should retrieve it from Serval, and save it locally
if (chapterUsj.Count < chapterNum)
{
DraftUsfmConfig config =
project.TranslateConfig.DraftConfig.UsfmConfig ?? new DraftUsfmConfig();
string usfm = await preTranslationService.GetPreTranslationUsfmAsync(
sfProjectId,
bookNum,
chapterNum: 0,
config,
cancellationToken
);
// If the usfm is invalid, skip this book
if (string.IsNullOrWhiteSpace(usfm))
{
result.Failures.Add(book);
await hubContext.NotifyDraftApplyProgress(
sfProjectId,
new DraftApplyState
{
State = $"No draft available for {Canon.BookNumberToId(bookNum)}.",
}
);
break;
}
// If the book id is invalid, skip this book
if (DeltaUsxMapper.ExtractBookId(usfm) != book)
{
result.Failures.Add(book);
await hubContext.NotifyDraftApplyProgress(
sfProjectId,
new DraftApplyState
{
State =
$"Could not retrieve a valid draft for {Canon.BookNumberToId(bookNum)}.",
}
);
break;
}
// Get the USFM as a list of USJ chapters
chapterUsj =
[
.. paratextService.GetChaptersAsUsj(userSecret, project.ParatextId, bookNum, usfm),
];
// If the chapter is still not present, go to the next book
if (chapterUsj.Count < chapterNum)
{
// Don't report an error here, as sometimes the versification will report more chapters than the USFM has
break;
}
}
// Get the chapter USJ
usj = chapterUsj[chapterNum - 1];
// If the chapter is invalid, skip it
if (usj.Content.Count == 0)
{
// A blank chapter from Serval
result.Failures.Add($"{Canon.BookNumberToId(bookNum)} {chapterNum}");
await hubContext.NotifyDraftApplyProgress(
sfProjectId,
new DraftApplyState
{
State =
$"Could not retrieve draft for {Canon.BookNumberToId(bookNum)} {chapterNum}.",
}
);
continue;
}
// Save the chapter to the realtime server
await SaveTextDocumentAsync(textDocument, usj);
}
// If the chapter is invalid, skip it
if (usj.Content.Count == 0)
{
// Likely a blank draft in the database
result.Failures.Add($"{Canon.BookNumberToId(bookNum)} {chapterNum}");
await hubContext.NotifyDraftApplyProgress(
sfProjectId,
new DraftApplyState
{
State = $"Could not retrieve draft for {Canon.BookNumberToId(bookNum)} {chapterNum}.",
}
);
continue;
}
// Then convert it to USX
XDocument usxDoc = UsjToUsx.UsjToUsxXDocument(usj);
// Then convert it to a Delta
IEnumerable<ChapterDelta> deltas = deltaUsxMapper.ToChapterDeltas(usxDoc);
// Ensure that the chapter was present in the USFM
ChapterDelta chapterDelta = deltas.FirstOrDefault();
if (chapterDelta is not null)
{
chapterDeltas.Add((chapterDelta, bookNum));
}
}
}
}
catch (Exception e)
{
// Log the error, report to bugsnag, and report to the user via SignalR
string message =
$"Apply pre-translation draft exception occurred for project {sfProjectId.Sanitize()} running in background job.";
logger.LogError(e, message);
exceptionHandler.ReportException(e);
result.Log += $"{message}\n";
result.Log += $"{e}\n";
await hubContext.NotifyDraftApplyProgress(
sfProjectId,
new DraftApplyState { Failed = true, State = result.Log }
);
// Do not proceed to save the draft to the project
return result;
}
bool successful = false;
try
{
// Begin the transaction
connection.BeginTransaction();
// Begin a transaction, and update the project
foreach ((ChapterDelta chapterDelta, int bookNum) in chapterDeltas)
{
// Create the new chapter record
Chapter chapter = new Chapter
{
DraftApplied = true,
IsValid = chapterDelta.IsValid,
Number = chapterDelta.Number,
LastVerse = chapterDelta.LastVerse,
};
// Create or update the relevant book and chapter records in the project
int textIndex = targetProjectDoc.Data.Texts.FindIndex(t => t.BookNum == bookNum);
if (textIndex == -1)
{
// Create the new book record with the chapter
TextInfo text = new TextInfo { BookNum = bookNum, Chapters = [chapter] };
await targetProjectDoc.SubmitJson0OpAsync(op => op.Add(pd => pd.Texts, text));
// Record that the book and chapter were created
createdBooks.Add(bookNum);
createdChapters.Add(bookNum, [chapterDelta.Number]);
}
else
{
int chapterIndex = targetProjectDoc
.Data.Texts[textIndex]
.Chapters.FindIndex(c => c.Number == chapterDelta.Number);
if (chapterIndex == -1)
{
// Create a new chapter record
await targetProjectDoc.SubmitJson0OpAsync(op =>
op.Add(pd => pd.Texts[textIndex].Chapters, chapter)
);
// Record that the chapter was created
if (createdChapters.TryGetValue(bookNum, out List<int> chapters))
{
chapters.Add(chapterDelta.Number);
}
else
{
createdChapters.Add(bookNum, [chapterDelta.Number]);
}
}
else
{
// Update the existing chapter record
await targetProjectDoc.SubmitJson0OpAsync(op =>
{
op.Set(pd => pd.Texts[textIndex].Chapters[chapterIndex].DraftApplied, chapter.DraftApplied);
op.Set(pd => pd.Texts[textIndex].Chapters[chapterIndex].IsValid, chapter.IsValid);
op.Set(pd => pd.Texts[textIndex].Chapters[chapterIndex].LastVerse, chapter.LastVerse);
});
}
}
}
// Update the permissions
if (chapterDeltas.Count > 0)
{
await hubContext.NotifyDraftApplyProgress(
sfProjectId,
new DraftApplyState { State = "Loading permissions from Paratext." }
);
if (createdBooks.Count == 0)
{
// Update books for which chapters were added
await projectService.UpdatePermissionsAsync(
curUserId,
targetProjectDoc,
users: null,
books: chapterDeltas.Select(c => c.bookNum).Distinct().ToList(),
cancellationToken
);
}
else
{
// Update permissions for new books
await paratextService.UpdateParatextPermissionsForNewBooksAsync(
userSecret,
targetProjectDoc.Data.ParatextId,
targetProjectDoc,
writeToParatext: false
);
}
}
// Create the text data documents, using the permissions matrix calculated above for permissions
foreach ((ChapterDelta chapterDelta, int bookNum) in chapterDeltas)
{
// Ensure that the user has permission to write the book
int textIndex = targetProjectDoc.Data.Texts.FindIndex(t => t.BookNum == bookNum);
if (textIndex == -1)
{
string bookId = Canon.BookNumberToId(bookNum);
if (result.Failures.Add(bookId))
{
// Only notify the book failure once per book
await hubContext.NotifyDraftApplyProgress(
sfProjectId,
new DraftApplyState { State = $"Could not save draft for {Canon.BookNumberToId(bookNum)}." }
);
}
continue;
}
bool canWriteBook =
targetProjectDoc.Data.Texts[textIndex].Permissions.TryGetValue(curUserId, out string bookPermission)
&& bookPermission == TextInfoPermission.Write;
if (!canWriteBook)
{
// Remove the book from the project if we created it, and proceed to add the next chapter
if (createdBooks.Contains(bookNum))
{
await targetProjectDoc.SubmitJson0OpAsync(op => op.Remove(pd => pd.Texts, textIndex));
}
string bookId = Canon.BookNumberToId(bookNum);
if (result.Failures.Add(bookId))
{
// Only notify the book failure once per book
await hubContext.NotifyDraftApplyProgress(
sfProjectId,
new DraftApplyState { State = $"Could not save draft for {Canon.BookNumberToId(bookNum)}." }
);
}
continue;
}
// Ensure that the user has permission to write the chapter
int chapterIndex = targetProjectDoc
.Data.Texts[textIndex]
.Chapters.FindIndex(c => c.Number == chapterDelta.Number);
if (chapterIndex == -1)
{
result.Failures.Add($"{Canon.BookNumberToId(bookNum)} {chapterDelta.Number}");
await hubContext.NotifyDraftApplyProgress(
sfProjectId,
new DraftApplyState
{
State = $"Could not save draft for {Canon.BookNumberToId(bookNum)} {chapterDelta.Number}.",
}
);
continue;
}
bool canWriteChapter =
targetProjectDoc
.Data.Texts[textIndex]
.Chapters[chapterIndex]
.Permissions.TryGetValue(curUserId, out string chapterPermission)
&& chapterPermission == TextInfoPermission.Write;
if (!canWriteChapter)
{
// Remove the chapter from the project if we created it, and proceed to add the next chapter
if (
createdChapters.TryGetValue(bookNum, out List<int> chapters)
&& chapters.Contains(chapterDelta.Number)
)
{
await targetProjectDoc.SubmitJson0OpAsync(op =>
op.Remove(pd => pd.Texts[textIndex].Chapters, chapterIndex)
);
}
result.Failures.Add($"{Canon.BookNumberToId(bookNum)} {chapterDelta.Number}");
await hubContext.NotifyDraftApplyProgress(
sfProjectId,
new DraftApplyState
{
State = $"Could not save draft for {Canon.BookNumberToId(bookNum)} {chapterDelta.Number}.",
}
);
continue;
}
// Create or update the chapter's text document
string id = TextData.GetTextDocId(targetProjectDoc.Id, bookNum, chapterDelta.Number);
TextData newTextData = new TextData(chapterDelta.Delta);
IDocument<TextData> textDataDoc = connection.Get<TextData>(id);
await textDataDoc.FetchAsync();
if (textDataDoc.IsLoaded)
{
// Update the existing text data document
Delta diffDelta = textDataDoc.Data.Diff(newTextData);
if (diffDelta.Ops.Count > 0)
{
await textDataDoc.SubmitOpAsync(diffDelta, OpSource.Draft);
}
await hubContext.NotifyDraftApplyProgress(
sfProjectId,
new DraftApplyState
{
State = $"Updating {Canon.BookNumberToId(bookNum)} {chapterDelta.Number}.",
}
);
}
else
{
// Create a new text data document
await textDataDoc.CreateAsync(newTextData);
await hubContext.NotifyDraftApplyProgress(
sfProjectId,
new DraftApplyState
{
State = $"Creating {Canon.BookNumberToId(bookNum)} {chapterDelta.Number}.",
}
);
}
// A draft has been applied
successful = true;
}
}
catch (Exception e)
{
// Log the error and report to bugsnag
string message =
$"Apply pre-translation draft exception occurred for project {sfProjectId.Sanitize()} running in background job.";
logger.LogError(e, message);
exceptionHandler.ReportException(e);
result.Log += $"{message}\n";
result.Log += $"{e}\n";
// Do not commit the transaction
successful = false;
}
finally
{
if (successful)
{
await connection.CommitTransactionAsync();
await hubContext.NotifyDraftApplyProgress(
sfProjectId,
new DraftApplyState { Success = true, State = result.Log }
);
}
else
{
connection.RollbackTransaction();
await hubContext.NotifyDraftApplyProgress(
sfProjectId,
new DraftApplyState { Failed = true, State = result.Log }
);
}
result.ChangesSaved = successful;
}
return result;
}
public async Task BuildCompletedAsync(string sfProjectId, string buildId, string buildState, Uri websiteUrl)
{
try
{
// Retrieve the build started from the event metric. We do this as there may be multiple builds started,
// and this ensures that only builds that want to send an email will have one sent.
var eventMetrics = await eventMetricService.GetEventMetricsAsync(
sfProjectId,
scopes: [EventScope.Drafting],
eventTypes: [nameof(MachineProjectService.BuildProjectAsync)]
);
EventMetric eventMetric = eventMetrics.Results.LastOrDefault(e => e.Result == buildId);
if (eventMetric is not null && !string.IsNullOrWhiteSpace(eventMetric.UserId))
{
// Get the build config from the event metric, by converting BSON to JSON, and then to the object type
BuildConfig buildConfig = JsonConvert.DeserializeObject<BuildConfig>(
eventMetric.Payload["buildConfig"].ToJson()
);
// Send the email if requested
if (buildConfig.SendEmailOnBuildFinished)
{
await machineProjectService.SendBuildCompletedEmailAsync(
eventMetric.UserId,
sfProjectId,
buildId,
buildState,
websiteUrl
);
}
}
else
{
logger.LogInformation(
"The build event metric could not be retrieve for project {projectId} running in background job.",
sfProjectId.Sanitize()
);
}
}
catch (Exception e)
{
// Log the error and report to bugsnag
logger.LogError(
e,
"Build exception occurred for project {projectId} running in background job.",
sfProjectId.Sanitize()
);
exceptionHandler.ReportException(e);
}
}
public async Task<string?> CancelPreTranslationBuildAsync(
string curUserId,
string sfProjectId,
CancellationToken cancellationToken
)
{
// Ensure that the user has permission
await EnsureProjectPermissionAsync(curUserId, sfProjectId, isServalAdmin: false, cancellationToken);
// If we have pre-translation job information
if (
(await projectSecrets.TryGetAsync(sfProjectId, cancellationToken)).TryResult(
out SFProjectSecret projectSecret
)
&& (
projectSecret.ServalData?.PreTranslationJobId is not null
|| projectSecret.ServalData?.PreTranslationQueuedAt is not null
)
)
{
// Cancel the Hangfire job
if (projectSecret.ServalData?.PreTranslationJobId is not null)
{
backgroundJobClient.Delete(projectSecret.ServalData?.PreTranslationJobId);
}
// Clear the pre-translation queued status and job id
await projectSecrets.UpdateAsync(
sfProjectId,
u =>
{
u.Unset(p => p.ServalData.PreTranslationJobId);
u.Unset(p => p.ServalData.PreTranslationQueuedAt);
},
cancellationToken: cancellationToken
);
}
// Get the translation engine id
string translationEngineId = GetTranslationEngineId(projectSecret, preTranslate: true);
try
{
// Cancel the build on Serval
TranslationBuild translationBuild = await translationEnginesClient.CancelBuildAsync(
translationEngineId,
cancellationToken
);
// Return the build id so it can be logged
return translationBuild.Id;
}
catch (ServalApiException e) when (e.StatusCode == StatusCodes.Status404NotFound)
{
// We do not mind if a 404 exception comes from Serval - we can assume the job is now cancelled
}
catch (ServalApiException e)
{
ProcessServalApiException(e);
}
// No build was cancelled
return null;
}
public async Task ExecuteWebhookAsync(string json, string signature)
{
// Generate a signature for the JSON
string calculatedSignature = CalculateSignature(json);
// Ensure that the signatures match
if (signature != calculatedSignature)
{
throw new ArgumentException(@"Signatures do not match", nameof(signature));
}
// Get the translation id from the JSON
var anonymousType = new
{
Event = string.Empty,
Payload = new
{
Build = new { Id = string.Empty },
Engine = new { Id = string.Empty },
BuildState = string.Empty,
},
};
var delivery = JsonConvert.DeserializeAnonymousType(json, anonymousType);
// Retrieve the translation engine id from the delivery
string translationEngineId = delivery.Payload?.Engine?.Id;
if (string.IsNullOrWhiteSpace(translationEngineId))
{
throw new DataNotFoundException("A translation engine id could not be retrieved from the webhook");
}
// Get the project id from the project secret
string? projectId = await projectSecrets
.Query()
.Where(p => p.ServalData.PreTranslationEngineId == translationEngineId)
.Select(p => p.Id)
.FirstOrDefaultAsync();
// Ensure we have a project id
if (string.IsNullOrWhiteSpace(projectId))
{
// Log the error in the console. We do not need to throw it, as the engine will be for another SF environment
logger.LogWarning(
"A project id could not be found for translation engine id {translationEngineId}",
translationEngineId
);
return;
}
// Notify any SignalR clients subscribed to the project
string buildId = delivery.Payload.Build.Id;
string buildState = delivery.Payload.BuildState;
await hubContext.NotifyBuildProgress(projectId, new ServalBuildState { BuildId = buildId, State = buildState });
// We only support translation build finished events for completed builds
if (delivery.Event != nameof(WebhookEvent.TranslationBuildFinished))
{
return;
}
// Job was canceled or faulted
if (buildState != nameof(JobState.Completed))
{
backgroundJobClient.Enqueue<IMachineApiService>(r =>
r.BuildCompletedAsync(projectId, buildId, buildState, httpRequestAccessor.SiteRoot)
);
return;
}
// Record that the webhook was run successfully
var arguments = new Dictionary<string, object>
{
{ "buildId", buildId },
{ "buildState", buildState },
{ "event", delivery.Event },
{ "translationEngineId", delivery.Payload.Engine.Id },
};
await eventMetricService.SaveEventMetricAsync(
projectId,
userId: null,
nameof(ExecuteWebhookAsync),
EventScope.Drafting,
arguments,
result: buildId
);
// Run the background job
string jobId = backgroundJobClient.Enqueue<IMachineApiService>(r =>
r.RetrievePreTranslationStatusAsync(projectId, CancellationToken.None)
);
// Run the build completed job afterward, which will notify the user if needed
backgroundJobClient.ContinueJobWith<IMachineApiService>(
jobId,
r => r.BuildCompletedAsync(projectId, buildId, buildState, httpRequestAccessor.SiteRoot),
JobContinuationOptions.OnAnyFinishedState
);
}
public async Task<ServalBuildDto?> GetBuildAsync(
string curUserId,
string sfProjectId,
string buildId,
long? minRevision,
bool preTranslate,
bool isServalAdmin,
CancellationToken cancellationToken
)
{
ServalBuildDto? buildDto = null;
// Ensure that the user has permission
SFProject project = await EnsureProjectPermissionAsync(
curUserId,
sfProjectId,
isServalAdmin,
cancellationToken
);
// Execute on Serval, if it is enabled
string translationEngineId = await GetTranslationIdAsync(sfProjectId, preTranslate);
try
{
TranslationBuild translationBuild = await translationEnginesClient.GetBuildAsync(
translationEngineId,
buildId,
minRevision,
cancellationToken
);
buildDto = CreateDto(translationBuild);
}
catch (ServalApiException e)
{
ProcessServalApiException(e);
}
// Make sure the DTO conforms to the machine-api V2 URLs
if (buildDto is not null)
{
buildDto = UpdateDto(buildDto, project.TranslateConfig.DraftConfig);
buildDto = UpdateDto(buildDto, sfProjectId);
}
return buildDto;
}
public async Task<TranslationBuild?> GetRawBuildAsync(
string curUserId,
string sfProjectId,
string buildId,
long? minRevision,
bool preTranslate,
bool isServalAdmin,
CancellationToken cancellationToken
)
{
// Ensure that the user has permission
await EnsureProjectPermissionAsync(curUserId, sfProjectId, isServalAdmin, cancellationToken);
TranslationBuild? translationBuild = null;
// Execute on Serval, if it is enabled
string translationEngineId = await GetTranslationIdAsync(sfProjectId, preTranslate);
try
{
translationBuild = await translationEnginesClient.GetBuildAsync(
translationEngineId,
buildId,
minRevision,
cancellationToken
);
}
catch (ServalApiException e)
{
ProcessServalApiException(e);
}
return translationBuild;
}
/// <summary>
/// Gets the builds for the specified project.
/// </summary>
/// <param name="curUserId">The current user identifier.</param>
/// <param name="sfProjectId">The Scripture Forge project identifier.</param>
/// <param name="preTranslate">If <c>true</c>, return NMT builds only; otherwise, return SMT builds.</param>
/// <param name="isServalAdmin">If <c>true</c>, the current user is a Serval Administrator.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The builds.</returns>
/// <remarks>This function is virtual to allow mocking in unit tests.</remarks>
public virtual async Task<IReadOnlyList<ServalBuildDto>> GetBuildsAsync(
string curUserId,
string sfProjectId,
bool preTranslate,
bool isServalAdmin,
CancellationToken cancellationToken
)
{
// Set up the list of builds to be returned
List<ServalBuildDto> builds = [];
// Ensure that the user has permission
await EnsureProjectPermissionAsync(curUserId, sfProjectId, isServalAdmin, cancellationToken);
// Execute on Serval, if it is enabled
string translationEngineId = await GetTranslationIdAsync(sfProjectId, preTranslate);
// Get the builds from Serval
IList<TranslationBuild> translationBuilds = [];
try
{
translationBuilds = await translationEnginesClient.GetAllBuildsAsync(
translationEngineId,
cancellationToken
);
}
catch (ServalApiException e)
{
ProcessServalApiException(e);
}
// Get the event metrics for build configurations, if we are pre-translating
QueryResults<EventMetric> eventMetrics = QueryResults<EventMetric>.Empty;
if (preTranslate)
{
eventMetrics = await eventMetricService.GetEventMetricsAsync(
sfProjectId,
scopes: [EventScope.Drafting],
eventTypes:
[
nameof(MachineProjectService.BuildProjectAsync),
nameof(RetrievePreTranslationStatusAsync),
nameof(StartPreTranslationBuildAsync),
]
);
}
// Return the builds as DTOs
foreach (TranslationBuild translationBuild in translationBuilds)
{
ServalBuildDto buildDto = CreateDto(translationBuild);
// See if we have event metrics for downloading the pre-translation USFM to Scripture Forge
EventMetric eventMetric = eventMetrics.Results.FirstOrDefault(e =>
e.Result == translationBuild.Id && e.EventType == nameof(RetrievePreTranslationStatusAsync)
);
if (eventMetric is not null)
{
buildDto.AdditionalInfo!.DateGenerated = new DateTimeOffset(eventMetric.TimeStamp, TimeSpan.Zero);
}
// If we have event metrics for sending the build to Serval, add the scripture ranges to the DTO
eventMetric = eventMetrics.Results.FirstOrDefault(e =>
e.Result == translationBuild.Id && e.EventType == nameof(MachineProjectService.BuildProjectAsync)
);
if (eventMetric is not null)
{
buildDto = UpdateDto(buildDto, eventMetric);
}
else if (preTranslate)
{
// Fallback for builds previous to the event metric being recorded:
// - As there is no event metric, get the translation scripture range from the pre-translation corpus
// - We cannot accurately determine the source projects, so do not record the training scripture ranges.
// Get the translation scripture range
PretranslateCorpus translationCorpus = translationBuild.Pretranslate?.FirstOrDefault();
if (translationCorpus is not null)
{
#pragma warning disable CS0612 // Type or member is obsolete
string scriptureRange =
translationCorpus.SourceFilters?.FirstOrDefault()?.ScriptureRange
?? translationCorpus.ScriptureRange;
#pragma warning restore CS0612 // Type or member is obsolete
if (!string.IsNullOrWhiteSpace(scriptureRange))
{
buildDto.AdditionalInfo!.TranslationScriptureRanges.Add(
new ProjectScriptureRange { ProjectId = sfProjectId, ScriptureRange = scriptureRange }
);
}
}
// Get the training scripture range
TrainingCorpus trainingCorpus = translationBuild.TrainOn?.FirstOrDefault();
if (trainingCorpus is not null)
{