|
| 1 | +// Copyright © 2024-Present The Synapse Authors |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"), |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +// |
| 8 | +// Unless required by applicable law or agreed to in writing, software |
| 9 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +// See the License for the specific language governing permissions and |
| 12 | +// limitations under the License. |
| 13 | + |
| 14 | +using Microsoft.Extensions.DependencyInjection; |
| 15 | +using Microsoft.Extensions.Hosting; |
| 16 | +using Microsoft.Extensions.Logging; |
| 17 | +using Microsoft.Extensions.Options; |
| 18 | +using ServerlessWorkflow.Sdk.IO; |
| 19 | +using ServerlessWorkflow.Sdk.Models; |
| 20 | +using Synapse.Api.Application.Configuration; |
| 21 | +using Synapse.Resources; |
| 22 | +using System.Diagnostics; |
| 23 | + |
| 24 | +namespace Synapse.Api.Application.Services; |
| 25 | + |
| 26 | +/// <summary> |
| 27 | +/// Defines the fundamentals of a service used to initialize the Synapse workflow database |
| 28 | +/// </summary> |
| 29 | +/// <param name="serviceProvider">The current <see cref="IServiceProvider"/></param> |
| 30 | +/// <param name="logger">The service used to perform logging</param> |
| 31 | +/// <param name="workflowDefinitionReader">The service used to read <see cref="WorkflowDefinition"/>s</param> |
| 32 | +/// <param name="options">The service used to access the current <see cref="ApiServerOptions"/></param> |
| 33 | +public class WorkflowDatabaseInitializer(IServiceProvider serviceProvider, ILogger<WorkflowDatabaseInitializer> logger, IWorkflowDefinitionReader workflowDefinitionReader, IOptions<ApiServerOptions> options) |
| 34 | + : IHostedService |
| 35 | +{ |
| 36 | + |
| 37 | + /// <summary> |
| 38 | + /// Gets the current <see cref="IServiceProvider"/> |
| 39 | + /// </summary> |
| 40 | + protected IServiceProvider ServiceProvider { get; } = serviceProvider; |
| 41 | + |
| 42 | + /// <summary> |
| 43 | + /// Gets the service used to perform logging |
| 44 | + /// </summary> |
| 45 | + protected ILogger Logger { get; } = logger; |
| 46 | + |
| 47 | + /// <summary> |
| 48 | + /// Gets the service used to read <see cref="WorkflowDefinition"/>s |
| 49 | + /// </summary> |
| 50 | + protected IWorkflowDefinitionReader WorkflowDefinitionReader { get; } = workflowDefinitionReader; |
| 51 | + |
| 52 | + /// <summary> |
| 53 | + /// Gets the current <see cref="ApiServerOptions"/> |
| 54 | + /// </summary> |
| 55 | + protected ApiServerOptions Options { get; } = options.Value; |
| 56 | + |
| 57 | + /// <inheritdoc/> |
| 58 | + public virtual async Task StartAsync(CancellationToken cancellationToken) |
| 59 | + { |
| 60 | + using var scope = this.ServiceProvider.CreateScope(); |
| 61 | + var resources = scope.ServiceProvider.GetRequiredService<IResourceRepository>(); |
| 62 | + var stopwatch = new Stopwatch(); |
| 63 | + if (this.Options.Seeding.Reset) |
| 64 | + { |
| 65 | + this.Logger.LogInformation("Starting resetting database..."); |
| 66 | + stopwatch.Start(); |
| 67 | + await foreach (var correlation in resources.GetAllAsync<Correlation>(cancellationToken: cancellationToken).ConfigureAwait(false)) await resources.RemoveAsync<Correlation>(correlation.GetName(), correlation.GetNamespace(), false, cancellationToken).ConfigureAwait(false); |
| 68 | + await foreach (var correlator in resources.GetAllAsync<Correlator>(cancellationToken: cancellationToken).ConfigureAwait(false)) await resources.RemoveAsync<Correlator>(correlator.GetName(), correlator.GetNamespace(), false, cancellationToken).ConfigureAwait(false); |
| 69 | + await foreach (var ns in resources.GetAllAsync<Namespace>(cancellationToken: cancellationToken).Where(ns => ns.GetName() != Namespace.DefaultNamespaceName)) await resources.RemoveAsync<Namespace>(ns.GetName(), ns.GetNamespace(), false, cancellationToken).ConfigureAwait(false); |
| 70 | + await foreach (var @operator in resources.GetAllAsync<Operator>(cancellationToken: cancellationToken).ConfigureAwait(false)) await resources.RemoveAsync<Operator>(@operator.GetName(), @operator.GetNamespace(), false, cancellationToken).ConfigureAwait(false); |
| 71 | + await foreach (var serviceAccount in resources.GetAllAsync<ServiceAccount>(cancellationToken: cancellationToken).ConfigureAwait(false)) await resources.RemoveAsync<ServiceAccount>(serviceAccount.GetName(), serviceAccount.GetNamespace(), false, cancellationToken).ConfigureAwait(false); |
| 72 | + await foreach (var workflow in resources.GetAllAsync<Workflow>(cancellationToken: cancellationToken).ConfigureAwait(false)) await resources.RemoveAsync<Workflow>(workflow.GetName(), workflow.GetNamespace(), false, cancellationToken).ConfigureAwait(false); |
| 73 | + await foreach (var workflowInstance in resources.GetAllAsync<WorkflowInstance>(cancellationToken: cancellationToken).ConfigureAwait(false)) await resources.RemoveAsync<WorkflowInstance>(workflowInstance.GetName(), workflowInstance.GetNamespace(), false, cancellationToken).ConfigureAwait(false); |
| 74 | + stopwatch.Stop(); |
| 75 | + this.Logger.LogInformation("Database reset completed in {ms} milliseconds", stopwatch.Elapsed.TotalMilliseconds); |
| 76 | + } |
| 77 | + var directory = new DirectoryInfo(this.Options.Seeding.Directory); |
| 78 | + if (!directory.Exists) |
| 79 | + { |
| 80 | + this.Logger.LogWarning("The directory '{directory}' does not exist or cannot be found. Skipping static resource import", directory.FullName); |
| 81 | + return; |
| 82 | + } |
| 83 | + this.Logger.LogInformation("Starting importing static resources from directory '{directory}'...", directory.FullName); |
| 84 | + var files = directory.GetFiles(this.Options.Seeding.FilePattern, SearchOption.AllDirectories).Where(f => f.FullName.EndsWith(".json", StringComparison.OrdinalIgnoreCase) || f.FullName.EndsWith(".yml", StringComparison.OrdinalIgnoreCase) || f.FullName.EndsWith(".yaml", StringComparison.OrdinalIgnoreCase)); |
| 85 | + if (!files.Any()) |
| 86 | + { |
| 87 | + this.Logger.LogWarning("No static resource files matching search pattern '{pattern}' found in directory '{directory}'. Skipping import.", this.Options.Seeding.FilePattern, directory.FullName); |
| 88 | + return; |
| 89 | + } |
| 90 | + var count = 0; |
| 91 | + stopwatch.Restart(); |
| 92 | + foreach (var file in files) |
| 93 | + { |
| 94 | + try |
| 95 | + { |
| 96 | + using var stream = file.OpenRead(); |
| 97 | + var workflowDefinition = await this.WorkflowDefinitionReader.ReadAsync(stream, new() { BaseDirectory = file.Directory!.FullName }, cancellationToken).ConfigureAwait(false); |
| 98 | + var workflow = await resources.GetAsync<Workflow>(workflowDefinition.Document.Name, workflowDefinition.Document.Namespace, cancellationToken).ConfigureAwait(false); |
| 99 | + if (workflow == null) |
| 100 | + { |
| 101 | + workflow = new() |
| 102 | + { |
| 103 | + Metadata = new() |
| 104 | + { |
| 105 | + Namespace = workflowDefinition.Document.Namespace, |
| 106 | + Name = workflowDefinition.Document.Name |
| 107 | + }, |
| 108 | + Spec = new() |
| 109 | + { |
| 110 | + Versions = [workflowDefinition] |
| 111 | + } |
| 112 | + }; |
| 113 | + if (await resources.GetAsync<Namespace>(workflow.GetNamespace()!, cancellationToken: cancellationToken).ConfigureAwait(false) == null) |
| 114 | + { |
| 115 | + await resources.AddAsync(new Namespace() { Metadata = new() { Name = workflow.GetNamespace()! } }, false, cancellationToken).ConfigureAwait(false); |
| 116 | + this.Logger.LogInformation("Successfully created namespace '{namespace}'", workflow.GetNamespace()); |
| 117 | + } |
| 118 | + await resources.AddAsync(workflow, false, cancellationToken).ConfigureAwait(false); |
| 119 | + } |
| 120 | + else |
| 121 | + { |
| 122 | + var version = workflow.Spec.Versions.Get(workflowDefinition.Document.Version); |
| 123 | + if (version != null) |
| 124 | + { |
| 125 | + if (this.Options.Seeding.Overwrite) |
| 126 | + { |
| 127 | + workflow.Spec.Versions.Remove(version); |
| 128 | + workflow.Spec.Versions.Add(workflowDefinition); |
| 129 | + await resources.ReplaceAsync(workflow, false, cancellationToken).ConfigureAwait(false); |
| 130 | + } |
| 131 | + else |
| 132 | + { |
| 133 | + this.Logger.LogInformation("Skipped the import of workflow '{workflow}' from file '{file}' because it already exists", $"{workflowDefinition.Document.Name}.{workflowDefinition.Document.Namespace}:{workflowDefinition.Document.Version}", file.FullName); |
| 134 | + continue; |
| 135 | + } |
| 136 | + } |
| 137 | + } |
| 138 | + this.Logger.LogInformation("Successfully imported workflow '{workflow}' from file '{file}'", $"{workflowDefinition.Document.Name}.{workflowDefinition.Document.Namespace}:{workflowDefinition.Document.Version}", file.FullName); |
| 139 | + count++; |
| 140 | + } |
| 141 | + catch(Exception ex) |
| 142 | + { |
| 143 | + this.Logger.LogError("An error occurred while reading a workflow definition from file '{file}': {ex}", file.FullName, ex); |
| 144 | + continue; |
| 145 | + } |
| 146 | + } |
| 147 | + stopwatch.Stop(); |
| 148 | + this.Logger.LogInformation("Completed importing {count} static resources in {ms} milliseconds", count, stopwatch.Elapsed.TotalMilliseconds); |
| 149 | + } |
| 150 | + |
| 151 | + /// <inheritdoc/> |
| 152 | + public virtual Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; |
| 153 | + |
| 154 | +} |
0 commit comments