forked from facebook/react-native
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRuntimeScheduler_Modern.cpp
More file actions
352 lines (281 loc) · 9.98 KB
/
RuntimeScheduler_Modern.cpp
File metadata and controls
352 lines (281 loc) · 9.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "RuntimeScheduler_Modern.h"
#include "SchedulerPriorityUtils.h"
#include <cxxreact/ErrorUtils.h>
#include <react/featureflags/ReactNativeFeatureFlags.h>
#include <react/renderer/consistency/ScopedShadowTreeRevisionLock.h>
#include <react/renderer/debug/SystraceSection.h>
#include <react/utils/OnScopeExit.h>
#include <utility>
namespace facebook::react {
#pragma mark - Public
RuntimeScheduler_Modern::RuntimeScheduler_Modern(
RuntimeExecutor runtimeExecutor,
std::function<RuntimeSchedulerTimePoint()> now)
: runtimeExecutor_(std::move(runtimeExecutor)), now_(std::move(now)) {}
void RuntimeScheduler_Modern::scheduleWork(RawCallback&& callback) noexcept {
SystraceSection s("RuntimeScheduler::scheduleWork");
scheduleTask(SchedulerPriority::ImmediatePriority, std::move(callback));
}
std::shared_ptr<Task> RuntimeScheduler_Modern::scheduleTask(
SchedulerPriority priority,
jsi::Function&& callback) noexcept {
SystraceSection s(
"RuntimeScheduler::scheduleTask",
"priority",
serialize(priority),
"callbackType",
"jsi::Function");
auto expirationTime = now_() + timeoutForSchedulerPriority(priority);
auto task =
std::make_shared<Task>(priority, std::move(callback), expirationTime);
scheduleTask(task);
return task;
}
std::shared_ptr<Task> RuntimeScheduler_Modern::scheduleTask(
SchedulerPriority priority,
RawCallback&& callback) noexcept {
SystraceSection s(
"RuntimeScheduler::scheduleTask",
"priority",
serialize(priority),
"callbackType",
"RawCallback");
auto expirationTime = now_() + timeoutForSchedulerPriority(priority);
auto task =
std::make_shared<Task>(priority, std::move(callback), expirationTime);
scheduleTask(task);
return task;
}
bool RuntimeScheduler_Modern::getShouldYield() const noexcept {
std::shared_lock lock(schedulingMutex_);
return syncTaskRequests_ > 0 ||
(!taskQueue_.empty() && taskQueue_.top() != currentTask_);
}
void RuntimeScheduler_Modern::cancelTask(Task& task) noexcept {
task.callback.reset();
}
SchedulerPriority RuntimeScheduler_Modern::getCurrentPriorityLevel()
const noexcept {
return currentPriority_;
}
RuntimeSchedulerTimePoint RuntimeScheduler_Modern::now() const noexcept {
return now_();
}
void RuntimeScheduler_Modern::executeNowOnTheSameThread(
RawCallback&& callback) {
SystraceSection s("RuntimeScheduler::executeNowOnTheSameThread");
syncTaskRequests_++;
executeSynchronouslyOnSameThread_CAN_DEADLOCK(
runtimeExecutor_,
[this, callback = std::move(callback)](jsi::Runtime& runtime) mutable {
SystraceSection s2(
"RuntimeScheduler::executeNowOnTheSameThread callback");
syncTaskRequests_--;
auto currentTime = now_();
auto priority = SchedulerPriority::ImmediatePriority;
auto expirationTime =
currentTime + timeoutForSchedulerPriority(priority);
auto task = std::make_shared<Task>(
priority, std::move(callback), expirationTime);
executeTask(runtime, task, currentTime);
});
bool shouldScheduleWorkLoop = false;
{
// Unique access because we might write to `isWorkLoopScheduled_`.
std::unique_lock lock(schedulingMutex_);
// We only need to schedule the work loop if there any remaining tasks
// in the queue.
if (!taskQueue_.empty() && !isWorkLoopScheduled_) {
isWorkLoopScheduled_ = true;
shouldScheduleWorkLoop = true;
}
}
if (shouldScheduleWorkLoop) {
scheduleWorkLoop();
}
}
void RuntimeScheduler_Modern::callExpiredTasks(jsi::Runtime& runtime) {
// If we have first-class support for microtasks, this a no-op.
if (ReactNativeFeatureFlags::enableMicrotasks()) {
return;
}
SystraceSection s("RuntimeScheduler::callExpiredTasks");
startWorkLoop(runtime, true);
}
void RuntimeScheduler_Modern::scheduleRenderingUpdate(
RuntimeSchedulerRenderingUpdate&& renderingUpdate) {
SystraceSection s("RuntimeScheduler::scheduleRenderingUpdate");
if (ReactNativeFeatureFlags::batchRenderingUpdatesInEventLoop()) {
pendingRenderingUpdates_.push(renderingUpdate);
} else {
if (renderingUpdate != nullptr) {
renderingUpdate();
}
}
}
void RuntimeScheduler_Modern::setShadowTreeRevisionConsistencyManager(
ShadowTreeRevisionConsistencyManager*
shadowTreeRevisionConsistencyManager) {
shadowTreeRevisionConsistencyManager_ = shadowTreeRevisionConsistencyManager;
}
#pragma mark - Private
void RuntimeScheduler_Modern::scheduleTask(std::shared_ptr<Task> task) {
bool shouldScheduleWorkLoop = false;
{
std::unique_lock lock(schedulingMutex_);
// We only need to schedule the work loop if the task we're about to
// schedule is the only one in the queue.
// Otherwise, we don't need to schedule it because there's another one
// running already that will pick up the new task.
if (taskQueue_.empty() && !isWorkLoopScheduled_) {
isWorkLoopScheduled_ = true;
shouldScheduleWorkLoop = true;
}
taskQueue_.push(task);
}
if (shouldScheduleWorkLoop) {
scheduleWorkLoop();
}
}
void RuntimeScheduler_Modern::scheduleWorkLoop() {
runtimeExecutor_(
[this](jsi::Runtime& runtime) { startWorkLoop(runtime, false); });
}
void RuntimeScheduler_Modern::startWorkLoop(
jsi::Runtime& runtime,
bool onlyExpired) {
SystraceSection s("RuntimeScheduler::startWorkLoop");
auto previousPriority = currentPriority_;
try {
while (syncTaskRequests_ == 0) {
auto currentTime = now_();
auto topPriorityTask = selectTask(currentTime, onlyExpired);
if (!topPriorityTask) {
// No pending work to do.
// Events will restart the loop when necessary.
break;
}
executeTask(runtime, topPriorityTask, currentTime);
}
} catch (jsi::JSError& error) {
handleJSError(runtime, error, true);
}
currentPriority_ = previousPriority;
}
std::shared_ptr<Task> RuntimeScheduler_Modern::selectTask(
RuntimeSchedulerTimePoint currentTime,
bool onlyExpired) {
// We need a unique lock here because we'll also remove executed tasks from
// the top of the queue.
std::unique_lock lock(schedulingMutex_);
// It's safe to reset the flag here, as its access is also synchronized with
// the access to the task queue.
isWorkLoopScheduled_ = false;
// Skip executed tasks
while (!taskQueue_.empty() && !taskQueue_.top()->callback) {
taskQueue_.pop();
}
if (!taskQueue_.empty()) {
auto task = taskQueue_.top();
auto didUserCallbackTimeout = task->expirationTime <= currentTime;
if (!onlyExpired || didUserCallbackTimeout) {
return task;
}
}
return nullptr;
}
void RuntimeScheduler_Modern::executeTask(
jsi::Runtime& runtime,
const std::shared_ptr<Task>& task,
RuntimeSchedulerTimePoint currentTime) {
auto didUserCallbackTimeout = task->expirationTime <= currentTime;
SystraceSection s(
"RuntimeScheduler::executeTask",
"priority",
serialize(task->priority),
"didUserCallbackTimeout",
didUserCallbackTimeout);
currentTask_ = task;
currentPriority_ = task->priority;
{
ScopedShadowTreeRevisionLock revisionLock(
shadowTreeRevisionConsistencyManager_);
executeMacrotask(runtime, task, didUserCallbackTimeout);
if (ReactNativeFeatureFlags::enableMicrotasks()) {
// "Perform a microtask checkpoint" step.
performMicrotaskCheckpoint(runtime);
}
if (ReactNativeFeatureFlags::batchRenderingUpdatesInEventLoop()) {
// "Update the rendering" step.
updateRendering();
}
}
}
/**
* This is partially equivalent to the "Update the rendering" step in the Web
* event loop. See
* https://html.spec.whatwg.org/multipage/webappapis.html#update-the-rendering.
*/
void RuntimeScheduler_Modern::updateRendering() {
SystraceSection s("RuntimeScheduler::updateRendering");
while (!pendingRenderingUpdates_.empty()) {
auto& pendingRenderingUpdate = pendingRenderingUpdates_.front();
if (pendingRenderingUpdate != nullptr) {
pendingRenderingUpdate();
}
pendingRenderingUpdates_.pop();
}
}
void RuntimeScheduler_Modern::executeMacrotask(
jsi::Runtime& runtime,
std::shared_ptr<Task> task,
bool didUserCallbackTimeout) const {
SystraceSection s("RuntimeScheduler::executeMacrotask");
auto result = task->execute(runtime, didUserCallbackTimeout);
if (result.isObject() && result.getObject(runtime).isFunction(runtime)) {
// If the task returned a continuation callback, we re-assign it to the task
// and keep the task in the queue.
task->callback = result.getObject(runtime).getFunction(runtime);
}
}
/**
* This is partially equivalent to the "Perform a microtask checkpoint" step in
* the Web event loop. See
* https://html.spec.whatwg.org/multipage/webappapis.html#perform-a-microtask-checkpoint.
*
* Iterates on \c drainMicrotasks until it completes or hits the retries bound.
*/
void RuntimeScheduler_Modern::performMicrotaskCheckpoint(
jsi::Runtime& runtime) {
SystraceSection s("RuntimeScheduler::performMicrotaskCheckpoint");
if (performingMicrotaskCheckpoint_) {
return;
}
performingMicrotaskCheckpoint_ = true;
OnScopeExit restoreFlag([&]() { performingMicrotaskCheckpoint_ = false; });
uint8_t retries = 0;
// A heuristic number to guard infinite or absurd numbers of retries.
const static unsigned int kRetriesBound = 255;
while (retries < kRetriesBound) {
try {
// The default behavior of \c drainMicrotasks is unbounded execution.
// We may want to make it bounded in the future.
if (runtime.drainMicrotasks()) {
break;
}
} catch (jsi::JSError& error) {
handleJSError(runtime, error, true);
}
retries++;
}
if (retries == kRetriesBound) {
throw std::runtime_error("Hits microtasks retries bound.");
}
}
} // namespace facebook::react