summaryrefslogtreecommitdiff
path: root/platform/default/online_file_source.cpp
blob: f9c1fdb9122dd8770f514ef168cdae873ba857a1 (plain)
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
#include <mbgl/storage/online_file_source.hpp>
#include <mbgl/storage/asset_context_base.hpp>
#include <mbgl/storage/http_context_base.hpp>
#include <mbgl/storage/network_status.hpp>

#include <mbgl/storage/response.hpp>
#include <mbgl/platform/platform.hpp>
#include <mbgl/platform/log.hpp>

#include <mbgl/util/thread.hpp>
#include <mbgl/util/mapbox.hpp>
#include <mbgl/util/exception.hpp>
#include <mbgl/util/chrono.hpp>
#include <mbgl/util/async_task.hpp>
#include <mbgl/util/noncopyable.hpp>
#include <mbgl/util/timer.hpp>
#include <mbgl/util/url.hpp>

#include <algorithm>
#include <cassert>
#include <set>
#include <unordered_map>

namespace mbgl {

class RequestBase;

class OnlineFileRequest : public FileRequest {
public:
    OnlineFileRequest(const Resource& resource_,
                       OnlineFileSource& fileSource_)
        : resource(resource_),
          fileSource(fileSource_) {
    }

    ~OnlineFileRequest() {
        fileSource.cancel(resource, this);
    }

    Resource resource;
    OnlineFileSource& fileSource;

    std::unique_ptr<WorkRequest> workRequest;
};

class OnlineFileRequestImpl : public util::noncopyable {
public:
    using Callback = std::function<void (Response)>;

    OnlineFileRequestImpl(const Resource&);
    ~OnlineFileRequestImpl();

    // Observer accessors.
    void addObserver(FileRequest*, Callback, OnlineFileSource::Impl&);
    void removeObserver(FileRequest*);
    bool hasObservers() const;

    void networkIsReachableAgain(OnlineFileSource::Impl&);

private:
    void startCacheRequest(OnlineFileSource::Impl&);
    void startRealRequest(OnlineFileSource::Impl&);
    void reschedule(OnlineFileSource::Impl&);

    const Resource resource;
    std::unique_ptr<WorkRequest> cacheRequest;
    RequestBase* realRequest = nullptr;
    util::Timer realRequestTimer;

    // Set the response of this request object and notify all observers.
    void setResponse(const std::shared_ptr<const Response>&);

    // Returns the seconds we have to wait until we need to redo this request. A value of 0
    // means that we need to redo it immediately, and a negative value means that we're not setting
    // a timeout at all.
    Seconds getRetryTimeout() const;

    // Stores a set of all observing Request objects.
    std::unordered_map<FileRequest*, Callback> observers;

    // The current response data. We're storing it because we can satisfy requests for the same
    // resource directly by returning this response object. We also need it to create conditional
    // HTTP requests, and to check whether new responses we got changed any data.
    std::shared_ptr<const Response> response;

    // Counts the number of subsequent failed requests. We're using this value for exponential
    // backoff when retrying requests.
    int failedRequests = 0;
};

class OnlineFileSource::Impl {
public:
    using Callback = std::function<void (Response)>;

    Impl(FileCache*, const std::string& = "");
    ~Impl();

    void networkIsReachableAgain();

    void add(Resource, FileRequest*, Callback);
    void cancel(Resource, FileRequest*);

private:
    friend OnlineFileRequestImpl;

    std::unordered_map<Resource, std::unique_ptr<OnlineFileRequestImpl>, Resource::Hash> pending;
    FileCache* const cache;
    const std::string assetRoot;
    const std::unique_ptr<AssetContextBase> assetContext;
    const std::unique_ptr<HTTPContextBase> httpContext;
    util::AsyncTask reachability;
};

OnlineFileSource::OnlineFileSource(FileCache* cache, const std::string& root)
    : thread(std::make_unique<util::Thread<Impl>>(
          util::ThreadContext{ "OnlineFileSource", util::ThreadType::Unknown, util::ThreadPriority::Low },
          cache,
          root)) {
}

OnlineFileSource::~OnlineFileSource() = default;

std::unique_ptr<FileRequest> OnlineFileSource::request(const Resource& resource, Callback callback) {
    if (!callback) {
        throw util::MisuseException("FileSource callback can't be empty");
    }

    std::string url;

    switch (resource.kind) {
    case Resource::Kind::Style:
        url = mbgl::util::mapbox::normalizeStyleURL(resource.url, accessToken);
        break;

    case Resource::Kind::Source:
        url = util::mapbox::normalizeSourceURL(resource.url, accessToken);
        break;

    case Resource::Kind::Glyphs:
        url = util::mapbox::normalizeGlyphsURL(resource.url, accessToken);
        break;

    case Resource::Kind::SpriteImage:
    case Resource::Kind::SpriteJSON:
        url = util::mapbox::normalizeSpriteURL(resource.url, accessToken);
        break;

    default:
        url = resource.url;
    }

    Resource res { resource.kind, url };
    auto req = std::make_unique<OnlineFileRequest>(res, *this);
    req->workRequest = thread->invokeWithCallback(&Impl::add, callback, res, req.get());
    return std::move(req);
}

void OnlineFileSource::cancel(const Resource& res, FileRequest* req) {
    thread->invoke(&Impl::cancel, res, req);
}

// ----- Impl -----

OnlineFileSource::Impl::Impl(FileCache* cache_, const std::string& root)
    : cache(cache_),
      assetRoot(root.empty() ? platform::assetRoot() : root),
      assetContext(AssetContextBase::createContext()),
      httpContext(HTTPContextBase::createContext()),
      reachability(std::bind(&Impl::networkIsReachableAgain, this)) {
    // Subscribe to network status changes, but make sure that this async handle doesn't keep the
    // loop alive; otherwise our app wouldn't terminate. After all, we only need status change
    // notifications when our app is still running.
    NetworkStatus::Subscribe(&reachability);
}

OnlineFileSource::Impl::~Impl() {
    NetworkStatus::Unsubscribe(&reachability);
}

void OnlineFileSource::Impl::networkIsReachableAgain() {
    for (auto& req : pending) {
        req.second->networkIsReachableAgain(*this);
    }
}

void OnlineFileSource::Impl::add(Resource resource, FileRequest* req, Callback callback) {
    auto& request = *pending.emplace(resource,
        std::make_unique<OnlineFileRequestImpl>(resource)).first->second;

    // Add this request as an observer so that it'll get notified when something about this
    // request changes.
    request.addObserver(req, callback, *this);
}

void OnlineFileSource::Impl::cancel(Resource resource, FileRequest* req) {
    auto it = pending.find(resource);
    if (it != pending.end()) {
        // If the number of dependent requests of the OnlineFileRequest drops to zero,
        // cancel the request and remove it from the pending list.
        auto& request = *it->second;
        request.removeObserver(req);
        if (!request.hasObservers()) {
            pending.erase(it);
        }
    } else {
        // There is no request for this URL anymore. Likely, the request already completed
        // before we got around to process the cancelation request.
    }
}

// ----- OnlineFileRequest -----

OnlineFileRequestImpl::OnlineFileRequestImpl(const Resource& resource_)
    : resource(resource_) {
}

OnlineFileRequestImpl::~OnlineFileRequestImpl() {
    if (realRequest) {
        realRequest->cancel();
        realRequest = nullptr;
    }
    // realRequestTimer and cacheRequest are automatically canceled upon destruction.
}

void OnlineFileRequestImpl::addObserver(FileRequest* req, Callback callback, OnlineFileSource::Impl& impl) {
    if (response) {
        // We've at least obtained a cache value, potentially we also got a final response.
        // Before returning the existing response, update the `stale` flag if necessary.
        if (!response->stale && response->isExpired()) {
            // Create a new Response object with `stale = true`, but the same data, and
            // replace the current request object we have.
            // We're not immediately swapping the member variable because it's declared as `const`, and
            // we first have to update the `stale` flag.
            auto staleResponse = std::make_shared<Response>(*response);
            staleResponse->stale = true;
            response = staleResponse;
        }

        callback(*response);

        if (response->stale && !realRequest) {
            // We've returned a stale response; now make sure the requester also gets a fresh
            // response eventually. It's possible that there's already a request in progress.
            // Note that this will also trigger updates to all other existing listeners.
            // Since we already have data, we're going to verify
            startRealRequest(impl);
        } else {
            // The response is still fresh (or there's already a request for refreshing the resource
            // in progress), so there's nothing we need to do.
        }
    } else if (!cacheRequest && !realRequest) {
        // There is no request in progress, and we don't have a response yet. This means we'll have
        // to start the request ourselves.
        if (impl.cache && !util::isAssetURL(resource.url)) {
            startCacheRequest(impl);
        } else {
            startRealRequest(impl);
        }
    } else {
        // There is a request in progress. We just have to wait.
    }

    observers.emplace(req, callback);
}

void OnlineFileRequestImpl::removeObserver(FileRequest* req) {
    observers.erase(req);
}

bool OnlineFileRequestImpl::hasObservers() const {
    return !observers.empty();
}

void OnlineFileRequestImpl::startCacheRequest(OnlineFileSource::Impl& impl) {
    // Check the cache for existing data so that we can potentially
    // revalidate the information without having to redownload everything.
    cacheRequest =
        impl.cache->get(resource, [this, &impl](std::shared_ptr<Response> response_) {
            cacheRequest = nullptr;
            if (response_) {
                response_->stale = response_->isExpired();
                setResponse(response_);
            }

            if (!response_ || response_->stale) {
                // No response or stale cache. Run the real request.
                startRealRequest(impl);
            }

            reschedule(impl);
        });
}

void OnlineFileRequestImpl::startRealRequest(OnlineFileSource::Impl& impl) {
    assert(!realRequest);

    // Ensure the timer is stopped.
    realRequestTimer.stop();

    auto callback = [this, &impl](std::shared_ptr<const Response> response_) {
        realRequest = nullptr;

        // Only update the cache for successful or 404 responses.
        // In particular, we don't want to write a Canceled request, or one that failed due to
        // connection errors to the cache. Server errors are hopefully also temporary, so we're not
        // caching them either.
        if (impl.cache && !util::isAssetURL(resource.url) &&
            (!response_->error || (response_->error->reason == Response::Error::Reason::NotFound))) {
            // Store response in database. Make sure we only refresh the expires column if the data
            // didn't change.
            FileCache::Hint hint = FileCache::Hint::Full;
            if (response && response_->data == response->data) {
                hint = FileCache::Hint::Refresh;
            }
            impl.cache->put(resource, response_, hint);
        }

        setResponse(response_);
        reschedule(impl);
    };

    if (util::isAssetURL(resource.url)) {
        realRequest = impl.assetContext->createRequest(resource.url, callback, impl.assetRoot);
    } else {
        realRequest = impl.httpContext->createRequest(resource.url, callback, response);
    }
}

void OnlineFileRequestImpl::reschedule(OnlineFileSource::Impl& impl) {
    if (realRequest) {
        // There's already a request in progress; don't start another one.
        return;
    }

    const Seconds timeout = getRetryTimeout();

    if (timeout >= Seconds::zero()) {
        realRequestTimer.start(timeout, Duration::zero(), [this, &impl] {
            assert(!realRequest);
            startRealRequest(impl);
        });
    }
}

void OnlineFileRequestImpl::networkIsReachableAgain(OnlineFileSource::Impl& impl) {
    // We need all requests to fail at least once before we are going to start retrying
    // them, and we only immediately restart request that failed due to connection issues.
    if (!realRequest && response && response->error && response->error->reason == Response::Error::Reason::Connection) {
        startRealRequest(impl);
    }
}

void OnlineFileRequestImpl::setResponse(const std::shared_ptr<const Response>& response_) {
    response = response_;

    if (response->error) {
        failedRequests++;
    } else {
        // Reset the number of subsequent failed requests after we got a successful one.
        failedRequests = 0;
    }

    // Notify in all cases; requestors can decide whether they want to use stale responses.
    for (auto& req : observers) {
        req.second(*response);
    }
}

Seconds OnlineFileRequestImpl::getRetryTimeout() const {
    Seconds timeout = Seconds::zero();

    if (!response) {
        // If we don't have a response, we should retry immediately.
        return timeout;
    }

    // A value < 0 means that we should not retry.
    timeout = Seconds(-1);

    if (response->error) {
        assert(failedRequests > 0);
        switch (response->error->reason) {
        case Response::Error::Reason::Server: {
            // Retry immediately, unless we have a certain number of attempts already
            const int graceRetries = 3;
            if (failedRequests <= graceRetries) {
                timeout = Seconds(1);
            } else {
                timeout = Seconds(1 << std::min(failedRequests - graceRetries, 31));
            }
        } break;
        case Response::Error::Reason::Connection: {
            // Exponential backoff
            timeout = Seconds(1 << std::min(failedRequests - 1, 31));
        } break;
        default:
            // Do not retry due to error.
            break;
        }
    }

    // Check to see if this response expires earlier than a potential error retry.
    if (response->expires > Seconds::zero()) {
        const Seconds secsToExpire = response->expires - toSeconds(SystemClock::now());
        // Only update the timeout if we don't have one yet, and only if the new timeout is shorter
        // than the previous one.
        timeout = timeout < Seconds::zero() ? secsToExpire: std::min(timeout, std::max(Seconds::zero(), secsToExpire));
    }

    return timeout;
}

} // namespace mbgl