Skip to content
9 changes: 9 additions & 0 deletions packages/sync/src/providers/http-polling/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,15 @@ export const MAX_UPDATE_SIZE_IN_BYTES =
// WP_HTTP_Polling_Sync_Server::MAX_ROOMS_PER_REQUEST.
export const MAX_ROOMS_PER_REQUEST = 50;

// Corresponds with server-side
// WP_HTTP_Polling_Sync_Server::MAX_BODY_SIZE, with 1 MiB of headroom for
// serialization details and future metadata.
export const MAX_SYNC_REQUEST_BODY_SIZE_IN_BYTES = 15 * 1024 * 1024;

// Keep a single maximum-sized encoded update plus room metadata sendable if a
// request-body-too-large response forces the client to shrink its retry budget.
export const MIN_SYNC_REQUEST_BODY_SIZE_LIMIT_IN_BYTES = 2 * 1024 * 1024;

export const POLLING_INTERVAL_IN_MS = applyFilters(
'sync.pollingManager.pollingInterval',
4000 // 4 seconds
Expand Down
165 changes: 151 additions & 14 deletions packages/sync/src/providers/http-polling/polling-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import {
DEFAULT_CLIENT_LIMIT_PER_ROOM,
ERROR_RETRY_DELAYS_SOLO_MS,
ERROR_RETRY_DELAYS_WITH_COLLABORATORS_MS,
MAX_SYNC_REQUEST_BODY_SIZE_IN_BYTES,
MIN_SYNC_REQUEST_BODY_SIZE_LIMIT_IN_BYTES,
MAX_ROOMS_PER_REQUEST,
MAX_UPDATE_SIZE_IN_BYTES,
POLLING_INTERVAL_IN_MS,
Expand Down Expand Up @@ -111,6 +113,21 @@ function isForbiddenError( error: unknown ): error is WPRestError {
return ( error as WPRestError | undefined )?.data?.status === 403;
}

/**
* Check if an error is the sync server's deterministic request-body-size
* rejection. The server rejects this before the sync handler stores updates, so
* the client can safely retry the exact same updates in smaller request bodies.
*
* @param error The caught error to inspect.
*/
function isRequestBodyTooLargeError( error: unknown ): error is WPRestError {
return (
( error as WPRestError | undefined )?.data?.status === 413 &&
( error as WPRestError | undefined )?.code ===
'rest_sync_body_too_large'
);
}

/**
* Try to identify which room caused a forbidden error by checking if any
* room name from the request appears in the error message. The WordPress
Expand Down Expand Up @@ -440,6 +457,7 @@ let isPolling = false;
let isUnloadPending = false;
let pollInterval = POLLING_INTERVAL_IN_MS;
let pollingTimeoutId: ReturnType< typeof setTimeout > | null = null;
let syncRequestBodySizeLimit = MAX_SYNC_REQUEST_BODY_SIZE_IN_BYTES;

// When more rooms are registered than the server allows per request
// (MAX_ROOMS_PER_REQUEST), the primary room is sent every poll and the
Expand Down Expand Up @@ -561,6 +579,105 @@ function selectRoomsForRequest(): RoomState[] {
return overflowSlice;
}

const textEncoder = new TextEncoder();

function getJsonByteLength( value: unknown ): number {
return textEncoder.encode( JSON.stringify( value ) ).byteLength;
}

function createPayloadRoom(
state: RoomState,
updates: SyncUpdate[] = []
): SyncPayload[ 'rooms' ][ number ] {
return {
after: state.endCursor ?? 0,
awareness: state.localAwarenessState,
client_id: state.clientId,
room: state.room,
updates,
};
}

function getUpdatePayloadSizeDelta(
existingUpdateCount: number,
update: SyncUpdate
): number {
const commaSize = existingUpdateCount === 0 ? 0 : 1;
return commaSize + getJsonByteLength( update );
}

function buildPayloadForRequest( selectedRoomStates: RoomState[] ): {
payload: SyncPayload;
roomsInRequest: RoomState[];
} {
const payload: SyncPayload = { rooms: [] };
const roomsInRequest: RoomState[] = [];

for ( const state of selectedRoomStates ) {
const room = createPayloadRoom( state );
const candidate = { rooms: [ ...payload.rooms, room ] };
if (
payload.rooms.length > 0 &&
getJsonByteLength( candidate ) > syncRequestBodySizeLimit
) {
break;
}

payload.rooms.push( room );
roomsInRequest.push( state );
}

const pendingUpdates = roomsInRequest.map( ( state ) =>
state.updateQueue.peek()
);
const sentUpdateCounts = roomsInRequest.map( () => 0 );

let payloadSize = getJsonByteLength( payload );
let addedUpdate = true;

while ( addedUpdate ) {
addedUpdate = false;

for ( let i = 0; i < roomsInRequest.length; i++ ) {
const update = pendingUpdates[ i ][ sentUpdateCounts[ i ] ];

if ( ! update ) {
continue;
}

const sizeDelta = getUpdatePayloadSizeDelta(
sentUpdateCounts[ i ],
update
);
if ( payloadSize + sizeDelta > syncRequestBodySizeLimit ) {
continue;
}

sentUpdateCounts[ i ]++;
payloadSize += sizeDelta;
addedUpdate = true;
}
}

for ( let i = 0; i < roomsInRequest.length; i++ ) {
payload.rooms[ i ].updates = roomsInRequest[ i ].updateQueue.take(
sentUpdateCounts[ i ]
);
}

return { payload, roomsInRequest };
}

function restoreExactUpdates( payload: SyncPayload ): void {
for ( const room of payload.rooms ) {
if ( ! roomStates.has( room.room ) || room.updates.length === 0 ) {
continue;
}

roomStates.get( room.room )!.updateQueue.restoreExact( room.updates );
}
}

function poll(): void {
isPolling = true;
pollingTimeoutId = null;
Expand All @@ -576,20 +693,12 @@ function poll(): void {
// cancels a beforeunload dialog.
isUnloadPending = false;

// Create a payload with all queued updates. We include rooms even if they
// have no updates to ensure we receive any incoming updates. Note that we
// withhold our own updates until we detect another collaborator using the
// queue's pause / resume mechanism.
const roomsInRequest = selectRoomsForRequest();
const payload: SyncPayload = {
rooms: roomsInRequest.map( ( state ) => ( {
after: state.endCursor ?? 0,
awareness: state.localAwarenessState,
client_id: state.clientId,
room: state.room,
updates: state.updateQueue.get(),
} ) ),
};
// Create a payload with queued updates. We include rooms even if they
// have no updates to ensure we receive any incoming updates, while keeping
// the serialized body below the server's aggregate request-size limit.
const { payload, roomsInRequest } = buildPayloadForRequest(
selectRoomsForRequest()
);

// Emit 'connecting' status only for rooms in this request. Rooms
// rotated out of this poll keep their prior status.
Expand All @@ -603,6 +712,7 @@ function poll(): void {
// Emit 'connected' status.
consecutiveFailures = 0;
isManualRetry = false;
syncRequestBodySizeLimit = MAX_SYNC_REQUEST_BODY_SIZE_IN_BYTES;
roomsInRequest.forEach( ( state ) => {
// Skip rooms unregistered during the await (e.g. the
// size-limit handler in onDocUpdate). Their terminal
Expand Down Expand Up @@ -719,6 +829,32 @@ function poll(): void {
isPolling = false;
return;
}
} else if ( isRequestBodyTooLargeError( error ) ) {
syncRequestBodySizeLimit = Math.max(
MIN_SYNC_REQUEST_BODY_SIZE_LIMIT_IN_BYTES,
Math.floor( syncRequestBodySizeLimit / 2 )
);
pollInterval = hasCollaborators
? ERROR_RETRY_DELAYS_WITH_COLLABORATORS_MS[ 0 ]
: ERROR_RETRY_DELAYS_SOLO_MS[ 0 ];
restoreExactUpdates( payload );

for ( const room of payload.rooms ) {
if ( ! roomStates.has( room.room ) ) {
continue;
}

roomStates.get( room.room )!.log(
'Sync request body too large, retrying with smaller batches',
{
error,
nextPoll: pollInterval,
syncRequestBodySizeLimit,
},
'error',
true // force
);
}
} else {
// Use the explicit retry delay schedule for backoff.
consecutiveFailures++;
Expand Down Expand Up @@ -967,6 +1103,7 @@ function unregisterRoom(
hasCheckedConnectionLimit = false;
consecutiveFailures = 0;
roomOverflowOffset = 0;
syncRequestBodySizeLimit = MAX_SYNC_REQUEST_BODY_SIZE_IN_BYTES;
}
}

Expand Down
Loading
Loading