Skip to content

Streams & SSE

PAM can send a response while your code is still producing it. Instead of building a 200 MB CSV in a string, you yield it row by row; instead of polling, a browser keeps one connection open and receives Server-Sent Events. Every chunk passes through a bounded queue in Rust, so a slow client makes your producer wait rather than making the worker’s memory grow.

The same ideas apply to raw sockets: the Pam\Stream classes read and write in bounded chunks and suspend the request Fiber while the network catches up.

Response::stream() sends every item of an iterable as a chunk. Generators are the natural fit:

index.php
<?php
declare(strict_types=1);
use Pam\Http\Request;
use Pam\Http\Response;
use Pam\Http\Server;
use function Pam\Async\delay;
Server::create(static function (Request $request, Response $response): Response {
return $response->stream((static function (): Generator {
foreach (['one', 'two', 'three'] as $word) {
yield $word . "\n";
delay(0.05);
}
})(), 'text/plain; charset=utf-8');
})->listen(3000, '127.0.0.1');
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
transfer-encoding: chunked
one
two
three

The signature is stream(iterable $chunks, string $contentType = 'application/octet-stream'): Response. Chunks are cast to strings (null becomes an empty string, booleans become true/false). Set the status and any other headers before calling stream(): the headers are sent with the first chunk.

Existing code that echoes (templates, CSV writers, fpassthru()) can be streamed with streamOutput(). Everything the callable prints is captured by an output buffer and sent in chunks of $chunkBytes (64 KiB by default):

return $response
->header('content-type', 'text/csv')
->header('content-disposition', 'attachment; filename="users.csv"')
->streamOutput(static function () use ($users): void {
echo "id,name\n";
foreach ($users->cursor() as $user) {
echo "{$user->id},{$user->name}\n";
}
});

writeChunk(string $chunk) sends one chunk immediately. stream(), sse() and streamOutput() are built on it; use it when your code is already a loop rather than a generator.

Response::sse() turns an iterable of events into a text/event-stream. Strings are sent as-is; anything else is JSON-encoded. Each line of the payload becomes a data: line:

use function Pam\Async\delay;
return $response->sse((static function (): Generator {
for ($sequence = 1; $sequence <= 3; $sequence++) {
yield ['sequence' => $sequence];
delay(1.0);
}
})());
HTTP/1.1 200 OK
connection: keep-alive
cache-control: no-cache
content-type: text/event-stream; charset=utf-8
transfer-encoding: chunked
data: {"sequence":1}
data: {"sequence":2}
data: {"sequence":3}

On the client, the standard EventSource API receives each object:

public/app.js
const source = new EventSource('/events');
source.onmessage = (event) => console.log(JSON.parse(event.data));

An SSE endpoint holds its request Fiber open for as long as the client is connected. Keep a few things in mind:

  • The request deadline still applies. A stream that should outlive requestTimeoutMs (30 seconds by default) needs a larger value in your listen() options, or should end and let EventSource reconnect.
  • When the client disconnects, PAM cancels the Fiber and runs your finally blocks. Put cleanup (unsubscribe, release a lock) there.
  • Each open stream counts against maxConcurrentRequests. For thousands of mostly idle subscribers, WebSockets with rooms are usually a better fit.

Chunks travel from PHP to the client through a bounded queue. When the queue is full because the client reads slowly, the next yield/writeChunk() suspends your Fiber until there is room, so a generator never runs ahead of the network.

These listen() options control it (defaults shown):

Option Default Effect
responseStreamQueueCapacity 16 Chunks buffered between PHP and the socket
maxResponseBytes 268435456 (256 MiB) Total body limit for one response
maxResponseChunkBytes 1048576 (1 MiB) Largest single chunk operation

If a stream exceeds maxResponseBytes after its headers were sent, PAM closes the connection with an error so the client cannot mistake a truncated body for a complete one. HTTP/1.1, HTTP/2 and HTTP/3 all receive chunks incrementally.

$server->listen(3000, '127.0.0.1', [
'responseStreamQueueCapacity' => 32,
'maxResponseBytes' => 512 * 1024 * 1024,
]);

For sockets, pipes and files, the Pam\Stream namespace wraps PHP stream resources with a bounded, suspending API:

Class Purpose
Readable read(?int $length = null, ?float $timeout = null), chunks(?float $timeout = null), eof(), close()
Writable write(string $data, ?float $timeout = null): int, close()
Duplex Both, over one resource (a socket)
Streams Factories: readable(), writable(), connect(), pipe()

Each object has a highWaterMark (64 KiB by default, between 1 byte and 16 MiB): reads return at most that many bytes and writes are split into chunks of that size. Wrapping a resource switches it to non-blocking mode.

use Pam\Stream\Streams;
$socket = Streams::connect('127.0.0.1:9000', timeout: 2.0);
$socket->write("PING\n");
$reply = $socket->read(timeout: 2.0);
$socket->close();

Streams::connect(string $address, float $timeout = 10.0, bool $tls = false, int $highWaterMark = 65536) returns a Duplex. Pass tls: true for a TLS connection.

use Pam\Stream\Streams;
$readable = Streams::readable(fopen('/var/log/app.log', 'rb'));
foreach ($readable->chunks(timeout: 5.0) as $chunk) {
$response->writeChunk($chunk);
}

Streams::pipe($source, $destination, ?float $timeout = null): int copies a readable stream into a writable one chunk by chunk and returns the number of bytes written:

use Pam\Stream\Streams;
$copied = Streams::pipe(
Streams::readable(fopen('php://stdin', 'rb')),
Streams::writable(fopen('/tmp/upload.bin', 'wb')),
);
  • WebSockets: bidirectional, room-based messaging.
  • Responses: status codes, headers and cookies.
  • Async I/O: the socket functions these classes use.