Backed out 6 changesets (bug 1416879) for bc permafailures on windows on browser_multie10s_update.js r=backout a=backout

Backed out changeset 840a6e04bcea (bug 1416879)
Backed out changeset 994dc643a2ab (bug 1416879)
Backed out changeset 8e4fd74e7f5e (bug 1416879)
Backed out changeset 5453b8a58f0c (bug 1416879)
Backed out changeset d156f6b687e1 (bug 1416879)
Backed out changeset 714d3942fb10 (bug 1416879)
This commit is contained in:
Brindusan Cristian 2018-01-07 11:55:44 +02:00
Родитель 87bd56c8e5
Коммит f42618c99d
18 изменённых файлов: 27 добавлений и 639 удалений

Просмотреть файл

@ -1087,37 +1087,25 @@ FetchDriver::OnDataAvailable(nsIRequest* aRequest,
}
}
// Needs to be initialized to 0 because in some cases nsStringInputStream may
// not write to aRead.
uint32_t aRead = 0;
uint32_t aRead;
MOZ_ASSERT(mResponse);
MOZ_ASSERT(mPipeOutputStream);
// From "Main Fetch" step 19: SRI-part2.
// Note: Avoid checking the hidden opaque body.
nsresult rv;
if (mResponse->Type() != ResponseType::Opaque &&
ShouldCheckSRI(mRequest, mResponse)) {
MOZ_ASSERT(mSRIDataVerifier);
SRIVerifierAndOutputHolder holder(mSRIDataVerifier, mPipeOutputStream);
rv = aInputStream->ReadSegments(CopySegmentToStreamAndSRI,
&holder, aCount, &aRead);
} else {
rv = aInputStream->ReadSegments(NS_CopySegmentToStream,
mPipeOutputStream,
aCount, &aRead);
nsresult rv = aInputStream->ReadSegments(CopySegmentToStreamAndSRI,
&holder, aCount, &aRead);
return rv;
}
// If no data was read, it's possible the output stream is closed but the
// ReadSegments call followed its contract of returning NS_OK despite write
// errors. Unfortunately, nsIOutputStream has an ill-conceived contract when
// taken together with ReadSegments' contract, because the pipe will just
// NS_OK if we try and invoke its Write* functions ourselves with a 0 count.
// So we must just assume the pipe is broken.
if (aRead == 0 && aCount != 0) {
return NS_BASE_STREAM_CLOSED;
}
nsresult rv = aInputStream->ReadSegments(NS_CopySegmentToStream,
mPipeOutputStream,
aCount, &aRead);
return rv;
}

Просмотреть файл

@ -34,10 +34,7 @@ public:
{
if (!mWasNotified) {
mWasNotified = true;
// The WorkerPrivate does have a context available, and we could pass it
// here to trigger cancellation of the reader, but the author of this
// comment chickened out.
mReader->CloseAndRelease(nullptr, NS_ERROR_DOM_INVALID_STATE_ERR);
mReader->CloseAndRelease(NS_ERROR_DOM_INVALID_STATE_ERR);
}
return true;
@ -127,17 +124,11 @@ FetchStreamReader::FetchStreamReader(nsIGlobalObject* aGlobal)
FetchStreamReader::~FetchStreamReader()
{
CloseAndRelease(nullptr, NS_BASE_STREAM_CLOSED);
CloseAndRelease(NS_BASE_STREAM_CLOSED);
}
// If a context is provided, an attempt will be made to cancel the reader. The
// only situation where we don't expect to have a context is when closure is
// being triggered from the destructor or the WorkerHolder is notifying. If
// we're at the destructor, it's far too late to cancel anything. And if the
// WorkerHolder is being notified, the global is going away, so there's also
// no need to do further JS work.
void
FetchStreamReader::CloseAndRelease(JSContext* aCx, nsresult aStatus)
FetchStreamReader::CloseAndRelease(nsresult aStatus)
{
NS_ASSERT_OWNINGTHREAD(FetchStreamReader);
@ -148,22 +139,6 @@ FetchStreamReader::CloseAndRelease(JSContext* aCx, nsresult aStatus)
RefPtr<FetchStreamReader> kungFuDeathGrip = this;
if (aCx) {
MOZ_ASSERT(mReader);
RefPtr<DOMException> error = DOMException::Create(aStatus);
JS::Rooted<JS::Value> errorValue(aCx);
if (ToJSValue(aCx, error, &errorValue)) {
JS::Rooted<JSObject*> reader(aCx, mReader);
// It's currently safe to cancel an already closed reader because, per the
// comments in ReadableStream::cancel() conveying the spec, step 2 of
// 3.4.3 that specified ReadableStreamCancel is: If stream.[[state]] is
// "closed", return a new promise resolved with undefined.
JS::ReadableStreamReaderCancel(aCx, reader, errorValue);
}
}
mStreamClosed = true;
mGlobal = nullptr;
@ -191,7 +166,7 @@ FetchStreamReader::StartConsuming(JSContext* aCx,
JS::ReadableStreamReaderMode::Default));
if (!reader) {
aRv.StealExceptionFromJSContext(aCx);
CloseAndRelease(aCx, NS_ERROR_DOM_INVALID_STATE_ERR);
CloseAndRelease(NS_ERROR_DOM_INVALID_STATE_ERR);
return;
}
@ -231,14 +206,14 @@ FetchStreamReader::OnOutputStreamReady(nsIAsyncOutputStream* aStream)
reader));
if (NS_WARN_IF(!promise)) {
// Let's close the stream.
CloseAndRelease(aes.cx(), NS_ERROR_DOM_INVALID_STATE_ERR);
CloseAndRelease(NS_ERROR_DOM_INVALID_STATE_ERR);
return NS_ERROR_FAILURE;
}
RefPtr<Promise> domPromise = Promise::CreateFromExisting(mGlobal, promise);
if (NS_WARN_IF(!domPromise)) {
// Let's close the stream.
CloseAndRelease(aes.cx(), NS_ERROR_DOM_INVALID_STATE_ERR);
CloseAndRelease(NS_ERROR_DOM_INVALID_STATE_ERR);
return NS_ERROR_FAILURE;
}
@ -265,13 +240,13 @@ FetchStreamReader::ResolvedCallback(JSContext* aCx,
FetchReadableStreamReadDataDone valueDone;
if (!valueDone.Init(aCx, aValue)) {
JS_ClearPendingException(aCx);
CloseAndRelease(aCx, NS_ERROR_DOM_INVALID_STATE_ERR);
CloseAndRelease(NS_ERROR_DOM_INVALID_STATE_ERR);
return;
}
if (valueDone.mDone) {
// Stream is completed.
CloseAndRelease(aCx, NS_BASE_STREAM_CLOSED);
CloseAndRelease(NS_BASE_STREAM_CLOSED);
return;
}
@ -279,7 +254,7 @@ FetchStreamReader::ResolvedCallback(JSContext* aCx,
new FetchReadableStreamReadDataArray);
if (!value->Init(aCx, aValue) || !value->mValue.WasPassed()) {
JS_ClearPendingException(aCx);
CloseAndRelease(aCx, NS_ERROR_DOM_INVALID_STATE_ERR);
CloseAndRelease(NS_ERROR_DOM_INVALID_STATE_ERR);
return;
}
@ -299,12 +274,7 @@ FetchStreamReader::ResolvedCallback(JSContext* aCx,
mBufferOffset = 0;
mBufferRemaining = len;
nsresult rv = WriteBuffer();
if (NS_FAILED(rv)) {
// DOMException only understands errors from domerr.msg, so we normalize to
// identifying an abort if the write fails.
CloseAndRelease(aCx, NS_ERROR_DOM_ABORT_ERR);
}
WriteBuffer();
}
nsresult
@ -326,6 +296,7 @@ FetchStreamReader::WriteBuffer()
}
if (NS_WARN_IF(NS_FAILED(rv))) {
CloseAndRelease(rv);
return rv;
}
@ -341,6 +312,7 @@ FetchStreamReader::WriteBuffer()
nsresult rv = mPipeOut->AsyncWait(this, 0, 0, mOwningEventTarget);
if (NS_WARN_IF(NS_FAILED(rv))) {
CloseAndRelease(rv);
return rv;
}
@ -352,7 +324,7 @@ FetchStreamReader::RejectedCallback(JSContext* aCx,
JS::Handle<JS::Value> aValue)
{
ReportErrorToConsole(aCx, aValue);
CloseAndRelease(aCx, NS_ERROR_FAILURE);
CloseAndRelease(NS_ERROR_FAILURE);
}
void

Просмотреть файл

@ -40,12 +40,8 @@ public:
void
RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override;
// Idempotently close the output stream and null out all state. If aCx is
// provided, the reader will also be canceled. aStatus must be a DOM error
// as understood by DOMException because it will be provided as the
// cancellation reason.
void
CloseAndRelease(JSContext* aCx, nsresult aStatus);
CloseAndRelease(nsresult aStatus);
void
StartConsuming(JSContext* aCx,

Просмотреть файл

@ -4,21 +4,16 @@ support-files =
browser_cached_force_refresh.html
download/window.html
download/worker.js
download_canceled/page_download_canceled.html
download_canceled/server-stream-download.sjs
download_canceled/sw_download_canceled.js
fetch.js
file_multie10s_update.html
file_userContextId_openWindow.js
force_refresh_browser_worker.js
empty.html
server_multie10s_update.sjs
utils.js
[browser_devtools_serviceworker_interception.js]
[browser_force_refresh.js]
[browser_download.js]
[browser_download_canceled.js]
[browser_multie10s_update.js]
skip-if = !e10s || os != "win" # Bug 1404914
[browser_userContextId_openWindow.js]

Просмотреть файл

@ -1,166 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
/*
* Test cancellation of a download in order to test edge-cases related to
* channel diversion. Channel diversion occurs in cases of file (and PSM cert)
* downloads where we realize in the child that we really want to consume the
* channel data in the parent. For data "sourced" by the parent, like network
* data, data streaming to the child is suspended and the parent waits for the
* child to send back the data it already received, then the channel is resumed.
* For data generated by the child, such as (the current, to be mooted by
* parent-intercept) child-side intercept, the data (currently) stream is
* continually pumped up to the parent.
*
* In particular, we want to reproduce the circumstances of Bug 1418795 where
* the child-side input-stream pump attempts to send data to the parent process
* but the parent has canceled the channel and so the IPC Actor has been torn
* down. Diversion begins once the nsURILoader receives the OnStartRequest
* notification with the headers, so there are two ways to produce
*/
Cu.import('resource://gre/modules/Services.jsm');
const { Downloads } = Cu.import("resource://gre/modules/Downloads.jsm", {});
/**
* Clear the downloads list so other tests don't see our byproducts.
*/
async function clearDownloads() {
const downloads = await Downloads.getList(Downloads.ALL);
downloads.removeFinished();
}
/**
* Returns a Promise that will be resolved once the download dialog shows up and
* we have clicked the given button.
*
* Derived from browser/components/downloads/test/browser/head.js's
* self-contained promiseAlertDialogOpen helper, but modified to work on the
* download dialog instead of commonDialog.xul.
*/
function promiseClickDownloadDialogButton(buttonAction) {
return new Promise(resolve => {
Services.ww.registerNotification(function onOpen(win, topic, data) {
if (topic === "domwindowopened" && win instanceof Ci.nsIDOMWindow) {
// The test listens for the "load" event which guarantees that the alert
// class has already been added (it is added when "DOMContentLoaded" is
// fired).
win.addEventListener("load", function() {
info(`found window of type: ${win.document.documentURI}`);
if (win.document.documentURI ===
"chrome://mozapps/content/downloads/unknownContentType.xul") {
Services.ww.unregisterNotification(onOpen);
// nsHelperAppDlg.js currently uses an eval-based setTimeout(0) to
// invoke its postShowCallback that results in a misleading error to
// the console if we close the dialog before it gets a chance to
// run. Just a setTimeout is not sufficient because it appears we
// get our "load" listener before the document's, so we use
// executeSoon to defer until after its load handler runs, then
// use setTimeout(0) to end up after its eval.
executeSoon(function() {
setTimeout(function() {
const button = win.document.documentElement.getButton(buttonAction);
button.disabled = false;
info(`clicking ${buttonAction} button`);
button.click();
resolve();
}, 0);
});
}
}, {once: true});
}
});
});
}
async function performCanceledDownload(tab, path) {
// Start waiting for the download dialog before triggering the download.
info("watching for download popup");
const cancelDownload = promiseClickDownloadDialogButton("cancel");
// Trigger the download.
info(`triggering download of "${path}"`);
await ContentTask.spawn(
tab.linkedBrowser,
path,
function(path) {
// Put a Promise in place that we can wait on for stream closure.
content.wrappedJSObject.trackStreamClosure(path);
// Create the link and trigger the download.
const link = content.document.createElement('a');
link.href = path;
link.download = path;
content.document.body.appendChild(link);
link.click();
});
// Wait for the cancelation to have been triggered.
info("waiting for download popup");
await cancelDownload;
ok(true, "canceled download");
// Wait for confirmation that the stream stopped.
info(`wait for the ${path} stream to close.`);
const why = await ContentTask.spawn(
tab.linkedBrowser,
path,
function(path) {
return content.wrappedJSObject.streamClosed[path].promise;
});
is(why.why, "canceled", "Ensure the stream canceled instead of timing out.");
// Note that for the "sw-stream-download" case, we end up with a bogus
// reason of "'close' may only be called on a stream in the 'readable' state."
// Since we aren't actually invoking close(), I'm assuming this is an
// implementation bug that will be corrected in the web platform tests.
info(`Cancellation reason: ${why.message} after ${why.ticks} ticks`);
}
const gTestRoot = getRootDirectory(gTestPath)
.replace("chrome://mochitests/content/", "http://mochi.test:8888/");
const PAGE_URL = `${gTestRoot}download_canceled/page_download_canceled.html`;
add_task(async function interruptedDownloads() {
await SpecialPowers.pushPrefEnv({'set': [
['dom.serviceWorkers.enabled', true],
['dom.serviceWorkers.exemptFromPerDomainMax', true],
['dom.serviceWorkers.testing.enabled', true],
["javascript.options.streams", true],
["dom.streams.enabled", true],
]});
// Open the tab
const tab = await BrowserTestUtils.openNewForegroundTab({
gBrowser,
opening: PAGE_URL
});
// Wait for it to become controlled. Check that it was a promise that
// resolved as expected rather than undefined by checking the return value.
const controlled = await ContentTask.spawn(
tab.linkedBrowser,
null,
function() {
// This is a promise set up by the page during load, and we are post-load.
return content.wrappedJSObject.controlled;
});
is(controlled, "controlled", "page became controlled");
// Download a pass-through fetch stream.
await performCanceledDownload(tab, "sw-passthrough-download");
// Download a SW-generated stream
await performCanceledDownload(tab, "sw-stream-download");
// Cleanup
await ContentTask.spawn(
tab.linkedBrowser,
null,
function() {
return content.wrappedJSObject.registration.unregister();
});
await BrowserTestUtils.removeTab(tab);
await clearDownloads();
});

Просмотреть файл

@ -1,58 +0,0 @@
<!--
Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/
-->
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script src="../utils.js"></script>
<script type="text/javascript">
function wait_until_controlled() {
return new Promise(function(resolve) {
if (navigator.serviceWorker.controller) {
return resolve('controlled');
}
navigator.serviceWorker.addEventListener('controllerchange', function onController() {
if (navigator.serviceWorker.controller) {
navigator.serviceWorker.removeEventListener('controllerchange', onController);
return resolve('controlled');
}
});
});
}
addEventListener('load', async function(event) {
window.controlled = wait_until_controlled();
window.registration =
await navigator.serviceWorker.register('sw_download_canceled.js');
let sw = registration.installing || registration.waiting ||
registration.active;
await waitForState(sw, 'activated');
sw.postMessage('claim');
});
// Place to hold promises for stream closures reported by the SW.
window.streamClosed = {};
// The ServiceWorker will postMessage to this BroadcastChannel when the streams
// are closed. (Alternately, the SW could have used the clients API to post at
// us, but the mechanism by which that operates would be different when this
// test is uplifted, and it's desirable to avoid timing changes.)
//
// The browser test will use this promise to wait on stream shutdown.
window.swStreamChannel = new BroadcastChannel("stream-closed");
function trackStreamClosure(path) {
let resolve;
const promise = new Promise(r => { resolve = r });
window.streamClosed[path] = { promise, resolve };
}
window.swStreamChannel.onmessage = ({ data }) => {
window.streamClosed[data.what].resolve(data);
};
</script>
</body>
</html>

Просмотреть файл

@ -1,123 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
Cu.import("resource://gre/modules/Timer.jsm");
Cu.import("resource://gre/modules/NetUtil.jsm");
// stolen from file_blocked_script.sjs
function setGlobalState(data, key)
{
x = { data: data, QueryInterface: function(iid) { return this } };
x.wrappedJSObject = x;
setObjectState(key, x);
}
function getGlobalState(key)
{
var data;
getObjectState(key, function(x) {
data = x && x.wrappedJSObject.data;
});
return data;
}
/*
* We want to let the sw_download_canceled.js service worker know when the
* stream was canceled. To this end, we let it issue a monitor request which we
* fulfill when the stream has been canceled. In order to coordinate between
* multiple requests, we use the getObjectState/setObjectState mechanism that
* httpd.js exposes to let data be shared and/or persist between requests. We
* handle both possible orderings of the requests because we currently don't
* try and impose an ordering between the two requests as issued by the SW, and
* file_blocked_script.sjs encourages us to do this, but we probably could order
* them.
*/
const MONITOR_KEY = "stream-monitor";
function completeMonitorResponse(response, data) {
response.write(JSON.stringify(data));
response.finish();
}
function handleMonitorRequest(request, response) {
response.setHeader("Content-Type", "application/json");
response.setStatusLine(request.httpVersion, 200, "Found");
response.processAsync();
// Necessary to cause the headers to be flushed; that or touching the
// bodyOutputStream getter.
response.write("");
dump("server-stream-download.js: monitor headers issued\n");
const alreadyCompleted = getGlobalState(MONITOR_KEY);
if (alreadyCompleted) {
completeMonitorResponse(response, alreadyCompleted);
setGlobalState(null, MONITOR_KEY);
} else {
setGlobalState(response, MONITOR_KEY);
}
}
const MAX_TICK_COUNT = 3000;
const TICK_INTERVAL = 2;
function handleStreamRequest(request, response) {
const name = "server-stream-download";
// Create some payload to send.
let strChunk =
'Static routes are the future of ServiceWorkers! So say we all!\n';
while (strChunk.length < 1024) {
strChunk += strChunk;
}
response.setHeader("Content-Disposition", `attachment; filename="${name}"`);
response.setHeader("Content-Type", `application/octet-stream; name="${name}"`);
response.setHeader("Content-Length", `${strChunk.length * MAX_TICK_COUNT}`);
response.setStatusLine(request.httpVersion, 200, "Found");
response.processAsync();
response.write(strChunk);
dump("server-stream-download.js: stream headers + first payload issued\n");
let count = 0;
let intervalId;
function closeStream(why, message) {
dump("server-stream-download.js: closing stream: " + why + "\n");
clearInterval(intervalId);
response.finish();
const data = { why, message };
const monitorResponse = getGlobalState(MONITOR_KEY);
if (monitorResponse) {
completeMonitorResponse(monitorResponse, data);
setGlobalState(null, MONITOR_KEY);
} else {
setGlobalState(data, MONITOR_KEY);
}
}
function tick() {
try {
// bound worst-case behavior.
if (count++ > MAX_TICK_COUNT) {
closeStream("timeout", "timeout");
return;
}
response.write(strChunk);
} catch(e) {
closeStream("canceled", e.message);
}
}
intervalId = setInterval(tick, TICK_INTERVAL);
}
Components.utils.importGlobalProperties(["URLSearchParams"]);
function handleRequest(request, response) {
dump("server-stream-download.js: processing request for " + request.path +
"?" + request.queryString + "\n");
const query = new URLSearchParams(request.queryString);
if (query.has("monitor")) {
handleMonitorRequest(request, response);
} else {
handleStreamRequest(request, response);
}
}

Просмотреть файл

@ -1,136 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
// This file is derived from :bkelly's https://glitch.com/edit/#!/html-sw-stream
addEventListener("install", evt => {
evt.waitUntil(self.skipWaiting());
});
// Create a BroadcastChannel to notify when we have closed our streams.
const channel = new BroadcastChannel("stream-closed");
const MAX_TICK_COUNT = 3000;
const TICK_INTERVAL = 4;
/**
* Generate a continuous stream of data at a sufficiently high frequency that a
* there"s a good chance of racing channel cancellation.
*/
function handleStream(evt, filename) {
// Create some payload to send.
const encoder = new TextEncoder();
let strChunk =
"Static routes are the future of ServiceWorkers! So say we all!\n";
while (strChunk.length < 1024) {
strChunk += strChunk;
}
const dataChunk = encoder.encode(strChunk);
evt.waitUntil(new Promise(resolve => {
let body = new ReadableStream({
start: controller => {
const closeStream = (why) => {
console.log("closing stream: " + JSON.stringify(why) + "\n");
clearInterval(intervalId);
resolve();
// In event of error, the controller will automatically have closed.
if (why.why != "canceled") {
try {
controller.close();
} catch(ex) {
// If we thought we should cancel but experienced a problem,
// that's a different kind of failure and we need to report it.
// (If we didn't catch the exception here, we'd end up erroneously
// in the tick() method's canceled handler.)
channel.postMessage({
what: filename,
why: "close-failure",
message: ex.message,
ticks: why.ticks
});
return;
}
}
// Post prior to performing any attempt to close...
channel.postMessage(why);
};
controller.enqueue(dataChunk);
let count = 0;
let intervalId;
function tick() {
try {
// bound worst-case behavior.
if (count++ > MAX_TICK_COUNT) {
closeStream({
what: filename, why: "timeout", message: "timeout", ticks: count
});
return;
}
controller.enqueue(dataChunk);
} catch(e) {
closeStream({
what: filename, why: "canceled", message: e.message, ticks: count
});
}
}
// Alternately, streams' pull mechanism could be used here, but this
// test doesn't so much want to saturate the stream as to make sure the
// data is at least flowing a little bit. (Also, the author had some
// concern about slowing down the test by overwhelming the event loop
// and concern that we might not have sufficent back-pressure plumbed
// through and an infinite pipe might make bad things happen.)
intervalId = setInterval(tick, TICK_INTERVAL);
tick();
},
});
evt.respondWith(new Response(body, {
headers: {
"Content-Disposition": `attachment; filename="${filename}"`,
"Content-Type": "application/octet-stream"
}
}));
}));
}
/**
* Use an .sjs to generate a similar stream of data to the above, passing the
* response through directly. Because we're handing off the response but also
* want to be able to report when cancellation occurs, we create a second,
* overlapping long-poll style fetch that will not finish resolving until the
* .sjs experiences closure of its socket and terminates the payload stream.
*/
function handlePassThrough(evt, filename) {
evt.waitUntil((async () => {
console.log("issuing monitor fetch request");
const response = await fetch("server-stream-download.sjs?monitor");
console.log("monitor headers received, awaiting body");
const data = await response.json();
console.log("passthrough monitor fetch completed, notifying.");
channel.postMessage({
what: filename,
why: data.why,
message: data.message
});
})());
evt.respondWith(fetch("server-stream-download.sjs").then(response => {
console.log("server-stream-download.sjs Response received, propagating");
return response;
}));
}
addEventListener("fetch", evt => {
console.log(`SW processing fetch of ${evt.request.url}`);
if (evt.request.url.indexOf("sw-stream-download") >= 0) {
return handleStream(evt, "sw-stream-download");
}
if (evt.request.url.indexOf("sw-passthrough-download") >= 0) {
return handlePassThrough(evt, "sw-passthrough-download");
}
})
addEventListener("message", evt => {
if (evt.data === "claim") {
evt.waitUntil(clients.claim());
}
});

Просмотреть файл

@ -37,21 +37,6 @@ public:
// Suspend()/Resume() functions.
virtual nsresult SuspendMessageDiversion() = 0;
virtual nsresult ResumeMessageDiversion() = 0;
// Cancel an ongoing diversion by using IPC to invoke Cancel() in the child.
// This is necessary because most of the channel's state machine is suspended
// during diversion, so an explicit action must be taken to interrupt the
// diversion process so cancellation can be fully processed.
//
// Historically, diversions were assumed to be shortlived, where it was merely
// a question of diverting some small amount of network traffic back to the
// parent. However, Service Worker child interception made it possible for
// the data to entirely be sourced from the child, which makes diversion
// potentially long-lived. Especially when large files are involved.
//
// This mechanism is expected to be removed when ServiceWorkers move from
// child intercept to parent intercept (in the short to medium term).
virtual nsresult CancelDiversion() = 0;
};
} // namespace net

Просмотреть файл

@ -737,15 +737,6 @@ FTPChannelParent::ResumeMessageDiversion()
return NS_OK;
}
nsresult
FTPChannelParent::CancelDiversion()
{
// Only HTTP channels can have child-process-sourced-data that's long-lived
// so this isn't currently relevant for FTP channels and there is nothing to
// do.
return NS_OK;
}
void
FTPChannelParent::DivertTo(nsIStreamListener *aListener)
{

Просмотреть файл

@ -54,8 +54,6 @@ public:
nsresult SuspendForDiversion() override;
nsresult SuspendMessageDiversion() override;
nsresult ResumeMessageDiversion() override;
nsresult CancelDiversion() override;
// Calls OnStartRequest for "DivertTo" listener, then notifies child channel
// that it should divert OnDataAvailable and OnStopRequest calls to this

Просмотреть файл

@ -615,6 +615,8 @@ HttpChannelChild::OnStartRequest(const nsresult& channelStatus,
DoOnStartRequest(this, mListenerContext);
}
namespace {
class SyntheticDiversionListener final : public nsIStreamListener
{
RefPtr<HttpChannelChild> mChannel;
@ -641,10 +643,7 @@ public:
OnStopRequest(nsIRequest* aRequest, nsISupports* aContext,
nsresult aStatus) override
{
if (mChannel->mIPCOpen) {
mChannel->SendDivertOnStopRequest(aStatus);
mChannel->SendDivertComplete();
}
mChannel->SendDivertOnStopRequest(aStatus);
return NS_OK;
}
@ -653,11 +652,6 @@ public:
nsIInputStream* aInputStream, uint64_t aOffset,
uint32_t aCount) override
{
if (!mChannel->mIPCOpen) {
aRequest->Cancel(NS_ERROR_ABORT);
return NS_ERROR_ABORT;
}
nsAutoCString data;
nsresult rv = NS_ConsumeStream(aInputStream, aCount, data);
if (NS_WARN_IF(NS_FAILED(rv))) {
@ -674,6 +668,8 @@ public:
NS_IMPL_ISUPPORTS(SyntheticDiversionListener, nsIStreamListener);
} // anonymous namespace
void
HttpChannelChild::DoOnStartRequest(nsIRequest* aRequest, nsISupports* aContext)
{
@ -1886,11 +1882,7 @@ HttpChannelChild::FlushedForDiversion()
// received from the parent channel, nor dequeued from the ChannelEventQueue.
mFlushedForDiversion = true;
// If we're synthesized, it's up to the SyntheticDiversionListener to invoke
// SendDivertComplete after it has sent the DivertOnStopRequestMessage.
if (!mSynthesizedResponse) {
SendDivertComplete();
}
SendDivertComplete();
}
void
@ -3875,21 +3867,6 @@ HttpChannelChild::RecvAttachStreamFilter(Endpoint<extensions::PStreamFilterParen
return IPC_OK();
}
mozilla::ipc::IPCResult
HttpChannelChild::RecvCancelDiversion()
{
MOZ_ASSERT(NS_IsMainThread());
// This method is a very special case for cancellation of a diverted
// intercepted channel. Normally we would go through the mEventQ in order to
// serialize event execution in the face of sync XHR and now background
// channels. However, similar to how CancelOnMainThread describes, Cancel()
// pre-empts everything. (And frankly, we want this stack frame on the stack
// if a crash happens.)
Cancel(NS_ERROR_ABORT);
return IPC_OK();
}
void
HttpChannelChild::ActorDestroy(ActorDestroyReason aWhy)
{

Просмотреть файл

@ -47,7 +47,6 @@ namespace net {
class HttpBackgroundChannelChild;
class InterceptedChannelContent;
class InterceptStreamListener;
class SyntheticDiversionListener;
class HttpChannelChild final : public PHttpChannelChild
, public HttpBaseChannel
@ -169,8 +168,6 @@ protected:
mozilla::ipc::IPCResult RecvAttachStreamFilter(Endpoint<extensions::PStreamFilterParent>&& aEndpoint) override;
mozilla::ipc::IPCResult RecvCancelDiversion() override;
virtual void ActorDestroy(ActorDestroyReason aWhy) override;
MOZ_MUST_USE bool
@ -475,7 +472,6 @@ private:
friend class HttpAsyncAborter<HttpChannelChild>;
friend class InterceptStreamListener;
friend class InterceptedChannelContent;
friend class SyntheticDiversionListener;
friend class HttpBackgroundChannelChild;
friend class NeckoTargetChannelEvent<HttpChannelChild>;
};

Просмотреть файл

@ -2011,16 +2011,6 @@ HttpChannelParent::ResumeMessageDiversion()
return NS_OK;
}
nsresult
HttpChannelParent::CancelDiversion()
{
LOG(("HttpChannelParent::CancelDiversion [this=%p]", this));
if (!mIPCClosed) {
Unused << SendCancelDiversion();
}
return NS_OK;
}
/* private, supporting function for ADivertableParentChannel */
nsresult
HttpChannelParent::ResumeForDiversion()

Просмотреть файл

@ -83,7 +83,6 @@ public:
MOZ_MUST_USE nsresult SuspendForDiversion() override;
MOZ_MUST_USE nsresult SuspendMessageDiversion() override;
MOZ_MUST_USE nsresult ResumeMessageDiversion() override;
MOZ_MUST_USE nsresult CancelDiversion() override;
// Calls OnStartRequest for "DivertTo" listener, then notifies child channel
// that it should divert OnDataAvailable and OnStopRequest calls to this

Просмотреть файл

@ -32,7 +32,6 @@ InterceptedHttpChannel::InterceptedHttpChannel(PRTime aCreationTime,
, mResumeStartPos(0)
, mSynthesizedOrReset(Invalid)
, mCallingStatusAndProgress(false)
, mDiverting(false)
{
// Pre-set the creation and AsyncOpen times based on the original channel
// we are intercepting. We don't want our extra internal redirect to mask
@ -501,15 +500,6 @@ InterceptedHttpChannel::Cancel(nsresult aStatus)
mStatus = aStatus;
}
// Everything is suspended during diversion until it completes. Since the
// intercepted channel could be a long-running stream, we need to request that
// cancellation be triggered in the child, completing the diversion and
// allowing cancellation to run to completion.
if (mDiverting) {
Unused << mParentChannel->CancelDiversion();
// (We want the pump to be canceled as well, so don't directly return.)
}
if (mPump) {
return mPump->Cancel(mStatus);
}
@ -1123,7 +1113,6 @@ InterceptedHttpChannel::MessageDiversionStarted(ADivertableParentChannel* aParen
{
MOZ_ASSERT(!mParentChannel);
mParentChannel = aParentChannel;
mDiverting = true;
uint32_t suspendCount = mSuspendCount;
while(suspendCount--) {
mParentChannel->SuspendMessageDiversion();
@ -1136,7 +1125,6 @@ InterceptedHttpChannel::MessageDiversionStop()
{
MOZ_ASSERT(mParentChannel);
mParentChannel = nullptr;
mDiverting = false;
return NS_OK;
}

Просмотреть файл

@ -94,7 +94,6 @@ private:
Reset
} mSynthesizedOrReset;
Atomic<bool> mCallingStatusAndProgress;
bool mDiverting;
InterceptedHttpChannel(PRTime aCreationTime,
const TimeStamp& aCreationTimestamp,

Просмотреть файл

@ -150,9 +150,6 @@ child:
async AttachStreamFilter(Endpoint<PStreamFilterParent> aEndpoint);
// See ADivertableParentChannel::CancelDiversion
async CancelDiversion();
both:
// After receiving this message, the parent also calls
// SendFinishInterceptedRedirect, and makes sure not to send any more messages