-
-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathEntriesController.cs
More file actions
686 lines (611 loc) · 24.1 KB
/
EntriesController.cs
File metadata and controls
686 lines (611 loc) · 24.1 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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
using System.Text.Json;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Nocturne.API.Attributes;
using Nocturne.API.Authorization;
using Nocturne.API.Extensions;
using Nocturne.Core.Contracts.Glucose;
using Nocturne.Core.Contracts.Legacy;
using Nocturne.Core.Contracts.Alerts;
using Nocturne.Core.Models;
using Nocturne.Core.Models.Extensions;
namespace Nocturne.API.Controllers.V3;
/// <summary>
/// V3 Entries controller that provides full V3 API compatibility with Nightscout entries endpoints.
/// Implements the /api/v3/entries endpoints with pagination, field selection, sorting, and advanced filtering.
/// </summary>
/// <seealso cref="IEntryService"/>
/// <seealso cref="IAlertOrchestrator"/>
/// <seealso cref="Entry"/>
/// <seealso cref="BaseV3Controller{T}"/>
[ApiController]
[Route("api/v3/[controller]")]
[Authorize(Policy = PolicyNames.HasPermissions)]
public class EntriesController : BaseV3Controller<Entry>
{
private readonly IEntryService _entryService;
private readonly IAlertOrchestrator _alertOrchestrator;
public EntriesController(
IDocumentProcessingService documentProcessingService,
IEntryService entryService,
IAlertOrchestrator alertOrchestrator,
ILogger<EntriesController> logger
)
: base(documentProcessingService, logger)
{
_entryService = entryService;
_alertOrchestrator = alertOrchestrator;
}
/// <summary>
/// Get entries with V3 API features including pagination, field selection, and advanced filtering.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>
/// A Nightscout V3-compatible response containing <see cref="Entry"/> objects
/// wrapped in <c>{"status": 200, "result": [...]}</c>.
/// </returns>
/// <remarks>
/// Supports the full V3 query parameter set: limit, offset, fields, sort, sort$desc, filter,
/// and <see cref="V3FilterCriteria"/>-based filtering (e.g., <c>type$eq=sgv</c>).
/// Conditional requests via If-None-Match and If-Modified-Since are honored, returning 304 when appropriate.
/// Entries are transformed to the V3 response format via <c>ToV3Responses()</c> before being returned.
/// </remarks>
/// <response code="200">V3 collection of entries.</response>
/// <response code="304">Not modified (conditional request matched).</response>
/// <response code="400">Invalid request parameters.</response>
/// <response code="500">Internal server error.</response>
[HttpGet]
[NightscoutEndpoint("/api/v3/entries")]
[ProducesResponseType(typeof(V3CollectionResponse<object>), 200)]
[ProducesResponseType(typeof(V3ErrorResponse), 400)]
[ProducesResponseType(304)]
[ProducesResponseType(500)]
public async Task<ActionResult> GetEntries(CancellationToken cancellationToken = default)
{
_logger.LogDebug(
"V3 entries endpoint requested from {RemoteIpAddress}",
HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "unknown"
);
try
{
var parameters = ParseV3QueryParameters();
// Convert V3 parameters to V1 query for backend compatibility
var type = ExtractTypeFromFilter(parameters.Filter);
// Convert V3 filter criteria (field$op=value) to MongoDB-style JSON query
var findQuery =
ConvertFilterCriteriaToFindQuery(parameters.FilterCriteria)
?? ConvertV3FilterToV1Find(parameters.Filter);
// Determine sort direction from sort$desc query parameter
// Nightscout V3: sort$desc=field means descending (newest first)
// reverseResults=false means descending, reverseResults=true means ascending
var hasSortDesc = HttpContext?.Request.Query.ContainsKey("sort$desc") ?? false;
var reverseResults = !hasSortDesc && ExtractSortDirection(parameters.Sort);
// Get entries using service layer with V3 parameters
var entries = await _entryService.GetEntriesWithAdvancedFilterAsync(
type: type,
count: parameters.Limit,
skip: parameters.Offset,
findQuery: findQuery,
dateString: null, // V3 uses filter instead
reverseResults: reverseResults,
cancellationToken: cancellationToken
);
var entriesList = entries.ToList();
// Check for conditional requests (304 Not Modified)
var lastModified = GetLastModified(entriesList);
var etag = GenerateETag(entriesList);
if (ShouldReturn304(etag, lastModified, parameters))
{
return StatusCode(304);
}
// Transform entries to V3 response format with computed fields
var v3Entries = entriesList.ToV3Responses().ToList();
_logger.LogDebug(
"Successfully returned {Count} entries with V3 format",
entriesList.Count
);
// Return Nightscout V3-compatible response with transformed V3 entries
return CreateV3SuccessResponse(v3Entries);
}
catch (ArgumentException ex)
{
_logger.LogWarning(ex, "Invalid V3 entries request parameters");
return CreateV3ErrorResponse(400, "Invalid request parameters", ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error retrieving V3 entries");
return CreateV3ErrorResponse(500, "Internal server error", ex.Message);
}
}
/// <summary>
/// Get a specific entry by ID with V3 format
/// </summary>
/// <param name="id">Entry ID</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Single entry in V3 format</returns>
[HttpGet("{id}")]
[NightscoutEndpoint("/api/v3/entries/:id")]
[ProducesResponseType(typeof(Entry), 200)]
[ProducesResponseType(typeof(V3ErrorResponse), 404)]
[ProducesResponseType(500)]
public async Task<ActionResult<Entry>> GetEntry(
string id,
CancellationToken cancellationToken = default
)
{
_logger.LogDebug("V3 entry by ID requested: {Id}", id);
try
{
var entry = await _entryService.GetEntryByIdAsync(id, cancellationToken);
if (entry == null)
{
return CreateV3ErrorResponse(
404,
"Entry not found",
$"No entry found with ID: {id}"
);
}
// Set appropriate headers
var etag = GenerateETag(new[] { entry });
Response.Headers["ETag"] = $"\"{etag}\"";
Response.Headers["Cache-Control"] = "public, max-age=60";
return Ok(entry.ToV3Response());
}
catch (Exception ex)
{
_logger.LogError(ex, "Error retrieving V3 entry {Id}", id);
return CreateV3ErrorResponse(500, "Internal server error", ex.Message);
}
}
/// <summary>
/// Create a new entry via V3 API.
/// </summary>
/// <param name="entry">The <see cref="Entry"/> to create.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The created <see cref="Entry"/> in V3 format.</returns>
/// <remarks>
/// Supports AAPS deduplication: if an entry with the same device, type, SGV value,
/// and timestamp (within a 1-minute window) already exists, returns a 200 response
/// with <c>isDeduplication: true</c> instead of creating a duplicate.
/// After creation, alerts are evaluated via <see cref="IAlertOrchestrator"/> for the new reading.
/// </remarks>
/// <response code="201">Entry created successfully.</response>
/// <response code="200">Duplicate entry detected (deduplication response for AAPS).</response>
/// <response code="400">Invalid entry data.</response>
/// <response code="500">Internal server error.</response>
[HttpPost]
[Authorize]
[NightscoutEndpoint("/api/v3/entries")]
[ProducesResponseType(typeof(Entry), 201)]
[ProducesResponseType(typeof(V3ErrorResponse), 400)]
[ProducesResponseType(500)]
public async Task<ActionResult<Entry>> CreateEntry(
[FromBody] Entry entry,
CancellationToken cancellationToken = default
)
{
_logger.LogDebug("V3 entry creation requested");
try
{
if (entry == null)
{
return CreateV3ErrorResponse(
400,
"Entry data is required",
"Request body cannot be null"
);
}
// Check for duplicate entry (AAPS expects isDeduplication response)
if (entry.Mills > 0)
{
var existingEntry = await _entryService.CheckForDuplicateEntryAsync(
entry.Device,
entry.Type ?? "sgv",
entry.Sgv,
entry.Mills,
windowMinutes: 1,
cancellationToken: cancellationToken
);
if (existingEntry != null)
{
return Ok(
new
{
status = 200,
identifier = existingEntry.Id,
isDeduplication = true,
deduplicatedIdentifier = existingEntry.Id,
}
);
}
}
// Process the entry
var processedEntry = _documentProcessingService.ProcessEntry(entry); // Save to database
var createdEntries = await _entryService.CreateEntriesAsync(
new[] { processedEntry },
cancellationToken
);
var createdEntry = createdEntries.FirstOrDefault();
if (createdEntry == null)
{
return CreateV3ErrorResponse(
500,
"Failed to create entry",
"Entry creation failed"
);
}
_logger.LogDebug("Successfully created V3 entry {Id}", createdEntry.Id);
await EvaluateAlertsAsync(new[] { createdEntry }, cancellationToken);
// Set location header for created resource
Response.Headers["Location"] = $"/api/v3/entries/{createdEntry.Id}";
return CreatedAtAction(
nameof(GetEntry),
new { id = createdEntry.Id },
createdEntry.ToV3Response()
);
}
catch (ArgumentException ex)
{
_logger.LogWarning(ex, "Invalid V3 entry data");
return CreateV3ErrorResponse(400, "Invalid entry data", ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error creating V3 entry");
return CreateV3ErrorResponse(500, "Internal server error", ex.Message);
}
}
/// <summary>
/// Create multiple entries via V3 API (bulk operation)
/// </summary>
/// <param name="entries">Entries to create</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Created entries</returns>
[HttpPost("bulk")]
[Authorize]
[NightscoutEndpoint("/api/v3/entries/bulk")]
[ProducesResponseType(typeof(Entry[]), 201)]
[ProducesResponseType(typeof(V3ErrorResponse), 400)]
[ProducesResponseType(500)]
public async Task<ActionResult<Entry[]>> CreateEntries(
[FromBody] Entry[] entries,
CancellationToken cancellationToken = default
)
{
_logger.LogDebug(
"V3 bulk entry creation requested for {Count} entries",
entries?.Length ?? 0
);
try
{
if (entries == null || entries.Length == 0)
{
return CreateV3ErrorResponse(
400,
"Entries data is required",
"Request body must contain at least one entry"
);
}
// Validate bulk limit
if (entries.Length > 1000)
{
return CreateV3ErrorResponse(
400,
"Too many entries",
"Bulk operations are limited to 1000 entries per request"
);
}
// Process all entries
var processedEntries = entries
.Select(entry => _documentProcessingService.ProcessEntry(entry))
.ToList();
// Save to database
var createdEntries = await _entryService.CreateEntriesAsync(
processedEntries,
cancellationToken
);
_logger.LogDebug(
"Successfully created {Count} V3 entries via bulk operation",
createdEntries.Count()
);
await EvaluateAlertsAsync(createdEntries.ToArray(), cancellationToken);
return StatusCode(201, createdEntries.ToV3Responses());
}
catch (ArgumentException ex)
{
_logger.LogWarning(ex, "Invalid V3 bulk entry data");
return CreateV3ErrorResponse(400, "Invalid entries data", ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error creating V3 bulk entries");
return CreateV3ErrorResponse(500, "Internal server error", ex.Message);
}
}
/// <summary>
/// Update an entry via V3 API
/// </summary>
/// <param name="id">Entry ID</param>
/// <param name="entry">Updated entry data</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Updated entry</returns>
[HttpPut("{id}")]
[Authorize]
[NightscoutEndpoint("/api/v3/entries/:id")]
[ProducesResponseType(typeof(Entry), 200)]
[ProducesResponseType(typeof(V3ErrorResponse), 404)]
[ProducesResponseType(typeof(V3ErrorResponse), 400)]
[ProducesResponseType(500)]
public async Task<ActionResult<Entry>> UpdateEntry(
string id,
[FromBody] Entry entry,
CancellationToken cancellationToken = default
)
{
_logger.LogDebug("V3 entry update requested for {Id}", id);
try
{
if (entry == null)
{
return CreateV3ErrorResponse(
400,
"Entry data is required",
"Request body cannot be null"
);
}
// Ensure the ID matches
entry.Id = id;
// Process the entry
var processedEntry = _documentProcessingService.ProcessEntry(entry);
// Update in database
var updatedEntry = await _entryService.UpdateEntryAsync(
id,
processedEntry,
cancellationToken
);
if (updatedEntry == null)
{
return CreateV3ErrorResponse(
404,
"Entry not found",
$"No entry found with ID: {id}"
);
}
_logger.LogDebug("Successfully updated V3 entry {Id}", id);
return Ok(updatedEntry.ToV3Response());
}
catch (ArgumentException ex)
{
_logger.LogWarning(ex, "Invalid V3 entry update data for {Id}", id);
return CreateV3ErrorResponse(400, "Invalid entry data", ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error updating V3 entry {Id}", id);
return CreateV3ErrorResponse(500, "Internal server error", ex.Message);
}
}
/// <summary>
/// Delete an entry via V3 API
/// </summary>
/// <param name="id">Entry ID</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>No content on success</returns>
[HttpDelete("{id}")]
[Authorize]
[NightscoutEndpoint("/api/v3/entries/:id")]
[ProducesResponseType(204)]
[ProducesResponseType(typeof(V3ErrorResponse), 404)]
[ProducesResponseType(500)]
public async Task<ActionResult> DeleteEntry(
string id,
CancellationToken cancellationToken = default
)
{
_logger.LogDebug("V3 entry deletion requested for {Id}", id);
try
{
var deleted = await _entryService.DeleteEntryAsync(id, cancellationToken);
if (!deleted)
{
return CreateV3ErrorResponse(
404,
"Entry not found",
$"No entry found with ID: {id}"
);
}
_logger.LogDebug("Successfully deleted V3 entry {Id}", id);
return NoContent();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error deleting V3 entry {Id}", id);
return CreateV3ErrorResponse(500, "Internal server error", ex.Message);
}
}
/// <summary>
/// Get entries modified since a given timestamp (for AAPS incremental sync).
/// </summary>
/// <param name="lastModified">Unix timestamp in milliseconds. Only entries modified after this time are returned.</param>
/// <param name="limit">Maximum number of entries to return (1-1000, default 1000).</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>V3 collection of <see cref="Entry"/> objects modified since the given timestamp.</returns>
/// <response code="200">Entries modified since the given timestamp.</response>
/// <response code="500">Internal server error.</response>
[HttpGet("history/{lastModified:long}")]
[NightscoutEndpoint("/api/v3/entries/history/{lastModified}")]
[ProducesResponseType(typeof(object), 200)]
[ProducesResponseType(500)]
public async Task<ActionResult> GetEntryHistory(
long lastModified,
[FromQuery] int limit = 1000,
CancellationToken cancellationToken = default
)
{
_logger.LogDebug(
"V3 entry history requested since {LastModified} with limit {Limit}",
lastModified,
limit
);
try
{
limit = Math.Min(Math.Max(limit, 1), 1000);
// Build a find query for entries since the given timestamp
var findQuery = $"{{\"date\":{{\"$gte\":{lastModified}}}}}";
var entries = await _entryService.GetEntriesWithAdvancedFilterAsync(
type: null,
count: limit,
skip: 0,
findQuery: findQuery,
dateString: null,
reverseResults: false,
cancellationToken: cancellationToken
);
var v3Entries = entries.ToV3Responses().ToList();
return CreateV3SuccessResponse(v3Entries);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error retrieving entry history");
return CreateV3ErrorResponse(500, "Internal server error", ex.Message);
}
}
#region Helper Methods
private new string? ExtractTypeFromFilter(JsonElement? filter)
{
if (!filter.HasValue)
return null;
try
{
if (filter.Value.TryGetProperty("type", out var typeElement))
{
return typeElement.GetString();
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to extract type from V3 filter");
}
return null;
}
private new string? ConvertV3FilterToV1Find(JsonElement? filter)
{
if (!filter.HasValue)
return null;
try
{
// Convert V3 JSON filter to V1 query string format
// This is a simplified conversion - full implementation would need more sophisticated mapping
var filterObj = filter.Value;
var queryParts = new List<string>();
foreach (var property in filterObj.EnumerateObject())
{
if (property.Name == "type")
continue; // Handled separately
var value = property.Value;
if (value.ValueKind == JsonValueKind.Object)
{
// Handle operators like $gte, $lte, etc.
foreach (var op in value.EnumerateObject())
{
queryParts.Add($"find[{property.Name}][{op.Name}]={op.Value}");
}
}
else
{
// Simple equality
queryParts.Add($"find[{property.Name}]={value}");
}
}
return queryParts.Count > 0 ? string.Join("&", queryParts) : null;
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to convert V3 filter to V1 find query");
return null;
}
}
/// <summary>
/// Convert V3 filter criteria (field$op=value format) to MongoDB-style JSON query
/// </summary>
/// <param name="filterCriteria">List of parsed filter criteria</param>
/// <returns>MongoDB-style JSON query string, or null if no criteria</returns>
private string? ConvertFilterCriteriaToFindQuery(List<V3FilterCriteria>? filterCriteria)
{
if (filterCriteria == null || filterCriteria.Count == 0)
return null;
var conditions = new Dictionary<string, object>();
foreach (var criteria in filterCriteria)
{
var mongoOp = criteria.Operator switch
{
"eq" => null, // Direct equality doesn't need operator
"ne" => "$ne",
"gt" => "$gt",
"gte" => "$gte",
"lt" => "$lt",
"lte" => "$lte",
"in" => "$in",
"nin" => "$nin",
"re" => "$regex",
_ => null,
};
if (mongoOp == null && criteria.Operator == "eq")
{
// Direct equality: { "field": "value" }
conditions[criteria.Field] = criteria.Value ?? "";
}
else if (mongoOp != null)
{
// Operator form: { "field": { "$op": "value" } }
conditions[criteria.Field] = new Dictionary<string, object?>
{
[mongoOp] = criteria.Value,
};
}
}
if (conditions.Count == 0)
return null;
return JsonSerializer.Serialize(conditions);
}
private DateTimeOffset GetLastModified(List<Entry> entries)
{
if (entries.Count == 0)
return DateTimeOffset.UtcNow;
// Use the most recent entry's date as last modified
var latestMills = entries.Max(e => e.Mills);
return DateTimeOffset.FromUnixTimeMilliseconds(latestMills);
}
private string GetUserId()
{
var authContext = HttpContext.GetAuthContext();
return authContext?.SubjectId?.ToString()
?? HttpContext.GetSubjectIdString()
?? "00000000-0000-0000-0000-000000000001";
}
private async Task EvaluateAlertsAsync(Entry[] entries, CancellationToken ct)
{
try
{
var latest = entries
.Where(e => e.Sgv.HasValue && e.Sgv.Value > 0)
.OrderByDescending(e => e.Mills)
.FirstOrDefault();
if (latest is null) return;
var context = new SensorContext
{
LatestValue = (decimal?)latest.Sgv,
LatestTimestamp = latest.Date ?? DateTimeOffset.FromUnixTimeMilliseconds(latest.Mills).UtcDateTime,
TrendRate = (decimal?)latest.TrendRate,
LastReadingAt = latest.Date ?? DateTimeOffset.FromUnixTimeMilliseconds(latest.Mills).UtcDateTime,
};
await _alertOrchestrator.EvaluateAsync(context, ct);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Alert evaluation failed after V3 entry creation");
}
}
#endregion
}