Repository navigation
Expand file tree
/
Copy pathHttpLoader.mm
More file actions
611 lines (554 loc) · 24.1 KB
/
Copy pathHttpLoader.mm
File metadata and controls
611 lines (554 loc) · 24.1 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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
#include "HttpLoader.h"
#import <Foundation/Foundation.h>
#include <algorithm>
#include <cctype>
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <utility>
#include <vector>
#include "Helpers.h"
#include "ModuleUrl.h"
#include "RuntimeConfig.h"
#include "ns/http/ModuleTransport.h"
#include "ns/loader/LoaderState.h"
namespace tns {
using nativescript::common::http::AttemptOutcome;
using nativescript::common::http::AttemptRequest;
using nativescript::common::http::FetchPath;
using nativescript::common::http::ModuleTransport;
std::string CanonicalizeNormalizedHttpUrlKey(const std::string& normalizedUrl) {
return nativescript::common::http::CanonicalizeNormalizedHttpUrlKey(
normalizedUrl,
nativescript::common::loader::CanonicalizationConfigFor(v8::Isolate::TryGetCurrent()));
}
std::optional<std::vector<std::optional<std::string>>> RemoteModuleAllowlistItems(id value) {
if (![value isKindOfClass:[NSArray class]]) {
return std::nullopt;
}
std::vector<std::optional<std::string>> items;
for (id item in (NSArray*)value) {
items.push_back([item isKindOfClass:[NSString class]] ? ToExactUtf8((NSString*)item)
: std::nullopt);
}
return items;
}
// ─────────────────────────────────────────────────────────────
// The module HTTP cache
//
// Module fetches use ephemeral sessions, so no cookies or credentials persist.
// Each origin fetched with the cache on has an on-disk NSURLCache in its own
// directory, so one origin's cache can be dropped without touching another's;
// the app's shared NSURLCache is never read, replaced or resized. Fetches with
// the cache off go through sessions without a cache.
//
// The graph walk and the synchronous fallback each have sessions of their
// own, configured alike, so a blocking fallback fetch never waits for a
// connection held by the walk's fetches to the same host. An origin's two
// sessions share its one NSURLCache instance, so what either path stores the
// other reads.
//
// Every session's delegate queue is its own background queue, never the main
// queue, so a thread blocked waiting on one of its tasks does not hold up the
// completion it waits for.
//
// On disk, under AppCachesDirectory()/ns-module-http-cache:
// origins/<percent-encoded origin>/<generation>/ one NSURLCache directory
// trash/ deleted in the background
// A cache is dropped by moving its directory into trash, which is atomic; its
// sessions finish the tasks they have in flight, and anything those tasks store
// lands in the moved directory or, should a write recreate the old path, in a
// generation older than the one the origin uses next. An origin always opens
// its highest generation, and removes the others when it does. At most
// kModuleCacheMaxOrigins origin directories outlive a launch.
//
// All of it is process-wide, guarded by one mutex: fetch completions, every
// isolate's thread and the inspector's socket thread read and change it. An
// attempt's outcome goes to the core, which may clear the cache in response, so
// nothing is delivered to the core while that mutex is held.
static constexpr NSUInteger kModuleCacheMemoryCapacity = 8 * 1024 * 1024;
static constexpr NSUInteger kModuleCacheDiskCapacity = 256 * 1024 * 1024;
// Origins come and go with dev-server addresses (a new LAN IP or port is a new
// origin), so the partitions kept on disk need a bound: launch keeps this many
// of the most recently opened ones.
static constexpr NSUInteger kModuleCacheMaxOrigins = 8;
namespace {
// One session per path; the fallback's is created on first use, since most
// processes never take the fallback.
struct ModuleSessions {
NSURLSession* graphWalk = nil; // retained
NSURLSession* synchronousFallback = nil; // retained
NSURLSession*& For(FetchPath path) {
return path == FetchPath::kGraphWalk ? graphWalk : synchronousFallback;
}
};
struct ModuleCachePartition {
NSURLCache* cache = nil; // retained
ModuleSessions sessions;
NSURL* directory = nil; // retained
uint64_t generation = 0;
};
struct ModuleHttpCacheState {
std::mutex mutex;
bool initialized = false;
std::map<std::string, ModuleCachePartition> partitions;
// The generation each origin must open next, set when its cache is dropped
// in this process.
std::map<std::string, uint64_t> reservedGenerations;
ModuleSessions uncached;
NSURL* root = nil; // retained
};
NSURLSessionConfiguration* ModuleSessionConfiguration(NSURLCache* cache) {
NSURLSessionConfiguration* config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
// nil, not the ephemeral configuration's default in-memory cache: an
// uncached session must not cache at all.
config.URLCache = cache;
config.HTTPShouldSetCookies = NO;
config.HTTPMaximumConnectionsPerHost = 32;
return config;
}
// The session `path` uses with `cache` (nil: uncached), created on first use.
NSURLSession* SessionLocked(ModuleSessions& sessions, FetchPath path, NSURLCache* cache) {
NSURLSession*& session = sessions.For(path);
if (session == nil) {
session = [[NSURLSession sessionWithConfiguration:ModuleSessionConfiguration(cache)] retain];
}
return session;
}
// The sessions finish what they have in flight without being used again.
void RetireSessions(ModuleSessions& sessions) {
for (NSURLSession* session : {sessions.graphWalk, sessions.synchronousFallback}) {
[session finishTasksAndInvalidate];
[session release];
}
sessions = ModuleSessions();
}
NSURL* OriginsDirectory(ModuleHttpCacheState& state) {
return [state.root URLByAppendingPathComponent:@"origins" isDirectory:YES];
}
NSURL* TrashDirectory(ModuleHttpCacheState& state) {
return [state.root URLByAppendingPathComponent:@"trash" isDirectory:YES];
}
// Moves `item` into trash under a fresh name. Returns false only when `item`
// still exists afterwards, with the reason in `error`.
bool MoveToTrash(ModuleHttpCacheState& state, NSURL* item, std::string* error = nullptr) {
NSFileManager* fm = [NSFileManager defaultManager];
NSURL* trash = TrashDirectory(state);
[fm createDirectoryAtURL:trash withIntermediateDirectories:YES attributes:nil error:nil];
NSURL* destination = [trash URLByAppendingPathComponent:[NSUUID UUID].UUIDString];
if ([fm moveItemAtURL:item toURL:destination error:nil]) {
return true;
}
if (![fm fileExistsAtPath:item.path]) {
return true;
}
NSError* removeError = nil;
if ([fm removeItemAtURL:item error:&removeError]) {
return true;
}
if (error != nullptr) {
NSString* description = removeError.localizedDescription
?: [NSString stringWithFormat:@"could not remove %@", item.path];
*error = description.UTF8String ?: "could not remove a cache directory";
}
return false;
}
// Only removes what is inside trash, so concurrent purges, and a purge racing
// a MoveToTrash, at worst both try to remove one item.
void PurgeTrashInBackground(ModuleHttpCacheState& state) {
NSURL* trash = TrashDirectory(state);
dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
@autoreleasepool {
NSFileManager* fm = [NSFileManager defaultManager];
for (NSURL* item in [fm contentsOfDirectoryAtURL:trash
includingPropertiesForKeys:nil
options:0
error:nil]) {
[fm removeItemAtURL:item error:nil];
}
}
});
}
// "http://127.0.0.1:8080" → "http%3A%2F%2F127.0.0.1%3A8080": collision-free
// and a single path component.
NSString* OriginDirectoryName(const std::string& origin) {
static const char kHex[] = "0123456789ABCDEF";
std::string name;
for (unsigned char c : origin) {
if (isalnum(c) || c == '.' || c == '-') {
name += (char)c;
} else {
name += '%';
name += kHex[c >> 4];
name += kHex[c & 0xF];
}
}
return [NSString stringWithUTF8String:name.c_str()];
}
NSURL* OriginDirectory(ModuleHttpCacheState& state, const std::string& origin) {
return [OriginsDirectory(state) URLByAppendingPathComponent:OriginDirectoryName(origin)
isDirectory:YES];
}
// Keeps the kModuleCacheMaxOrigins origin directories opened most recently
// (PartitionLocked stamps each one's modification date) and trashes the rest;
// one whose date cannot be read counts as the oldest. Only safe before any
// partition is open.
void PruneOriginsLocked(ModuleHttpCacheState& state) {
NSArray<NSURL*>* origins =
[[NSFileManager defaultManager] contentsOfDirectoryAtURL:OriginsDirectory(state)
includingPropertiesForKeys:@[ NSURLContentModificationDateKey ]
options:0
error:nil];
if (origins.count <= kModuleCacheMaxOrigins) {
return;
}
auto openedAt = ^NSDate*(NSURL* url) {
NSDate* date = nil;
[url getResourceValue:&date forKey:NSURLContentModificationDateKey error:nil];
return date ?: [NSDate distantPast];
};
NSArray<NSURL*>* newestFirst =
[origins sortedArrayUsingComparator:^NSComparisonResult(NSURL* a, NSURL* b) {
return [openedAt(b) compare:openedAt(a)];
}];
for (NSUInteger i = kModuleCacheMaxOrigins; i < newestFirst.count; i++) {
MoveToTrash(state, newestFirst[i]);
}
}
// Before the first fetch and the first clear in the process.
void InitializeModuleHttpCacheLocked(ModuleHttpCacheState& state) {
if (state.initialized) {
return;
}
state.initialized = true;
const std::string cachesDir = AppCachesDirectory();
NSURL* caches = cachesDir.empty() ? nil
: [NSURL fileURLWithFileSystemRepresentation:cachesDir.c_str()
isDirectory:YES
relativeToURL:nil];
state.root = [[caches URLByAppendingPathComponent:@"ns-module-http-cache"
isDirectory:YES] retain];
// Anything at the root besides the two directories above is not a cache
// this runtime opens, so it goes too.
NSFileManager* fm = [NSFileManager defaultManager];
const bool clearAtLaunch =
[[NSProcessInfo processInfo].arguments containsObject:@"--nativescript-clear-module-cache"];
for (NSURL* item in [fm contentsOfDirectoryAtURL:state.root
includingPropertiesForKeys:nil
options:0
error:nil]) {
NSString* name = item.lastPathComponent;
if ([name isEqualToString:@"trash"] || ([name isEqualToString:@"origins"] && !clearAtLaunch)) {
continue;
}
MoveToTrash(state, item);
}
PruneOriginsLocked(state);
PurgeTrashInBackground(state);
}
// The partition for `origin`, opened on first use in this process. Opening
// reuses the origin's highest generation on disk unless its cache was dropped
// in this process, and removes every other generation.
ModuleCachePartition& PartitionLocked(ModuleHttpCacheState& state, const std::string& origin) {
auto it = state.partitions.find(origin);
if (it != state.partitions.end()) {
return it->second;
}
NSFileManager* fm = [NSFileManager defaultManager];
NSURL* originDirectory = OriginDirectory(state, origin);
uint64_t highest = 0;
NSArray<NSURL*>* entries = [fm contentsOfDirectoryAtURL:originDirectory
includingPropertiesForKeys:nil
options:0
error:nil];
for (NSURL* entry in entries) {
const char* name = entry.lastPathComponent.UTF8String;
char* end = nullptr;
const unsigned long long generation = strtoull(name, &end, 10);
if (end != name && *end == '\0') {
highest = std::max<uint64_t>(highest, generation);
}
}
auto reserved = state.reservedGenerations.find(origin);
const uint64_t generation = reserved != state.reservedGenerations.end()
? reserved->second
: std::max<uint64_t>(highest, 1);
NSString* generationName = [NSString stringWithFormat:@"%llu", (unsigned long long)generation];
for (NSURL* entry in entries) {
if (![entry.lastPathComponent isEqualToString:generationName]) {
MoveToTrash(state, entry);
}
}
NSURL* directory = [originDirectory URLByAppendingPathComponent:generationName isDirectory:YES];
[fm createDirectoryAtURL:directory withIntermediateDirectories:YES attributes:nil error:nil];
// When it was last opened, which is what PruneOriginsLocked keeps by.
[fm setAttributes:@{NSFileModificationDate : [NSDate date]}
ofItemAtPath:originDirectory.path
error:nil];
ModuleCachePartition& partition = state.partitions[origin];
partition.cache = [[NSURLCache alloc] initWithMemoryCapacity:kModuleCacheMemoryCapacity
diskCapacity:kModuleCacheDiskCapacity
directoryURL:directory];
partition.directory = [directory retain];
partition.generation = generation;
return partition;
}
// Drops the cache of one open partition: its directory moves to trash, an
// empty directory for the next generation takes its place, and both sessions
// are retired. False when the old directory could not be removed.
bool DropPartitionLocked(ModuleHttpCacheState& state, const std::string& origin,
std::string* error) {
auto it = state.partitions.find(origin);
if (it == state.partitions.end()) {
return true;
}
ModuleCachePartition partition = it->second;
state.partitions.erase(it);
const bool trashed = MoveToTrash(state, partition.directory, error);
const uint64_t next = partition.generation + 1;
state.reservedGenerations[origin] = next;
NSURL* nextDirectory = [[partition.directory URLByDeletingLastPathComponent]
URLByAppendingPathComponent:[NSString stringWithFormat:@"%llu", (unsigned long long)next]
isDirectory:YES];
[[NSFileManager defaultManager] createDirectoryAtURL:nextDirectory
withIntermediateDirectories:YES
attributes:nil
error:nil];
RetireSessions(partition.sessions);
[partition.cache release];
[partition.directory release];
return trashed;
}
nativescript::common::http::CacheOpResult CacheOpFailed(const std::string& error) {
return {false, "could not clear the module HTTP cache: " + error};
}
void ApplyRequestHeaders(NSMutableURLRequest* urlRequest, const AttemptRequest& request) {
for (const auto& header : request.headers) {
NSString* name = [NSString stringWithUTF8String:header.name.c_str()];
NSString* value = [NSString stringWithUTF8String:header.value.c_str()];
if (name != nil && value != nil) {
[urlRequest addValue:value forHTTPHeaderField:name];
}
}
}
// Autoreleased; nil when NSURL cannot parse the URL.
NSMutableURLRequest* BuildModuleFetchRequest(const AttemptRequest& request) {
NSString* string = [NSString stringWithUTF8String:request.url.c_str()];
NSURL* url = string != nil ? [NSURL URLWithString:string] : nil;
if (url == nil) {
return nil;
}
NSMutableURLRequest* urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod:@"GET"];
ApplyRequestHeaders(urlRequest, request);
[urlRequest setTimeoutInterval:std::chrono::duration<double>(request.timeout).count()];
[urlRequest setHTTPShouldHandleCookies:NO];
if (!request.useCache) {
[urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
}
return urlRequest;
}
std::string Utf8(NSString* string) {
const char* utf8 = string.UTF8String;
return utf8 != nullptr ? std::string(utf8) : std::string();
}
// What a finished task produced. NSURLSession reports a body that failed after
// the status line as an error alongside the response, so a response counts as
// arrived only without an error; its status and headers are still reported.
AttemptOutcome ReadModuleFetchOutcome(NSData* data, NSURLResponse* response, NSError* error) {
AttemptOutcome outcome;
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
outcome.arrived = error == nil;
outcome.status = (int)httpResponse.statusCode;
outcome.contentType = Utf8([httpResponse valueForHTTPHeaderField:@"Content-Type"]);
outcome.finalUrl = Utf8(httpResponse.URL.absoluteString);
NSString* clearSiteData = [httpResponse valueForHTTPHeaderField:@"Clear-Site-Data"];
if (clearSiteData != nil) {
outcome.clearSiteData.push_back(Utf8(clearSiteData));
}
}
if (data.length > 0) {
outcome.body.assign(static_cast<const char*>(data.bytes), static_cast<size_t>(data.length));
}
if (error != nil) {
NSString* description = error.localizedDescription ?: @"<no description>";
NSString* domain = error.domain ?: @"<no domain>";
outcome.errorDescription =
Utf8(domain) + " code=" + std::to_string((long)error.code) + " " + Utf8(description);
}
return outcome;
}
class NSURLSessionModuleTransport final : public ModuleTransport {
public:
const char* Name() const override { return "nsurlsession"; }
bool SchedulesItself() const override { return true; }
AttemptOutcome FetchBlocking(const AttemptRequest& request) override {
@autoreleasepool {
NSMutableURLRequest* urlRequest = BuildModuleFetchRequest(request);
if (urlRequest == nil) {
return MalformedUrl();
}
// Shared with the completion handler, which can outlive this frame when
// the wait expires.
struct SyncFetchState {
dispatch_semaphore_t done = dispatch_semaphore_create(0);
AttemptOutcome outcome;
~SyncFetchState() { dispatch_release(done); }
};
auto sync = std::make_shared<SyncFetchState>();
NSURLSessionDataTask* task =
StartTask(request, urlRequest, ^(NSData* data, NSURLResponse* response, NSError* error) {
@autoreleasepool {
try {
sync->outcome = ReadModuleFetchOutcome(data, response, error);
} catch (...) {
sync->outcome = AttemptOutcome();
}
}
dispatch_semaphore_signal(sync->done);
});
if (task == nil) {
return NoTask();
}
const dispatch_time_t waitUntil =
request.waitBound.count() > 0
? dispatch_time(
DISPATCH_TIME_NOW,
std::chrono::duration_cast<std::chrono::nanoseconds>(request.waitBound).count())
: DISPATCH_TIME_FOREVER;
if (dispatch_semaphore_wait(sync->done, waitUntil) != 0) {
[task cancel];
AttemptOutcome expired;
expired.waitExpired = true;
return expired;
}
return std::move(sync->outcome);
}
}
void FetchAsync(AttemptRequest request, std::function<void(AttemptOutcome)> done) override {
auto deliver = std::make_shared<std::function<void(AttemptOutcome)>>(std::move(done));
@autoreleasepool {
NSMutableURLRequest* urlRequest = BuildModuleFetchRequest(request);
if (urlRequest == nil) {
(*deliver)(MalformedUrl());
return;
}
NSURLSessionDataTask* task =
StartTask(request, urlRequest, ^(NSData* data, NSURLResponse* response, NSError* error) {
// NSURLSession invokes this block, so an exception leaving it is an
// std::terminate rather than a failed fetch.
@autoreleasepool {
AttemptOutcome outcome;
try {
outcome = ReadModuleFetchOutcome(data, response, error);
} catch (...) {
outcome = AttemptOutcome();
}
try {
(*deliver)(std::move(outcome));
} catch (...) {
}
}
});
if (task == nil) {
(*deliver)(NoTask());
}
}
}
bool PostDelayed(std::chrono::milliseconds delay, std::function<void()> task) override {
auto run = std::make_shared<std::function<void()>>(std::move(task));
dispatch_after(
dispatch_time(DISPATCH_TIME_NOW,
std::chrono::duration_cast<std::chrono::nanoseconds>(delay).count()),
dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
@autoreleasepool {
try {
(*run)();
} catch (...) {
}
}
});
return true;
}
nativescript::common::http::CacheOpResult ClearAll() override {
std::lock_guard<std::mutex> lock(state_.mutex);
@autoreleasepool {
InitializeModuleHttpCacheLocked(state_);
// Every origin at once, opened in this process or not; the open ones
// then get their next-generation directory back.
std::string error;
const bool trashed = MoveToTrash(state_, OriginsDirectory(state_), &error);
std::vector<std::string> open;
for (const auto& entry : state_.partitions) {
open.push_back(entry.first);
}
for (const std::string& origin : open) {
DropPartitionLocked(state_, origin, nullptr);
}
PurgeTrashInBackground(state_);
return trashed ? nativescript::common::http::CacheOpResult{} : CacheOpFailed(error);
}
}
// Each call drops what the origin has now. Called twice for one origin, the
// second finds no open partition and trashes the origin's directory, the
// reserved next generation included; PartitionLocked recreates that
// generation's directory when it reopens the origin.
nativescript::common::http::CacheOpResult ClearOrigin(const std::string& origin) override {
std::lock_guard<std::mutex> lock(state_.mutex);
@autoreleasepool {
InitializeModuleHttpCacheLocked(state_);
std::string error;
const bool trashed = state_.partitions.count(origin) != 0
? DropPartitionLocked(state_, origin, &error)
: MoveToTrash(state_, OriginDirectory(state_, origin), &error);
PurgeTrashInBackground(state_);
return trashed ? nativescript::common::http::CacheOpResult{} : CacheOpFailed(error);
}
}
private:
static AttemptOutcome MalformedUrl() {
AttemptOutcome outcome;
outcome.malformedUrl = true;
return outcome;
}
static AttemptOutcome NoTask() {
AttemptOutcome outcome;
outcome.errorDescription = "NSURLSession created no task";
return outcome;
}
// Creates and resumes the task for `request` on the session its path and
// cache choice use; autoreleased, nil when the session would not create one.
// `handler` runs on the session's delegate queue.
NSURLSessionDataTask* StartTask(const AttemptRequest& request, NSMutableURLRequest* urlRequest,
void (^handler)(NSData*, NSURLResponse*, NSError*)) {
std::lock_guard<std::mutex> lock(state_.mutex);
InitializeModuleHttpCacheLocked(state_);
const std::string origin = request.useCache ? HttpUrlOrigin(request.url) : std::string();
NSURLSession* session = nil;
if (!origin.empty()) {
ModuleCachePartition& partition = PartitionLocked(state_, origin);
session = SessionLocked(partition.sessions, request.path, partition.cache);
} else {
[urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
session = SessionLocked(state_.uncached, request.path, nil);
}
// Created and resumed under the lock: a cache dropped on another thread
// invalidates its session, which then refuses new tasks.
NSURLSessionDataTask* task = [session dataTaskWithRequest:urlRequest completionHandler:handler];
[task resume];
return task;
}
ModuleHttpCacheState state_;
};
} // namespace
ModuleTransport& ModuleHttpTransport() {
static auto* transport = new NSURLSessionModuleTransport();
return *transport;
}
} // namespace tns