1#include "http_emscripten.h"
2#if defined(CONF_PLATFORM_EMSCRIPTEN)
3
4#include <base/dbg.h>
5#include <base/log.h>
6#include <base/str.h>
7#include <base/thread.h>
8#include <base/time.h>
9
10#include <engine/shared/config.h>
11#include <engine/storage.h>
12
13#include <emscripten/emscripten.h>
14#include <emscripten/fetch.h>
15
16#include <limits>
17#include <thread>
18
19CHttpRequestEmscripten::CHttpRequestEmscripten(const char *pUrl) :
20 IHttpRequest(pUrl)
21{
22}
23
24CHttpRequestEmscripten::~CHttpRequestEmscripten()
25{
26 dbg_assert(m_pFetch == nullptr, "HTTP request fetch handle was not closed");
27}
28
29void CHttpRequestEmscripten::Header(const char *pNameColonValue)
30{
31 const char *pColon = str_find(pNameColonValue, ":");
32 dbg_assert(pColon != nullptr, "Header name and value not separated with colon: '%s'", pNameColonValue);
33 std::string Name = std::string(pNameColonValue, pColon - pNameColonValue);
34 std::string Value = std::string(str_skip_whitespaces_const(pColon + 1));
35 m_vRequestHeaders.emplace_back(std::move(Name), std::move(Value));
36}
37
38void CHttpRequestEmscripten::Abort()
39{
40 if(m_Abort.load(std::memory_order_acquire))
41 {
42 return;
43 }
44
45 IHttpRequest::Abort();
46
47 if(m_Initialized.load(std::memory_order_acquire))
48 {
49 m_pHttp->AddPendingStateChange(m_RequestId, EHttpState::ABORTED);
50 }
51}
52
53EM_JS(void, FormatTimestampJsImpl, (char *pBuf, size_t Size, time_t Timestamp), {
54 const timestampString = new Date(Number(Timestamp) * 1000).toUTCString();
55 stringToUTF8(timestampString, pBuf, Size);
56});
57
58EM_JS(bool, IsValidUrlJsImpl, (const char *pUrl), {
59 try
60 {
61 new URL(UTF8ToString(pUrl));
62 return true;
63 }
64 catch(_)
65 {
66 return false;
67 }
68});
69
70bool CHttpRequestEmscripten::ConfigureAndRun()
71{
72 if(!BeforeInit())
73 {
74 return false;
75 }
76
77 if(!str_startswith(m_aUrl, "https://") &&
78 (!g_Config.m_HttpAllowInsecure || !str_startswith(m_aUrl, "http://")))
79 {
80 log_error("http", "unsupported protocol: %s", m_aUrl);
81 return false;
82 }
83
84 if(!IsValidUrlJsImpl(m_aUrl))
85 {
86 log_error("http", "invalid URL: %s", m_aUrl);
87 return false;
88 }
89
90 HeaderString("User-Agent", USER_AGENT_STRING);
91
92 if(m_Type == REQUEST::POST_JSON)
93 {
94 Header("Content-Type: application/json");
95 }
96 else if(m_Type == REQUEST::POST)
97 {
98 Header("Content-Type:");
99 }
100
101 if(m_IfModifiedSince >= 0)
102 {
103 char aTimestamp[64];
104 FormatTimestampJsImpl(aTimestamp, sizeof(aTimestamp), m_IfModifiedSince);
105 HeaderString("If-Modified-Since", aTimestamp);
106 }
107
108 m_LowSpeedOffset = 0;
109 m_LowSpeedCheckTime = time_get_nanoseconds();
110
111 std::vector<const char *> vpPackedHeaders;
112 vpPackedHeaders.reserve(2 * m_vRequestHeaders.size() + 1);
113 for(const auto &[Name, Value] : m_vRequestHeaders)
114 {
115 vpPackedHeaders.push_back(Name.c_str());
116 vpPackedHeaders.push_back(Value.c_str());
117 }
118 vpPackedHeaders.push_back(nullptr);
119
120 emscripten_fetch_attr_t FetchAttributes;
121 emscripten_fetch_attr_init(&FetchAttributes);
122 str_copy(FetchAttributes.requestMethod, GetRequestType(m_Type));
123 FetchAttributes.userData = this;
124 FetchAttributes.onsuccess = FetchCallbackSuccess;
125 FetchAttributes.onerror = FetchCallbackFailure;
126 FetchAttributes.onprogress = FetchCallbackProgress;
127 FetchAttributes.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY;
128 // Only timeout property for whole transfer is supported by Fetch API.
129 // We implement low speed timeout ourselves in `OnProgress` function.
130 FetchAttributes.timeoutMSecs = m_Timeout.m_TimeoutMs;
131 FetchAttributes.requestHeaders = vpPackedHeaders.data();
132 FetchAttributes.requestData = reinterpret_cast<const char *>(m_pBody);
133 FetchAttributes.requestDataSize = m_BodyLength;
134
135 {
136 std::unique_lock WaitLock(m_WaitMutex);
137 m_State = EHttpState::RUNNING;
138 }
139 m_pFetch = emscripten_fetch(&FetchAttributes, m_aUrl);
140 dbg_assert(m_pFetch != nullptr, "emscripten_fetch failure");
141
142 return true;
143}
144
145void CHttpRequestEmscripten::OnSuccess()
146{
147 dbg_assert(!m_CallbackFinished, "OnSuccess was called multiple times");
148 dbg_assert(m_pFetch != nullptr, "OnSuccess was called with an unset fetch handle");
149 m_CallbackFinished = true;
150
151 const bool Success = OnData(m_pFetch->data, m_pFetch->numBytes) == m_pFetch->numBytes;
152
153 m_pHttp->AddPendingStateChange(m_RequestId, Success ? EHttpState::DONE : EHttpState::ERROR);
154}
155
156void CHttpRequestEmscripten::OnFailure()
157{
158 if(m_CallbackFinished || m_pFetch == nullptr)
159 {
160 // Failure callback may be called several times after the fetch handle has already been closed.
161 return;
162 }
163 m_CallbackFinished = true;
164
165 const bool Success = m_pFetch->status >= 200 && (m_pFetch->status < 400 || !m_FailOnErrorStatus);
166
167 m_pHttp->AddPendingStateChange(m_RequestId, Success ? EHttpState::DONE : EHttpState::ERROR);
168}
169
170void CHttpRequestEmscripten::OnProgress()
171{
172 if(m_MaxResponseSize >= 0 &&
173 (m_pFetch->totalBytes > (uint64_t)m_MaxResponseSize ||
174 m_pFetch->dataOffset > (uint64_t)m_MaxResponseSize))
175 {
176 m_pHttp->AddPendingStateChange(m_RequestId, EHttpState::ERROR);
177 return;
178 }
179
180 if(m_Timeout.m_LowSpeedLimit > 0 && m_Timeout.m_LowSpeedTime > 0)
181 {
182 const std::chrono::nanoseconds Now = time_get_nanoseconds();
183 if(m_pFetch->dataOffset - m_LowSpeedOffset >= (uint64_t)m_Timeout.m_LowSpeedLimit)
184 {
185 m_LowSpeedOffset = m_pFetch->dataOffset;
186 m_LowSpeedCheckTime = Now;
187 }
188 else if(Now - m_LowSpeedCheckTime > std::chrono::seconds(m_Timeout.m_LowSpeedTime))
189 {
190 m_pHttp->AddPendingStateChange(m_RequestId, EHttpState::ERROR);
191 return;
192 }
193 }
194
195 m_Current.store(m_pFetch->dataOffset, std::memory_order_relaxed);
196 m_Size.store(m_pFetch->totalBytes, std::memory_order_relaxed);
197 m_Progress.store(m_pFetch->totalBytes == 0 ? 0 : (100 * m_pFetch->dataOffset) / m_pFetch->totalBytes, std::memory_order_relaxed);
198 if(m_pProgressCallback != nullptr)
199 {
200 m_pProgressCallback->OnProgress();
201 }
202}
203
204EM_JS(int64_t, ParseDateJsImpl, (const char *pStr), {
205 const parsedDate = Date.parse(UTF8ToString(pStr));
206 if(isNaN(parsedDate)) // Invalid dates are represented as NaN for some reason
207 {
208 return -1;
209 }
210 return BigInt(Math.floor(parsedDate / 1000));
211});
212
213void CHttpRequestEmscripten::OnHeader(const char *pName, const char *pValue)
214{
215 if(str_comp_nocase(pName, "Date") == 0)
216 {
217 const int64_t Value = ParseDateJsImpl(pValue);
218 if(Value != -1)
219 {
220 m_ResultDate = Value;
221 }
222 }
223 else if(str_comp_nocase(pName, "Last-Modified") == 0)
224 {
225 const int64_t Value = ParseDateJsImpl(pValue);
226 if(Value != -1)
227 {
228 m_ResultLastModified = Value;
229 }
230 }
231}
232
233void CHttpRequestEmscripten::OnCompletionInternal(EHttpState State, const char *pErrorDetail)
234{
235 if(m_pFetch != nullptr)
236 {
237 const size_t HeadersLength = emscripten_fetch_get_response_headers_length(m_pFetch);
238 if(HeadersLength != 0)
239 {
240 char *pHeaders = static_cast<char *>(malloc(HeadersLength + 1));
241 dbg_assert(emscripten_fetch_get_response_headers(m_pFetch, pHeaders, HeadersLength + 1) == HeadersLength + 1, "emscripten_fetch_get_response_headers failure");
242 char **ppUnpackedHeaders = emscripten_fetch_unpack_response_headers(pHeaders);
243 if(ppUnpackedHeaders != nullptr)
244 {
245 int HeaderIndex = 0;
246 while(ppUnpackedHeaders[HeaderIndex] != nullptr)
247 {
248 const char *pName = ppUnpackedHeaders[HeaderIndex];
249 ++HeaderIndex;
250 const char *pValue = ppUnpackedHeaders[HeaderIndex];
251 ++HeaderIndex;
252 dbg_assert(pValue != nullptr, "emscripten_fetch_unpack_response_headers result unexpected: value is nullptr for header '%s'", pName);
253 OnHeader(pName, pValue);
254 }
255 emscripten_fetch_free_unpacked_response_headers(ppUnpackedHeaders);
256 }
257 free(pHeaders);
258 }
259
260 m_StatusCode = m_pFetch->status;
261 }
262
263 if(State == EHttpState::DONE)
264 {
265 if(g_Config.m_DbgHttp || m_LogProgress >= HTTPLOG::ALL)
266 {
267 log_info("http", "task done: %s", m_aUrl);
268 }
269 }
270 else
271 {
272 if(g_Config.m_DbgHttp || m_LogProgress >= HTTPLOG::FAILURE)
273 {
274 const char *pError =
275 pErrorDetail != nullptr ? pErrorDetail :
276 State == EHttpState::ABORTED ? "Request aborted" :
277 (m_pFetch != nullptr && m_pFetch->statusText[0] != '\0') ? m_pFetch->statusText :
278 "Unknown (check the web browser console)";
279 log_error("http", "%s failed. fetch error: %s", m_aUrl, pError);
280 }
281 }
282
283 if(m_pFetch != nullptr)
284 {
285 // Unset member variable before closing handle so completion callbacks are not called again.
286 emscripten_fetch_t *pFetch = m_pFetch;
287 m_pFetch = nullptr;
288 dbg_assert(emscripten_fetch_close(pFetch) == EMSCRIPTEN_RESULT_SUCCESS, "emscripten_fetch_close failure");
289 }
290
291 IHttpRequest::OnCompletionInternal(State);
292}
293
294void CHttpRequestEmscripten::FetchCallbackSuccess(emscripten_fetch_t *pFetch)
295{
296 static_cast<CHttpRequestEmscripten *>(pFetch->userData)->OnSuccess();
297}
298
299void CHttpRequestEmscripten::FetchCallbackFailure(emscripten_fetch_t *pFetch)
300{
301 static_cast<CHttpRequestEmscripten *>(pFetch->userData)->OnFailure();
302}
303
304void CHttpRequestEmscripten::FetchCallbackProgress(emscripten_fetch_t *pFetch)
305{
306 static_cast<CHttpRequestEmscripten *>(pFetch->userData)->OnProgress();
307}
308
309std::unique_ptr<IHttpRequest> CreateHttpRequest(const char *pUrl)
310{
311 return std::make_unique<CHttpRequestEmscripten>(pUrl);
312}
313
314bool CHttpEmscripten::Init(std::chrono::milliseconds ShutdownDelay)
315{
316 m_ShutdownDelay = ShutdownDelay;
317
318 m_pThread = thread_init(CHttpEmscripten::ThreadMain, this, "http");
319
320 std::unique_lock Lock(m_Lock);
321 m_ConditionVariableInit.wait(Lock, [this]() { return m_Initialized.load(std::memory_order_seq_cst); });
322
323 return true;
324}
325
326void CHttpEmscripten::Shutdown()
327{
328 {
329 std::unique_lock Lock(m_Lock);
330 if(m_Shutdown || !m_Initialized)
331 {
332 return;
333 }
334 m_Shutdown = true;
335 }
336 m_ConditionVariableLoop.notify_all();
337}
338
339CHttpEmscripten::~CHttpEmscripten()
340{
341 if(!m_pThread)
342 {
343 return;
344 }
345
346 Shutdown();
347 thread_wait(m_pThread);
348}
349
350void CHttpEmscripten::Run(std::shared_ptr<IHttpRequest> pRequest)
351{
352 {
353 std::unique_lock Lock(m_Lock);
354 dbg_assert(m_Initialized, "HTTP not initialized");
355 std::shared_ptr<CHttpRequestEmscripten> pRequestImpl = std::static_pointer_cast<CHttpRequestEmscripten>(pRequest);
356 pRequestImpl->m_pHttp = this;
357 pRequestImpl->m_RequestId = m_NextRequestId;
358 pRequestImpl->m_Initialized.store(true, std::memory_order_release);
359 ++m_NextRequestId;
360 if(m_Shutdown)
361 {
362 pRequestImpl->OnCompletionInternal(EHttpState::ABORTED, "Shutting down");
363 return;
364 }
365 m_PendingRequests.emplace_back(pRequestImpl);
366 }
367 m_ConditionVariableLoop.notify_all();
368}
369
370EM_JS(void, EscapeUrlJsImpl, (char *pBuf, size_t Size, const char *pStr), {
371 const escapedString = encodeURIComponent(UTF8ToString(pStr));
372 stringToUTF8(escapedString, pBuf, Size);
373});
374
375void EscapeUrl(char *pBuf, size_t Size, const char *pStr)
376{
377 EscapeUrlJsImpl(pBuf, Size, pStr);
378}
379
380bool CHttpEmscripten::HasIpresolveBug() const
381{
382 return false;
383}
384
385void CHttpEmscripten::ThreadMain(void *pUser)
386{
387 static_cast<CHttpEmscripten *>(pUser)->RunLoop();
388}
389
390void CHttpEmscripten::RunLoop()
391{
392 {
393 std::unique_lock Lock(m_Lock);
394 m_Initialized = true;
395 }
396 m_ConditionVariableInit.notify_all();
397
398 while(true)
399 {
400 {
401 std::unique_lock Lock(m_Lock);
402 if(m_Shutdown)
403 {
404 if(m_RunningRequests.empty() && m_PendingRequests.empty())
405 break;
406
407 const auto Now = std::chrono::steady_clock::now();
408 if(!m_ShutdownTime.has_value())
409 {
410 m_ShutdownTime = Now + m_ShutdownDelay;
411 }
412 else if(m_ShutdownTime < Now)
413 {
414 if(m_StartedShutdown)
415 {
416 break;
417 }
418 else
419 {
420 for(auto &[_, pRequest] : m_RunningRequests)
421 {
422 auto [ExistingElement, Inserted] = m_PendingFetchChanges.emplace(pRequest->m_RequestId, EHttpState::ABORTED);
423 if(!Inserted)
424 {
425 ExistingElement->second = EHttpState::ABORTED;
426 }
427 }
428 m_StartedShutdown = true;
429 m_ShutdownTime = Now + m_ShutdownDelay;
430 }
431 }
432 }
433 }
434
435 decltype(m_PendingRequests) PendingRequests = {};
436 decltype(m_PendingFetchChanges) PendingFetchChanges = {};
437 {
438 std::unique_lock Lock(m_Lock);
439 std::swap(m_PendingRequests, PendingRequests);
440 std::swap(m_PendingFetchChanges, PendingFetchChanges);
441 }
442
443 while(!PendingRequests.empty())
444 {
445 auto &pRequest = PendingRequests.front();
446 if(g_Config.m_DbgHttp)
447 {
448 log_debug("http", "task: %s %s", CHttpRequestEmscripten::GetRequestType(pRequest->m_Type), pRequest->m_aUrl);
449 }
450
451 if(pRequest->ShouldSkipRequest())
452 {
453 if(pRequest->m_pProgressCallback != nullptr)
454 {
455 pRequest->m_pProgressCallback->OnCompletion(EHttpState::DONE);
456 }
457 {
458 std::unique_lock WaitLock(pRequest->m_WaitMutex);
459 pRequest->m_State = EHttpState::DONE;
460 }
461 pRequest->m_WaitCondition.notify_all();
462 PendingRequests.pop_front();
463 continue;
464 }
465
466 if(m_StartedShutdown || pRequest->IsAbortRequested())
467 {
468 pRequest->OnCompletionInternal(EHttpState::ABORTED, m_StartedShutdown ? "Shutting down" : "Request aborted");
469 PendingRequests.pop_front();
470 continue;
471 }
472
473 if(!pRequest->ConfigureAndRun())
474 {
475 pRequest->OnCompletionInternal(EHttpState::ERROR, "Failed to initialize request");
476 PendingRequests.pop_front();
477 continue;
478 }
479
480 if(pRequest->IsAbortRequested())
481 {
482 pRequest->OnCompletionInternal(EHttpState::ABORTED, "Request aborted");
483 PendingRequests.pop_front();
484 continue;
485 }
486
487 {
488 uint64_t RequestId = pRequest->m_RequestId;
489 auto [_, Inserted] = m_RunningRequests.emplace(RequestId, std::move(pRequest));
490 dbg_assert(Inserted, "Request with same ID already running");
491 }
492 PendingRequests.pop_front();
493 }
494
495 for(const auto &[RequestId, NewState] : PendingFetchChanges)
496 {
497 auto pRequest = m_RunningRequests.find(RequestId);
498 if(pRequest == m_RunningRequests.end())
499 {
500 // Requests can be aborted even if they are not in m_RunningRequests anymore.
501 // We only hold the lock to swap the pending fetch changes above, so another
502 // pending state change to abort a request can be added while the HTTP thread
503 // is removing the running request in the branch below.
504 dbg_assert(NewState == EHttpState::ABORTED, "Request for pending fetch state change not found");
505 }
506 else
507 {
508 pRequest->second->OnCompletionInternal(NewState, nullptr);
509 m_RunningRequests.erase(pRequest);
510 }
511 }
512 PendingFetchChanges.clear();
513
514 // Return control to the browser so the created fetch handles are serviced.
515 // This will cause the success, failure and progress callbacks to be called.
516 emscripten_sleep(0);
517
518 // Wait a bit for state changes, but also wake up periodically because we
519 // need to call emscripten_sleep to service the handles.
520 std::unique_lock Lock(m_Lock);
521 const auto &&WaitPredicate = [this]() { return m_Shutdown || !m_PendingRequests.empty() || !m_PendingFetchChanges.empty(); };
522 const auto WaitTime = std::chrono::milliseconds(100);
523 const auto Now = std::chrono::steady_clock::now();
524 if(m_ShutdownTime.has_value() && m_ShutdownTime.value() - Now < WaitTime)
525 {
526 m_ConditionVariableLoop.wait_until(Lock, m_ShutdownTime.value(), WaitPredicate);
527 }
528 else
529 {
530 m_ConditionVariableLoop.wait_for(Lock, WaitTime, WaitPredicate);
531 }
532 }
533
534 std::unique_lock Lock(m_Lock);
535 for(auto &pRequest : m_PendingRequests)
536 {
537 pRequest->OnCompletionInternal(EHttpState::ABORTED, "Shutting down");
538 }
539 m_PendingRequests.clear();
540
541 for(auto &[_, pRequest] : m_RunningRequests)
542 {
543 pRequest->OnCompletionInternal(EHttpState::ABORTED, "Shutting down");
544 }
545 m_RunningRequests.clear();
546}
547
548void CHttpEmscripten::AddPendingStateChange(uint64_t RequestId, EHttpState State)
549{
550 {
551 std::unique_lock Lock(m_Lock);
552 auto [ExistingElement, Inserted] = m_PendingFetchChanges.emplace(RequestId, State);
553 if(!Inserted && ExistingElement->second != EHttpState::ABORTED)
554 {
555 ExistingElement->second = State;
556 }
557 }
558 m_ConditionVariableLoop.notify_all();
559}
560
561IEngineHttp *CreateEngineHttp()
562{
563 return new CHttpEmscripten;
564}
565
566#endif // CONF_PLATFORM_EMSCRIPTEN
567