-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupload_scheduler.hpp
More file actions
90 lines (77 loc) · 2.49 KB
/
Copy pathupload_scheduler.hpp
File metadata and controls
90 lines (77 loc) · 2.49 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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
//
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2025-Present Datadog, Inc.
#pragma once
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <queue>
#include <vector>
#include "datadog/impl/core/feature.hpp"
#include "datadog/impl/core/platform/clock.hpp"
#include "datadog/impl/core/types.hpp"
namespace datadog::impl {
/**
* Keeps track of when upload cycles should run next for all registered features.
*/
class UploadScheduler {
/**
* A record of the next scheduled upload cycle for the given feature.
*/
struct Item {
FeatureId feature_id;
Timestamp next_cycle_at;
bool operator>(const Item& other) const {
return next_cycle_at > other.next_cycle_at;
}
};
/**
* Used to read the current system time.
*/
const platform::IClock& _clock;
/**
* Flag used to signal that scheduling is stopped and the upload thread should exit.
*/
std::atomic<bool> _stopped{false};
/**
* Min-heap containing the timestamps at which the next upload cycle for each feature
* should begin. Only accessed from the upload thread.
*/
std::priority_queue<Item, std::vector<Item>, std::greater<Item>> _pq;
/**
* Wakes the upload thread in response to shutdown, so that the upload thread can
* sleep for long periods of time without periodically waking up to check the shutdown
* flag.
*/
std::condition_variable _cv;
/**
* Synchronizes access to _cv. Does NOT synchronize access to _pq, as _pq is only
* accessed on the upload thread.
*/
std::mutex _mutex;
public:
explicit UploadScheduler(const platform::IClock& clock);
/**
* Ceases any further scheduling of upload cycles, setting an atomic flag that should
* notify the upload thread to stop processing uploads.
*/
void Stop();
/**
* Schedules the next upload cycle for the given feature to occur after the specified
* delay.
*/
void Schedule(FeatureId feature_id, Duration next_cycle_in);
/**
* Blocks until the next feature is ready to be processed for upload, returning its ID
* when the time comes to initiate an upload cycle for that feature.
*
* Returns std::nullopt to indicate that upload processing has stopped.
*/
std::optional<FeatureId> WaitForNext();
private:
bool SleepFor(Duration duration);
};
} // namespace datadog::impl