aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Telemetry/StatisticsService.cs
blob: 52299c9de36cd36ea9ae548486412a886fcd78e5 (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
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
// <copyright file="StatisticsService.cs" company="slskd Team">
//     Copyright (c) slskd Team. All rights reserved.
//
//     This program is free software: you can redistribute it and/or modify
//     it under the terms of the GNU Affero General Public License as published
//     by the Free Software Foundation, either version 3 of the License, or
//     (at your option) any later version.
//
//     This program is distributed in the hope that it will be useful,
//     but WITHOUT ANY WARRANTY; without even the implied warranty of
//     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//     GNU Affero General Public License for more details.
//
//     You should have received a copy of the GNU Affero General Public License
//     along with this program.  If not, see https://www.gnu.org/licenses/.
// </copyright>

namespace slskd.Telemetry;

using System;
using System.Collections.Generic;
using Dapper;
using Microsoft.Data.Sqlite;
using Soulseek;

public class StatisticsService
{
    /// <summary>
    ///     Initializes a new instance of the <see cref="StatisticsService"/> class.
    /// </summary>
    /// <param name="connectionStringDictionary"></param>
    public StatisticsService(ConnectionStringDictionary connectionStringDictionary)
    {
        ConnectionStrings = connectionStringDictionary;
    }

    private ConnectionStringDictionary ConnectionStrings { get; }

    /// <summary>
    ///     Returns a summary of all transfer data grouped by direction and final transfer state. Includes only
    ///     completed transfers.
    /// </summary>
    /// <param name="start">The optional start time of the summary window.</param>
    /// <param name="end">The optional end time of the summary window.</param>
    /// <param name="direction">The optional direction (Upload or Download) for the summary.</param>
    /// <param name="username">The optional username by which to filter results.</param>
    /// <returns>A nested dictionary keyed by direction and state and containing summary information.</returns>
    /// <exception cref="ArgumentException">Thrown if end time is not later than start time.</exception>
    public Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>> GetTransferSummary(
        DateTime? start = null,
        DateTime? end = null,
        TransferDirection? direction = null,
        string username = null)
    {
        start ??= DateTime.MinValue;
        end ??= DateTime.MaxValue;

        if (end <= start)
        {
            throw new ArgumentException("End time must be later than start time");
        }

        var dict = new Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>>()
        {
            { TransferDirection.Download, new Dictionary<TransferStates, TransferSummary>() },
            { TransferDirection.Upload, new Dictionary<TransferStates, TransferSummary>() },
        };

        var sql = @$"
            SELECT
                Direction,
                StateDescription,
                SUM(Size) AS TotalBytes,
                COUNT(*) AS Count,
                AVG(AverageSpeed) AS AverageSpeed,
                AVG(strftime('%s', StartedAt) - strftime('%s', EnqueuedAt)) AS AverageWait,
                AVG(strftime('%s', EndedAt) - strftime('%s', StartedAt)) AS AverageDuration
            FROM Transfers
            WHERE EndedAt IS NOT NULL
                AND EndedAt BETWEEN @Start AND @End
                {(direction is not null ? "AND Direction = @Direction" : string.Empty)}
                {(username is not null ? "AND Username = @Username" : string.Empty)}
            GROUP BY Direction, StateDescription
        ";

        using var connection = new SqliteConnection(ConnectionStrings[Database.Transfers]);

        var param = new
        {
            Direction = direction?.ToString(),
            Username = username,
            Start = start,
            End = end,
        };

        var results = connection.Query<TransferSummaryRow>(sql, param);

        foreach (var result in results)
        {
            var record = new TransferSummary
            {
                TotalBytes = result.TotalBytes,
                Count = result.Count,
                AverageSpeed = result.AverageSpeed,
                AverageWait = result.AverageWait,
                AverageDuration = result.AverageDuration,
            };

            dict[result.Direction].Add(result.StateDescription & ~TransferStates.Completed, record);
        }

        return dict;
    }

    /// <summary>
    ///     Returns the top <paramref name="limit"/> user summaries by total count and direction, order by total count
    ///     descending. Only successful transfers are included in counts.
    /// </summary>
    /// <param name="direction">The direction (Upload or Download) for the summary.</param>
    /// <param name="start">The optional start time of the summary window.</param>
    /// <param name="end">The optional end time of the summary window.</param>
    /// <param name="limit">The number of records to return (default: 25).</param>
    /// <returns>A dictionary keyed by username and containing summary information.</returns>
    /// <exception cref="ArgumentException">
    ///     Thrown if end time is not later than start time, or limit is not greater than zero.
    /// </exception>
    public Dictionary<string, TransferSummary> GetSuccessfulTransferSummaryByDirectionAndUsername(
        TransferDirection direction,
        DateTime? start = null,
        DateTime? end = null,
        int limit = 25)
    {
        start ??= DateTime.MinValue;
        end ??= DateTime.MaxValue;

        if (end <= start)
        {
            throw new ArgumentException("End time must be later than start time");
        }

        if (limit <= 0)
        {
            throw new ArgumentOutOfRangeException("Limit must be greater than zero");
        }

        var dict = new Dictionary<string, TransferSummary>();

        var sql = @$"
            SELECT
                Username,
                Direction,
                StateDescription,
                SUM(Size) AS TotalBytes,
                COUNT(*) AS Count,
                AVG(AverageSpeed) AS AverageSpeed,
                AVG(strftime('%s', StartedAt) - strftime('%s', EnqueuedAt)) AS AverageWait,
                AVG(strftime('%s', EndedAt) - strftime('%s', StartedAt)) AS AverageDuration
            FROM Transfers
            WHERE Direction = @Direction
                AND State = 48
                AND EndedAt IS NOT NULL
                AND EndedAt BETWEEN @Start AND @End
            GROUP BY Username, Direction, StateDescription
            ORDER BY Count DESC
            LIMIT @Limit
        ";

        using var connection = new SqliteConnection(ConnectionStrings[Database.Transfers]);

        var param = new
        {
            Direction = direction.ToString(),
            Limit = limit,
            Start = start,
            End = end,
        };

        var results = connection.Query<TransferSummaryRow>(sql, param);

        foreach (var result in results)
        {
            dict.Add(result.Username, new TransferSummary
            {
                TotalBytes = result.TotalBytes,
                Count = result.Count,
                AverageSpeed = result.AverageSpeed,
                AverageWait = result.AverageWait,
                AverageDuration = result.AverageDuration,
            });
        }

        return dict;
    }

    private record TransferSummaryRow
    {
        public string Username { get; init; }
        public TransferDirection Direction { get; init; }
        public TransferStates StateDescription { get; init; }
        public long TotalBytes { get; init; }
        public long Count { get; init; }
        public double AverageSpeed { get; init; }
        public double AverageWait { get; init; }
        public double AverageDuration { get; init; }
    }
}