-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHistoryService.cs
More file actions
204 lines (175 loc) · 7.37 KB
/
HistoryService.cs
File metadata and controls
204 lines (175 loc) · 7.37 KB
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
using Microsoft.EntityFrameworkCore;
using ThingConnect.Pulse.Server.Data;
using ThingConnect.Pulse.Server.Helpers;
using ThingConnect.Pulse.Server.Models;
namespace ThingConnect.Pulse.Server.Services;
public interface IHistoryService
{
Task<HistoryResponseDto?> GetEndpointHistoryAsync(Guid endpointId, DateTimeOffset from, DateTimeOffset to, string bucket = "15m");
}
public sealed class HistoryService : IHistoryService
{
private readonly PulseDbContext _context;
private readonly ILogger<HistoryService> _logger;
public HistoryService(PulseDbContext context, ILogger<HistoryService> logger)
{
_context = context;
_logger = logger;
}
public async Task<HistoryResponseDto?> GetEndpointHistoryAsync(Guid endpointId, DateTimeOffset from, DateTimeOffset to, string bucket = "15m")
{
_logger.LogDebug("Getting endpoint history: endpointId={EndpointId}, from={From}, to={To}, bucket={Bucket}",
endpointId, from, to, bucket);
// Validate date range
if (from >= to)
{
throw new ArgumentException("From date must be earlier than to date");
}
// Validate date range isn't too large (max 90 days for raw data, 2 years for rollups)
TimeSpan maxRange = bucket == "raw" ? TimeSpan.FromDays(90) : TimeSpan.FromDays(730);
if (to - from > maxRange)
{
throw new ArgumentException($"Date range too large for bucket type '{bucket}'. Maximum: {maxRange.TotalDays} days");
}
// Get the endpoint
Data.Endpoint? endpoint = await _context.Endpoints
.Include(e => e.Group)
.FirstOrDefaultAsync(e => e.Id == endpointId);
if (endpoint == null)
{
return null;
}
var response = new HistoryResponseDto
{
Endpoint = MapToEndpointDto(endpoint)
};
// Fetch data based on bucket type
switch (bucket.ToLower())
{
case "raw":
response.Raw = await GetRawDataAsync(endpointId, from, to);
break;
case "15m":
response.Rollup15m = await GetRollup15mDataAsync(endpointId, from, to);
break;
case "daily":
response.RollupDaily = await GetRollupDailyDataAsync(endpointId, from, to);
break;
default:
throw new ArgumentException($"Invalid bucket type: {bucket}. Valid values: raw, 15m, daily");
}
// Always include outages for the time range
response.Outages = await GetOutagesAsync(endpointId, from, to);
return response;
}
private async Task<List<RawCheckDto>> GetRawDataAsync(Guid endpointId, DateTimeOffset from, DateTimeOffset to)
{
long fromUnix = UnixTimestamp.ToUnixSeconds(from);
long toUnix = UnixTimestamp.ToUnixSeconds(to);
// SQLite limitation: fetch all data and filter in memory
var rawData = await _context.CheckResultsRaw
.Where(c => c.EndpointId == endpointId)
.Select(c => new { c.Ts, c.Status, c.RttMs, c.Error })
.ToListAsync();
return rawData
.Where(c => c.Ts >= fromUnix && c.Ts <= toUnix)
.OrderBy(c => c.Ts)
.Select(c => new RawCheckDto
{
Ts = UnixTimestamp.FromUnixSeconds(c.Ts),
Status = c.Status == UpDown.up ? "up" : "down",
RttMs = c.RttMs,
Error = c.Error
})
.ToList();
}
private async Task<List<RollupBucketDto>> GetRollup15mDataAsync(Guid endpointId, DateTimeOffset from, DateTimeOffset to)
{
long fromUnix = UnixTimestamp.ToUnixSeconds(from);
long toUnix = UnixTimestamp.ToUnixSeconds(to);
// SQLite limitation: fetch all data and filter in memory
var rollupData = await _context.Rollups15m
.Where(r => r.EndpointId == endpointId)
.Select(r => new { r.BucketTs, r.UpPct, r.AvgRttMs, r.DownEvents })
.ToListAsync();
return rollupData
.Where(r => r.BucketTs >= fromUnix && r.BucketTs <= toUnix)
.OrderBy(r => r.BucketTs)
.Select(r => new RollupBucketDto
{
BucketTs = UnixTimestamp.FromUnixSeconds(r.BucketTs),
UpPct = r.UpPct,
AvgRttMs = r.AvgRttMs,
DownEvents = r.DownEvents
})
.ToList();
}
private async Task<List<DailyBucketDto>> GetRollupDailyDataAsync(Guid endpointId, DateTimeOffset from, DateTimeOffset to)
{
// Convert DateTimeOffset to Unix timestamp at midnight for filtering
long fromUnix = UnixTimestamp.ToUnixDate(DateOnly.FromDateTime(from.Date));
long toUnix = UnixTimestamp.ToUnixDate(DateOnly.FromDateTime(to.Date));
// SQLite limitation: fetch all data and filter in memory
var dailyData = await _context.RollupsDaily
.Where(r => r.EndpointId == endpointId)
.Select(r => new { r.BucketDate, r.UpPct, r.AvgRttMs, r.DownEvents })
.ToListAsync();
return dailyData
.Where(r => r.BucketDate >= fromUnix && r.BucketDate <= toUnix)
.OrderBy(r => r.BucketDate)
.Select(r => new DailyBucketDto
{
BucketDate = UnixTimestamp.FromUnixDate(r.BucketDate),
UpPct = r.UpPct,
AvgRttMs = r.AvgRttMs,
DownEvents = r.DownEvents
})
.ToList();
}
private async Task<List<OutageDto>> GetOutagesAsync(Guid endpointId, DateTimeOffset from, DateTimeOffset to)
{
long fromUnix = UnixTimestamp.ToUnixSeconds(from);
long toUnix = UnixTimestamp.ToUnixSeconds(to);
// SQLite limitation: fetch all data and filter in memory
var outageData = await _context.Outages
.Where(o => o.EndpointId == endpointId)
.Select(o => new { o.StartedTs, o.EndedTs, o.DurationSeconds, o.LastError })
.ToListAsync();
return outageData
.Where(o => o.StartedTs <= toUnix && (o.EndedTs == null || o.EndedTs >= fromUnix))
.OrderBy(o => o.StartedTs)
.Select(o => new OutageDto
{
StartedTs = UnixTimestamp.FromUnixSeconds(o.StartedTs),
EndedTs = o.EndedTs.HasValue ? UnixTimestamp.FromUnixSeconds(o.EndedTs.Value) : null,
DurationS = o.DurationSeconds,
LastError = o.LastError
})
.ToList();
}
private EndpointDto MapToEndpointDto(Data.Endpoint endpoint)
{
return new EndpointDto
{
Id = endpoint.Id,
Name = endpoint.Name,
Group = new GroupDto
{
Id = endpoint.Group.Id,
Name = endpoint.Group.Name,
ParentId = endpoint.Group.ParentId,
Color = endpoint.Group.Color,
SortOrder = endpoint.Group.SortOrder
},
Type = endpoint.Type.ToString().ToLower(),
Host = endpoint.Host,
Port = endpoint.Port,
HttpPath = endpoint.HttpPath,
HttpMatch = endpoint.HttpMatch,
IntervalSeconds = endpoint.IntervalSeconds,
TimeoutMs = endpoint.TimeoutMs,
Retries = endpoint.Retries,
Enabled = endpoint.Enabled
};
}
}