WICG / pending-beacon

A better beaconing API
Other
43 stars 8 forks source link

Atomic replacement of existing request #84

Open fergald opened 11 months ago

fergald commented 11 months ago

Problem

Our current design allows a request to be cancelled. It was argued that there was no need for

as these could both be implemented in JS. While it's true that they can be implemented, they are vulnerable to data loss if a crash occurs. E.g. the sample code to update a beacon is

let beaconResult = null;
let beaconAbort = null;

function updateBeacon(data) {
  const pending = !beaconResult || !beaconResult.sent;
  if (pending && beaconAbort) {
    beaconAbort.abort();
  }

  createBeacon(data);
}

function createBeacon(data) {
  if (beaconResult && beaconResult.sent) {
    // Avoid creating duplicated beacon if the previous one is still pending.
    return;
  }

  beaconAbort = new AbortController();
  beaconResult = fetchLater({
    url: data
    signal: beaconAbort.signal
  });
}

If the process running JS dies between abort and createBeacon then it's possible that the old request will be aborted but no new request will be created.

A similar problem exists when devs abort a fetchLater and do an immediate fetch. If a death occurs, between these then it's possible that neither request will actually be sent.

Severity

Using Chrome (and I believe WebKit) terminology, JS is running in the renderer, fetchLater requests are managed by the browser.

The window in which the death must occur is varies by case

The immediate send case may be considerably longer but given that deaths are fairly rare (if JS is running then we are likely not in the background etc).

fergald commented 10 months ago

I'm just going to leave this here for the record, I want to show that the current API could easily be extended to give atomic operations. These are just straw-person APIs

replaces option

Add a replaces option to the fetch options. The replaces option gives a handle to an existing pending fetch later that should be cancelled in favour of the new request. It would be accepted by fetchLater and fetch.

So you can do something like

let laterHandle = fetchLater({
    url: data
});
...
// Now we want to update the fetch. This cancels the old one and queues a new one
// atomically.
laterHandle = fetchlater({
    url: newData,
    replaces: laterHandle,
});

// Now we want to do an immediate send of a pending fetch. This cancels the old one and immediately starts a new one
// atomically.
let fetchHandle = fetch({
    replaces: laterHandle,
});

Maybe when switching to fetch, it keeps all of the attributes of the old fetchLater including it's keep-alive nature. There is some question over whether it would be allowed to set new options in that call. The point is that making these operations atomic does not require a breaking change in the API.