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
|
//
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2023
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#pragma once
#include "td/actor/impl/ActorInfo-decl.h"
#include "td/actor/impl/Scheduler-decl.h"
#include "td/utils/common.h"
#include "td/utils/Heap.h"
#include "td/utils/logging.h"
#include "td/utils/ObjectPool.h"
#include "td/utils/port/detail/PollableFd.h"
#include "td/utils/port/PollFlags.h"
#include "td/utils/Promise.h"
#include "td/utils/Slice.h"
#include "td/utils/Time.h"
#include <atomic>
#include <tuple>
#include <utility>
namespace td {
/*** EventGuard ***/
class EventGuard {
public:
EventGuard(Scheduler *scheduler, ActorInfo *actor_info);
bool can_run() const {
return event_context_.flags == 0;
}
EventGuard(const EventGuard &) = delete;
EventGuard &operator=(const EventGuard &) = delete;
EventGuard(EventGuard &&) = delete;
EventGuard &operator=(EventGuard &&) = delete;
~EventGuard();
private:
Scheduler::EventContext event_context_;
Scheduler::EventContext *event_context_ptr_;
Scheduler *scheduler_;
ActorContext *save_context_;
const char *save_log_tag2_;
void swap_context(ActorInfo *info);
};
/*** Scheduler ***/
inline SchedulerGuard Scheduler::get_guard() {
return SchedulerGuard(this);
}
inline SchedulerGuard Scheduler::get_const_guard() {
return SchedulerGuard(this, false);
}
inline int32 Scheduler::sched_id() const {
return sched_id_;
}
inline int32 Scheduler::sched_count() const {
return sched_n_;
}
template <class ActorT, class... Args>
ActorOwn<ActorT> Scheduler::create_actor(Slice name, Args &&...args) {
return register_actor_impl(name, new ActorT(std::forward<Args>(args)...), Actor::Deleter::Destroy, sched_id_);
}
template <class ActorT, class... Args>
ActorOwn<ActorT> Scheduler::create_actor_on_scheduler(Slice name, int32 sched_id, Args &&...args) {
return register_actor_impl(name, new ActorT(std::forward<Args>(args)...), Actor::Deleter::Destroy, sched_id);
}
template <class ActorT>
ActorOwn<ActorT> Scheduler::register_actor(Slice name, ActorT *actor_ptr, int32 sched_id) {
return register_actor_impl(name, actor_ptr, Actor::Deleter::None, sched_id);
}
template <class ActorT>
ActorOwn<ActorT> Scheduler::register_actor(Slice name, unique_ptr<ActorT> actor_ptr, int32 sched_id) {
return register_actor_impl(name, actor_ptr.release(), Actor::Deleter::Destroy, sched_id);
}
template <class ActorT>
ActorOwn<ActorT> Scheduler::register_actor_impl(Slice name, ActorT *actor_ptr, Actor::Deleter deleter, int32 sched_id) {
CHECK(has_guard_);
if (sched_id == -1) {
sched_id = sched_id_;
}
#if TD_THREAD_UNSUPPORTED || TD_EVENTFD_UNSUPPORTED
sched_id = 0;
#endif
LOG_CHECK(sched_id == sched_id_ || (0 <= sched_id && sched_id < static_cast<int32>(outbound_queues_.size())))
<< sched_id;
auto info = actor_info_pool_->create_empty();
actor_count_++;
auto weak_info = info.get_weak();
auto actor_info = info.get();
actor_info->init(sched_id_, name, std::move(info), static_cast<Actor *>(actor_ptr), deleter,
ActorTraits<ActorT>::need_context, ActorTraits<ActorT>::need_start_up);
VLOG(actor) << "Create actor " << *actor_info << " (actor_count = " << actor_count_ << ')';
ActorId<ActorT> actor_id = weak_info->actor_id(actor_ptr);
if (sched_id != sched_id_) {
send<ActorSendType::Later>(actor_id, Event::start());
do_migrate_actor(actor_info, sched_id);
} else {
pending_actors_list_.put(weak_info->get_list_node());
if (ActorTraits<ActorT>::need_start_up) {
send<ActorSendType::Later>(actor_id, Event::start());
}
}
return ActorOwn<ActorT>(actor_id);
}
template <class ActorT>
ActorOwn<ActorT> Scheduler::register_existing_actor(unique_ptr<ActorT> actor_ptr) {
CHECK(!actor_ptr->empty());
auto actor_info = actor_ptr->get_info();
CHECK(actor_info->migrate_dest_flag_atomic().first == sched_id_);
return actor_info->transfer_ownership_to_scheduler(std::move(actor_ptr));
}
inline void Scheduler::destroy_actor(ActorInfo *actor_info) {
VLOG(actor) << "Destroy actor " << *actor_info << " (actor_count = " << actor_count_ << ')';
LOG_CHECK(actor_info->migrate_dest() == sched_id_) << actor_info->migrate_dest() << " " << sched_id_;
cancel_actor_timeout(actor_info);
actor_info->get_list_node()->remove();
// called by ObjectPool
// actor_info->clear();
actor_count_--;
CHECK(actor_count_ >= 0);
}
template <class RunFuncT, class EventFuncT>
void Scheduler::flush_mailbox(ActorInfo *actor_info, const RunFuncT &run_func, const EventFuncT &event_func) {
auto &mailbox = actor_info->mailbox_;
size_t mailbox_size = mailbox.size();
CHECK(mailbox_size != 0);
EventGuard guard(this, actor_info);
size_t i = 0;
for (; i < mailbox_size && guard.can_run(); i++) {
do_event(actor_info, std::move(mailbox[i]));
}
if (run_func) {
if (guard.can_run()) {
(*run_func)(actor_info);
} else {
mailbox.insert(mailbox.begin() + i, (*event_func)());
}
}
mailbox.erase(mailbox.begin(), mailbox.begin() + i);
}
inline void Scheduler::send_to_scheduler(int32 sched_id, const ActorId<Actor> &actor_id, Event &&event) {
if (sched_id == sched_id_) {
ActorInfo *actor_info = actor_id.get_actor_info();
pending_events_[actor_info].push_back(std::move(event));
} else {
send_to_other_scheduler(sched_id, actor_id, std::move(event));
}
}
template <class T>
void Scheduler::destroy_on_scheduler(int32 sched_id, T &value) {
if (!value.empty()) {
destroy_on_scheduler_impl(sched_id, PromiseCreator::lambda([value = std::move(value)](Unit) {
// destroy value
}));
}
}
template <class... ArgsT>
void Scheduler::destroy_on_scheduler(int32 sched_id, ArgsT &...values) {
destroy_on_scheduler_impl(sched_id, PromiseCreator::lambda([values = std::make_tuple(std::move(values)...)](Unit) {
// destroy values
}));
}
inline void Scheduler::before_tail_send(const ActorId<> &actor_id) {
// TODO
}
template <ActorSendType send_type, class RunFuncT, class EventFuncT>
void Scheduler::send_impl(const ActorId<> &actor_id, const RunFuncT &run_func, const EventFuncT &event_func) {
ActorInfo *actor_info = actor_id.get_actor_info();
if (unlikely(actor_info == nullptr || close_flag_)) {
return;
}
CHECK(actor_info != nullptr);
int32 actor_sched_id;
bool is_migrating;
std::tie(actor_sched_id, is_migrating) = actor_info->migrate_dest_flag_atomic();
bool on_current_sched = !is_migrating && sched_id_ == actor_sched_id;
CHECK(has_guard_ || !on_current_sched);
if (likely(send_type == ActorSendType::Immediate && on_current_sched && !actor_info->is_running() &&
actor_info->mailbox_.empty())) { // run immediately
EventGuard guard(this, actor_info);
run_func(actor_info);
} else {
if (on_current_sched) {
add_to_mailbox(actor_info, event_func());
} else {
send_to_scheduler(actor_sched_id, actor_id, event_func());
}
}
}
template <ActorSendType send_type, class EventT>
void Scheduler::send_lambda(ActorRef actor_ref, EventT &&lambda) {
return send_impl<send_type>(
actor_ref.get(),
[&](ActorInfo *actor_info) {
event_context_ptr_->link_token = actor_ref.token();
lambda();
},
[&] {
auto event = Event::lambda(std::forward<EventT>(lambda));
event.set_link_token(actor_ref.token());
return event;
});
}
template <ActorSendType send_type, class EventT>
void Scheduler::send_closure(ActorRef actor_ref, EventT &&closure) {
return send_impl<send_type>(
actor_ref.get(),
[&](ActorInfo *actor_info) {
event_context_ptr_->link_token = actor_ref.token();
closure.run(static_cast<typename EventT::ActorType *>(actor_info->get_actor_unsafe()));
},
[&] {
auto event = Event::immediate_closure(std::forward<EventT>(closure));
event.set_link_token(actor_ref.token());
return event;
});
}
template <ActorSendType send_type>
void Scheduler::send(ActorRef actor_ref, Event &&event) {
event.set_link_token(actor_ref.token());
return send_impl<send_type>(
actor_ref.get(), [&](ActorInfo *actor_info) { do_event(actor_info, std::move(event)); },
[&] { return std::move(event); });
}
inline void Scheduler::subscribe(PollableFd fd, PollFlags flags) {
instance()->poll_.subscribe(std::move(fd), flags);
}
inline void Scheduler::unsubscribe(PollableFdRef fd) {
instance()->poll_.unsubscribe(std::move(fd));
}
inline void Scheduler::unsubscribe_before_close(PollableFdRef fd) {
instance()->poll_.unsubscribe_before_close(std::move(fd));
}
inline void Scheduler::yield_actor(Actor *actor) {
yield_actor(actor->get_info());
}
inline void Scheduler::yield_actor(ActorInfo *actor_info) {
send<ActorSendType::Later>(actor_info->actor_id(), Event::yield());
}
inline void Scheduler::stop_actor(Actor *actor) {
stop_actor(actor->get_info());
}
inline void Scheduler::stop_actor(ActorInfo *actor_info) {
CHECK(event_context_ptr_->actor_info == actor_info);
event_context_ptr_->flags |= EventContext::Stop;
}
inline uint64 Scheduler::get_link_token(Actor *actor) {
return get_link_token(actor->get_info());
}
inline uint64 Scheduler::get_link_token(ActorInfo *actor_info) {
LOG_CHECK(event_context_ptr_->actor_info == actor_info) << actor_info->get_name();
return event_context_ptr_->link_token;
}
inline void Scheduler::finish_migrate_actor(Actor *actor) {
register_migrated_actor(actor->get_info());
}
inline double Scheduler::get_actor_timeout(const Actor *actor) const {
return get_actor_timeout(actor->get_info());
}
inline void Scheduler::set_actor_timeout_in(Actor *actor, double timeout) {
set_actor_timeout_in(actor->get_info(), timeout);
}
inline void Scheduler::set_actor_timeout_at(Actor *actor, double timeout_at) {
set_actor_timeout_at(actor->get_info(), timeout_at);
}
inline void Scheduler::cancel_actor_timeout(Actor *actor) {
cancel_actor_timeout(actor->get_info());
}
inline void Scheduler::cancel_actor_timeout(ActorInfo *actor_info) {
HeapNode *heap_node = actor_info->get_heap_node();
if (heap_node->in_heap()) {
timeout_queue_.erase(heap_node);
}
}
inline void Scheduler::finish() {
if (callback_) {
callback_->on_finish();
}
yield();
}
inline void Scheduler::yield() {
yield_flag_ = true;
}
inline void Scheduler::wakeup() {
std::atomic_thread_fence(std::memory_order_release);
#if !TD_THREAD_UNSUPPORTED && !TD_EVENTFD_UNSUPPORTED
inbound_queue_->writer_put({});
#endif
}
inline void Scheduler::run(Timestamp timeout) {
auto guard = get_guard();
run_no_guard(timeout);
}
/*** Interface to current scheduler ***/
template <class ActorT, class... Args>
ActorOwn<ActorT> create_actor(Slice name, Args &&...args) {
return Scheduler::instance()->create_actor<ActorT>(name, std::forward<Args>(args)...);
}
template <class ActorT, class... Args>
ActorOwn<ActorT> create_actor_on_scheduler(Slice name, int32 sched_id, Args &&...args) {
return Scheduler::instance()->create_actor_on_scheduler<ActorT>(name, sched_id, std::forward<Args>(args)...);
}
template <class ActorT>
ActorOwn<ActorT> register_actor(Slice name, ActorT *actor_ptr, int32 sched_id) {
return Scheduler::instance()->register_actor<ActorT>(name, actor_ptr, sched_id);
}
template <class ActorT>
ActorOwn<ActorT> register_actor(Slice name, unique_ptr<ActorT> actor_ptr, int32 sched_id) {
return Scheduler::instance()->register_actor<ActorT>(name, std::move(actor_ptr), sched_id);
}
template <class ActorT>
ActorOwn<ActorT> register_existing_actor(unique_ptr<ActorT> actor_ptr) {
return Scheduler::instance()->register_existing_actor(std::move(actor_ptr));
}
} // namespace td
|