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
|
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_MAIN_RESOURCE_LOADER_H_
#define CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_MAIN_RESOURCE_LOADER_H_
#include <memory>
#include <string>
#include <vector>
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "base/time/time.h"
#include "content/browser/loader/navigation_loader_interceptor.h"
#include "content/browser/service_worker/service_worker_cache_storage_matcher.h"
#include "content/browser/service_worker/service_worker_fetch_dispatcher.h"
#include "content/browser/service_worker/service_worker_synthetic_response_manager.h"
#include "content/common/content_export.h"
#include "content/common/service_worker/forwarded_race_network_request_url_loader_factory.h"
#include "content/common/service_worker/race_network_request_url_loader_client.h"
#include "content/common/service_worker/service_worker_resource_loader.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "net/url_request/redirect_info.h"
#include "services/network/public/mojom/network_interface_change_listener.mojom.h"
#include "services/network/public/mojom/service_worker_router_info.mojom-shared.h"
#include "services/network/public/mojom/url_loader.mojom.h"
#include "third_party/blink/public/common/service_worker/embedded_worker_status.h"
#include "third_party/blink/public/common/service_worker/service_worker_router_rule.h"
#include "third_party/blink/public/mojom/blob/blob.mojom.h"
#include "third_party/blink/public/mojom/fetch/fetch_api_response.mojom.h"
#include "third_party/blink/public/mojom/service_worker/service_worker_stream_handle.mojom.h"
namespace content {
class ServiceWorkerClient;
class ServiceWorkerVersion;
// ServiceWorkerMainResourceLoader is the URLLoader used for main resource
// requests (i.e., navigation and shared worker requests) that go through a
// service worker. This loader is only used for the main resource request; once
// the response is delivered, the resulting client loads subresources via
// ServiceWorkerSubresourceLoader.
//
// This class is owned by ServiceWorkerControlleeRequestHandler until it is
// bound to a URLLoader request. After it is bound |this| is kept alive until
// the Mojo connection to this URLLoader is dropped.
class CONTENT_EXPORT ServiceWorkerMainResourceLoader
: public network::mojom::URLLoader,
public ServiceWorkerResourceLoader {
public:
// Created by ServiceWorkerControlleeRequestHandler
// after it determines the load should go through a service worker.
//
// For the navigation case, this job typically works in the following order:
// 1. ServiceWorkerControlleeRequestHandler::MaybeCreateLoader() creates the
// ServiceWorkerMainResourceLoader, passing StartRequest() as the
// RequestHandler.
// 2. At this point, the NavigationURLLoaderImpl can throttle the request,
// and invoke the RequestHandler later with a possibly modified request.
// 3. StartRequest is invoked. This dispatches a FetchEvent.
// 4. DidDispatchFetchEvent() determines the request's final destination. If
// it turns out we need to fallback to network, it calls
// |fallback_callback|.
// 5. Otherwise if the SW returned a stream or blob as a response
// this job passes the response to the network::mojom::URLLoaderClient
// connected to NavigationURLLoaderImpl (for resource loading for
// navigation), that was given to StartRequest. This forwards the
// blob/stream data pipe to the NavigationURLLoader.
//
// Loads for shared workers work similarly, except SharedWorkerScriptLoader
// is used instead of NavigationURLLoaderImpl.
ServiceWorkerMainResourceLoader(
NavigationLoaderInterceptor::FallbackCallback fallback_callback,
std::string fetch_event_client_id,
base::WeakPtr<ServiceWorkerClient> service_worker_client,
base::TimeTicks find_registration_start_time);
ServiceWorkerMainResourceLoader(const ServiceWorkerMainResourceLoader&) =
delete;
ServiceWorkerMainResourceLoader& operator=(
const ServiceWorkerMainResourceLoader&) = delete;
~ServiceWorkerMainResourceLoader() override;
// Passed as the RequestHandler for
// NavigationLoaderInterceptor::MaybeCreateLoader.
void StartRequest(
mojo::PendingReceiver<network::mojom::URLLoader> loader,
int32_t request_id,
uint32_t options,
const network::ResourceRequest& request,
mojo::PendingRemote<network::mojom::URLLoaderClient> client,
const net::MutableNetworkTrafficAnnotationTag& traffic_annotation);
// The navigation request that was holding this job is
// going away. Calling this internally calls |DeleteIfNeeded()|
// and may delete |this| if it is not bound to a endpoint.
// Otherwise |this| will be kept around as far as the loader
// endpoint is held by the client.
void DetachedFromRequest();
base::WeakPtr<ServiceWorkerMainResourceLoader> AsWeakPtr();
private:
class RaceNetworkRequestURLLoaderClient;
class StreamWaiter;
enum class Status {
kNotStarted,
// |receiver_| is bound and the fetch event is being dispatched to the
// service worker.
kStarted,
// The data pipe for the response body has been sent to
// |url_loader_client_|. The body is being written to the pipe.
kSentBody,
// OnComplete() was called on |url_loader_client_|, or fallback to network
// occurred so the request was not handled.
kCompleted,
};
enum class RaceNetworkRequestMode { kDefault, kForced, kSkipped };
void DidPrepareFetchEvent(scoped_refptr<ServiceWorkerVersion> version,
blink::EmbeddedWorkerStatus initial_worker_status);
void DidDispatchFetchEvent(
blink::ServiceWorkerStatusCode status,
ServiceWorkerFetchDispatcher::FetchEventResult fetch_result,
blink::mojom::FetchAPIResponsePtr response,
blink::mojom::ServiceWorkerStreamHandlePtr body_as_stream,
blink::mojom::ServiceWorkerFetchEventTimingPtr timing,
scoped_refptr<ServiceWorkerVersion> version);
void StartResponse(blink::mojom::FetchAPIResponsePtr response,
scoped_refptr<ServiceWorkerVersion> version,
blink::mojom::ServiceWorkerStreamHandlePtr body_as_stream);
// ServiceWorkerResourceLoader overrides:
// Calls url_loader_client_->OnReceiveResponse() with
// |response_head|, |response_body| and |cached_metadata|.
void CommitResponseBody(
const network::mojom::URLResponseHeadPtr& response_head,
mojo::ScopedDataPipeConsumerHandle response_body,
std::optional<mojo_base::BigBuffer> cached_metadata) override;
// Creates and sends an empty response's body with the net::OK status.
// Sends net::ERR_INSUFFICIENT_RESOURCES when it can't be created.
void CommitEmptyResponseAndComplete() override;
// Calls url_loader_client_->OnComplete(). |reason| will be recorded as an
// argument of TRACE_EVENT.
void CommitCompleted(int error_code, const char* reason) override;
// Calls url_loader_client_->OnReceiveRedirect().
void HandleRedirect(
const net::RedirectInfo& redirect_info,
const network::mojom::URLResponseHeadPtr& response_head) override;
bool IsMainResourceLoader() override;
// network::mojom::URLLoader:
void FollowRedirect(
const std::vector<std::string>& removed_headers,
const net::HttpRequestHeaders& modified_headers,
const net::HttpRequestHeaders& modified_cors_exempt_headers,
const std::optional<GURL>& new_url) override;
void SetPriority(net::RequestPriority priority,
int32_t intra_priority_value) override;
void OnBlobReadingComplete(int net_error);
void SetCommitResponsibility(FetchResponseFrom fetch_response_from) override;
void OnConnectionClosed();
void InvalidateAndDeleteIfNeeded();
void DeleteIfNeeded();
network::mojom::ServiceWorkerStatus ConvertToServiceWorkerStatus(
blink::EmbeddedWorkerStatus embedded_status,
bool is_warming_up,
bool is_warmed_up);
void Fallback(ResponseHeadUpdateParams response_header_params);
std::string GetInitialServiceWorkerStatusString();
std::string GetFrameTreeNodeTypeString();
bool IsEligibleForRecordingTimingMetrics();
void RecordFindRegistrationToCompletedTrace();
// Called when the fetch handler handles the request.
void RecordTimingMetricsForFetchHandlerHandledCase();
// Called when the fetch handler doesn't handle the request (i.e. network
// fallback case).
void RecordTimingMetricsForNetworkFallbackCase();
// Called when the response from RaceNetworkRequest is faster than the
// response from the fetch handler.
void RecordTimingMetricsForRaceNetworkRequestCase();
void RecordFindRegistrationToRequestStartTiming();
// Time between the request is made and the request is routed to this loader.
void RecordRequestStartToForwardServiceWorkerTiming();
// Time spent for service worker startup.
void RecordForwardServiceWorkerToWorkerReadyTiming();
// Browser -> Renderer IPC delay.
void RecordWorkerReadyToFetchHandlerStartTiming();
// Time spent by fetch handlers.
void RecordFetchHandlerStartToFetchHandlerEndTiming();
// Renderer -> Browser IPC delay.
void RecordFetchHandlerEndToResponseReceivedTiming();
// Time spent reading response body.
void RecordResponseReceivedToCompletedTiming();
void RecordFindRegistrationToCompletedTiming();
// Time between the request is made and complete reading response body.
void RecordRequestStartToCompletedTiming(
const base::TimeTicks& request_start);
void RecordFindRegistrationToFallbackNetworkTiming();
// Time between the request is made and network fallback.
void RecordStartToFallbackNetworkTiming();
// Renderer -> Browser IPC delay (network fallback case).
void RecordFetchHandlerEndToFallbackNetworkTiming();
// Records metrics related to the fetch event handler execution.
void RecordFetchEventHandlerMetrics(
ServiceWorkerFetchDispatcher::FetchEventResult fetch_result);
void RecordFindRegistrationTiming(bool is_fallback);
void TransitionToStatus(Status new_status);
// Dispatch preloading request based on the condition and feature enablement
// status, and set dispatched_preload_type.
void MaybeDispatchPreload(
RaceNetworkRequestMode race_network_request_mode,
scoped_refptr<ServiceWorkerContextWrapper> context_wrapper,
scoped_refptr<ServiceWorkerVersion> version);
// Returns false if fails to start the race network request.
// The caller should run the regular path instead.
bool StartRaceNetworkRequest(
scoped_refptr<ServiceWorkerContextWrapper> context_wrapper,
scoped_refptr<ServiceWorkerVersion> version);
// If the feature is enabled, invoke the preload network request.
// See this doc for the high-level code flow in
// ServiceWorkerMainResourceLoader.
// https://docs.google.com/presentation/d/13A54OUqaBPrgkIQZE3a3CnhT3pe3C70j07HCisjNZlI/edit#slide=id.g2753dd0eed3_0_0
bool MaybeStartAutoPreload(
scoped_refptr<ServiceWorkerContextWrapper> context_wrapper,
scoped_refptr<ServiceWorkerVersion> version);
bool MaybeStartNavigationPreload(
scoped_refptr<ServiceWorkerContextWrapper> context_wrapper);
// If the request URL is eligible, and it's an outermost main frame,
// SyntheticResponse is triggered.
//
// This initiates a network request, and stores its response header to
// `ServiceWorkerVersion` so that it can be used for the next navigation with
// SyntheticResponse. The stored header is always refreshed with the new one.
//
// If the header already exists at the time of navigation, this method
// immediately return the response with the stored header and empty body. The
// remaining body is appended after receiving the actual response from the
// network.
bool MaybeStartSyntheticNetworkRequest(
scoped_refptr<ServiceWorkerContextWrapper> context_wrapper,
scoped_refptr<ServiceWorkerVersion> version);
void OnReceiveResponseFromSyntheticNetworkRequest(
network::mojom::URLResponseHeadPtr response_head,
mojo::ScopedDataPipeConsumerHandle body);
void OnCompleteSyntheticNetworkRequest(
const network::URLLoaderCompletionStatus& status);
void CreateAndRunCacheMatcher(
const std::optional<std::string>& cache_name,
scoped_refptr<ServiceWorkerVersion> active_worker);
NavigationLoaderInterceptor::FallbackCallback fallback_callback_;
int32_t request_id_ = 0;
uint32_t options_ = 0;
network::ResourceRequest resource_request_;
net::MutableNetworkTrafficAnnotationTag traffic_annotation_;
base::WeakPtr<ServiceWorkerClient> service_worker_client_;
std::unique_ptr<ServiceWorkerFetchDispatcher> fetch_dispatcher_;
std::unique_ptr<ServiceWorkerCacheStorageMatcher> cache_matcher_;
std::unique_ptr<StreamWaiter> stream_waiter_;
// The blob needs to be held while it's read to keep it alive.
mojo::Remote<blink::mojom::Blob> body_as_blob_;
network::mojom::URLResponseHeadPtr response_head_ =
network::mojom::URLResponseHead::New();
bool devtools_attached_ = false;
blink::mojom::ServiceWorkerFetchEventTimingPtr fetch_event_timing_;
base::TimeTicks completion_time_;
network::mojom::FetchResponseSource response_source_ =
network::mojom::FetchResponseSource::kUnspecified;
// Pointer to the URLLoaderClient (i.e. NavigationURLLoader).
mojo::Remote<network::mojom::URLLoaderClient> url_loader_client_;
mojo::Receiver<network::mojom::URLLoader> receiver_{this};
Status status_ = Status::kNotStarted;
std::optional<network::mojom::ServiceWorkerStatus>
initial_service_worker_status_;
const bool is_browser_startup_completed_;
const std::string frame_tree_node_type_;
bool is_detached_ = false;
scoped_refptr<network::SharedURLLoaderFactory>
race_network_request_url_loader_factory_;
std::optional<ServiceWorkerRaceNetworkRequestURLLoaderClient>
race_network_request_url_loader_client_;
std::optional<ServiceWorkerForwardedRaceNetworkRequestURLLoaderFactory>
forwarded_race_network_request_url_loader_factory_;
std::optional<ServiceWorkerSyntheticResponseManager>
synthetic_response_manager_;
base::TimeTicks find_registration_start_time_;
// FetchEvent.clientId
// https://w3c.github.io/ServiceWorker/#fetch-event-clientid
const std::string fetch_event_client_id_;
bool has_fetch_event_finished_ = false;
bool is_synthetic_response_used_ = false;
base::WeakPtrFactory<ServiceWorkerMainResourceLoader> weak_factory_{this};
};
// Owns a loader and calls DetachedFromRequest() to release it.
class ServiceWorkerMainResourceLoaderWrapper {
public:
explicit ServiceWorkerMainResourceLoaderWrapper(
std::unique_ptr<ServiceWorkerMainResourceLoader> loader);
ServiceWorkerMainResourceLoaderWrapper(
const ServiceWorkerMainResourceLoaderWrapper&) = delete;
ServiceWorkerMainResourceLoaderWrapper& operator=(
const ServiceWorkerMainResourceLoaderWrapper&) = delete;
~ServiceWorkerMainResourceLoaderWrapper();
ServiceWorkerMainResourceLoader* get() { return loader_.get(); }
private:
std::unique_ptr<ServiceWorkerMainResourceLoader> loader_;
};
} // namespace content
#endif // CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_MAIN_RESOURCE_LOADER_H_
|