Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/workerd/api/tests/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -1290,6 +1290,19 @@ wd_test(
data = ["websocket-allow-half-open-test.js"],
)

# The limit is off while its kill switch autogate is on, so this has no @all-autogates variant.
# websocket-accept-limit-killswitch-test below covers the kill switch being on.
wd_test(
src = "websocket-accept-limit-test.wd-test",
data = ["websocket-accept-limit-test.js"],
generate_all_autogates_variant = False,
Comment thread
rinkle-cf marked this conversation as resolved.
Resolved
)

wd_test(
src = "websocket-accept-limit-killswitch-test.wd-test",
data = ["websocket-accept-limit-killswitch-test.js"],
)

wd_test(
src = "websocket-constructor-test.wd-test",
args = ["--experimental"],
Expand Down
29 changes: 29 additions & 0 deletions src/workerd/api/tests/websocket-accept-limit-killswitch-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright (c) 2026 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
// https://opensource.org/licenses/Apache-2.0

import { DurableObject } from 'cloudflare:workers';

const LIMIT = 32768;

export class WebSocketLimitObject extends DurableObject {
// Every pair the test creates, held so that none is garbage-collected.
#pairs = [];

// With the limit's kill switch on, this actor can accept more WebSockets than the limit.
run() {
for (let i = 0; i < LIMIT / 2 + 1; i++) {
const [client, server] = Object.values(new WebSocketPair());
client.accept();
server.accept();
this.#pairs.push({ client, server });
}
}
}

export const acceptPastLimit = {
async test(ctrl, env) {
const stub = env.ns.get(env.ns.idFromName('accept-past-limit'));
await stub.run();
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using Workerd = import "/workerd/workerd.capnp";

const unitTests :Workerd.Config = (
services = [
(name = "websocket-accept-limit-killswitch-test", worker = .testWorker),
],
autogates = ["workerd-autogate-durable-object-websocket-limit-killswitch"],
);

const testWorker :Workerd.Worker = (
compatibilityFlags = ["nodejs_compat", "rpc"],

modules = [
(name = "worker", esModule = embed "websocket-accept-limit-killswitch-test.js"),
],

durableObjectNamespaces = [
(className = "WebSocketLimitObject", uniqueKey = "websocket-accept-limit-killswitch-test-object"),
],

durableObjectStorage = (inMemory = void),

bindings = [
(name = "ns", durableObjectNamespace = "WebSocketLimitObject"),
],
);
142 changes: 142 additions & 0 deletions src/workerd/api/tests/websocket-accept-limit-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
// Copyright (c) 2026 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
// https://opensource.org/licenses/Apache-2.0

import { DurableObject } from 'cloudflare:workers';
import assert from 'node:assert';

const LIMIT = 32768;
const LIMIT_MESSAGE = `only ${LIMIT} non-hibernatable websockets can be open on a single Durable Object instance`;

export class WebSocketLimitObject extends DurableObject {
// Every WebSocket the test creates is held here, so that none is garbage-collected. A collected
// WebSocket, or the collected peer of an accepted one, disconnects and gives its slot back.
#connections = []; // Opened with `new WebSocket(url)`.
#pairs = []; // Created with `new WebSocketPair()`, as { client, server }.

// Opens a WebSocket with `new WebSocket(url)`, through the global outbound below, and keeps it
// even if it fails, so that only the runtime can close its connection. Resolves to the WebSocket
// once it opens, or rejects with the error it reports if the connection fails.
#connect() {
const ws = new WebSocket('ws://example.com/');
this.#connections.push(ws);
return new Promise((resolve, reject) => {
ws.addEventListener('open', () => resolve(ws));
ws.addEventListener('error', (event) => reject(event.error));
});
}

// Creates a WebSocketPair, accepting neither end.
#pair() {
const [client, server] = Object.values(new WebSocketPair());
const pair = { client, server };
this.#pairs.push(pair);
return pair;
}

// Creates a WebSocketPair and accepts both ends, which uses two slots.
#acceptPair() {
const pair = this.#pair();
pair.client.accept();
pair.server.accept();
return pair;
}

async run() {
// Fill the limit with two WebSockets opened with `new WebSocket(url)` and LIMIT / 2 - 1
// accepted pairs.
const firstOutgoingWebSocket = await this.#connect();
await this.#connect();
for (let i = 0; i < LIMIT / 2 - 2; i++) {
this.#acceptPair();
}
const lastConnectedPair = this.#acceptPair();

const extra = this.#pair();
assert.throws(() => extra.server.accept(), { message: LIMIT_MESSAGE });

// Hibernatable WebSockets have their own limit, so this actor can still accept one.
this.ctx.acceptWebSocket(this.#pair().server);

// Closing a pair frees its two slots. Each end gives its slot back once its outgoing close
// frame has been sent, which for the client can be after the server's close event. Opening
// a connection takes a round trip through the global outbound, by which time both have.
const serverClosed = new Promise((resolve) => {
lastConnectedPair.server.addEventListener('close', resolve);
});
lastConnectedPair.client.addEventListener('close', () =>
lastConnectedPair.client.close()
);
lastConnectedPair.server.close();
await serverClosed;
await this.#connect();
await this.#connect();

// Now full again: a connection is rejected once it opens, and is closed rather than kept, even
// when its 'error' listener throws.
const rejected = new WebSocket('ws://example.com/');
this.#connections.push(rejected);
const rejection = await new Promise((resolve) => {
rejected.addEventListener('error', (event) => {
resolve(event.error);
throw new Error('error listener failure');
});
});
assert.strictEqual(rejection.message, LIMIT_MESSAGE);
await this.env.server
.get(this.env.server.idFromName('server'))
.waitForDisconnect();
assert.throws(() => extra.server.accept(), { message: LIMIT_MESSAGE });

// A WebSocket whose message listener throws is torn down while its JS object is still held,
// and gives back exactly its own slot. Its peer is in the server object, so it doesn't count.
const failed = new Promise((resolve) => {
firstOutgoingWebSocket.addEventListener('error', resolve);
});
firstOutgoingWebSocket.addEventListener('message', () => {
throw new Error('message listener failure');
});
firstOutgoingWebSocket.send('ping');
const event = await failed;
assert.strictEqual(event.error.message, 'message listener failure');
assert.doesNotThrow(() => this.#pair().server.accept());
assert.throws(() => extra.server.accept(), { message: LIMIT_MESSAGE });
}
}

// The remote end of every `new WebSocket(url)` connection the test opens, which echoes back each
// message it receives. It is a separate Durable Object, so its WebSockets count toward its own
// limit, not the one under test.
export class WebSocketServerObject extends DurableObject {
// The server ends, held so that none is garbage-collected, which would disconnect its client.
#open = [];
#disconnected = Promise.withResolvers();

fetch() {
const [client, server] = Object.values(new WebSocketPair());
this.#open.push(server);
server.accept();
server.addEventListener('message', (event) => server.send(event.data));
server.addEventListener('close', () => this.#disconnected.resolve());
return new Response(null, { status: 101, webSocket: client });
}

// Resolves once the remote end of any connection has gone away.
async waitForDisconnect() {
await this.#disconnected.promise;
}
}

// The global outbound, which passes every request to the server object.
export const webSocketServer = {
fetch(request, env) {
return env.server.get(env.server.idFromName('server')).fetch(request);
},
};

export const acceptLimit = {
async test(ctrl, env) {
const stub = env.ns.get(env.ns.idFromName('accept-limit'));
await stub.run();
},
};
29 changes: 29 additions & 0 deletions src/workerd/api/tests/websocket-accept-limit-test.wd-test
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using Workerd = import "/workerd/workerd.capnp";

const unitTests :Workerd.Config = (
services = [
(name = "websocket-accept-limit-test", worker = .testWorker),
],
);

const testWorker :Workerd.Worker = (
compatibilityFlags = ["nodejs_compat", "rpc"],

modules = [
(name = "worker", esModule = embed "websocket-accept-limit-test.js"),
],

durableObjectNamespaces = [
(className = "WebSocketLimitObject", uniqueKey = "websocket-accept-limit-test-object"),
(className = "WebSocketServerObject", uniqueKey = "websocket-accept-limit-test-server"),
],

durableObjectStorage = (inMemory = void),

globalOutbound = (name = "websocket-accept-limit-test", entrypoint = "webSocketServer"),

bindings = [
(name = "ns", durableObjectNamespace = "WebSocketLimitObject"),
(name = "server", durableObjectNamespace = "WebSocketServerObject"),
],
);
50 changes: 47 additions & 3 deletions src/workerd/api/web-socket.c++
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@
// commented-out helpers are also waiting on that.
//
// #include "hibernatable-adapter.h"
//
// #include <workerd/util/autogate.h>
#include <workerd/util/autogate.h>
#include <workerd/util/sentry.h>

#include <kj/compat/url.h>
Expand Down Expand Up @@ -281,6 +280,35 @@ void WebSocket::visitForMemoryInfo(jsg::MemoryTracker& tracker) const {
// LegacyWebSocketAdapter — operational implementation.
// =============================================================================

// The most non-hibernatable WebSockets a single Durable Object instance can have open at once,
// whether accepted with accept() or opened with `new WebSocket(url)`. Enabling the
// DURABLE_OBJECT_WEBSOCKET_LIMIT_KILLSWITCH autogate removes this limit. Hibernatable WebSockets
// have their own limit of the same size (LegacyHibernationManagerImpl::ACTIVE_CONNECTION_LIMIT) and
// don't count toward this one.
static constexpr uint32_t MAX_NON_HIBERNATABLE_WEBSOCKETS_PER_ACTOR = 1024 * 32;

namespace {

// Throws if the current Durable Object already has the most non-hibernatable WebSockets it can.
// Otherwise returns the count a newly accepted WebSocket should be charged to, or none if the limit
// doesn't apply (outside Durable Objects, or while its kill switch is on).
kj::Maybe<kj::Rc<NonHibernatableWebSocketCount>> checkNonHibernatableWebSocketLimit(
IoContext& context) {
if (util::Autogate::isEnabled(util::AutogateKey::DURABLE_OBJECT_WEBSOCKET_LIMIT_KILLSWITCH)) {
return kj::none;
}
KJ_IF_SOME(actor, context.getActor()) {
auto count = actor.getNonHibernatableWebSocketCount();
JSG_REQUIRE(count->count < MAX_NON_HIBERNATABLE_WEBSOCKETS_PER_ACTOR, Error, "only ",
MAX_NON_HIBERNATABLE_WEBSOCKETS_PER_ACTOR,
" non-hibernatable websockets can be open on a single Durable Object instance");
return kj::mv(count);
}
return kj::none;
}

} // namespace

IoOwn<LegacyWebSocketAdapter::Native> LegacyWebSocketAdapter::initNative(IoContext& ioContext,
kj::Rc<kj::WebSocket> ws,
kj::Array<kj::String> tags,
Expand Down Expand Up @@ -368,6 +396,12 @@ void LegacyWebSocketAdapter::initConnection(jsg::Lock& js, kj::Promise<PackedWeb
pending.canceler.release();
}

// Check the limit before taking ownership of the connection, so that a rejected connection is
// closed before any listener runs. internalAccept() below checks it again, but by then this
// WebSocket holds the connection, and an 'error' listener that throws can stop reportError()
// from releasing it.
checkNonHibernatableWebSocketLimit(IoContext::current());

native.state.init<AwaitingAcceptanceOrCoupling>(
AwaitingAcceptanceOrCoupling{IoContext::current().addObject(kj::mv(packedSocket.ws))});

Expand Down Expand Up @@ -767,8 +801,15 @@ void LegacyWebSocketAdapter::accept(
void LegacyWebSocketAdapter::internalAccept(
jsg::Lock& js, kj::Maybe<kj::Rc<InputGate::CriticalSection>> cs) {
auto& native = *farNative;
auto& context = IoContext::current();
// Check the limit before changing state, so that a rejected WebSocket is left as it was.
auto acceptedCount = checkNonHibernatableWebSocketLimit(context);
auto nativeWs = kj::mv(KJ_ASSERT_NONNULL(native.state.tryGet<AwaitingAcceptanceOrCoupling>()).ws);
native.state.init<Accepted>(kj::mv(nativeWs), native, IoContext::current());
auto& accepted = native.state.init<Accepted>(kj::mv(nativeWs), native, context);
KJ_IF_SOME(count, acceptedCount) {
++count->count;
accepted.nonHibernatableWebSocketCount = kj::mv(count);
}
return startReadLoop(js, kj::mv(cs));
}

Expand Down Expand Up @@ -835,6 +876,9 @@ LegacyWebSocketAdapter::Accepted::~Accepted() noexcept(false) {
KJ_IF_SOME(a, actorMetrics) {
a.get()->webSocketClosed();
}
KJ_IF_SOME(count, nonHibernatableWebSocketCount) {
--count->count;
}
}

// Default max WebSocket message size limit. Note that kj-http's own default is 1MiB
Expand Down
7 changes: 6 additions & 1 deletion src/workerd/api/web-socket.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@

namespace workerd {
class ActorObserver;
}
struct NonHibernatableWebSocketCount;
} // namespace workerd

namespace workerd::api {

Expand Down Expand Up @@ -758,6 +759,10 @@ class LegacyWebSocketAdapter final: public WebSocketAdapter {

kj::Maybe<kj::Own<ActorObserver>> actorMetrics;

// Set when this WebSocket counts toward its actor's limit on non-hibernatable WebSockets. The
// destructor gives the count back.
kj::Maybe<kj::Rc<NonHibernatableWebSocketCount>> nonHibernatableWebSocketCount;

private:
// Cancels the operations started with wrapIo() when leaving the Accepted state.
kj::Canceler canceler;
Expand Down
7 changes: 7 additions & 0 deletions src/workerd/io/worker.c++
Original file line number Diff line number Diff line change
Expand Up @@ -3960,6 +3960,9 @@ struct Worker::Actor::Impl {

kj::Own<ActorObserver> metrics;

kj::Rc<NonHibernatableWebSocketCount> nonHibernatableWebSocketCount =
kj::rc<NonHibernatableWebSocketCount>();

// When a boolean, indicates whether a `transient` should exist. If true, it will be initialized
// on the first `ensureConstructed()`.
kj::OneOf<bool, jsg::JsRef<jsg::JsValue>> transient;
Expand Down Expand Up @@ -4750,6 +4753,10 @@ ActorObserver& Worker::Actor::getMetrics() {
return *impl->metrics;
}

kj::Rc<NonHibernatableWebSocketCount> Worker::Actor::getNonHibernatableWebSocketCount() {
return impl->nonHibernatableWebSocketCount.addRef();
}

kj::Own<Worker::Actor::WaitUntilTaskHandle> Worker::Actor::addedWaitUntilTask() {
KJ_IF_SOME(tracker, waitUntilTaskTracker) {
return tracker->registerTask();
Expand Down
Loading
Loading