-
-
Notifications
You must be signed in to change notification settings - Fork 515
/
Copy pathEventController.cs
1457 lines (1301 loc) · 80.9 KB
/
EventController.cs
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Text;
using AutoMapper;
using Exceptionless.Core;
using Exceptionless.Core.Authorization;
using Exceptionless.Core.Extensions;
using Exceptionless.Core.Geo;
using Exceptionless.Core.Models;
using Exceptionless.Core.Models.Data;
using Exceptionless.Core.Plugins.Formatting;
using Exceptionless.Core.Queries.Validation;
using Exceptionless.Core.Queues.Models;
using Exceptionless.Core.Repositories;
using Exceptionless.Core.Repositories.Base;
using Exceptionless.Core.Repositories.Configuration;
using Exceptionless.Core.Repositories.Queries;
using Exceptionless.Core.Services;
using Exceptionless.DateTimeExtensions;
using Exceptionless.Web.Extensions;
using Exceptionless.Web.Models;
using Exceptionless.Web.Utility;
using FluentValidation;
using Foundatio.Caching;
using Foundatio.Queues;
using Foundatio.Repositories;
using Foundatio.Repositories.Elasticsearch.Extensions;
using Foundatio.Repositories.Extensions;
using Foundatio.Repositories.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json;
namespace Exceptionless.Web.Controllers;
[Route(API_PREFIX + "/events")]
[Authorize(Policy = AuthorizationRoles.ClientPolicy)]
public class EventController : RepositoryApiController<IEventRepository, PersistentEvent, PersistentEvent, PersistentEvent, UpdateEvent>
{
private static readonly HashSet<string> _ignoredKeys = new(StringComparer.OrdinalIgnoreCase) { "access_token", "api_key", "apikey" };
private readonly IOrganizationRepository _organizationRepository;
private readonly IProjectRepository _projectRepository;
private readonly IStackRepository _stackRepository;
private readonly EventPostService _eventPostService;
private readonly IQueue<EventUserDescription> _eventUserDescriptionQueue;
private readonly IValidator<UserDescription> _userDescriptionValidator;
private readonly FormattingPluginManager _formattingPluginManager;
private readonly ICacheClient _cache;
private readonly JsonSerializerSettings _jsonSerializerSettings;
private readonly AppOptions _appOptions;
public EventController(IEventRepository repository,
IOrganizationRepository organizationRepository,
IProjectRepository projectRepository,
IStackRepository stackRepository,
EventPostService eventPostService,
IQueue<EventUserDescription> eventUserDescriptionQueue,
IValidator<UserDescription> userDescriptionValidator,
FormattingPluginManager formattingPluginManager,
ICacheClient cacheClient,
JsonSerializerSettings jsonSerializerSettings,
IMapper mapper,
PersistentEventQueryValidator validator,
AppOptions appOptions,
TimeProvider timeProvider,
ILoggerFactory loggerFactory
) : base(repository, mapper, validator, timeProvider, loggerFactory)
{
_organizationRepository = organizationRepository;
_projectRepository = projectRepository;
_stackRepository = stackRepository;
_eventPostService = eventPostService;
_eventUserDescriptionQueue = eventUserDescriptionQueue;
_userDescriptionValidator = userDescriptionValidator;
_formattingPluginManager = formattingPluginManager;
_cache = cacheClient;
_jsonSerializerSettings = jsonSerializerSettings;
_appOptions = appOptions;
AllowedDateFields.Add(EventIndex.Alias.Date);
DefaultDateField = EventIndex.Alias.Date;
}
/// <summary>
/// Count
/// </summary>
/// <param name="filter">A filter that controls what data is returned from the server.</param>
/// <param name="aggregations">A list of values you want returned. Example: avg:value cardinality:value sum:users max:value min:value</param>
/// <param name="time">The time filter that limits the data being returned to a specific date range.</param>
/// <param name="offset">The time offset in minutes that controls what data is returned based on the time filter. This is used for time zone support.</param>
/// <param name="mode">If no mode is set then the whole event object will be returned. If the mode is set to summary than a lightweight object will be returned.</param>
/// <response code="400">Invalid filter.</response>
[HttpGet("count")]
[Authorize(Policy = AuthorizationRoles.UserPolicy)]
public async Task<ActionResult<CountResult>> GetCountAsync(string? filter = null, string? aggregations = null, string? time = null, string? offset = null, string? mode = null)
{
var organizations = await GetSelectedOrganizationsAsync(_organizationRepository, _projectRepository, _stackRepository, filter);
if (organizations.All(o => o.IsSuspended))
return Ok(CountResult.Empty);
var ti = GetTimeInfo(time, offset, organizations.GetRetentionUtcCutoff(_appOptions.MaximumRetentionDays, _timeProvider));
var sf = new AppFilter(organizations) { IsUserOrganizationsFilter = true };
return await CountInternalAsync(sf, ti, filter, aggregations, mode);
}
/// <summary>
/// Count by organization
/// </summary>
/// <param name="organizationId">The identifier of the organization.</param>
/// <param name="filter">A filter that controls what data is returned from the server.</param>
/// <param name="aggregations">A list of values you want returned. Example: avg:value cardinality:value sum:users max:value min:value</param>
/// <param name="time">The time filter that limits the data being returned to a specific date range.</param>
/// <param name="offset">The time offset in minutes that controls what data is returned based on the time filter. This is used for time zone support.</param>
/// <param name="mode">If no mode is set then the whole event object will be returned. If the mode is set to summary than a lightweight object will be returned.</param>
/// <response code="400">Invalid filter.</response>
[HttpGet("~/" + API_PREFIX + "/organizations/{organizationId:objectid}/events/count")]
[Authorize(Policy = AuthorizationRoles.UserPolicy)]
public async Task<ActionResult<CountResult>> GetCountByOrganizationAsync(string organizationId, string? filter = null, string? aggregations = null, string? time = null, string? offset = null, string? mode = null)
{
var organization = await GetOrganizationAsync(organizationId);
if (organization is null)
return NotFound();
if (organization.IsSuspended)
return PlanLimitReached("Unable to view event occurrences for the suspended organization.");
var ti = GetTimeInfo(time, offset, organization.GetRetentionUtcCutoff(_appOptions.MaximumRetentionDays, _timeProvider));
var sf = new AppFilter(organization);
return await CountInternalAsync(sf, ti, filter, aggregations, mode);
}
/// <summary>
/// Count by project
/// </summary>
/// <param name="projectId">The identifier of the project.</param>
/// <param name="filter">A filter that controls what data is returned from the server.</param>
/// <param name="aggregations">A list of values you want returned. Example: avg:value cardinality:value sum:users max:value min:value</param>
/// <param name="time">The time filter that limits the data being returned to a specific date range.</param>
/// <param name="offset">The time offset in minutes that controls what data is returned based on the time filter. This is used for time zone support.</param>
/// <param name="mode">If mode is set to stack_new, then additional filters will be added.</param>
/// <response code="400">Invalid filter.</response>
[HttpGet("~/" + API_PREFIX + "/projects/{projectId:objectid}/events/count")]
[Authorize(Policy = AuthorizationRoles.UserPolicy)]
public async Task<ActionResult<CountResult>> GetCountByProjectAsync(string projectId, string? filter = null, string? aggregations = null, string? time = null, string? offset = null, string? mode = null)
{
var project = await GetProjectAsync(projectId);
if (project is null)
return NotFound();
var organization = await GetOrganizationAsync(project.OrganizationId);
if (organization is null)
return NotFound();
if (organization.IsSuspended)
return PlanLimitReached("Unable to view event occurrences for the suspended organization.");
var ti = GetTimeInfo(time, offset, organization.GetRetentionUtcCutoff(project, _appOptions.MaximumRetentionDays, _timeProvider));
var sf = new AppFilter(project, organization);
return await CountInternalAsync(sf, ti, filter, aggregations, mode);
}
/// <summary>
/// Get by id
/// </summary>
/// <param name="id">The identifier of the event.</param>
/// <param name="time">The time filter that limits the data being returned to a specific date range.</param>
/// <param name="offset">The time offset in minutes that controls what data is returned based on the time filter. This is used for time zone support.</param>
/// <response code="404">The event occurrence could not be found.</response>
/// <response code="426">Unable to view event occurrence due to plan limits.</response>
[HttpGet("{id:objectid}", Name = "GetPersistentEventById")]
[Authorize(Policy = AuthorizationRoles.UserPolicy)]
public async Task<ActionResult<PersistentEvent>> GetAsync(string id, string? time = null, string? offset = null)
{
var model = await GetModelAsync(id, false);
if (model is null)
return NotFound();
var organization = await GetOrganizationAsync(model.OrganizationId);
if (organization is null)
return NotFound();
if (organization.IsSuspended || organization.RetentionDays > 0 && model.Date.UtcDateTime < _timeProvider.GetUtcNow().UtcDateTime.SubtractDays(organization.RetentionDays))
return PlanLimitReached("Unable to view event occurrence due to plan limits.");
var ti = GetTimeInfo(time, offset, organization.GetRetentionUtcCutoff(_appOptions.MaximumRetentionDays, _timeProvider));
var sf = new AppFilter(organization);
var result = await _repository.GetPreviousAndNextEventIdsAsync(model, sf, ti.Range.UtcStart, ti.Range.UtcEnd);
return OkWithLinks(model, [GetEntityResourceLink(result.Previous, "previous"),
GetEntityResourceLink(result.Next, "next"),
GetEntityResourceLink<Stack>(model.StackId, "parent")
]);
}
/// <summary>
/// Get all
/// </summary>
/// <param name="filter">A filter that controls what data is returned from the server.</param>
/// <param name="sort">Controls the sort order that the data is returned in. In this example -date returns the results descending by date.</param>
/// <param name="time">The time filter that limits the data being returned to a specific date range.</param>
/// <param name="offset">The time offset in minutes that controls what data is returned based on the time filter. This is used for time zone support.</param>
/// <param name="mode">If no mode is set then the whole event object will be returned. If the mode is set to summary than a lightweight object will be returned.</param>
/// <param name="page">The page parameter is used for pagination. This value must be greater than 0.</param>
/// <param name="limit">A limit on the number of objects to be returned. Limit can range between 1 and 100 items.</param>
/// <param name="before">The before parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <param name="after">The after parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <response code="400">Invalid filter.</response>
/// <response code="426">Unable to view event occurrences for the suspended organization.</response>
[HttpGet]
[Authorize(Policy = AuthorizationRoles.UserPolicy)]
[ProducesResponseType(typeof(ICollection<EventSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<StackSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<PersistentEvent>), 200)]
public async Task<ActionResult<ICollection<PersistentEvent>>> GetAllAsync(string? filter = null, string? sort = null, string? time = null, string? offset = null, string? mode = null, int? page = null, int limit = 10, string? before = null, string? after = null)
{
var organizations = await GetSelectedOrganizationsAsync(_organizationRepository, _projectRepository, _stackRepository, filter);
if (organizations.All(o => o.IsSuspended))
return Ok(EmptyModels);
var ti = GetTimeInfo(time, offset, organizations.GetRetentionUtcCutoff(_appOptions.MaximumRetentionDays, _timeProvider));
var sf = new AppFilter(organizations) { IsUserOrganizationsFilter = true };
return await GetInternalAsync(sf, ti, filter, sort, mode, page, limit, before, after);
}
private async Task<ActionResult<CountResult>> CountInternalAsync(AppFilter sf, TimeInfo ti, string? filter = null, string? aggregations = null, string? mode = null)
{
var pr = await _validator.ValidateQueryAsync(filter);
if (!pr.IsValid)
return BadRequest(pr.Message);
var far = await _validator.ValidateAggregationsAsync(aggregations);
if (!far.IsValid)
return BadRequest(far.Message);
sf.UsesPremiumFeatures = pr.UsesPremiumFeatures || far.UsesPremiumFeatures;
if (mode == "stack_new")
filter = AddFirstOccurrenceFilter(ti.Range, filter);
var query = new RepositoryQuery<PersistentEvent>()
.AppFilter(ShouldApplySystemFilter(sf, filter) ? sf : null)
.DateRange(ti.Range.UtcStart, ti.Range.UtcEnd, ti.Field)
.Index(ti.Range.UtcStart, ti.Range.UtcEnd);
CountResult result;
try
{
result = await _repository.CountAsync(q => q.SystemFilter(query).FilterExpression(filter).EnforceEventStackFilter().AggregationsExpression(aggregations));
}
catch (Exception ex)
{
using var _ = _logger.BeginScope(new ExceptionlessState().Property("Search Filter", new { SystemFilter = sf, UserFilter = filter, Time = ti, Aggregations = aggregations }).Tag("Search").Identity(CurrentUser.EmailAddress).Property("User", CurrentUser).SetHttpContext(HttpContext));
_logger.LogError(ex, "An error has occurred. Please check your filter or aggregations: {Message}", ex.Message);
throw;
}
return Ok(result);
}
private async Task<ActionResult<ICollection<PersistentEvent>>> GetInternalAsync(AppFilter sf, TimeInfo ti, string? filter = null, string? sort = null, string? mode = null, int? page = null, int limit = 10, string? before = null, string? after = null, bool usesPremiumFeatures = false)
{
using var _ = _logger.BeginScope(new ExceptionlessState()
.Property("Search Filter", new
{
Mode = mode,
SystemFilter = sf,
UserFilter = filter,
Time = ti,
Page = page,
Limit = limit,
Before = before,
After = after
})
.Tag("Search")
.Identity(CurrentUser.EmailAddress)
.Property("User", CurrentUser)
.SetHttpContext(HttpContext)
);
int resolvedPage = GetPage(page.GetValueOrDefault(1));
limit = GetLimit(limit);
int skip = GetSkip(resolvedPage, limit);
if (skip > MAXIMUM_SKIP)
return Ok(EmptyModels);
var pr = await _validator.ValidateQueryAsync(filter);
if (!pr.IsValid)
return BadRequest(pr.Message);
sf.UsesPremiumFeatures = pr.UsesPremiumFeatures || usesPremiumFeatures;
try
{
FindResults<PersistentEvent> events;
switch (mode)
{
case "summary":
events = await GetEventsInternalAsync(sf, ti, filter, sort, page, limit, before, after);
return OkWithResourceLinks(events.Documents.Select(e =>
{
var summaryData = _formattingPluginManager.GetEventSummaryData(e);
return new EventSummaryModel
{
Id = summaryData.Id,
TemplateKey = summaryData.TemplateKey,
Date = e.Date,
Data = summaryData.Data
};
}).ToList(), events.HasMore && !NextPageExceedsSkipLimit(page, limit), page, events.Total, events.Hits.FirstOrDefault()?.GetSortToken(), events.Hits.LastOrDefault()?.GetSortToken());
case "stack_recent":
case "stack_frequent":
case "stack_new":
case "stack_users":
if (!String.IsNullOrEmpty(sort))
return BadRequest("Sort is not supported in stack mode.");
var systemFilter = new RepositoryQuery<PersistentEvent>()
.AppFilter(ShouldApplySystemFilter(sf, filter) ? sf : null)
.EnforceEventStackFilter()
.DateRange(ti.Range.UtcStart, ti.Range.UtcEnd, (PersistentEvent e) => e.Date)
.Index(ti.Range.UtcStart, ti.Range.UtcEnd);
string? stackAggregations = mode switch
{
"stack_recent" => "cardinality:user sum:count~1 min:date -max:date",
"stack_frequent" => "cardinality:user -sum:count~1 min:date max:date",
"stack_new" => "cardinality:user sum:count~1 -min:date max:date",
"stack_users" => "-cardinality:user sum:count~1 min:date max:date",
_ => null
};
if (mode == "stack_new")
filter = AddFirstOccurrenceFilter(ti.Range, filter);
var countResponse = await _repository.CountAsync(q => q
.SystemFilter(systemFilter)
.FilterExpression(filter)
.EnforceEventStackFilter()
.AggregationsExpression($"terms:(stack_id~{GetSkip(resolvedPage + 1, limit) + 1} {stackAggregations})"));
var stackTerms = countResponse.Aggregations.Terms<string>("terms_stack_id");
if (stackTerms is null || stackTerms.Buckets.Count == 0)
return Ok(EmptyModels);
string[] stackIds = stackTerms.Buckets.Skip(skip).Take(limit + 1).Select(t => t.Key).ToArray();
var stacks = (await _stackRepository.GetByIdsAsync(stackIds)).Select(s => s.ApplyOffset(ti.Offset)).ToList();
var summaries = await GetStackSummariesAsync(stacks, stackTerms.Buckets, sf, ti);
long total = (stackTerms.Data?.GetValueOrDefault("SumOtherDocCount") as long? ?? 0L) + stackTerms.Buckets.Count;
return OkWithResourceLinks(summaries.Take(limit).ToList(), summaries.Count > limit && !NextPageExceedsSkipLimit(resolvedPage, limit), resolvedPage, total);
default:
events = await GetEventsInternalAsync(sf, ti, filter, sort, page, limit, before, after);
return OkWithResourceLinks(events.Documents.ToArray(), events.HasMore && !NextPageExceedsSkipLimit(page, limit), page, events.Total, events.Hits.FirstOrDefault()?.GetSortToken(), events.Hits.LastOrDefault()?.GetSortToken());
}
}
catch (ApplicationException ex)
{
string message = "An error has occurred: Please check your search filter.";
if (ex is DocumentLimitExceededException)
message = $"An error has occurred: {ex.Message ?? "Please limit your search criteria."}";
_logger.LogError(ex, message);
throw;
}
}
private static string AddFirstOccurrenceFilter(DateTimeRange timeRange, string? filter)
{
bool inverted = false;
if (filter is not null && filter.StartsWith("@!"))
{
inverted = true;
filter = filter.Substring(2);
}
var sb = new StringBuilder();
if (inverted)
sb.Append("@!");
sb.Append("first_occurrence:[\"");
sb.Append(timeRange.UtcStart.ToString("O"));
sb.Append("\" TO \"");
sb.Append(timeRange.UtcEnd.ToString("O"));
sb.Append("\"]");
if (String.IsNullOrEmpty(filter))
return sb.ToString();
sb.Append(' ');
bool isGrouped = filter.StartsWith('(') && filter.EndsWith(')');
if (isGrouped)
sb.Append(filter);
else
sb.Append('(').Append(filter).Append(')');
return sb.ToString();
}
private Task<FindResults<PersistentEvent>> GetEventsInternalAsync(AppFilter sf, TimeInfo ti, string? filter, string? sort, int? page, int limit, string? before, string? after)
{
if (String.IsNullOrEmpty(sort))
sort = $"-{EventIndex.Alias.Date}";
return _repository.FindAsync(
q => q.AppFilter(ShouldApplySystemFilter(sf, filter) ? sf : null)
.FilterExpression(filter)
.EnforceEventStackFilter()
.SortExpression(sort)
.DateRange(ti.Range.UtcStart, ti.Range.UtcEnd, ti.Field),
o => page.HasValue
? o.PageNumber(page).PageLimit(limit)
: o.SearchBeforeToken(before).SearchAfterToken(after).PageLimit(limit));
}
/// <summary>
/// Get by organization
/// </summary>
/// <param name="organizationId">The identifier of the organization.</param>
/// <param name="filter">A filter that controls what data is returned from the server.</param>
/// <param name="sort">Controls the sort order that the data is returned in. In this example -date returns the results descending by date.</param>
/// <param name="time">The time filter that limits the data being returned to a specific date range.</param>
/// <param name="offset">The time offset in minutes that controls what data is returned based on the time filter. This is used for time zone support.</param>
/// <param name="mode">If no mode is set then the whole event object will be returned. If the mode is set to summary than a lightweight object will be returned.</param>
/// <param name="page">The page parameter is used for pagination. This value must be greater than 0.</param>
/// <param name="limit">A limit on the number of objects to be returned. Limit can range between 1 and 100 items.</param>
/// <param name="before">The before parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <param name="after">The after parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <response code="400">Invalid filter.</response>
/// <response code="404">The organization could not be found.</response>
/// <response code="426">Unable to view event occurrences for the suspended organization.</response>
[HttpGet("~/" + API_PREFIX + "/organizations/{organizationId:objectid}/events")]
[Authorize(Policy = AuthorizationRoles.UserPolicy)]
[ProducesResponseType(typeof(ICollection<EventSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<StackSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<PersistentEvent>), 200)]
public async Task<ActionResult<ICollection<PersistentEvent>>> GetByOrganizationAsync(string organizationId, string? filter = null, string? sort = null, string? time = null, string? offset = null, string? mode = null, int? page = null, int limit = 10, string? before = null, string? after = null)
{
var organization = await GetOrganizationAsync(organizationId);
if (organization is null)
return NotFound();
if (organization.IsSuspended)
return PlanLimitReached("Unable to view event occurrences for the suspended organization.");
var ti = GetTimeInfo(time, offset, organization.GetRetentionUtcCutoff(_appOptions.MaximumRetentionDays, _timeProvider));
var sf = new AppFilter(organization);
return await GetInternalAsync(sf, ti, filter, sort, mode, page, limit, before, after);
}
/// <summary>
/// Get by project
/// </summary>
/// <param name="projectId">The identifier of the project.</param>
/// <param name="filter">A filter that controls what data is returned from the server.</param>
/// <param name="sort">Controls the sort order that the data is returned in. In this example -date returns the results descending by date.</param>
/// <param name="time">The time filter that limits the data being returned to a specific date range.</param>
/// <param name="offset">The time offset in minutes that controls what data is returned based on the time filter. This is used for time zone support.</param>
/// <param name="mode">If no mode is set then the whole event object will be returned. If the mode is set to summary than a lightweight object will be returned.</param>
/// <param name="page">The page parameter is used for pagination. This value must be greater than 0.</param>
/// <param name="limit">A limit on the number of objects to be returned. Limit can range between 1 and 100 items.</param>
/// <param name="before">The before parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <param name="after">The after parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <response code="400">Invalid filter.</response>
/// <response code="404">The project could not be found.</response>
/// <response code="426">Unable to view event occurrences for the suspended organization.</response>
[HttpGet("~/" + API_PREFIX + "/projects/{projectId:objectid}/events")]
[Authorize(Policy = AuthorizationRoles.UserPolicy)]
[ProducesResponseType(typeof(ICollection<EventSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<StackSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<PersistentEvent>), 200)]
public async Task<ActionResult<ICollection<PersistentEvent>>> GetByProjectAsync(string projectId, string? filter = null, string? sort = null, string? time = null, string? offset = null, string? mode = null, int? page = null, int limit = 10, string? before = null, string? after = null)
{
var project = await GetProjectAsync(projectId);
if (project is null)
return NotFound();
var organization = await GetOrganizationAsync(project.OrganizationId);
if (organization is null)
return NotFound();
if (organization.IsSuspended)
return PlanLimitReached("Unable to view event occurrences for the suspended organization.");
var ti = GetTimeInfo(time, offset, organization.GetRetentionUtcCutoff(project, _appOptions.MaximumRetentionDays, _timeProvider));
var sf = new AppFilter(project, organization);
return await GetInternalAsync(sf, ti, filter, sort, mode, page, limit, before, after);
}
/// <summary>
/// Get by stack
/// </summary>
/// <param name="stackId">The identifier of the stack.</param>
/// <param name="filter">A filter that controls what data is returned from the server.</param>
/// <param name="sort">Controls the sort order that the data is returned in. In this example -date returns the results descending by date.</param>
/// <param name="time">The time filter that limits the data being returned to a specific date range.</param>
/// <param name="offset">The time offset in minutes that controls what data is returned based on the time filter. This is used for time zone support.</param>
/// <param name="mode">If no mode is set then the whole event object will be returned. If the mode is set to summary than a lightweight object will be returned.</param>
/// <param name="page">The page parameter is used for pagination. This value must be greater than 0.</param>
/// <param name="limit">A limit on the number of objects to be returned. Limit can range between 1 and 100 items.</param>
/// <param name="before">The before parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <param name="after">The after parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <response code="400">Invalid filter.</response>
/// <response code="404">The stack could not be found.</response>
/// <response code="426">Unable to view event occurrences for the suspended organization.</response>
[HttpGet("~/" + API_PREFIX + "/stacks/{stackId:objectid}/events")]
[Authorize(Policy = AuthorizationRoles.UserPolicy)]
[ProducesResponseType(typeof(ICollection<EventSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<StackSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<PersistentEvent>), 200)]
public async Task<ActionResult<ICollection<PersistentEvent>>> GetByStackAsync(string stackId, string? filter = null, string? sort = null, string? time = null, string? offset = null, string? mode = null, int? page = null, int limit = 10, string? before = null, string? after = null)
{
var stack = await GetStackAsync(stackId);
if (stack is null)
return NotFound();
var organization = await GetOrganizationAsync(stack.OrganizationId);
if (organization is null)
return NotFound();
if (organization.IsSuspended)
return PlanLimitReached("Unable to view event occurrences for the suspended organization.");
var ti = GetTimeInfo(time, offset, organization.GetRetentionUtcCutoff(stack, _appOptions.MaximumRetentionDays, _timeProvider));
var sf = new AppFilter(stack, organization);
return await GetInternalAsync(sf, ti, filter, sort, mode, page, limit, before, after);
}
/// <summary>
/// Get by reference id
/// </summary>
/// <param name="referenceId">An identifier used that references an event instance.</param>
/// <param name="offset">The time offset in minutes that controls what data is returned based on the time filter. This is used for time zone support.</param>
/// <param name="mode">If no mode is set then the whole event object will be returned. If the mode is set to summary than a lightweight object will be returned.</param>
/// <param name="page">The page parameter is used for pagination. This value must be greater than 0.</param>
/// <param name="limit">A limit on the number of objects to be returned. Limit can range between 1 and 100 items.</param>
/// <param name="before">The before parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <param name="after">The after parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <response code="400">Invalid filter.</response>
/// <response code="426">Unable to view event occurrences for the suspended organization.</response>
[HttpGet("by-ref/{referenceId:identifier}")]
[Authorize(Policy = AuthorizationRoles.UserPolicy)]
[ProducesResponseType(typeof(ICollection<EventSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<StackSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<PersistentEvent>), 200)]
public async Task<ActionResult<ICollection<PersistentEvent>>> GetByReferenceIdAsync(string referenceId, string? offset = null, string? mode = null, int? page = null, int limit = 10, string? before = null, string? after = null)
{
var organizations = await GetSelectedOrganizationsAsync(_organizationRepository, _projectRepository, _stackRepository);
if (organizations.All(o => o.IsSuspended))
return Ok(EmptyModels);
var ti = GetTimeInfo(null, offset, organizations.GetRetentionUtcCutoff(_appOptions.MaximumRetentionDays, _timeProvider));
var sf = new AppFilter(organizations) { IsUserOrganizationsFilter = true };
return await GetInternalAsync(sf, ti, String.Concat("reference:", referenceId), null, mode, page, limit, before, after);
}
/// <summary>
/// Get by reference id
/// </summary>
/// <param name="referenceId">An identifier used that references an event instance.</param>
/// <param name="projectId">The identifier of the project.</param>
/// <param name="offset">The time offset in minutes that controls what data is returned based on the time filter. This is used for time zone support.</param>
/// <param name="mode">If no mode is set then the whole event object will be returned. If the mode is set to summary than a lightweight object will be returned.</param>
/// <param name="page">The page parameter is used for pagination. This value must be greater than 0.</param>
/// <param name="limit">A limit on the number of objects to be returned. Limit can range between 1 and 100 items.</param>
/// <param name="before">The before parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <param name="after">The after parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <response code="400">Invalid filter.</response>
/// <response code="404">The project could not be found.</response>
/// <response code="426">Unable to view event occurrences for the suspended organization.</response>
[HttpGet("~/" + API_PREFIX + "/projects/{projectId:objectid}/events/by-ref/{referenceId:identifier}")]
[Authorize(Policy = AuthorizationRoles.UserPolicy)]
[ProducesResponseType(typeof(ICollection<EventSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<StackSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<PersistentEvent>), 200)]
public async Task<ActionResult<ICollection<PersistentEvent>>> GetByReferenceIdAsync(string referenceId, string projectId, string? offset = null, string? mode = null, int? page = null, int limit = 10, string? before = null, string? after = null)
{
var project = await GetProjectAsync(projectId);
if (project is null)
return NotFound();
var organization = await GetOrganizationAsync(project.OrganizationId);
if (organization is null)
return NotFound();
if (organization.IsSuspended)
return PlanLimitReached("Unable to view event occurrences for the suspended organization.");
var ti = GetTimeInfo(null, offset, organization.GetRetentionUtcCutoff(project, _appOptions.MaximumRetentionDays, _timeProvider));
var sf = new AppFilter(project, organization);
return await GetInternalAsync(sf, ti, String.Concat("reference:", referenceId), null, mode, page, limit, before, after);
}
/// <summary>
/// Get a list of all sessions or events by a session id
/// </summary>
/// <param name="sessionId">An identifier that represents a session of events.</param>
/// <param name="filter">A filter that controls what data is returned from the server.</param>
/// <param name="sort">Controls the sort order that the data is returned in. In this example -date returns the results descending by date.</param>
/// <param name="time">The time filter that limits the data being returned to a specific date range.</param>
/// <param name="offset">The time offset in minutes that controls what data is returned based on the time filter. This is used for time zone support.</param>
/// <param name="mode">If no mode is set then the whole event object will be returned. If the mode is set to summary than a lightweight object will be returned.</param>
/// <param name="page">The page parameter is used for pagination. This value must be greater than 0.</param>
/// <param name="limit">A limit on the number of objects to be returned. Limit can range between 1 and 100 items.</param>
/// <param name="before">The before parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <param name="after">The after parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <response code="400">Invalid filter.</response>
/// <response code="426">Unable to view event occurrences for the suspended organization.</response>
[HttpGet("sessions/{sessionId:identifier}")]
[Authorize(Policy = AuthorizationRoles.UserPolicy)]
[ProducesResponseType(typeof(ICollection<EventSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<StackSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<PersistentEvent>), 200)]
public async Task<ActionResult<ICollection<PersistentEvent>>> GetBySessionIdAsync(string sessionId, string? filter = null, string? sort = null, string? time = null, string? offset = null, string? mode = null, int? page = null, int limit = 10, string? before = null, string? after = null)
{
var organizations = await GetSelectedOrganizationsAsync(_organizationRepository, _projectRepository, _stackRepository, filter);
if (organizations.All(o => o.IsSuspended))
return Ok(EmptyModels);
var ti = GetTimeInfo(time, offset, organizations.GetRetentionUtcCutoff(_appOptions.MaximumRetentionDays, _timeProvider));
var sf = new AppFilter(organizations) { IsUserOrganizationsFilter = true };
return await GetInternalAsync(sf, ti, $"(reference:{sessionId} OR ref.session:{sessionId}) {filter}", sort, mode, page, limit, before, after, true);
}
/// <summary>
/// Get a list of by a session id
/// </summary>
/// <param name="sessionId">An identifier that represents a session of events.</param>
/// <param name="projectId">The identifier of the project.</param>
/// <param name="filter">A filter that controls what data is returned from the server.</param>
/// <param name="sort">Controls the sort order that the data is returned in. In this example -date returns the results descending by date.</param>
/// <param name="time">The time filter that limits the data being returned to a specific date range.</param>
/// <param name="offset">The time offset in minutes that controls what data is returned based on the time filter. This is used for time zone support.</param>
/// <param name="mode">If no mode is set then the whole event object will be returned. If the mode is set to summary than a lightweight object will be returned.</param>
/// <param name="page">The page parameter is used for pagination. This value must be greater than 0.</param>
/// <param name="limit">A limit on the number of objects to be returned. Limit can range between 1 and 100 items.</param>
/// <param name="before">The before parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <param name="after">The after parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <response code="400">Invalid filter.</response>
/// <response code="404">The project could not be found.</response>
/// <response code="426">Unable to view event occurrences for the suspended organization.</response>
[HttpGet("~/" + API_PREFIX + "/projects/{projectId:objectid}/events/sessions/{sessionId:identifier}")]
[Authorize(Policy = AuthorizationRoles.UserPolicy)]
[ProducesResponseType(typeof(ICollection<EventSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<StackSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<PersistentEvent>), 200)]
public async Task<ActionResult<ICollection<PersistentEvent>>> GetBySessionIdAndProjectAsync(string sessionId, string projectId, string? filter = null, string? sort = null, string? time = null, string? offset = null, string? mode = null, int? page = null, int limit = 10, string? before = null, string? after = null)
{
var project = await GetProjectAsync(projectId);
if (project is null)
return NotFound();
var organization = await GetOrganizationAsync(project.OrganizationId);
if (organization is null)
return NotFound();
if (organization.IsSuspended)
return PlanLimitReached("Unable to view event occurrences for the suspended organization.");
var ti = GetTimeInfo(time, offset, organization.GetRetentionUtcCutoff(project, _appOptions.MaximumRetentionDays, _timeProvider));
var sf = new AppFilter(project, organization);
return await GetInternalAsync(sf, ti, $"(reference:{sessionId} OR ref.session:{sessionId}) {filter}", sort, mode, page, limit, before, after, true);
}
/// <summary>
/// Get a list of all sessions
/// </summary>
/// <param name="filter">A filter that controls what data is returned from the server.</param>
/// <param name="sort">Controls the sort order that the data is returned in. In this example -date returns the results descending by date.</param>
/// <param name="time">The time filter that limits the data being returned to a specific date range.</param>
/// <param name="offset">The time offset in minutes that controls what data is returned based on the time filter. This is used for time zone support.</param>
/// <param name="mode">If no mode is set then the whole event object will be returned. If the mode is set to summary than a lightweight object will be returned.</param>
/// <param name="page">The page parameter is used for pagination. This value must be greater than 0.</param>
/// <param name="limit">A limit on the number of objects to be returned. Limit can range between 1 and 100 items.</param>
/// <param name="before">The before parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <param name="after">The after parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <response code="400">Invalid filter.</response>
[HttpGet("sessions")]
[Authorize(Policy = AuthorizationRoles.UserPolicy)]
[ProducesResponseType(typeof(ICollection<EventSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<StackSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<PersistentEvent>), 200)]
public async Task<ActionResult<ICollection<PersistentEvent>>> GetSessionsAsync(string? filter = null, string? sort = null, string? time = null, string? offset = null, string? mode = null, int? page = null, int limit = 10, string? before = null, string? after = null)
{
var organizations = await GetSelectedOrganizationsAsync(_organizationRepository, _projectRepository, _stackRepository, filter);
if (organizations.All(o => o.IsSuspended))
return Ok(EmptyModels);
var ti = GetTimeInfo(time, offset, organizations.GetRetentionUtcCutoff(_appOptions.MaximumRetentionDays, _timeProvider));
var sf = new AppFilter(organizations) { IsUserOrganizationsFilter = true };
return await GetInternalAsync(sf, ti, $"type:{Event.KnownTypes.Session} {filter}", sort, mode, page, limit, before, after, true);
}
/// <summary>
/// Get a list of all sessions
/// </summary>
/// <param name="organizationId">The identifier of the organization.</param>
/// <param name="filter">A filter that controls what data is returned from the server.</param>
/// <param name="sort">Controls the sort order that the data is returned in. In this example -date returns the results descending by date.</param>
/// <param name="time">The time filter that limits the data being returned to a specific date range.</param>
/// <param name="offset">The time offset in minutes that controls what data is returned based on the time filter. This is used for time zone support.</param>
/// <param name="mode">If no mode is set then the whole event object will be returned. If the mode is set to summary than a lightweight object will be returned.</param>
/// <param name="page">The page parameter is used for pagination. This value must be greater than 0.</param>
/// <param name="limit">A limit on the number of objects to be returned. Limit can range between 1 and 100 items.</param>
/// <param name="before">The before parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <param name="after">The after parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <response code="400">Invalid filter.</response>
/// <response code="404">The project could not be found.</response>
/// <response code="426">Unable to view event occurrences for the suspended organization.</response>
[HttpGet("~/" + API_PREFIX + "/organizations/{organizationId:objectid}/events/sessions")]
[Authorize(Policy = AuthorizationRoles.UserPolicy)]
[ProducesResponseType(typeof(ICollection<EventSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<StackSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<PersistentEvent>), 200)]
public async Task<ActionResult<ICollection<PersistentEvent>>> GetSessionByOrganizationAsync(string organizationId, string? filter = null, string? sort = null, string? time = null, string? offset = null, string? mode = null, int? page = null, int limit = 10, string? before = null, string? after = null)
{
var organization = await GetOrganizationAsync(organizationId);
if (organization is null)
return NotFound();
if (organization.IsSuspended)
return PlanLimitReached("Unable to view event occurrences for the suspended organization.");
var ti = GetTimeInfo(time, offset, organization.GetRetentionUtcCutoff(_appOptions.MaximumRetentionDays, _timeProvider));
var sf = new AppFilter(organization);
return await GetInternalAsync(sf, ti, $"type:{Event.KnownTypes.Session} {filter}", sort, mode, page, limit, before, after, true);
}
/// <summary>
/// Get a list of all sessions
/// </summary>
/// <param name="projectId">The identifier of the project.</param>
/// <param name="filter">A filter that controls what data is returned from the server.</param>
/// <param name="sort">Controls the sort order that the data is returned in. In this example -date returns the results descending by date.</param>
/// <param name="time">The time filter that limits the data being returned to a specific date range.</param>
/// <param name="offset">The time offset in minutes that controls what data is returned based on the time filter. This is used for time zone support.</param>
/// <param name="mode">If no mode is set then the whole event object will be returned. If the mode is set to summary than a lightweight object will be returned.</param>
/// <param name="page">The page parameter is used for pagination. This value must be greater than 0.</param>
/// <param name="limit">A limit on the number of objects to be returned. Limit can range between 1 and 100 items.</param>
/// <param name="before">The before parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <param name="after">The after parameter is a cursor used for pagination and defines your place in the list of results.</param>
/// <response code="400">Invalid filter.</response>
/// <response code="404">The project could not be found.</response>
/// <response code="426">Unable to view event occurrences for the suspended organization.</response>
[HttpGet("~/" + API_PREFIX + "/projects/{projectId:objectid}/events/sessions")]
[Authorize(Policy = AuthorizationRoles.UserPolicy)]
[ProducesResponseType(typeof(ICollection<EventSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<StackSummaryModel>), 200)]
[ProducesResponseType(typeof(ICollection<PersistentEvent>), 200)]
public async Task<ActionResult<ICollection<PersistentEvent>>> GetSessionByProjectAsync(string projectId, string? filter = null, string? sort = null, string? time = null, string? offset = null, string? mode = null, int? page = null, int limit = 10, string? before = null, string? after = null)
{
var project = await GetProjectAsync(projectId);
if (project is null)
return NotFound();
var organization = await GetOrganizationAsync(project.OrganizationId);
if (organization is null)
return NotFound();
if (organization.IsSuspended)
return PlanLimitReached("Unable to view event occurrences for the suspended organization.");
var ti = GetTimeInfo(time, offset, organization.GetRetentionUtcCutoff(project, _appOptions.MaximumRetentionDays, _timeProvider));
var sf = new AppFilter(project, organization);
return await GetInternalAsync(sf, ti, $"type:{Event.KnownTypes.Session} {filter}", sort, mode, page, limit, before, after, true);
}
/// <summary>
/// Set user description
/// </summary>
/// <remarks>You can also save an end users contact information and a description of the event. This is really useful for error events as a user can specify reproduction steps in the description.</remarks>
/// <param name="referenceId">An identifier used that references an event instance.</param>
/// <param name="description">The user description.</param>
/// <param name="projectId">The identifier of the project.</param>
/// <response code="400">Description must be specified.</response>
/// <response code="404">The event occurrence with the specified reference id could not be found.</response>
[HttpPost("by-ref/{referenceId:identifier}/user-description")]
[HttpPost("~/" + API_PREFIX + "/projects/{projectId:objectid}/events/by-ref/{referenceId:identifier}/user-description")]
[Consumes("application/json")]
[ConfigurationResponseFilter]
[ProducesResponseType(StatusCodes.Status202Accepted)]
public async Task<IActionResult> SetUserDescriptionAsync(string referenceId, UserDescription description, string? projectId = null)
{
string? claimProjectId = Request.GetProjectId();
if (projectId is not null && claimProjectId is not null && !String.Equals(projectId, claimProjectId))
{
_logger.ProjectRouteDoesNotMatch(claimProjectId, projectId);
return NotFound();
}
if (String.IsNullOrEmpty(referenceId))
return NotFound();
projectId ??= claimProjectId ?? Request.GetDefaultProjectId();
// must have a project id
if (String.IsNullOrEmpty(projectId))
return BadRequest("No project id specified and no default project was found");
var result = await _userDescriptionValidator.ValidateAsync(description);
if (!result.IsValid)
return BadRequest(result.Errors.ToErrorMessage());
var project = await GetProjectAsync(projectId);
if (project is null)
return NotFound();
// Set the project for the configuration response filter.
Request.SetProject(project);
var eventUserDescription = await MapAsync<EventUserDescription>(description);
eventUserDescription.ProjectId = project.Id;
eventUserDescription.ReferenceId = referenceId;
await _eventUserDescriptionQueue.EnqueueAsync(eventUserDescription);
return StatusCode(StatusCodes.Status202Accepted);
}
[Obsolete("Use PATCH /api/v2/events")]
[HttpPatch("~/api/v1/error/{id:objectid}")]
[Consumes("application/json")]
[ConfigurationResponseFilter]
public async Task<IActionResult> LegacyPatchAsync(string id, Delta<UpdateEvent> changes)
{
if (changes is null)
return Ok();
if (changes.UnknownProperties.TryGetValue("UserEmail", out object? value))
changes.TrySetPropertyValue("EmailAddress", value);
if (changes.UnknownProperties.TryGetValue("UserDescription", out value))
changes.TrySetPropertyValue("Description", value);
var userDescription = new UserDescription();
changes.Patch(userDescription);
return await SetUserDescriptionAsync(id, userDescription);
}
/// <summary>
/// Submit heartbeat
/// </summary>
/// <param name="id">The session id or user id.</param>
/// <param name="close">If true, the session will be closed.</param>
/// <response code="200">OK</response>
/// <response code="400">No project id specified and no default project was found.</response>
/// <response code="404">No project was found.</response>
[HttpGet("session/heartbeat")]
public async Task<IActionResult> RecordHeartbeatAsync(string? id = null, bool close = false)
{
if (_appOptions.EventSubmissionDisabled || String.IsNullOrEmpty(id))
return Ok();
string? projectId = Request.GetDefaultProjectId();
if (String.IsNullOrEmpty(projectId))
return BadRequest("No project id specified and no default project was found.");
string identityHash = id.ToSHA1();
string heartbeatCacheKey = String.Concat("Project:", projectId, ":heartbeat:", identityHash);
try
{
await Task.WhenAll(
_cache.SetAsync(heartbeatCacheKey, _timeProvider.GetUtcNow().UtcDateTime, TimeSpan.FromHours(2)),
close ? _cache.SetAsync(String.Concat(heartbeatCacheKey, "-close"), true, TimeSpan.FromHours(2)) : Task.CompletedTask
);
}
catch (Exception ex)
{
if (projectId != _appOptions.InternalProjectId)
{
using var _ = _logger.BeginScope(new ExceptionlessState().Project(projectId).Property("Id", id).Property("Close", close).SetHttpContext(HttpContext));
_logger.LogError(ex, "Error enqueuing session heartbeat: {Message}", ex.Message);
}
throw;
}
return Ok();
}
[Obsolete("Use GET /api/v2/events/submit")]
[HttpGet("~/api/v1/events/submit")]
[HttpGet("~/api/v1/events/submit/{type:minlength(1)}")]
[HttpGet("~/api/v1/projects/{projectId:objectid}/events/submit")]
[HttpGet("~/api/v1/projects/{projectId:objectid}/events/submit/{type:minlength(1)}")]
[ConfigurationResponseFilter]
public Task<ActionResult> GetSubmitEventV1Async(string? projectId = null, string? type = null, [FromHeader][UserAgent] string? userAgent = null, [FromQuery][QueryStringParameters] IQueryCollection? parameters = null)
{
return GetSubmitEventAsync(projectId, 1, type, userAgent, parameters);
}
/// <summary>
/// Submit event by GET
/// </summary>
/// <remarks>
/// You can submit an event using an HTTP GET and query string parameters. Any unknown query string parameters will be added to the extended data of the event.
///
/// Feature usage named build with a duration of 10:
/// <code><![CDATA[/events/submit?access_token=YOUR_API_KEY&type=usage&source=build&value=10]]></code>
///
/// Log with message, geo and extended data
/// <code><![CDATA[/events/submit?access_token=YOUR_API_KEY&type=log&message=Hello World&source=server01&geo=32.85,-96.9613&randomproperty=true]]></code>
/// </remarks>
/// <param name="type">The event type (ie. error, log message, feature usage).</param>
/// <param name="source">The event source (ie. machine name, log name, feature name).</param>
/// <param name="message">The event message.</param>
/// <param name="reference">An optional identifier to be used for referencing this event instance at a later time.</param>
/// <param name="date">The date that the event occurred on.</param>
/// <param name="count">The number of duplicated events.</param>
/// <param name="value">The value of the event if any.</param>
/// <param name="geo">The geo coordinates where the event happened.</param>
/// <param name="tags">A list of tags used to categorize this event (comma separated).</param>
/// <param name="identity">The user's identity that the event happened to.</param>
/// <param name="identityname">The user's friendly name that the event happened to.</param>
/// <param name="userAgent">The user agent that submitted the event.</param>
/// <param name="parameters">Query string parameters that control what properties are set on the event</param>
/// <response code="200">OK</response>
/// <response code="400">No project id specified and no default project was found.</response>
/// <response code="404">No project was found.</response>
[HttpGet("submit")]
[ConfigurationResponseFilter]
#pragma warning disable IDE0060
public Task<ActionResult> GetSubmitEventV2Async(string? type = null, string? source = null, string? message = null, string? reference = null,
string? date = null, int? count = null, decimal? value = null, string? geo = null, string? tags = null, string? identity = null,
string? identityname = null, [FromHeader][UserAgent] string? userAgent = null, [FromQuery][QueryStringParameters] IQueryCollection? parameters = null)
{
return GetSubmitEventAsync(null, 2, null, userAgent, parameters);
}
#pragma warning restore IDE0060
/// <summary>
/// Submit event type by GET
/// </summary>
/// <remarks>
/// You can submit an event using an HTTP GET and query string parameters.
///
/// Feature usage event named build with a value of 10:
/// <code><![CDATA[/events/submit/usage?access_token=YOUR_API_KEY&source=build&value=10]]></code>
///
/// Log event with message, geo and extended data
/// <code><![CDATA[/events/submit/log?access_token=YOUR_API_KEY&message=Hello World&source=server01&geo=32.85,-96.9613&randomproperty=true]]></code>
/// </remarks>
/// <param name="type">The event type (ie. error, log message, feature usage).</param>
/// <param name="source">The event source (ie. machine name, log name, feature name).</param>
/// <param name="message">The event message.</param>
/// <param name="reference">An optional identifier to be used for referencing this event instance at a later time.</param>
/// <param name="date">The date that the event occurred on.</param>
/// <param name="count">The number of duplicated events.</param>
/// <param name="value">The value of the event if any.</param>
/// <param name="geo">The geo coordinates where the event happened.</param>
/// <param name="tags">A list of tags used to categorize this event (comma separated).</param>
/// <param name="identity">The user's identity that the event happened to.</param>
/// <param name="identityname">The user's friendly name that the event happened to.</param>
/// <param name="userAgent">The user agent that submitted the event.</param>
/// <param name="parameters">Query string parameters that control what properties are set on the event</param>
/// <response code="200">OK</response>
/// <response code="400">No project id specified and no default project was found.</response>
/// <response code="404">No project was found.</response>
[HttpGet("submit/{type:minlength(1)}")]
[ConfigurationResponseFilter]
#pragma warning disable IDE0060
public Task<ActionResult> GetSubmitEventByTypeV2Async(string type, string? source = null, string? message = null, string? reference = null,
string? date = null, int? count = null, decimal? value = null, string? geo = null, string? tags = null, string? identity = null,
string? identityname = null, [FromHeader][UserAgent] string? userAgent = null, [FromQuery][QueryStringParameters] IQueryCollection? parameters = null)
{
return GetSubmitEventAsync(null, 2, type, userAgent, parameters);
}
#pragma warning restore IDE0060
/// <summary>
/// Submit event type by GET for a specific project
/// </summary>
/// <remarks>
/// You can submit an event using an HTTP GET and query string parameters.
///
/// Feature usage named build with a duration of 10:
/// <code><![CDATA[/projects/{projectId}/events/submit?access_token=YOUR_API_KEY&type=usage&source=build&value=10]]></code>
///
/// Log with message, geo and extended data
/// <code><![CDATA[/projects/{projectId}/events/submit?access_token=YOUR_API_KEY&type=log&message=Hello World&source=server01&geo=32.85,-96.9613&randomproperty=true]]></code>
/// </remarks>
/// <param name="projectId">The identifier of the project.</param>
/// <param name="type">The event type (ie. error, log message, feature usage).</param>
/// <param name="source">The event source (ie. machine name, log name, feature name).</param>
/// <param name="message">The event message.</param>
/// <param name="reference">An optional identifier to be used for referencing this event instance at a later time.</param>
/// <param name="date">The date that the event occurred on.</param>
/// <param name="count">The number of duplicated events.</param>
/// <param name="value">The value of the event if any.</param>
/// <param name="geo">The geo coordinates where the event happened.</param>
/// <param name="tags">A list of tags used to categorize this event (comma separated).</param>
/// <param name="identity">The user's identity that the event happened to.</param>
/// <param name="identityname">The user's friendly name that the event happened to.</param>
/// <param name="userAgent">The user agent that submitted the event.</param>
/// <param name="parameters">Query String parameters that control what properties are set on the event</param>
/// <response code="200">OK</response>
/// <response code="400">No project id specified and no default project was found.</response>
/// <response code="404">No project was found.</response>
[HttpGet("~/api/v2/projects/{projectId:objectid}/events/submit")]