/
MongoMonitoringApi.cs
795 lines (695 loc) · 28.1 KB
/
MongoMonitoringApi.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
using System;
using System.Collections.Generic;
using System.Linq;
using Hangfire.Common;
using Hangfire.Mongo.Database;
using Hangfire.Mongo.Dto;
using Hangfire.States;
using Hangfire.Storage;
using Hangfire.Storage.Monitoring;
using MongoDB.Bson;
using MongoDB.Driver;
using ServerDto = Hangfire.Storage.Monitoring.ServerDto;
namespace Hangfire.Mongo
{
#pragma warning disable 1591
public class MongoMonitoringApi : JobStorageMonitor
{
private readonly HangfireDbContext _dbContext;
public MongoMonitoringApi(HangfireDbContext dbContext)
{
_dbContext = dbContext;
}
public override IList<QueueWithTopEnqueuedJobsDto> Queues()
{
var queues = GetQueues();
var result = new List<QueueWithTopEnqueuedJobsDto>(queues.Count);
foreach (var queue in queues)
{
var enqueuedJobIds = GetEnqueuedJobIds(queue, 0, 5);
var counters = GetEnqueuedAndFetchedCount(queue);
result.Add(new QueueWithTopEnqueuedJobsDto
{
Name = queue,
Length = counters.EnqueuedCount ?? 0,
Fetched = counters.FetchedCount,
FirstJobs = EnqueuedJobs(enqueuedJobIds)
});
}
return result;
}
public override IList<ServerDto> Servers()
{
var servers = _dbContext.Server.AsQueryable().ToList().Select(b => new Dto.ServerDto(b));
var result = new List<ServerDto>();
foreach (var server in servers)
{
result.Add(new ServerDto
{
Name = server.Id,
Heartbeat = server.LastHeartbeat,
Queues = server.Queues,
StartedAt = server.StartedAt ?? DateTime.MinValue,
WorkersCount = server.WorkerCount
});
}
return result;
}
public override JobDetailsDto JobDetails(string jobId)
{
var id = ObjectId.Parse(jobId);
var filter = new BsonDocument
{
["_id"] = id,
["_t"] = nameof(JobDto)
};
var jobDoc = _dbContext.JobGraph.Find(filter).FirstOrDefault();
if (jobDoc == null)
{
return null;
}
var job = new JobDto(jobDoc);
var history = job.StateHistory.Select(x => new StateHistoryDto
{
StateName = x.Name,
CreatedAt = x.CreatedAt,
Reason = x.Reason,
Data = x.Data
})
.Reverse()
.ToList();
return new JobDetailsDto
{
CreatedAt = job.CreatedAt,
Job = DeserializeJob(job.InvocationData, job.Arguments),
History = history,
Properties = job.Parameters
};
}
private static readonly BsonArray StatisticsStateNames = new BsonArray
{
EnqueuedState.StateName,
FailedState.StateName,
ProcessingState.StateName,
ScheduledState.StateName,
AwaitingState.StateName,
};
public override StatisticsDto GetStatistics()
{
var stats = new StatisticsDto();
var filter = new BsonDocument
{
["_t"] = nameof(JobDto),
[nameof(JobDto.StateName)] = new BsonDocument
{
["$in"] = StatisticsStateNames
}
};
var pipeline = new BsonDocument[]
{
new BsonDocument("$match", filter),
new BsonDocument("$group",
new BsonDocument
{
{"_id", $"${nameof(JobDto.StateName)}"},
{"count", new BsonDocument("$sum", 1)}
})
};
var countByStates = _dbContext
.JobGraph
.Aggregate<BsonDocument>(pipeline)
.ToList()
.ToDictionary(b => b["_id"].ToString(), b => b["count"].AsInt32);
int GetCountIfExists(string name) => countByStates.TryGetValue(name, out var state) ? state : 0;
stats.Enqueued = GetCountIfExists(EnqueuedState.StateName);
stats.Failed = GetCountIfExists(FailedState.StateName);
stats.Processing = GetCountIfExists(ProcessingState.StateName);
stats.Scheduled = GetCountIfExists(ScheduledState.StateName);
stats.Awaiting = GetCountIfExists(AwaitingState.StateName);
stats.Servers = _dbContext.Server.Count(new BsonDocument());
var statsSucceeded = $@"stats:{State.Succeeded}";
filter = new BsonDocument
{
["_t"] = nameof(CounterDto),
[nameof(KeyJobDto.Key)] = statsSucceeded
};
var succeededCounter = _dbContext.JobGraph.Find(filter).FirstOrDefault();
stats.Succeeded = succeededCounter?.GetElement(nameof(CounterDto.Value)).Value.AsInt64 ?? 0;
var statsDeleted = $@"stats:{State.Deleted}";
filter = new BsonDocument
{
["_t"] = nameof(CounterDto),
[nameof(KeyJobDto.Key)] = statsDeleted
};
var deletedCounter = _dbContext.JobGraph.Find(filter).FirstOrDefault();
stats.Deleted = deletedCounter?.GetElement(nameof(CounterDto.Value)).Value.AsInt64 ?? 0;
filter = new BsonDocument
{
[nameof(KeyJobDto.Key)] = new BsonDocument("$regex", "^recurring-jobs"),
["_t"] = nameof(SetDto)
};
stats.Recurring = _dbContext.JobGraph.Count(filter);
stats.Queues = GetQueues().Count;
return stats;
}
public override JobList<EnqueuedJobDto> EnqueuedJobs(string queue, int from, int perPage)
{
var enqueuedJobIds = GetEnqueuedJobIds(queue, from, perPage);
return EnqueuedJobs(enqueuedJobIds);
}
public override JobList<FetchedJobDto> FetchedJobs(string queue, int from, int perPage)
{
var fetchedJobIds = GetFetchedJobIds(queue, from, perPage);
return FetchedJobs(_dbContext, fetchedJobIds);
}
public override JobList<ProcessingJobDto> ProcessingJobs(int from, int count)
{
return GetJobs(from, count,
ProcessingState.StateName,
(jobSummary, job, invocationData, loadException, stateData) => new ProcessingJobDto
{
Job = job,
LoadException = loadException,
InvocationData = invocationData,
InProcessingState =
ProcessingState.StateName.Equals(jobSummary.StateName, StringComparison.OrdinalIgnoreCase),
ServerId = stateData.TryGetValue("ServerId", out var value) ? value : stateData["ServerName"],
StartedAt = jobSummary.StateChanged,
StateData = stateData
});
}
public override JobList<ScheduledJobDto> ScheduledJobs(int from, int count)
{
return GetJobs(from, count, ScheduledState.StateName,
(sqlJob, job, invocationData, loadException, stateData) => new ScheduledJobDto
{
Job = job,
LoadException = loadException,
InvocationData = invocationData,
InScheduledState =
ScheduledState.StateName.Equals(sqlJob.StateName, StringComparison.OrdinalIgnoreCase),
EnqueueAt = JobHelper.DeserializeNullableDateTime(stateData["EnqueueAt"]) ?? DateTime.MinValue,
ScheduledAt = sqlJob.StateChanged,
StateData = stateData
});
}
public override JobList<SucceededJobDto> SucceededJobs(int from, int count)
{
return GetJobs(from, count, SucceededState.StateName,
(sqlJob, job, invocationData, loadException, stateData) => new SucceededJobDto
{
Job = job,
LoadException = loadException,
InvocationData = invocationData,
InSucceededState =
SucceededState.StateName.Equals(sqlJob.StateName, StringComparison.OrdinalIgnoreCase),
Result = stateData["Result"],
TotalDuration = stateData.ContainsKey("PerformanceDuration") &&
stateData.TryGetValue("Latency", out var value)
? (long?) long.Parse(stateData["PerformanceDuration"]) + (long?) long.Parse(value)
: null,
SucceededAt = sqlJob.StateChanged,
StateData = stateData
});
}
public override JobList<FailedJobDto> FailedJobs(int from, int count)
{
return GetJobs(from, count, FailedState.StateName,
(sqlJob, job, invocationData, loadException, stateData) => new FailedJobDto
{
Job = job,
LoadException = loadException,
InvocationData = invocationData,
InFailedState = FailedState.StateName.Equals(sqlJob.StateName, StringComparison.OrdinalIgnoreCase),
Reason = sqlJob.StateReason,
ExceptionDetails = stateData["ExceptionDetails"],
ExceptionMessage = stateData["ExceptionMessage"],
ExceptionType = stateData["ExceptionType"],
FailedAt = sqlJob.StateChanged,
StateData = stateData
});
}
public override JobList<DeletedJobDto> DeletedJobs(int from, int count)
{
return GetJobs(from, count, DeletedState.StateName,
(sqlJob, job, invocationData, loadException, stateData) => new DeletedJobDto
{
Job = job,
LoadException = loadException,
InvocationData = invocationData,
InDeletedState =
DeletedState.StateName.Equals(sqlJob.StateName, StringComparison.OrdinalIgnoreCase),
DeletedAt = sqlJob.StateChanged,
StateData = stateData
});
}
public override JobList<AwaitingJobDto> AwaitingJobs(int from, int count)
{
return GetJobs(from, count, AwaitingState.StateName,
(sqlJob, job, invocationData, loadException, stateData) => new AwaitingJobDto
{
Job = job,
LoadException = loadException,
InvocationData = invocationData,
InAwaitingState =
AwaitingState.StateName.Equals(sqlJob.StateName, StringComparison.OrdinalIgnoreCase),
AwaitingAt = sqlJob.StateChanged,
StateData = stateData
});
}
public override long ScheduledCount()
{
return GetNumberOfJobsByStateName(ScheduledState.StateName);
}
public override long EnqueuedCount(string queue)
{
var counters = GetEnqueuedAndFetchedCount(queue);
return counters.EnqueuedCount ?? 0;
}
public override long FetchedCount(string queue)
{
var counters = GetEnqueuedAndFetchedCount(queue);
return counters.FetchedCount ?? 0;
}
public override long FailedCount()
{
return GetNumberOfJobsByStateName(FailedState.StateName);
}
public override long ProcessingCount()
{
return GetNumberOfJobsByStateName(ProcessingState.StateName);
}
public override long SucceededListCount()
{
return GetNumberOfJobsByStateName(SucceededState.StateName);
}
public override long DeletedListCount()
{
return GetNumberOfJobsByStateName(DeletedState.StateName);
}
public override long AwaitingCount()
{
return GetNumberOfJobsByStateName(AwaitingState.StateName);
}
public override IDictionary<DateTime, long> SucceededByDatesCount()
{
return GetTimelineStats(State.Succeeded);
}
public override IDictionary<DateTime, long> FailedByDatesCount()
{
return GetTimelineStats(State.Failed);
}
public override IDictionary<DateTime, long> HourlySucceededJobs()
{
return GetHourlyTimelineStats(State.Succeeded);
}
public override IDictionary<DateTime, long> HourlyFailedJobs()
{
return GetHourlyTimelineStats(State.Failed);
}
public override IDictionary<DateTime, long> DeletedByDatesCount()
{
return GetTimelineStats(State.Deleted);
}
public override IDictionary<DateTime, long> HourlyDeletedJobs()
{
return GetHourlyTimelineStats(State.Deleted);
}
public virtual IReadOnlyList<string> GetQueues()
{
var onlyQueuesWithValue = new BsonDocument
{
["_t"] = nameof(JobDto),
[nameof(JobDto.Queue)] = new BsonDocument("$ne", BsonNull.Value)
};
var byQueue = new BsonDocument("_id", $"${nameof(JobDto.Queue)}");
var result = _dbContext.JobGraph.Aggregate<BsonDocument>(
new BsonDocument
[]
{
new("$match", onlyQueuesWithValue),
new("$group", byQueue)
})
.ToList();
var queues = result
.Select(b => b["_id"].AsString)
.OrderBy(s => s)
.ToArray();
return queues;
}
public virtual IReadOnlyList<string> GetEnqueuedJobIds(string queue, int from, int perPage)
{
var filter = new BsonDocument
{
["_t"] = nameof(JobDto),
[nameof(JobDto.Queue)] = queue,
[nameof(JobDto.FetchedAt)] = BsonNull.Value,
};
return _dbContext.JobGraph
.Find(filter)
.Skip(from)
.Limit(perPage)
.Project(new BsonDocument("_id", 1))
.ToList()
.Select(b => b["_id"].ToString())
.ToList();
}
public virtual IReadOnlyList<string> GetFetchedJobIds(string queue, int from, int perPage)
{
var filter = new BsonDocument
{
["_t"] = nameof(JobDto),
[nameof(JobDto.Queue)] = queue,
[nameof(JobDto.FetchedAt)] = new BsonDocument
{
["$ne"] = BsonNull.Value
}
};
return _dbContext.JobGraph
.Find(filter)
.Skip(from)
.Limit(perPage)
.Project(new BsonDocument("_id", 1))
.ToList()
.Select(b => b["_id"].ToString())
.ToList();
}
public virtual EnqueuedAndFetchedCountDto GetEnqueuedAndFetchedCount(string queue)
{
var nonFetched = new BsonDocument
{
["_t"] = nameof(JobDto),
[nameof(JobDto.Queue)] = queue,
[nameof(JobDto.FetchedAt)] = BsonNull.Value,
};
int enqueuedCount = (int) _dbContext.JobGraph.Count(nonFetched);
var fetched = new BsonDocument
{
["_t"] = nameof(JobDto),
[nameof(JobDto.Queue)] = queue,
[nameof(JobDto.FetchedAt)] = new BsonDocument
{
["$ne"] = BsonNull.Value
}
};
int fetchedCount = (int) _dbContext.JobGraph.Count(fetched);
return new EnqueuedAndFetchedCountDto
{
EnqueuedCount = enqueuedCount,
FetchedCount = fetchedCount
};
}
public virtual JobList<EnqueuedJobDto> EnqueuedJobs(IEnumerable<string> jobIds)
{
var jobObjectIds = new BsonArray(jobIds.Select(ObjectId.Parse));
var jobsByIdsFilter = new BsonDocument
{
["_t"] = nameof(JobDto),
[nameof(JobDto.Queue)] = new BsonDocument("$ne", BsonNull.Value),
[nameof(JobDto.FetchedAt)] = BsonNull.Value,
["_id"] = new BsonDocument
{
["$in"] = jobObjectIds
}
};
var jobs = _dbContext
.JobGraph
.Find(jobsByIdsFilter)
.ToList()
.Select(b => new JobDto(b));
var enqueuedJobs = jobs
.Select(job =>
{
var state = job.StateHistory.LastOrDefault();
return new JobSummary
{
Id = job.Id.ToString(),
InvocationData = job.InvocationData,
Arguments = job.Arguments,
CreatedAt = job.CreatedAt,
ExpireAt = job.ExpireAt,
FetchedAt = null,
StateName = job.StateName,
StateReason = state?.Reason,
StateData = state?.Data,
StateChanged = state?.CreatedAt
};
})
.ToList();
return DeserializeJobs(
enqueuedJobs,
(jobSummary, job, invocationData, loadException, stateData) => new EnqueuedJobDto
{
Job = job,
State = jobSummary.StateName,
LoadException = loadException,
InvocationData = invocationData,
InEnqueuedState =
EnqueuedState.StateName.Equals(jobSummary.StateName, StringComparison.OrdinalIgnoreCase),
EnqueuedAt =
EnqueuedState.StateName.Equals(jobSummary.StateName, StringComparison.OrdinalIgnoreCase)
? jobSummary.StateChanged
: null,
StateData = stateData
});
}
private static JobList<TDto> DeserializeJobs<TDto>(ICollection<JobSummary> jobs,
Func<JobSummary, Job, InvocationData, JobLoadException, SafeDictionary<string, string>, TDto> selector)
{
var result = new List<KeyValuePair<string, TDto>>(jobs.Count);
foreach (var job in jobs)
{
var dto = default(TDto);
if (job.InvocationData != null)
{
var deserializedData = job.StateData;
var stateData = deserializedData != null
? new SafeDictionary<string, string>(deserializedData, StringComparer.OrdinalIgnoreCase)
: null;
dto = selector(job, DeserializeJob(
job.InvocationData,
job.Arguments,
out var invocationData,
out var loadException),
invocationData,
loadException,
stateData);
}
result.Add(new KeyValuePair<string, TDto>(
job.Id.ToString(), dto));
}
return new JobList<TDto>(result);
}
public static Job DeserializeJob(
string invocationData,
string arguments, out InvocationData data, out JobLoadException exception)
{
data = InvocationData.DeserializePayload(invocationData);
if (!string.IsNullOrEmpty(arguments))
{
data.Arguments = arguments;
}
try
{
exception = null;
return data.DeserializeJob();
}
catch (JobLoadException ex)
{
exception = ex;
return null;
}
}
public static Job DeserializeJob(string invocationData, string arguments)
{
var data = JobHelper.FromJson<InvocationData>(invocationData);
data.Arguments = arguments;
try
{
return data.Deserialize();
}
catch (JobLoadException)
{
return null;
}
}
public virtual JobList<FetchedJobDto> FetchedJobs(HangfireDbContext connection, IEnumerable<string> jobIds)
{
if (!jobIds.Any())
{
return new JobList<FetchedJobDto>(new List<KeyValuePair<string, FetchedJobDto>>());
}
var jobObjectIds = new BsonArray(jobIds.Select(ObjectId.Parse));
var filter = new BsonDocument
{
["_t"] = nameof(JobDto),
[nameof(JobDto.FetchedAt)] = new BsonDocument("$ne", BsonNull.Value),
[nameof(JobDto.Queue)] = new BsonDocument("$ne", BsonNull.Value),
["_id"] = new BsonDocument
{
["$in"] = jobObjectIds
}
};
var jobs = connection
.JobGraph
.Find(filter)
.ToList()
.Select(b => new JobDto(b));
var fetcedJobs = jobs
.Select(job =>
{
var state = job.StateHistory.LastOrDefault(s => s.Name == job.StateName);
return new JobSummary
{
Id = job.Id.ToString(),
InvocationData = job.InvocationData,
Arguments = job.Arguments,
CreatedAt = job.CreatedAt,
ExpireAt = job.ExpireAt,
FetchedAt = null,
StateName = job.StateName,
StateReason = state?.Reason,
StateData = state?.Data
};
})
.ToList();
var result = new List<KeyValuePair<string, FetchedJobDto>>(fetcedJobs.Count);
foreach (var job in fetcedJobs)
{
result.Add(new KeyValuePair<string, FetchedJobDto>(job.Id,
new FetchedJobDto
{
Job = DeserializeJob(job.InvocationData, job.Arguments),
State = job.StateName,
FetchedAt = job.FetchedAt
}));
}
return new JobList<FetchedJobDto>(result);
}
private JobList<TDto> GetJobs<TDto>(int from, int count, string stateName,
Func<JobSummary, Job, InvocationData, JobLoadException, SafeDictionary<string, string>, TDto> selector)
{
// only retrieve job ids
var filter = new BsonDocument
{
["_t"] = nameof(JobDto),
[nameof(JobDto.StateName)] = stateName
};
var jobs = _dbContext
.JobGraph
.Find(filter)
.Sort(new BsonDocument("_id", -1))
.Skip(from)
.Limit(count)
.ToList()
.Select(b => new JobDto(b));
var joinedJobs = jobs
.Select(job =>
{
var state = job.StateHistory.LastOrDefault(s => s.Name == stateName);
return new JobSummary
{
Id = job.Id.ToString(),
InvocationData = job.InvocationData,
Arguments = job.Arguments,
CreatedAt = job.CreatedAt,
StateChanged = state?.CreatedAt,
ExpireAt = job.ExpireAt,
FetchedAt = null,
StateName = job.StateName,
StateReason = state?.Reason,
StateData = state?.Data
};
})
.ToList();
return DeserializeJobs(joinedJobs, selector);
}
public virtual long GetNumberOfJobsByStateName(string stateName)
{
var filter = new BsonDocument
{
["_t"] = nameof(JobDto),
[nameof(JobDto.StateName)] = stateName
};
var count = _dbContext.JobGraph.Count(filter);
return count;
}
public virtual Dictionary<DateTime, long> GetTimelineStats(string type)
{
var endDate = DateTime.UtcNow.Date;
var startDate = endDate.AddDays(-7);
var dates = new List<DateTime>();
while (startDate <= endDate)
{
dates.Add(endDate);
endDate = endDate.AddDays(-1);
}
var stringDates = dates.Select(x => x.ToString("yyyy-MM-dd")).ToList();
var keys = stringDates.Select(x => $"stats:{type}:{x}");
return CreateTimeLineStats(keys, dates);
}
public virtual Dictionary<DateTime, long> GetHourlyTimelineStats(string type)
{
var endDate = DateTime.UtcNow;
var dates = new List<DateTime>();
for (var i = 0; i < 24; i++)
{
dates.Add(endDate);
endDate = endDate.AddHours(-1);
}
var keys = dates.Select(x => $"stats:{type}:{x:yyyy-MM-dd-HH}");
return CreateTimeLineStats(keys, dates);
}
public virtual Dictionary<DateTime, long> CreateTimeLineStats(IEnumerable<string> keys, IList<DateTime> dates)
{
var bsonKeys = BsonArray.Create(keys);
var filter = new BsonDocument
{
["_t"] = nameof(CounterDto),
[nameof(CounterDto.Key)] = new BsonDocument
{
["$in"] = bsonKeys
}
};
var valuesMap = _dbContext.JobGraph
.Find(filter)
.ToList()
.Select(b => new CounterDto(b))
.GroupBy(counter => counter.Key, counter => counter)
.ToDictionary(counter => counter.Key, grouping => grouping.Sum(c => c.Value));
foreach (var key in keys.Where(key => !valuesMap.ContainsKey(key)))
{
valuesMap.Add(key, 0);
}
var result = new Dictionary<DateTime, long>();
for (var i = 0; i < dates.Count; i++)
{
var value = valuesMap[valuesMap.Keys.ElementAt(i)];
result.Add(dates[i], value);
}
return result;
}
/// <summary>
/// Overloaded dictionary that doesn't throw if given an invalid key
/// Fixes issues such as https://github.com/HangfireIO/Hangfire/issues/871
/// </summary>
private class SafeDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
public SafeDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer)
: base(dictionary, comparer)
{
}
public new TValue this[TKey i]
{
get { return ContainsKey(i) ? base[i] : default(TValue); }
set { base[i] = value; }
}
}
private class ParentStateDto
{
public long Id { get; set; }
public string StateName { get; set; }
}
}
#pragma warning restore 1591
}