summary refs log tree commit diff
path: root/extra/admin-api/Spacebar.CleanSettingsRows/Worker.cs
blob: fd977d6e674d350f6a2cd24fb1a44e9b48064b5c (plain) (blame)
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
using System.Runtime.CompilerServices;
using Microsoft.EntityFrameworkCore;
using Spacebar.Db.Contexts;
using Spacebar.Db.Models;

namespace Spacebar.CleanSettingsRows;

public class Worker(ILogger<Worker> logger, IServiceProvider sp) : BackgroundService {
    protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
        logger.LogInformation("Starting settings row cleanup worker");

        using var scope = sp.CreateScope();
        var db = scope.ServiceProvider.GetRequiredService<SpacebarDbContext>();
        List<Task> tasks = [];
        await foreach (var chunk in GetChunks(db, 1000, stoppingToken)) {
            tasks.Add(ProcessChunk(chunk, stoppingToken));
        }

        await Task.WhenAll(tasks);

        logger.LogInformation("Finished settings row cleanup worker");
    }

    private async IAsyncEnumerable<UserSetting[]> GetChunks(SpacebarDbContext db, int chunkSize, [EnumeratorCancellation] CancellationToken stoppingToken) {
        var total = await db.UserSettings.CountAsync(stoppingToken);
        for (var i = 0; i < total; i += chunkSize) {
            var chunk = await db.UserSettings
                .Include(x => x.User)
                .OrderBy(x => x.Index)
                .Skip(i)
                .Take(chunkSize)
                .ToArrayAsync(stoppingToken);
            yield return chunk;
        }
    }

    private async Task ProcessChunk(UserSetting[] chunk, CancellationToken stoppingToken) {
        if (chunk.Length == 0) return;
        logger.LogInformation("Processing chunk of {Count} settings rows starting at idx={}", chunk.Length, chunk[0].Index);
        var scope = sp.CreateScope();
        var db = scope.ServiceProvider.GetRequiredService<SpacebarDbContext>();
        foreach (var setting in chunk) {
            if (stoppingToken.IsCancellationRequested) break;
            if (setting.User == null) {
                logger.LogInformation("Deleting orphaned settings row {Id}", setting.Index);
                db.UserSettings.Remove(setting);
            }
            else if (setting is {
                         // default settings
                         AfkTimeout: 3600,
                         AllowAccessibilityDetection: true,
                         AnimateEmoji: true,
                         AnimateStickers: 0,
                         ContactSyncEnabled: false,
                         ConvertEmoticons: false,
                         CustomStatus: null,
                         DefaultGuildsRestricted: false,
                         DetectPlatformAccounts: false,
                         DeveloperMode: true,
                         DisableGamesTab: true,
                         EnableTtsCommand: false,
                         ExplicitContentFilter: 0,
                         FriendSourceFlags: "{\"all\":true}",
                         GatewayConnected: false,
                         GifAutoPlay: false,
                         GuildFolders: "[]",
                         GuildPositions: "[]",
                         InlineAttachmentMedia: true,
                         InlineEmbedMedia: true,
                         MessageDisplayCompact: false,
                         NativePhoneIntegrationEnabled: true,
                         RenderEmbeds: true,
                         RenderReactions: true,
                         RestrictedGuilds: "[]",
                         ShowCurrentGame: true,
                         Status: "online",
                         StreamNotificationsEnabled: false,
                         Theme: "dark",
                         TimezoneOffset: 0,
                         FriendDiscoveryFlags: 0,
                         ViewNsfwGuilds: true,
                         // only different property:
                         //Locale: "en-US"
                     }) {
                logger.LogInformation("Deleting default settings row {Id} for user {UserId}", setting.Index, setting.User.Id);
                setting.User.SettingsIndex = null;
                db.UserSettings.Remove(setting);
            }
        }

        await db.SaveChangesAsync(stoppingToken);
    }
}