|
| 1 | +using System.Diagnostics; |
| 2 | +using FwHeadless.Services; |
| 3 | +using FwLiteProjectSync; |
| 4 | +using LcmCrdt; |
| 5 | +using LcmCrdt.RemoteSync; |
| 6 | +using LexCore.Sync; |
| 7 | +using LexData; |
| 8 | +using Microsoft.AspNetCore.Http.HttpResults; |
| 9 | +using Microsoft.EntityFrameworkCore; |
| 10 | +using Microsoft.Extensions.Options; |
| 11 | +using MiniLcm; |
| 12 | +using SIL.Harmony; |
| 13 | +using SIL.Harmony.Core; |
| 14 | + |
| 15 | +namespace FwHeadless.Routes; |
| 16 | + |
| 17 | +public static class MergeRoutes |
| 18 | +{ |
| 19 | + public static IEndpointConventionBuilder MapMergeRoutes(this WebApplication app) |
| 20 | + { |
| 21 | + var group = app.MapGroup("/api/merge").WithOpenApi(); |
| 22 | + |
| 23 | + group.MapPost("/execute", ExecuteMergeRequest); |
| 24 | + group.MapPost("/regenerate-snapshot", RegenerateProjectSnapshot); |
| 25 | + group.MapGet("/status", GetMergeStatus); |
| 26 | + group.MapGet("/await-finished", AwaitSyncFinished); |
| 27 | + return group; |
| 28 | + } |
| 29 | + |
| 30 | + |
| 31 | + static async Task<Results<Ok, NotFound, ProblemHttpResult>> ExecuteMergeRequest( |
| 32 | + SyncHostedService syncHostedService, |
| 33 | + ProjectLookupService projectLookupService, |
| 34 | + ILogger<Program> logger, |
| 35 | + CrdtHttpSyncService crdtHttpSyncService, |
| 36 | + IHttpClientFactory httpClientFactory, |
| 37 | + Guid projectId) |
| 38 | + { |
| 39 | + var projectCode = await projectLookupService.GetProjectCode(projectId); |
| 40 | + if (projectCode is null) |
| 41 | + { |
| 42 | + logger.LogError("Project ID {projectId} not found", projectId); |
| 43 | + return TypedResults.NotFound(); |
| 44 | + } |
| 45 | + |
| 46 | + logger.LogInformation("Project code is {projectCode}", projectCode); |
| 47 | + //if we can't sync with lexbox fail fast |
| 48 | + if (!await crdtHttpSyncService.TestAuth(httpClientFactory.CreateClient(FwHeadlessKernel.LexboxHttpClientName))) |
| 49 | + { |
| 50 | + logger.LogError("Unable to authenticate with Lexbox"); |
| 51 | + return TypedResults.Problem("Unable to authenticate with Lexbox"); |
| 52 | + } |
| 53 | + syncHostedService.QueueJob(projectId); |
| 54 | + return TypedResults.Ok(); |
| 55 | + } |
| 56 | + |
| 57 | + static async Task<Results<Ok, NotFound<string>>> RegenerateProjectSnapshot( |
| 58 | + Guid projectId, |
| 59 | + CurrentProjectService projectContext, |
| 60 | + ProjectLookupService projectLookupService, |
| 61 | + CrdtFwdataProjectSyncService syncService, |
| 62 | + IOptions<FwHeadlessConfig> config, |
| 63 | + HttpContext context |
| 64 | + ) |
| 65 | + { |
| 66 | + using var activity = FwHeadlessActivitySource.Value.StartActivity(); |
| 67 | + activity?.SetTag("app.project_id", projectId); |
| 68 | + var project = projectContext.MaybeProject; |
| 69 | + if (project is null) |
| 70 | + { |
| 71 | + // 404 only means "project doesn't exist"; if we don't know the status, then it hasn't synced before and is therefore ready to sync |
| 72 | + if (await projectLookupService.ProjectExists(projectId)) |
| 73 | + { |
| 74 | + activity?.SetStatus(ActivityStatusCode.Unset, "Project never synced"); |
| 75 | + return TypedResults.NotFound("Project never synced"); |
| 76 | + } |
| 77 | + |
| 78 | + activity?.SetStatus(ActivityStatusCode.Error, "Project not found"); |
| 79 | + return TypedResults.NotFound("Project not found"); |
| 80 | + } |
| 81 | + |
| 82 | + var miniLcmApi = context.RequestServices.GetRequiredService<IMiniLcmApi>(); |
| 83 | + await syncService.RegenerateProjectSnapshot(miniLcmApi, config.Value.GetFwDataProject(projectId)); |
| 84 | + return TypedResults.Ok(); |
| 85 | + } |
| 86 | + |
| 87 | + static async Task<Results<Ok<ProjectSyncStatus>, NotFound>> GetMergeStatus( |
| 88 | + CurrentProjectService projectContext, |
| 89 | + ProjectLookupService projectLookupService, |
| 90 | + SendReceiveService srService, |
| 91 | + IOptions<FwHeadlessConfig> config, |
| 92 | + SyncJobStatusService syncJobStatusService, |
| 93 | + IServiceProvider services, |
| 94 | + LexBoxDbContext lexBoxDb, |
| 95 | + SyncHostedService syncHostedService, |
| 96 | + Guid projectId) |
| 97 | + { |
| 98 | + using var activity = FwHeadlessActivitySource.Value.StartActivity(); |
| 99 | + activity?.SetTag("app.project_id", projectId); |
| 100 | + var jobStatus = syncJobStatusService.SyncStatus(projectId); |
| 101 | + if (jobStatus == SyncJobStatus.Running) return TypedResults.Ok(ProjectSyncStatus.Syncing); |
| 102 | + if (syncHostedService.IsJobQueuedOrRunning(projectId)) return TypedResults.Ok(ProjectSyncStatus.QueuedToSync); |
| 103 | + var project = projectContext.MaybeProject; |
| 104 | + if (project is null) |
| 105 | + { |
| 106 | + // 404 only means "project doesn't exist"; if we don't know the status, then it hasn't synced before and is therefore ready to sync |
| 107 | + if (await projectLookupService.ProjectExists(projectId)) |
| 108 | + { |
| 109 | + activity?.SetStatus(ActivityStatusCode.Unset, "Project never synced"); |
| 110 | + return TypedResults.Ok(ProjectSyncStatus.NeverSynced); |
| 111 | + } |
| 112 | + activity?.SetStatus(ActivityStatusCode.Error, "Project not found"); |
| 113 | + return TypedResults.NotFound(); |
| 114 | + } |
| 115 | + var lexboxProject = await lexBoxDb.Projects.Include(p => p.FlexProjectMetadata).FirstOrDefaultAsync(p => p.Id == projectId); |
| 116 | + if (lexboxProject is null) |
| 117 | + { |
| 118 | + // Can't sync if lexbox doesn't have this project |
| 119 | + activity?.SetStatus(ActivityStatusCode.Error, "Lexbox project not found"); |
| 120 | + return TypedResults.NotFound(); |
| 121 | + } |
| 122 | + activity?.SetTag("app.project_code", lexboxProject.Code); |
| 123 | + var projectFolder = config.Value.GetProjectFolder(lexboxProject.Code, projectId); |
| 124 | + if (!Directory.Exists(projectFolder)) Directory.CreateDirectory(projectFolder); |
| 125 | + var fwDataProject = config.Value.GetFwDataProject(lexboxProject.Code, projectId); |
| 126 | + var pendingHgCommits = srService.PendingCommitCount(fwDataProject, lexboxProject.Code); // NOT awaited here so that this long-running task can run in parallel with others |
| 127 | + |
| 128 | + var crdtCommitsOnServer = await lexBoxDb.Set<ServerCommit>().CountAsync(c => c.ProjectId == projectId); |
| 129 | + await using var lcmCrdtDbContext = await services.GetRequiredService<IDbContextFactory<LcmCrdtDbContext>>().CreateDbContextAsync(); |
| 130 | + var localCrdtCommits = await lcmCrdtDbContext.Set<Commit>().CountAsync(); |
| 131 | + var pendingCrdtCommits = crdtCommitsOnServer - localCrdtCommits; |
| 132 | + |
| 133 | + var lastCrdtCommitDate = await lcmCrdtDbContext.Set<Commit>().MaxAsync(commit => commit.HybridDateTime.DateTime); |
| 134 | + var lastHgCommitDate = lexboxProject.LastCommit; |
| 135 | + |
| 136 | + return TypedResults.Ok(ProjectSyncStatus.ReadyToSync(pendingCrdtCommits, await pendingHgCommits, lastCrdtCommitDate, lastHgCommitDate)); |
| 137 | + } |
| 138 | + |
| 139 | + static async Task<SyncJobResult> AwaitSyncFinished( |
| 140 | + SyncHostedService syncHostedService, |
| 141 | + SyncJobStatusService syncJobStatusService, |
| 142 | + CancellationToken cancellationToken, |
| 143 | + Guid projectId) |
| 144 | + { |
| 145 | + using var activity = FwHeadlessActivitySource.Value.StartActivity(); |
| 146 | + try |
| 147 | + { |
| 148 | + var result = await syncHostedService.AwaitSyncFinished(projectId, cancellationToken); |
| 149 | + if (result is null) |
| 150 | + { |
| 151 | + activity?.SetStatus(ActivityStatusCode.Error, "Sync job not found"); |
| 152 | + return new(SyncJobStatusEnum.SyncJobNotFound, "Sync job not found"); |
| 153 | + } |
| 154 | + |
| 155 | + activity?.SetStatus(ActivityStatusCode.Ok, "Sync finished"); |
| 156 | + return result; |
| 157 | + } |
| 158 | + catch (OperationCanceledException e) |
| 159 | + { |
| 160 | + if (e.CancellationToken == cancellationToken) |
| 161 | + { |
| 162 | + // The AwaitSyncFinished call was canceled, but the sync job was not (necessarily) canceled |
| 163 | + activity?.SetStatus(ActivityStatusCode.Unset, "Timed out awaiting sync status"); |
| 164 | + return new SyncJobResult(SyncJobStatusEnum.TimedOutAwaitingSyncStatus, "Timed out awaiting sync status"); |
| 165 | + } |
| 166 | + else |
| 167 | + { |
| 168 | + activity?.SetStatus(ActivityStatusCode.Error, "Sync job timed out"); |
| 169 | + return new SyncJobResult(SyncJobStatusEnum.SyncJobTimedOut, "Sync job timed out"); |
| 170 | + } |
| 171 | + } |
| 172 | + catch (Exception e) |
| 173 | + { |
| 174 | + activity?.AddException(e); |
| 175 | + var error = e.ToString(); |
| 176 | + // TODO: Consider only returning exception error for certain users (admins, devs, managers)? |
| 177 | + // Note 200 OK returned here; getting the status is a successful HTTP request even if the status is "the job failed and here's why" |
| 178 | + return new SyncJobResult(SyncJobStatusEnum.CrdtSyncFailed, error); |
| 179 | + } |
| 180 | + } |
| 181 | + |
| 182 | +} |
0 commit comments