Read-only mirrors. Development, issues and pull requests are on GitHub.

summaryrefslogtreecommitdiffhomepage
path: root/apps/api/ViGet/ViGetRegistration.cs
blob: 42da18e3ce42a29f8c47e325d0796af67e3f86cc (plain)
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
// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1

using Npgsql;
using Progmasoft.Progmaweb.Api.Accounts;

namespace Progmasoft.Progmaweb.Api.ViGet;

/// <summary>Registers ViGet: its catalog beside the accounts, and the publishing of plugins.</summary>
internal static class ViGetRegistration
{
    /// <summary>Adds the services of ViGet.</summary>
    /// <param name="services">The services of the API.</param>
    /// <param name="configuration">The configuration, whose section <c>ViGet</c> holds <see cref="ViGetOptions"/>.</param>
    /// <param name="accountStore">Where the accounts are kept; the catalog is kept in the same place.</param>
    public static void AddViGet(
        this IServiceCollection services,
        IConfiguration configuration,
        AccountStoreKind accountStore)
    {
        services.Configure<ViGetOptions>(configuration.GetSection(ViGetOptions.SectionName));
        if (accountStore is AccountStoreKind.PostgreSql)
        {
            services.AddSingleton<ITazelPluginCatalog, PostgresTazelPluginCatalog>();
            services.AddHostedService<ViGetSchemaInitializer>();
        }
        else
        {
            services.AddSingleton<ITazelPluginCatalog, InMemoryTazelPluginCatalog>();
        }

        services.AddSingleton<TazelPluginPublishing>();
    }
}

/// <summary>Brings the ViGet tables to the current schema before the service accepts requests.</summary>
/// <param name="dataSource">Connections to the database of the accounts.</param>
/// <param name="logger">Receives what was done.</param>
internal sealed class ViGetSchemaInitializer(
    NpgsqlDataSource dataSource,
    ILogger<ViGetSchemaInitializer> logger) : IHostedService
{
    /// <summary>Writes the schema version and the number of steps taken at this start.</summary>
    private static readonly Action<ILogger, int, int, Exception?> SchemaReport = LoggerMessage.Define<int, int>(
        LogLevel.Information,
        new EventId(1, "ViGetSchema"),
        "The ViGet tables are at schema version {Version}; {Taken} step(s) were taken at this start.");

    /// <inheritdoc/>
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        int taken = await ViGetSchema.ApplyAsync(dataSource, cancellationToken);
        SchemaReport(logger, ViGetSchema.CurrentVersion, taken, null);
    }

    /// <inheritdoc/>
    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}