Always validate the state of network resources (sockets, streams, connections) before performing operations to prevent errors, resource leaks, and ensure proper connection reuse.
Always validate the state of network resources (sockets, streams, connections) before performing operations to prevent errors, resource leaks, and ensure proper connection reuse.
Network resources have complex lifecycles and can be in various states (pending, active, closed, locked, disturbed). Performing operations on resources in invalid states can lead to connection failures, resource leaks, or security issues.
Key validations to perform:
Example implementation:
kj::Own<kj::AsyncIoStream> Socket::takeConnectionStream(jsg::Lock& js) {
// Validate no pending operations before detaching
writable->detach(js); // Will throw if pending writes
readable->detach(js); // Will throw if pending reads
// Update state to prevent further use
upgraded = true;
closedResolver.resolve(js);
return connectionStream->addWrappedRef();
}
// Before creating HTTP client from socket
JSG_ASSERT(!socket->isLocked(), Error, "Socket streams are locked");
JSG_ASSERT(!socket->isClosed(), Error, "Socket is already closed");
This validation prevents runtime errors, ensures proper resource cleanup, and maintains connection reuse capabilities essential for network performance.
Enter the URL of a public GitHub repository