Repository navigation
Expand file tree
/
Copy pathRequestBatchHandler.cpp
More file actions
246 lines (200 loc) · 8.57 KB
/
Copy pathRequestBatchHandler.cpp
File metadata and controls
246 lines (200 loc) · 8.57 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
/*
obs-websocket
Copyright (C) 2020-2021 Kyle Manning <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see <https://www.gnu.org/licenses/>
*/
#include <queue>
#include <condition_variable>
#include <util/profiler.hpp>
#include "RequestBatchHandler.h"
#include "../utils/Compat.h"
#include "../obs-websocket.h"
struct SerialFrameBatch {
RequestHandler &requestHandler;
std::queue<RequestBatchRequest> requests;
std::vector<RequestResult> results;
json &variables;
bool haltOnFailure;
size_t frameCount = 0;
size_t sleepUntilFrame = 0;
std::mutex conditionMutex;
std::condition_variable condition;
SerialFrameBatch(RequestHandler &requestHandler, json &variables, bool haltOnFailure)
: requestHandler(requestHandler),
variables(variables),
haltOnFailure(haltOnFailure)
{
}
};
struct ParallelBatchResults {
RequestHandler &requestHandler;
// One slot per request, in request order
std::vector<RequestResult> results;
size_t finishedCount = 0;
std::mutex conditionMutex;
std::condition_variable condition;
ParallelBatchResults(RequestHandler &requestHandler, size_t requestCount)
: requestHandler(requestHandler),
results(requestCount)
{
}
};
// `{"inputName": "inputNameVariable"}` is essentially `inputName = inputNameVariable`
static void PreProcessVariables(const json &variables, RequestBatchRequest &request)
{
if (variables.empty() || !request.InputVariables.is_object() || request.InputVariables.empty() ||
!request.RequestData.is_object())
return;
for (auto &[key, value] : request.InputVariables.items()) {
if (!value.is_string()) {
blog_debug(
"[WebSocketServer::ProcessRequestBatch] Value of field `%s` in `inputVariables `is not a string. Skipping!",
key.c_str());
continue;
}
std::string valueString = value;
if (!variables.contains(valueString)) {
blog_debug(
"[WebSocketServer::ProcessRequestBatch] `inputVariables` requested variable `%s`, but it does not exist. Skipping!",
valueString.c_str());
continue;
}
request.RequestData[key] = variables[valueString];
}
request.HasRequestData = !request.RequestData.empty();
}
// `{"sceneItemIdVariable": "sceneItemId"}` is essentially `sceneItemIdVariable = sceneItemId`
static void PostProcessVariables(json &variables, const RequestBatchRequest &request, const RequestResult &requestResult)
{
if (!request.OutputVariables.is_object() || request.OutputVariables.empty() || requestResult.ResponseData.empty())
return;
for (auto &[key, value] : request.OutputVariables.items()) {
if (!value.is_string()) {
blog_debug(
"[WebSocketServer::ProcessRequestBatch] Value of field `%s` in `outputVariables` is not a string. Skipping!",
key.c_str());
continue;
}
std::string valueString = value;
if (!requestResult.ResponseData.contains(valueString)) {
blog_debug(
"[WebSocketServer::ProcessRequestBatch] `outputVariables` requested responseData field `%s`, but it does not exist. Skipping!",
valueString.c_str());
continue;
}
variables[key] = requestResult.ResponseData[valueString];
}
}
static void ObsTickCallback(void *param, float)
{
ScopeProfiler prof{"obs_websocket_request_batch_frame_tick"};
auto serialFrameBatch = static_cast<SerialFrameBatch *>(param);
// Increment frame count
serialFrameBatch->frameCount++;
if (serialFrameBatch->sleepUntilFrame) {
if (serialFrameBatch->frameCount < serialFrameBatch->sleepUntilFrame)
// Do not process any requests if in "sleep mode"
return;
else
// Reset frame sleep until counter if not being used
serialFrameBatch->sleepUntilFrame = 0;
}
// Begin recursing any unprocessed requests
while (!serialFrameBatch->requests.empty()) {
// Fetch first in queue
RequestBatchRequest request = serialFrameBatch->requests.front();
// Pre-process batch variables
PreProcessVariables(serialFrameBatch->variables, request);
// Process request and get result
RequestResult requestResult = serialFrameBatch->requestHandler.ProcessRequest(request);
// Post-process batch variables
PostProcessVariables(serialFrameBatch->variables, request, requestResult);
// Add to results vector
serialFrameBatch->results.push_back(requestResult);
// Remove from front of queue
serialFrameBatch->requests.pop();
// If haltOnFailure and the request failed, clear the queue to make the batch return early.
if (serialFrameBatch->haltOnFailure && requestResult.StatusCode != RequestStatus::Success) {
serialFrameBatch->requests = std::queue<RequestBatchRequest>();
break;
}
// If the processed request tells us to sleep, do so accordingly
if (requestResult.SleepFrames) {
serialFrameBatch->sleepUntilFrame = serialFrameBatch->frameCount + requestResult.SleepFrames;
break;
}
}
// If request queue is empty, we can notify the paused worker thread
if (serialFrameBatch->requests.empty())
serialFrameBatch->condition.notify_one();
}
std::vector<RequestResult>
RequestBatchHandler::ProcessRequestBatch(QThreadPool &threadPool, SessionPtr session,
RequestBatchExecutionType::RequestBatchExecutionType executionType,
std::vector<RequestBatchRequest> &requests, json &variables, bool haltOnFailure)
{
RequestHandler requestHandler(session);
if (executionType == RequestBatchExecutionType::SerialRealtime) {
std::vector<RequestResult> ret;
// Recurse all requests in batch serially, processing the request then moving to the next one
for (auto &request : requests) {
PreProcessVariables(variables, request);
RequestResult requestResult = requestHandler.ProcessRequest(request);
PostProcessVariables(variables, request, requestResult);
ret.push_back(requestResult);
if (haltOnFailure && requestResult.StatusCode != RequestStatus::Success)
break;
}
return ret;
} else if (executionType == RequestBatchExecutionType::SerialFrame) {
SerialFrameBatch serialFrameBatch(requestHandler, variables, haltOnFailure);
// Create Request objects in the worker thread (avoid unnecessary processing in graphics thread)
for (auto &request : requests)
serialFrameBatch.requests.push(request);
// Create a callback entry for the graphics thread to execute on each video frame
obs_add_tick_callback(ObsTickCallback, &serialFrameBatch);
// Wait until the graphics thread processes the last request in the queue
std::unique_lock<std::mutex> lock(serialFrameBatch.conditionMutex);
serialFrameBatch.condition.wait(lock, [&serialFrameBatch] { return serialFrameBatch.requests.empty(); });
// Remove the created callback entry since we don't need it anymore
obs_remove_tick_callback(ObsTickCallback, &serialFrameBatch);
return serialFrameBatch.results;
} else if (executionType == RequestBatchExecutionType::Parallel) {
size_t requestCount = requests.size();
ParallelBatchResults parallelResults(requestHandler, requestCount);
// Acquire the lock early to prevent the batch from finishing before we're ready
std::unique_lock<std::mutex> lock(parallelResults.conditionMutex);
// Submit each request as a task to the thread pool to be processed ASAP.
// Each task stores its result at its request's index, so the results stay
// in request order whatever order the requests finish in.
for (size_t i = 0; i < requestCount; i++) {
RequestBatchRequest &request = requests[i];
threadPool.start(Utils::Compat::CreateFunctionRunnable([¶llelResults, &request, i]() {
RequestResult requestResult = parallelResults.requestHandler.ProcessRequest(request);
std::unique_lock<std::mutex> lock(parallelResults.conditionMutex);
parallelResults.results[i] = requestResult;
parallelResults.finishedCount++;
// Notify while holding the lock: once it is released the
// waiter may see the last result, return and destroy
// parallelResults, so this task must not touch it after.
parallelResults.condition.notify_one();
}));
}
// Wait for the last request to finish processing
parallelResults.condition.wait(lock, [¶llelResults, requestCount] {
return parallelResults.finishedCount == requestCount;
});
return parallelResults.results;
}
// Return empty vector if not a batch somehow
return std::vector<RequestResult>();
}