From 429454ca0e3795aa4b9b3350af173a297ece2a5d Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Mon, 4 May 2026 11:18:22 +0530 Subject: [PATCH 01/20] added handlers --- app/realtime.php | 407 ++---------------- src/Appwrite/Realtime/Message/Dispatcher.php | 150 +++++++ .../Handlers/AuthenticationHandler.php | 120 ++++++ .../Realtime/Message/Handlers/PingHandler.php | 28 ++ .../Message/Handlers/PresenceHandler.php | 110 +++++ .../Message/Handlers/SubscribeHandler.php | 109 +++++ .../Message/Handlers/UnsubscribeHandler.php | 74 ++++ .../Validators/SubscribePayloadValidator.php | 56 +++ .../UnsubscribePayloadValidator.php | 47 ++ 9 files changed, 720 insertions(+), 381 deletions(-) create mode 100644 src/Appwrite/Realtime/Message/Dispatcher.php create mode 100644 src/Appwrite/Realtime/Message/Handlers/AuthenticationHandler.php create mode 100644 src/Appwrite/Realtime/Message/Handlers/PingHandler.php create mode 100644 src/Appwrite/Realtime/Message/Handlers/PresenceHandler.php create mode 100644 src/Appwrite/Realtime/Message/Handlers/SubscribeHandler.php create mode 100644 src/Appwrite/Realtime/Message/Handlers/UnsubscribeHandler.php create mode 100644 src/Appwrite/Realtime/Message/Validators/SubscribePayloadValidator.php create mode 100644 src/Appwrite/Realtime/Message/Validators/UnsubscribePayloadValidator.php diff --git a/app/realtime.php b/app/realtime.php index 17edb7bbbc..b7b48ccdd3 100644 --- a/app/realtime.php +++ b/app/realtime.php @@ -10,6 +10,12 @@ use Appwrite\Extend\Exception as AppwriteException; use Appwrite\Messaging\Adapter\Realtime; use Appwrite\Network\Validator\Origin; use Appwrite\PubSub\Adapter\Pool as PubSubPool; +use Appwrite\Realtime\Message\Dispatcher as MessageDispatcher; +use Appwrite\Realtime\Message\Handlers\AuthenticationHandler; +use Appwrite\Realtime\Message\Handlers\PingHandler; +use Appwrite\Realtime\Message\Handlers\PresenceHandler; +use Appwrite\Realtime\Message\Handlers\SubscribeHandler; +use Appwrite\Realtime\Message\Handlers\UnsubscribeHandler; use Appwrite\Usage\Context; use Appwrite\Utopia\Database\Documents\User; use Appwrite\Utopia\Request; @@ -22,9 +28,6 @@ use Swoole\Table; use Swoole\Timer; use Utopia\Abuse\Abuse; use Utopia\Abuse\Adapters\TimeLimit\Redis as TimeLimitRedis; -use Utopia\Auth\Hashes\Sha; -use Utopia\Auth\Proofs\Token; -use Utopia\Auth\Store; use Utopia\Cache\Adapter\Pool as CachePool; use Utopia\Cache\Adapter\Sharding; use Utopia\Cache\Cache; @@ -417,6 +420,13 @@ $container->set('queueForRealtime', function () { $realtime = getRealtime(); $presenceState = new PresenceState(); +$messageDispatcher = (new MessageDispatcher()) + ->register(new PingHandler()) + ->register(new AuthenticationHandler()) + ->register(new SubscribeHandler()) + ->register(new UnsubscribeHandler()) + ->register(new PresenceHandler()); + /** * Table for statistics across all workers. */ @@ -1108,15 +1118,12 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server, } }); -$server->onMessage(function (int $connection, string $message) use ($server, $realtime, $containerId, $register, $presenceState) { +$server->onMessage(function (int $connection, string $message) use ($server, $realtime, $containerId, $register, $presenceState, $messageDispatcher) { $project = null; $authorization = null; $projectId = $realtime->connections[$connection]['projectId'] ?? null; $rawSize = \strlen($message); $messageType = 'invalid'; - $subscriptionDelta = 0; - $subscriptionsRequested = 0; - $subscriptionsRemoved = 0; $outboundBytes = 0; $responseCode = 200; $success = false; @@ -1194,378 +1201,20 @@ $server->onMessage(function (int $connection, string $message) use ($server, $re throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Message type is not valid.'); } - // Ping does not require project context; other messages do (e.g. after unsubscribe during auth) - if (empty($projectId) && ($message['type'] ?? '') !== 'ping') { - throw new Exception(Exception::REALTIME_POLICY_VIOLATION, 'Missing project context. Reconnect to the project first.'); - } + $messageContainer = new Container(); + $messageContainer->set('connection', fn () => $connection); + $messageContainer->set('server', fn () => $server); + $messageContainer->set('realtime', fn () => $realtime); + $messageContainer->set('register', fn () => $register); + $messageContainer->set('response', fn () => $response); + $messageContainer->set('presenceState', fn () => $presenceState); + $messageContainer->set('database', fn () => $database); + $messageContainer->set('authorization', fn () => $authorization); + $messageContainer->set('project', fn () => $project); + $messageContainer->set('projectId', fn () => $projectId); - switch ($message['type']) { - case 'ping': - $pongPayloadJson = json_encode([ - 'type' => 'pong' - ]); + $messageDispatcher->dispatch($messageContainer, $message, $outboundBytes); - $server->send([$connection], $pongPayloadJson); - $outboundBytes += \strlen($pongPayloadJson); - - if ($project !== null && !$project->isEmpty()) { - $pongOutboundBytes = \strlen($pongPayloadJson); - - if ($pongOutboundBytes > 0) { - triggerStats([ - METRIC_REALTIME_OUTBOUND => $pongOutboundBytes, - ], $project->getId()); - } - } - - break; - case 'authentication': - if (!array_key_exists('session', $message['data'])) { - throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Payload is not valid.'); - } - - $store = new Store(); - - $store->decode($message['data']['session']); - - /** @var User $user */ - $user = $database->getDocument('users', $store->getProperty('id', '')); - - /** - * TODO: - * Moving forward, we should try to use our dependency injection container - * to inject the proof for token. - * This way we will have one source of truth for the proof for token. - */ - $proofForToken = new Token(); - $proofForToken->setHash(new Sha()); - - if ( - empty($user->getId()) // Check a document has been found in the DB - || !$user->sessionVerify($store->getProperty('secret', ''), $proofForToken) // Validate user has valid login token - ) { - // cookie not valid - throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Session is not valid.'); - } - - $roles = $user->getRoles($database->getAuthorization()); - - $authorization = $realtime->connections[$connection]['authorization'] ?? null; - $projectId = $realtime->connections[$connection]['projectId'] ?? null; - // Capture the pre-auth userId so we can rebind any account channels - // that were stored under it (e.g. guest who subscribed to `account` - // and now authenticates). unsubscribe() below clears the connection - // entry, so we must read it first. - $previousUserId = $realtime->connections[$connection]['userId'] ?? ''; - - $subscriptionsBefore = \count($realtime->getSubscriptionMetadata($connection)); - $meta = $realtime->getSubscriptionMetadata($connection); - - $realtime->unsubscribe($connection); - - if (!empty($projectId)) { - foreach ($meta as $subscriptionId => $subscription) { - $queries = Query::parseQueries($subscription['queries'] ?? []); - $channels = Realtime::rebindAccountChannels( - $subscription['channels'] ?? [], - $previousUserId, - $user->getId() - ); - - $realtime->subscribe( - $projectId, - $connection, - $subscriptionId, - $roles, - $channels, - $queries, - $user->getId() - ); - } - } - - if ($authorization !== null) { - $realtime->connections[$connection]['authorization'] = $authorization; - } - - $subscriptionsAfter = \count($realtime->getSubscriptionMetadata($connection)); - $subscriptionDelta = $subscriptionsAfter - $subscriptionsBefore; - if ($subscriptionDelta !== 0) { - $register->get('telemetry.workerSubscriptionCounter')->add($subscriptionDelta, $register->get('telemetry.workerAttributes')); - } - - $user = $response->output($user, Response::MODEL_ACCOUNT); - - $authResponsePayloadJson = json_encode([ - 'type' => 'response', - 'data' => [ - 'to' => 'authentication', - 'success' => true, - 'user' => $user - ] - ]); - - $server->send([$connection], $authResponsePayloadJson); - $outboundBytes += \strlen($authResponsePayloadJson); - - if ($project !== null && !$project->isEmpty()) { - $authOutboundBytes = \strlen($authResponsePayloadJson); - - if ($authOutboundBytes > 0) { - triggerStats([ - METRIC_REALTIME_OUTBOUND => $authOutboundBytes, - ], $project->getId()); - } - } - - break; - - case 'subscribe': - /** - * Message based upsertion of a subscription - * If subscriptionId is given then it will match subId of the connection and update the subscription with channels and queries - * If non-existing subid is given or not given a new subid will be generated - * Similar to what we have now -> two subscribe() block with same channels and queries still two different subscriptions - * - * structure of the payload -> array of maps - * 'data' : [subscriptionId:"" , channels:[] , queries:[]] - */ - if (!is_array($message['data']) || !array_is_list($message['data'])) { - throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Payload is not valid.'); - } - - $roles = $realtime->connections[$connection]['roles'] ?? [Role::guests()->toString()]; - $userId = $realtime->connections[$connection]['userId'] ?? ''; - - // bulk validation + parsing before subscribing - $parsedPayloads = []; - $subscriptionsBefore = \count($realtime->getSubscriptionMetadata($connection)); - foreach ($message['data'] as $payload) { - if (!\is_array($payload)) { - throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Each subscribe payload must be an object.'); - } - if (!array_key_exists('channels', $payload)) { - throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'channels is not present in payload.'); - } - if (!is_array($payload['channels']) || !array_is_list($payload['channels'])) { - throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'channels is not a valid array.'); - } - // registering the queries if not present and check in the same payload later on - if (!array_key_exists('queries', $payload)) { - $payload['queries'] = []; - } - if (!is_array($payload['queries']) || !array_is_list($payload['queries'])) { - throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'queries is not a valid array.'); - } - - $subscriptionId = \array_key_exists('subscriptionId', $payload) - ? $payload['subscriptionId'] - : ID::unique(); - - try { - $convertedQueries = Realtime::convertQueries($payload['queries']); - } catch (QueryException $e) { - throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Invalid query: ' . $e->getMessage()); - } - - $convertedChannels = \array_keys(Realtime::convertChannels($payload['channels'], $userId)); - - $parsedPayloads[] = [ - 'subscriptionId' => $subscriptionId, - 'channels' => $payload['channels'], - 'convertedChannels' => $convertedChannels, - 'queries' => $convertedQueries, - ]; - } - - foreach ($parsedPayloads as $parsedPayload) { - $subscriptionId = $parsedPayload['subscriptionId']; - $channels = $parsedPayload['convertedChannels']; - $queries = $parsedPayload['queries']; - $realtime->subscribe($projectId, $connection, $subscriptionId, $roles, $channels, $queries); - } - $subscriptionsAfter = \count($realtime->getSubscriptionMetadata($connection)); - $subscriptionDelta = $subscriptionsAfter - $subscriptionsBefore; - $subscriptionsRequested = \count($parsedPayloads); - if ($subscriptionDelta !== 0) { - $register->get('telemetry.workerSubscriptionCounter')->add($subscriptionDelta, $register->get('telemetry.workerAttributes')); - } - - $responsePayload = json_encode([ - 'type' => 'response', - 'data' => [ - 'to' => 'subscribe', - 'success' => true, - 'subscriptions' => \array_map(function (array $parsedPayload) { - return [ - 'subscriptionId' => $parsedPayload['subscriptionId'], - 'channels' => $parsedPayload['convertedChannels'], - 'queries' => \array_map(fn ($q) => $q->toString(), $parsedPayload['queries']), - ]; - }, $parsedPayloads), - ] - ]); - - $server->send([$connection], $responsePayload); - $outboundBytes += \strlen($responsePayload); - - if ($project !== null && !$project->isEmpty()) { - $subscribeOutboundBytes = \strlen($responsePayload); - - if ($subscribeOutboundBytes > 0) { - triggerStats([ - METRIC_REALTIME_OUTBOUND => $subscribeOutboundBytes, - ], $project->getId()); - } - } - - break; - - case 'unsubscribe': - if (!\is_array($message['data']) || !\array_is_list($message['data'])) { - throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Payload is not valid.'); - } - - $subscriptionsBefore = \count($realtime->getSubscriptionMetadata($connection)); - - // Validate every payload before executing any removal so an invalid entry - // later in the batch does not leave earlier entries half-applied on the server. - $validatedIds = []; - foreach ($message['data'] as $payload) { - if ( - !\is_array($payload) - || !\array_key_exists('subscriptionId', $payload) - || !\is_string($payload['subscriptionId']) - || $payload['subscriptionId'] === '' - ) { - throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Each unsubscribe payload must include a non-empty subscriptionId.'); - } - $validatedIds[] = $payload['subscriptionId']; - } - - $unsubscribeResults = []; - foreach ($validatedIds as $subscriptionId) { - $wasRemoved = $realtime->unsubscribeSubscription($connection, $subscriptionId); - $unsubscribeResults[] = [ - 'subscriptionId' => $subscriptionId, - 'removed' => $wasRemoved, - ]; - } - $subscriptionsAfter = \count($realtime->getSubscriptionMetadata($connection)); - $subscriptionDelta = $subscriptionsAfter - $subscriptionsBefore; - $subscriptionsRequested = \count($validatedIds); - $subscriptionsRemoved = \count(\array_filter($unsubscribeResults, fn (array $item) => $item['removed'])); - if ($subscriptionDelta !== 0) { - $register->get('telemetry.workerSubscriptionCounter')->add($subscriptionDelta, $register->get('telemetry.workerAttributes')); - } - - $unsubscribeResponsePayload = json_encode([ - 'type' => 'response', - 'data' => [ - 'to' => 'unsubscribe', - 'success' => true, - 'subscriptions' => $unsubscribeResults, - ], - ]); - - $server->send([$connection], $unsubscribeResponsePayload); - $outboundBytes += \strlen($unsubscribeResponsePayload); - - if ($project !== null && !$project->isEmpty()) { - $unsubscribeOutboundBytes = \strlen($unsubscribeResponsePayload); - - if ($unsubscribeOutboundBytes > 0) { - triggerStats([ - METRIC_REALTIME_OUTBOUND => $unsubscribeOutboundBytes, - ], $project->getId()); - } - } - - break; - - case 'presence': - $userId = $realtime->connections[$connection]['userId']; - if (empty($userId)) { - throw new Exception(Exception::USER_UNAUTHORIZED, 'User must be authorized'); - } - /** @var User $user */ - $user = $database->getDocument('users', $userId); - - if ($user->isEmpty()) { - throw new Exception(Exception::USER_NOT_FOUND, params:[$userId]); - } - - if (!is_array($message['data'])) { - throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Payload is not valid.'); - } - - if (!array_key_exists('status', $message['data'])) { - throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Payload is not valid. status must be provided'); - } - - if (array_key_exists('permissions', $message['data']) && !\is_array($message['data']['permissions'])) { - throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Payload is not valid. permissions must be an array.'); - } - - $presenceData = [ - 'userInternalId' => $user->getSequence(), - 'userId' => $user->getId(), - 'source' => 'realtime', - 'status' => $message['data']['status'] - ]; - - // TODO: add the created presence id to the connections connection id array for deletion at the end(bulk delete) - - if (array_key_exists('metadata', $message['data'])) { - $presenceData['metadata'] = $message['data']['metadata']; - } - $presenceDocument = new Document($presenceData); - $presenceState->setPermissions($presenceDocument, $message['data']['permissions'] ?? null, $user, $authorization); - - $presenceId = $message['data']['presenceId'] ?? 'unique()'; - $presence = $presenceState->upsertForUser( - $database, - $presenceDocument, - $presenceId, - (string) $user->getSequence(), - function () use ($project): void { - if ($project !== null && !$project->isEmpty()) { - triggerPresenceUsage(1, $project->getId()); - } - } - ); - - $presence->removeAttribute('hostname'); - - $realtime->connections[$connection]['presences'] = array_merge($realtime->connections[$connection]['presences'] ?? [], [$presence->getId()]); - - $responsePayload = json_encode([ - 'type' => 'response', - 'data' => [ - 'to' => 'presence', - 'presence' => $presence->getArrayCopy() - ] - ]); - - $server->send([$connection], $responsePayload); - - if ($project !== null && !$project->isEmpty()) { - $subscribeOutboundBytes = \strlen($responsePayload); - - if ($subscribeOutboundBytes > 0) { - triggerStats([ - METRIC_REALTIME_OUTBOUND => $subscribeOutboundBytes, - ], $project->getId()); - } - } - - triggerPresenceEvent($server, $realtime, $project, $user, 'presences.[presenceId].upsert', $presence); - - break; - - default: - throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Message type is not valid.'); - } $success = true; } catch (Throwable $th) { logError($th, 'realtimeMessage', project: $project, authorization: $authorization); @@ -1601,10 +1250,6 @@ $server->onMessage(function (int $connection, string $message) use ($server, $re } finally { Span::add('realtime.success', $success); Span::add('realtime.responseCode', $responseCode); - Span::add('realtime.subscriptionDelta', $subscriptionDelta); - Span::add('realtime.subscriptionsRequested', $subscriptionsRequested); - Span::add('realtime.subscriptionsRemoved', $subscriptionsRemoved); - Span::add('realtime.subscribe.subscriptionsCount', $subscriptionsRequested); Span::add('realtime.outboundBytes', $outboundBytes); Span::add('realtime.projectId', $project?->getId() ?? $projectId); Span::add('realtime.userId', $realtime->connections[$connection]['userId'] ?? null); diff --git a/src/Appwrite/Realtime/Message/Dispatcher.php b/src/Appwrite/Realtime/Message/Dispatcher.php new file mode 100644 index 0000000000..729b0f7b11 --- /dev/null +++ b/src/Appwrite/Realtime/Message/Dispatcher.php @@ -0,0 +1,150 @@ + + */ + private array $handlers = []; + + public function register(Action $handler): self + { + $labels = $handler->getLabels(); + $type = $labels[self::LABEL_MESSAGE_TYPE] + ?? throw new \LogicException('Realtime message handler is missing the messageType label.'); + + $this->handlers[$type] = $handler; + return $this; + } + + /** + * @return array + */ + public function getHandlers(): array + { + return $this->handlers; + } + + /** + * Dispatches a parsed websocket message to the handler that registered for its `type`. + * + * On success: invokes the handler, sends the JSON response (when the handler returns a + * payload), and accumulates outbound bytes / outbound stats. Errors propagate so the + * outer onMessage handler can render them as websocket error frames. + * + * @param Container $container per-message container resolving 'connection', 'server', + * 'project', 'projectId' and any handler-declared injections. + * @param array $message decoded inbound websocket frame: `['type' => ..., 'data' => ...]`. + * @param int $outboundBytes counter incremented by the size of any response sent. + */ + public function dispatch(Container $container, array $message, int &$outboundBytes): void + { + $type = $message['type'] ?? ''; + if (!\is_string($type) || !isset($this->handlers[$type])) { + throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Message type is not valid.'); + } + + $handler = $this->handlers[$type]; + $labels = $handler->getLabels(); + + $requiresProject = $labels[self::LABEL_REQUIRES_PROJECT] ?? true; + if ($requiresProject && empty($container->get('projectId'))) { + throw new Exception( + Exception::REALTIME_POLICY_VIOLATION, + 'Missing project context. Reconnect to the project first.' + ); + } + + $shape = $labels[self::LABEL_PAYLOAD_SHAPE] ?? self::PAYLOAD_SHAPE_OBJECT; + $data = $message['data'] ?? ($shape === self::PAYLOAD_SHAPE_LIST ? [] : []); + + $args = $this->resolveArgs($handler, $data, $shape, $container); + + $payload = ($handler->getCallback())(...$args); + + if ($payload === null) { + return; + } + + $json = \json_encode($payload); + $server = $container->get('server'); + $server->send([$container->get('connection')], $json); + $outboundBytes += \strlen($json); + + /** @var ?Document $project */ + $project = $container->get('project'); + if ($project !== null && !$project->isEmpty() && \strlen($json) > 0) { + \triggerStats([METRIC_REALTIME_OUTBOUND => \strlen($json)], $project->getId()); + } + } + + /** + * Resolves the ordered argument list for the handler callback by walking the action's + * declared option sequence. Params come from the inbound `data` (for object shape) or + * the entire data list (for list shape). Injections come from the per-message container. + * + * @return array + */ + private function resolveArgs(Action $handler, mixed $data, string $shape, Container $container): array + { + $values = []; + + foreach ($handler->getParams() as $key => $param) { + if ($shape === self::PAYLOAD_SHAPE_LIST) { + $present = true; + $value = $data; + } else { + $present = \is_array($data) && \array_key_exists($key, $data); + $value = $present ? $data[$key] : $param['default']; + } + + if (!$present && !$param['optional']) { + throw new Exception( + Exception::REALTIME_MESSAGE_FORMAT_INVALID, + \sprintf('%s is required.', $key) + ); + } + + if ($present && !($param['skipValidation'] ?? false)) { + $validator = $param['validator']; + if (\is_callable($validator) && !($validator instanceof \Utopia\Validator)) { + $validator = $validator(); + } + if (!$validator->isValid($value)) { + throw new Exception( + Exception::REALTIME_MESSAGE_FORMAT_INVALID, + \sprintf('%s: %s', $key, $validator->getDescription()) + ); + } + } + + $values[$key] = $value; + } + + $ordered = []; + foreach ($handler->getOptions() as $optionKey => $option) { + if (($option['type'] ?? '') === 'param') { + $name = \substr($optionKey, \strlen('param:')); + $ordered[] = $values[$name] ?? null; + } else { + $ordered[] = $container->get($option['name']); + } + } + + return $ordered; + } +} diff --git a/src/Appwrite/Realtime/Message/Handlers/AuthenticationHandler.php b/src/Appwrite/Realtime/Message/Handlers/AuthenticationHandler.php new file mode 100644 index 0000000000..b6d8616f0b --- /dev/null +++ b/src/Appwrite/Realtime/Message/Handlers/AuthenticationHandler.php @@ -0,0 +1,120 @@ +desc('Authenticate the connection with a session token') + ->label(Dispatcher::LABEL_MESSAGE_TYPE, 'authentication') + ->param('session', '', new Text(2048), 'Encoded session token') + ->inject('connection') + ->inject('realtime') + ->inject('database') + ->inject('register') + ->inject('response') + ->callback($this->action(...)); + } + + /** + * @return array + */ + public function action( + string $session, + int $connection, + Realtime $realtime, + Database $database, + Registry $register, + Response $response, + ): array { + $store = new Store(); + $store->decode($session); + + /** @var User $user */ + $user = $database->getDocument('users', $store->getProperty('id', '')); + + // TODO: move proof construction to the DI container so there's one source of truth. + $proofForToken = new Token(); + $proofForToken->setHash(new Sha()); + + if ( + empty($user->getId()) + || !$user->sessionVerify($store->getProperty('secret', ''), $proofForToken) + ) { + throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Session is not valid.'); + } + + $roles = $user->getRoles($database->getAuthorization()); + + $authorization = $realtime->connections[$connection]['authorization'] ?? null; + $projectId = $realtime->connections[$connection]['projectId'] ?? null; + // Capture the pre-auth userId before unsubscribe() clears the connection entry, + // so we can rebind any account channels that were stored under it. + $previousUserId = $realtime->connections[$connection]['userId'] ?? ''; + + $subscriptionsBefore = \count($realtime->getSubscriptionMetadata($connection)); + $meta = $realtime->getSubscriptionMetadata($connection); + + $realtime->unsubscribe($connection); + + if (!empty($projectId)) { + foreach ($meta as $subscriptionId => $subscription) { + $queries = Query::parseQueries($subscription['queries'] ?? []); + $channels = Realtime::rebindAccountChannels( + $subscription['channels'] ?? [], + $previousUserId, + $user->getId(), + ); + + $realtime->subscribe( + $projectId, + $connection, + $subscriptionId, + $roles, + $channels, + $queries, + $user->getId(), + ); + } + } + + if ($authorization !== null) { + $realtime->connections[$connection]['authorization'] = $authorization; + } + + $subscriptionsAfter = \count($realtime->getSubscriptionMetadata($connection)); + $subscriptionDelta = $subscriptionsAfter - $subscriptionsBefore; + if ($subscriptionDelta !== 0) { + $register->get('telemetry.workerSubscriptionCounter') + ->add($subscriptionDelta, $register->get('telemetry.workerAttributes')); + } + + Span::add('realtime.subscriptionDelta', $subscriptionDelta); + + return [ + 'type' => 'response', + 'data' => [ + 'to' => 'authentication', + 'success' => true, + 'user' => $response->output($user, Response::MODEL_ACCOUNT), + ], + ]; + } +} diff --git a/src/Appwrite/Realtime/Message/Handlers/PingHandler.php b/src/Appwrite/Realtime/Message/Handlers/PingHandler.php new file mode 100644 index 0000000000..98fd6ab10b --- /dev/null +++ b/src/Appwrite/Realtime/Message/Handlers/PingHandler.php @@ -0,0 +1,28 @@ +desc('Reply to client heartbeat') + ->label(Dispatcher::LABEL_MESSAGE_TYPE, 'ping') + ->label(Dispatcher::LABEL_REQUIRES_PROJECT, false) + ->callback($this->action(...)); + } + + /** + * @return array + */ + public function action(): array + { + return [ + 'type' => 'pong', + ]; + } +} diff --git a/src/Appwrite/Realtime/Message/Handlers/PresenceHandler.php b/src/Appwrite/Realtime/Message/Handlers/PresenceHandler.php new file mode 100644 index 0000000000..ab38d8bbd7 --- /dev/null +++ b/src/Appwrite/Realtime/Message/Handlers/PresenceHandler.php @@ -0,0 +1,110 @@ +desc('Upsert a presence document for the authenticated user') + ->label(Dispatcher::LABEL_MESSAGE_TYPE, 'presence') + ->param('status', '', new Text(2048), 'Presence status') + ->param('presenceId', 'unique()', new Text(36), 'Presence document ID', optional: true) + ->param('metadata', null, new JSON(), 'Optional metadata payload', optional: true, skipValidation: true) + ->param('permissions', null, new ArrayList(new Text(2048)), 'Optional permissions list', optional: true) + ->inject('connection') + ->inject('server') + ->inject('realtime') + ->inject('database') + ->inject('authorization') + ->inject('presenceState') + ->inject('project') + ->callback($this->action(...)); + } + + /** + * @param array|null $permissions + * @return array + */ + public function action( + string $status, + string $presenceId, + mixed $metadata, + ?array $permissions, + int $connection, + Server $server, + Realtime $realtime, + Database $database, + Authorization $authorization, + PresenceState $presenceState, + ?Document $project, + ): array { + $userId = $realtime->connections[$connection]['userId'] ?? ''; + if (empty($userId)) { + throw new Exception(Exception::USER_UNAUTHORIZED, 'User must be authorized'); + } + + /** @var User $user */ + $user = $database->getDocument('users', $userId); + if ($user->isEmpty()) { + throw new Exception(Exception::USER_NOT_FOUND, params: [$userId]); + } + + $presenceData = [ + 'userInternalId' => $user->getSequence(), + 'userId' => $user->getId(), + 'source' => 'realtime', + 'status' => $status, + ]; + if ($metadata !== null) { + $presenceData['metadata'] = $metadata; + } + + $presenceDocument = new Document($presenceData); + $presenceState->setPermissions($presenceDocument, $permissions, $user, $authorization); + + $presence = $presenceState->upsertForUser( + $database, + $presenceDocument, + $presenceId, + (string) $user->getSequence(), + function () use ($project): void { + if ($project !== null && !$project->isEmpty()) { + \triggerPresenceUsage(1, $project->getId()); + } + }, + ); + + $presence->removeAttribute('hostname'); + + $realtime->connections[$connection]['presences'] = \array_merge( + $realtime->connections[$connection]['presences'] ?? [], + [$presence->getId()], + ); + + \triggerPresenceEvent($server, $realtime, $project, $user, 'presences.[presenceId].upsert', $presence); + + return [ + 'type' => 'response', + 'data' => [ + 'to' => 'presence', + 'presence' => $presence->getArrayCopy(), + ], + ]; + } +} diff --git a/src/Appwrite/Realtime/Message/Handlers/SubscribeHandler.php b/src/Appwrite/Realtime/Message/Handlers/SubscribeHandler.php new file mode 100644 index 0000000000..0e95d869a6 --- /dev/null +++ b/src/Appwrite/Realtime/Message/Handlers/SubscribeHandler.php @@ -0,0 +1,109 @@ +desc('Bulk subscribe to realtime channels') + ->label(Dispatcher::LABEL_MESSAGE_TYPE, 'subscribe') + ->label(Dispatcher::LABEL_PAYLOAD_SHAPE, Dispatcher::PAYLOAD_SHAPE_LIST) + ->param('items', null, new SubscribePayloadValidator(), 'Subscriptions to add') + ->inject('connection') + ->inject('realtime') + ->inject('register') + ->inject('projectId') + ->callback($this->action(...)); + } + + /** + * @param array, queries?: array, subscriptionId?: string}> $items + * @return array + */ + public function action( + array $items, + int $connection, + Realtime $realtime, + Registry $register, + ?string $projectId, + ): array { + $roles = $realtime->connections[$connection]['roles'] ?? [Role::guests()->toString()]; + $userId = $realtime->connections[$connection]['userId'] ?? ''; + + $parsedPayloads = []; + $subscriptionsBefore = \count($realtime->getSubscriptionMetadata($connection)); + + foreach ($items as $payload) { + $subscriptionId = \array_key_exists('subscriptionId', $payload) + ? $payload['subscriptionId'] + : ID::unique(); + + $queries = $payload['queries'] ?? []; + + try { + $convertedQueries = Realtime::convertQueries($queries); + } catch (QueryException $e) { + throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Invalid query: ' . $e->getMessage()); + } + + $convertedChannels = \array_keys(Realtime::convertChannels($payload['channels'], $userId)); + + $parsedPayloads[] = [ + 'subscriptionId' => $subscriptionId, + 'channels' => $payload['channels'], + 'convertedChannels' => $convertedChannels, + 'queries' => $convertedQueries, + ]; + } + + foreach ($parsedPayloads as $parsedPayload) { + $realtime->subscribe( + $projectId, + $connection, + $parsedPayload['subscriptionId'], + $roles, + $parsedPayload['convertedChannels'], + $parsedPayload['queries'], + ); + } + + $subscriptionsAfter = \count($realtime->getSubscriptionMetadata($connection)); + $subscriptionDelta = $subscriptionsAfter - $subscriptionsBefore; + $subscriptionsRequested = \count($parsedPayloads); + + if ($subscriptionDelta !== 0) { + $register->get('telemetry.workerSubscriptionCounter') + ->add($subscriptionDelta, $register->get('telemetry.workerAttributes')); + } + + Span::add('realtime.subscriptionDelta', $subscriptionDelta); + Span::add('realtime.subscriptionsRequested', $subscriptionsRequested); + Span::add('realtime.subscribe.subscriptionsCount', $subscriptionsRequested); + + return [ + 'type' => 'response', + 'data' => [ + 'to' => 'subscribe', + 'success' => true, + 'subscriptions' => \array_map(static fn (array $parsed): array => [ + 'subscriptionId' => $parsed['subscriptionId'], + 'channels' => $parsed['convertedChannels'], + 'queries' => \array_map(static fn ($q) => $q->toString(), $parsed['queries']), + ], $parsedPayloads), + ], + ]; + } +} diff --git a/src/Appwrite/Realtime/Message/Handlers/UnsubscribeHandler.php b/src/Appwrite/Realtime/Message/Handlers/UnsubscribeHandler.php new file mode 100644 index 0000000000..a6e6a38179 --- /dev/null +++ b/src/Appwrite/Realtime/Message/Handlers/UnsubscribeHandler.php @@ -0,0 +1,74 @@ +desc('Bulk remove subscriptions by id') + ->label(Dispatcher::LABEL_MESSAGE_TYPE, 'unsubscribe') + ->label(Dispatcher::LABEL_PAYLOAD_SHAPE, Dispatcher::PAYLOAD_SHAPE_LIST) + ->param('items', null, new UnsubscribePayloadValidator(), 'Subscriptions to remove') + ->inject('connection') + ->inject('realtime') + ->inject('register') + ->callback($this->action(...)); + } + + /** + * @param array $items + * @return array + */ + public function action( + array $items, + int $connection, + Realtime $realtime, + Registry $register, + ): array { + $subscriptionsBefore = \count($realtime->getSubscriptionMetadata($connection)); + + $unsubscribeResults = []; + foreach ($items as $payload) { + $subscriptionId = $payload['subscriptionId']; + $unsubscribeResults[] = [ + 'subscriptionId' => $subscriptionId, + 'removed' => $realtime->unsubscribeSubscription($connection, $subscriptionId), + ]; + } + + $subscriptionsAfter = \count($realtime->getSubscriptionMetadata($connection)); + $subscriptionDelta = $subscriptionsAfter - $subscriptionsBefore; + $subscriptionsRequested = \count($items); + $subscriptionsRemoved = \count(\array_filter( + $unsubscribeResults, + static fn (array $item): bool => $item['removed'] + )); + + if ($subscriptionDelta !== 0) { + $register->get('telemetry.workerSubscriptionCounter') + ->add($subscriptionDelta, $register->get('telemetry.workerAttributes')); + } + + Span::add('realtime.subscriptionDelta', $subscriptionDelta); + Span::add('realtime.subscriptionsRequested', $subscriptionsRequested); + Span::add('realtime.subscriptionsRemoved', $subscriptionsRemoved); + + return [ + 'type' => 'response', + 'data' => [ + 'to' => 'unsubscribe', + 'success' => true, + 'subscriptions' => $unsubscribeResults, + ], + ]; + } +} diff --git a/src/Appwrite/Realtime/Message/Validators/SubscribePayloadValidator.php b/src/Appwrite/Realtime/Message/Validators/SubscribePayloadValidator.php new file mode 100644 index 0000000000..5e59f39935 --- /dev/null +++ b/src/Appwrite/Realtime/Message/Validators/SubscribePayloadValidator.php @@ -0,0 +1,56 @@ +message; + } + + public function isArray(): bool + { + return true; + } + + public function getType(): string + { + return self::TYPE_ARRAY; + } + + public function isValid(mixed $value): bool + { + if (!\is_array($value) || !\array_is_list($value)) { + $this->message = 'Payload is not valid.'; + return false; + } + + foreach ($value as $payload) { + if (!\is_array($payload)) { + $this->message = 'Each subscribe payload must be an object.'; + return false; + } + if (!\array_key_exists('channels', $payload)) { + $this->message = 'channels is not present in payload.'; + return false; + } + if (!\is_array($payload['channels']) || !\array_is_list($payload['channels'])) { + $this->message = 'channels is not a valid array.'; + return false; + } + if (\array_key_exists('queries', $payload) + && (!\is_array($payload['queries']) || !\array_is_list($payload['queries'])) + ) { + $this->message = 'queries is not a valid array.'; + return false; + } + } + + return true; + } +} diff --git a/src/Appwrite/Realtime/Message/Validators/UnsubscribePayloadValidator.php b/src/Appwrite/Realtime/Message/Validators/UnsubscribePayloadValidator.php new file mode 100644 index 0000000000..eb1676af06 --- /dev/null +++ b/src/Appwrite/Realtime/Message/Validators/UnsubscribePayloadValidator.php @@ -0,0 +1,47 @@ +message; + } + + public function isArray(): bool + { + return true; + } + + public function getType(): string + { + return self::TYPE_ARRAY; + } + + public function isValid(mixed $value): bool + { + if (!\is_array($value) || !\array_is_list($value)) { + $this->message = 'Payload is not valid.'; + return false; + } + + foreach ($value as $payload) { + if ( + !\is_array($payload) + || !\array_key_exists('subscriptionId', $payload) + || !\is_string($payload['subscriptionId']) + || $payload['subscriptionId'] === '' + ) { + $this->message = 'Each unsubscribe payload must include a non-empty subscriptionId.'; + return false; + } + } + + return true; + } +} From 0e0e40f991c654c3addab7fd960ad1cb9f32b452 Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Mon, 4 May 2026 15:59:25 +0530 Subject: [PATCH 02/20] fixed the container inheritance bug --- app/realtime.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/app/realtime.php b/app/realtime.php index b7b48ccdd3..415ca3244d 100644 --- a/app/realtime.php +++ b/app/realtime.php @@ -1119,6 +1119,7 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server, }); $server->onMessage(function (int $connection, string $message) use ($server, $realtime, $containerId, $register, $presenceState, $messageDispatcher) { + global $container; $project = null; $authorization = null; $projectId = $realtime->connections[$connection]['projectId'] ?? null; @@ -1183,6 +1184,7 @@ $server->onMessage(function (int $connection, string $message) use ($server, $re } // Record realtime inbound bytes for this project + // not making this a part of the dispatcher as we need to get the inbound bytes as well even if we dont enter the dispatcher if ($project !== null && !$project->isEmpty()) { triggerStats([ METRIC_REALTIME_INBOUND => $rawSize, @@ -1201,7 +1203,11 @@ $server->onMessage(function (int $connection, string $message) use ($server, $re throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Message type is not valid.'); } - $messageContainer = new Container(); + // Child of the global container: per-message values like $connection and $project + // live on this scope so concurrent message coroutines don't clobber each other, + // while globally-registered services (pools, queueForRealtime, ...) remain reachable + // via the parent. + $messageContainer = new Container($container); $messageContainer->set('connection', fn () => $connection); $messageContainer->set('server', fn () => $server); $messageContainer->set('realtime', fn () => $realtime); From 29092b277bf2ecd7372f2b598139f08cffa604fb Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Mon, 4 May 2026 16:22:54 +0530 Subject: [PATCH 03/20] Update AuthenticationHandler to make session parameter optional and add validation for empty session tokens. Update error message in PresenceRealtimeClientTest for clarity. --- .../Realtime/Message/Handlers/AuthenticationHandler.php | 6 +++++- tests/e2e/Services/Presence/PresenceRealtimeClientTest.php | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/Appwrite/Realtime/Message/Handlers/AuthenticationHandler.php b/src/Appwrite/Realtime/Message/Handlers/AuthenticationHandler.php index b6d8616f0b..b17c672d91 100644 --- a/src/Appwrite/Realtime/Message/Handlers/AuthenticationHandler.php +++ b/src/Appwrite/Realtime/Message/Handlers/AuthenticationHandler.php @@ -24,7 +24,7 @@ class AuthenticationHandler extends Action $this ->desc('Authenticate the connection with a session token') ->label(Dispatcher::LABEL_MESSAGE_TYPE, 'authentication') - ->param('session', '', new Text(2048), 'Encoded session token') + ->param('session', '', new Text(2048), 'Encoded session token', optional: true) ->inject('connection') ->inject('realtime') ->inject('database') @@ -44,6 +44,10 @@ class AuthenticationHandler extends Action Registry $register, Response $response, ): array { + if ($session === '') { + throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Payload is not valid.'); + } + $store = new Store(); $store->decode($session); diff --git a/tests/e2e/Services/Presence/PresenceRealtimeClientTest.php b/tests/e2e/Services/Presence/PresenceRealtimeClientTest.php index e03dba110d..26a28d9387 100644 --- a/tests/e2e/Services/Presence/PresenceRealtimeClientTest.php +++ b/tests/e2e/Services/Presence/PresenceRealtimeClientTest.php @@ -382,7 +382,7 @@ class PresenceRealtimeClientTest extends Scope ], ])); $missingStatus = $this->receiveErrorMessage($client); - $this->assertStringContainsString('status must be provided', $missingStatus['data']['message'] ?? ''); + $this->assertStringContainsString('status is required', $missingStatus['data']['message'] ?? ''); $this->assertQuietFor( $client, fn (array $frame): bool => ($frame['type'] ?? null) === 'event' From ced5b88b57b94ccc08ef54223c70d8c07323d253 Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Mon, 4 May 2026 16:37:35 +0530 Subject: [PATCH 04/20] Refactor message dispatching and handler parameters for improved clarity and consistency. Update AuthenticationHandler and PresenceHandler to enforce required parameters. --- app/realtime.php | 22 +++++++++-- src/Appwrite/Realtime/Message/Dispatcher.php | 37 +++++-------------- .../Handlers/AuthenticationHandler.php | 2 +- .../Message/Handlers/PresenceHandler.php | 6 +-- 4 files changed, 33 insertions(+), 34 deletions(-) diff --git a/app/realtime.php b/app/realtime.php index 415ca3244d..fe7b55ff82 100644 --- a/app/realtime.php +++ b/app/realtime.php @@ -1118,8 +1118,7 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server, } }); -$server->onMessage(function (int $connection, string $message) use ($server, $realtime, $containerId, $register, $presenceState, $messageDispatcher) { - global $container; +$server->onMessage(function (int $connection, string $message) use ($container, $server, $realtime, $containerId, $register, $presenceState, $messageDispatcher) { $project = null; $authorization = null; $projectId = $realtime->connections[$connection]['projectId'] ?? null; @@ -1219,7 +1218,24 @@ $server->onMessage(function (int $connection, string $message) use ($server, $re $messageContainer->set('project', fn () => $project); $messageContainer->set('projectId', fn () => $projectId); - $messageDispatcher->dispatch($messageContainer, $message, $outboundBytes); + $responsePayload = $messageDispatcher->dispatch($messageContainer, $message); + + if ($responsePayload !== null) { + $responseJson = json_encode($responsePayload); + if ($responseJson === false) { + throw new \RuntimeException( + 'Failed to encode realtime response payload: ' . json_last_error_msg() + ); + } + + $server->send([$connection], $responseJson); + $bytes = \strlen($responseJson); + $outboundBytes += $bytes; + + if ($project !== null && !$project->isEmpty()) { + triggerStats([METRIC_REALTIME_OUTBOUND => $bytes], $project->getId()); + } + } $success = true; } catch (Throwable $th) { diff --git a/src/Appwrite/Realtime/Message/Dispatcher.php b/src/Appwrite/Realtime/Message/Dispatcher.php index 729b0f7b11..968b144c5b 100644 --- a/src/Appwrite/Realtime/Message/Dispatcher.php +++ b/src/Appwrite/Realtime/Message/Dispatcher.php @@ -3,7 +3,6 @@ namespace Appwrite\Realtime\Message; use Appwrite\Extend\Exception; -use Utopia\Database\Document; use Utopia\DI\Container; use Utopia\Platform\Action; @@ -40,18 +39,17 @@ class Dispatcher } /** - * Dispatches a parsed websocket message to the handler that registered for its `type`. + * Routes a parsed websocket message to the handler that registered for its `type`, + * runs param validation + dependency injection, and returns whatever the handler returns. + * Errors propagate so the caller can render them as websocket error frames. * - * On success: invokes the handler, sends the JSON response (when the handler returns a - * payload), and accumulates outbound bytes / outbound stats. Errors propagate so the - * outer onMessage handler can render them as websocket error frames. - * - * @param Container $container per-message container resolving 'connection', 'server', - * 'project', 'projectId' and any handler-declared injections. + * @param Container $container per-message container resolving 'connection', 'project', + * 'projectId' and any handler-declared injections. * @param array $message decoded inbound websocket frame: `['type' => ..., 'data' => ...]`. - * @param int $outboundBytes counter incremented by the size of any response sent. + * @return array|null the handler's response payload (already shaped for the + * wire), or null when the handler chooses not to reply. */ - public function dispatch(Container $container, array $message, int &$outboundBytes): void + public function dispatch(Container $container, array $message): ?array { $type = $message['type'] ?? ''; if (!\is_string($type) || !isset($this->handlers[$type])) { @@ -70,26 +68,11 @@ class Dispatcher } $shape = $labels[self::LABEL_PAYLOAD_SHAPE] ?? self::PAYLOAD_SHAPE_OBJECT; - $data = $message['data'] ?? ($shape === self::PAYLOAD_SHAPE_LIST ? [] : []); + $data = $message['data'] ?? []; $args = $this->resolveArgs($handler, $data, $shape, $container); - $payload = ($handler->getCallback())(...$args); - - if ($payload === null) { - return; - } - - $json = \json_encode($payload); - $server = $container->get('server'); - $server->send([$container->get('connection')], $json); - $outboundBytes += \strlen($json); - - /** @var ?Document $project */ - $project = $container->get('project'); - if ($project !== null && !$project->isEmpty() && \strlen($json) > 0) { - \triggerStats([METRIC_REALTIME_OUTBOUND => \strlen($json)], $project->getId()); - } + return ($handler->getCallback())(...$args); } /** diff --git a/src/Appwrite/Realtime/Message/Handlers/AuthenticationHandler.php b/src/Appwrite/Realtime/Message/Handlers/AuthenticationHandler.php index b17c672d91..9564aee7b4 100644 --- a/src/Appwrite/Realtime/Message/Handlers/AuthenticationHandler.php +++ b/src/Appwrite/Realtime/Message/Handlers/AuthenticationHandler.php @@ -24,7 +24,7 @@ class AuthenticationHandler extends Action $this ->desc('Authenticate the connection with a session token') ->label(Dispatcher::LABEL_MESSAGE_TYPE, 'authentication') - ->param('session', '', new Text(2048), 'Encoded session token', optional: true) + ->param('session', '', new Text(2048), 'Encoded session token', true) ->inject('connection') ->inject('realtime') ->inject('database') diff --git a/src/Appwrite/Realtime/Message/Handlers/PresenceHandler.php b/src/Appwrite/Realtime/Message/Handlers/PresenceHandler.php index ab38d8bbd7..ad623931c1 100644 --- a/src/Appwrite/Realtime/Message/Handlers/PresenceHandler.php +++ b/src/Appwrite/Realtime/Message/Handlers/PresenceHandler.php @@ -24,9 +24,9 @@ class PresenceHandler extends Action ->desc('Upsert a presence document for the authenticated user') ->label(Dispatcher::LABEL_MESSAGE_TYPE, 'presence') ->param('status', '', new Text(2048), 'Presence status') - ->param('presenceId', 'unique()', new Text(36), 'Presence document ID', optional: true) - ->param('metadata', null, new JSON(), 'Optional metadata payload', optional: true, skipValidation: true) - ->param('permissions', null, new ArrayList(new Text(2048)), 'Optional permissions list', optional: true) + ->param('presenceId', 'unique()', new Text(36), 'Presence document ID', true) + ->param('metadata', null, new JSON(), 'Optional metadata payload', true, [], true) + ->param('permissions', null, new ArrayList(new Text(2048)), 'Optional permissions list', true) ->inject('connection') ->inject('server') ->inject('realtime') From ec0f7cf683c4a138450e251b8daef40424220a5e Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Mon, 4 May 2026 16:39:47 +0530 Subject: [PATCH 05/20] Update error message in PresenceRealtimeClientTest for clarity on permissions validation --- tests/e2e/Services/Presence/PresenceRealtimeClientTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/e2e/Services/Presence/PresenceRealtimeClientTest.php b/tests/e2e/Services/Presence/PresenceRealtimeClientTest.php index 26a28d9387..3fbfb61543 100644 --- a/tests/e2e/Services/Presence/PresenceRealtimeClientTest.php +++ b/tests/e2e/Services/Presence/PresenceRealtimeClientTest.php @@ -398,7 +398,7 @@ class PresenceRealtimeClientTest extends Scope ], ])); $invalidPermissions = $this->receiveErrorMessage($client); - $this->assertStringContainsString('permissions must be an array', $invalidPermissions['data']['message'] ?? ''); + $this->assertStringContainsString('permissions: Value must a valid array', $invalidPermissions['data']['message'] ?? ''); $this->assertQuietFor( $client, fn (array $frame): bool => ($frame['type'] ?? null) === 'event' From 42542aec6168139b226740a6d1017fa09aae2af6 Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Mon, 4 May 2026 17:11:35 +0530 Subject: [PATCH 06/20] Enhance error handling and validation in Realtime message dispatchers. Update error messages for clarity and enforce required parameters in AuthenticationHandler. --- app/realtime.php | 7 ++++++ src/Appwrite/Realtime/Message/Dispatcher.php | 25 +++++++++++++------ .../Handlers/AuthenticationHandler.php | 6 +---- .../Presence/PresenceRealtimeClientTest.php | 2 +- .../Realtime/RealtimeConsoleClientTest.php | 2 +- .../Realtime/RealtimeCustomClientTest.php | 2 +- 6 files changed, 28 insertions(+), 16 deletions(-) diff --git a/app/realtime.php b/app/realtime.php index fe7b55ff82..19a9ae2565 100644 --- a/app/realtime.php +++ b/app/realtime.php @@ -1132,6 +1132,13 @@ $server->onMessage(function (int $connection, string $message) use ($container, Span::add('realtime.connectionId', $connection); Span::add('realtime.inboundBytes', $rawSize); Span::add('realtime.containerId', $containerId); + // Defaults so an exception thrown mid-handler still leaves these attrs on the span. + // Handlers (Subscribe/Unsubscribe/Authentication) override with real values via Span::add + // when their work succeeds. + Span::add('realtime.subscriptionDelta', 0); + Span::add('realtime.subscriptionsRequested', 0); + Span::add('realtime.subscriptionsRemoved', 0); + Span::add('realtime.subscribe.subscriptionsCount', 0); try { $response = new Response(new SwooleResponse()); diff --git a/src/Appwrite/Realtime/Message/Dispatcher.php b/src/Appwrite/Realtime/Message/Dispatcher.php index 968b144c5b..ad766309dd 100644 --- a/src/Appwrite/Realtime/Message/Dispatcher.php +++ b/src/Appwrite/Realtime/Message/Dispatcher.php @@ -15,6 +15,8 @@ class Dispatcher public const PAYLOAD_SHAPE_OBJECT = 'object'; public const PAYLOAD_SHAPE_LIST = 'list'; + private const REQUIRED_PARAM_ERROR_FORMAT = 'Payload is not valid. %s is required'; + /** * @var array */ @@ -68,7 +70,8 @@ class Dispatcher } $shape = $labels[self::LABEL_PAYLOAD_SHAPE] ?? self::PAYLOAD_SHAPE_OBJECT; - $data = $message['data'] ?? []; + $dataPresent = \array_key_exists('data', $message); + $data = $dataPresent ? $message['data'] : null; $args = $this->resolveArgs($handler, $data, $shape, $container); @@ -78,18 +81,24 @@ class Dispatcher /** * Resolves the ordered argument list for the handler callback by walking the action's * declared option sequence. Params come from the inbound `data` (for object shape) or - * the entire data list (for list shape). Injections come from the per-message container. + * the entire data value (for list shape). Injections come from the per-message container. * * @return array */ - private function resolveArgs(Action $handler, mixed $data, string $shape, Container $container): array - { + private function resolveArgs( + Action $handler, + mixed $data, + string $shape, + Container $container, + ): array { $values = []; - + $dataPresent = $data !== null; foreach ($handler->getParams() as $key => $param) { if ($shape === self::PAYLOAD_SHAPE_LIST) { - $present = true; - $value = $data; + // The whole `data` field is the value of this single param. `present` reflects + // whether the inbound message actually contained the `data` key. + $present = $dataPresent; + $value = $dataPresent ? $data : $param['default']; } else { $present = \is_array($data) && \array_key_exists($key, $data); $value = $present ? $data[$key] : $param['default']; @@ -98,7 +107,7 @@ class Dispatcher if (!$present && !$param['optional']) { throw new Exception( Exception::REALTIME_MESSAGE_FORMAT_INVALID, - \sprintf('%s is required.', $key) + \sprintf(self::REQUIRED_PARAM_ERROR_FORMAT, $key), ); } diff --git a/src/Appwrite/Realtime/Message/Handlers/AuthenticationHandler.php b/src/Appwrite/Realtime/Message/Handlers/AuthenticationHandler.php index 9564aee7b4..b6d8616f0b 100644 --- a/src/Appwrite/Realtime/Message/Handlers/AuthenticationHandler.php +++ b/src/Appwrite/Realtime/Message/Handlers/AuthenticationHandler.php @@ -24,7 +24,7 @@ class AuthenticationHandler extends Action $this ->desc('Authenticate the connection with a session token') ->label(Dispatcher::LABEL_MESSAGE_TYPE, 'authentication') - ->param('session', '', new Text(2048), 'Encoded session token', true) + ->param('session', '', new Text(2048), 'Encoded session token') ->inject('connection') ->inject('realtime') ->inject('database') @@ -44,10 +44,6 @@ class AuthenticationHandler extends Action Registry $register, Response $response, ): array { - if ($session === '') { - throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Payload is not valid.'); - } - $store = new Store(); $store->decode($session); diff --git a/tests/e2e/Services/Presence/PresenceRealtimeClientTest.php b/tests/e2e/Services/Presence/PresenceRealtimeClientTest.php index 3fbfb61543..ce5267b10a 100644 --- a/tests/e2e/Services/Presence/PresenceRealtimeClientTest.php +++ b/tests/e2e/Services/Presence/PresenceRealtimeClientTest.php @@ -382,7 +382,7 @@ class PresenceRealtimeClientTest extends Scope ], ])); $missingStatus = $this->receiveErrorMessage($client); - $this->assertStringContainsString('status is required', $missingStatus['data']['message'] ?? ''); + $this->assertStringContainsString('Payload is not valid. status is required', $missingStatus['data']['message'] ?? ''); $this->assertQuietFor( $client, fn (array $frame): bool => ($frame['type'] ?? null) === 'event' diff --git a/tests/e2e/Services/Realtime/RealtimeConsoleClientTest.php b/tests/e2e/Services/Realtime/RealtimeConsoleClientTest.php index 3da00898c9..feebe8839e 100644 --- a/tests/e2e/Services/Realtime/RealtimeConsoleClientTest.php +++ b/tests/e2e/Services/Realtime/RealtimeConsoleClientTest.php @@ -257,7 +257,7 @@ class RealtimeConsoleClientTest extends Scope $this->assertEquals('error', $response['type']); $this->assertNotEmpty($response['data']); $this->assertEquals(1003, $response['data']['code']); - $this->assertEquals('Payload is not valid.', $response['data']['message']); + $this->assertEquals('Payload is not valid. session is required', $response['data']['message']); $client->send(\json_encode([ 'type' => 'unknown', diff --git a/tests/e2e/Services/Realtime/RealtimeCustomClientTest.php b/tests/e2e/Services/Realtime/RealtimeCustomClientTest.php index 813ef70ff0..436de5b1d0 100644 --- a/tests/e2e/Services/Realtime/RealtimeCustomClientTest.php +++ b/tests/e2e/Services/Realtime/RealtimeCustomClientTest.php @@ -239,7 +239,7 @@ class RealtimeCustomClientTest extends Scope $this->assertEquals('error', $response['type']); $this->assertNotEmpty($response['data']); $this->assertEquals(1003, $response['data']['code']); - $this->assertEquals('Payload is not valid.', $response['data']['message']); + $this->assertEquals('Payload is not valid. session is required', $response['data']['message']); $client->send(\json_encode([ 'type' => 'unknown', From 4822164e32ae644a0b2382f3a16f098fc04a251e Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Mon, 4 May 2026 17:14:09 +0530 Subject: [PATCH 07/20] Inject global helpers into PresenceHandler for improved testability and maintainability. --- app/realtime.php | 5 +++++ .../Realtime/Message/Handlers/PresenceHandler.php | 13 ++++++++++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/app/realtime.php b/app/realtime.php index 19a9ae2565..12d2a5c600 100644 --- a/app/realtime.php +++ b/app/realtime.php @@ -1224,6 +1224,11 @@ $server->onMessage(function (int $connection, string $message) use ($container, $messageContainer->set('authorization', fn () => $authorization); $messageContainer->set('project', fn () => $project); $messageContainer->set('projectId', fn () => $projectId); + // Wrap the global helpers as first-class callables so handlers receive them via + // injection rather than reaching into the global namespace. Keeps PresenceHandler + // unit-testable without bootstrapping app/realtime.php. + $messageContainer->set('triggerPresenceUsage', fn () => triggerPresenceUsage(...)); + $messageContainer->set('triggerPresenceEvent', fn () => triggerPresenceEvent(...)); $responsePayload = $messageDispatcher->dispatch($messageContainer, $message); diff --git a/src/Appwrite/Realtime/Message/Handlers/PresenceHandler.php b/src/Appwrite/Realtime/Message/Handlers/PresenceHandler.php index ad623931c1..a9924fdb1e 100644 --- a/src/Appwrite/Realtime/Message/Handlers/PresenceHandler.php +++ b/src/Appwrite/Realtime/Message/Handlers/PresenceHandler.php @@ -7,6 +7,7 @@ use Appwrite\Extend\Exception; use Appwrite\Messaging\Adapter\Realtime; use Appwrite\Realtime\Message\Dispatcher; use Appwrite\Utopia\Database\Documents\User; +use Closure; use Utopia\Database\Database; use Utopia\Database\Document; use Utopia\Database\Validator\Authorization; @@ -34,11 +35,15 @@ class PresenceHandler extends Action ->inject('authorization') ->inject('presenceState') ->inject('project') + ->inject('triggerPresenceUsage') + ->inject('triggerPresenceEvent') ->callback($this->action(...)); } /** * @param array|null $permissions + * @param Closure(int, string): void $triggerPresenceUsage + * @param Closure(Server, Realtime, ?Document, User, string, Document): void $triggerPresenceEvent * @return array */ public function action( @@ -53,6 +58,8 @@ class PresenceHandler extends Action Authorization $authorization, PresenceState $presenceState, ?Document $project, + Closure $triggerPresenceUsage, + Closure $triggerPresenceEvent, ): array { $userId = $realtime->connections[$connection]['userId'] ?? ''; if (empty($userId)) { @@ -83,9 +90,9 @@ class PresenceHandler extends Action $presenceDocument, $presenceId, (string) $user->getSequence(), - function () use ($project): void { + function () use ($project, $triggerPresenceUsage): void { if ($project !== null && !$project->isEmpty()) { - \triggerPresenceUsage(1, $project->getId()); + $triggerPresenceUsage(1, $project->getId()); } }, ); @@ -97,7 +104,7 @@ class PresenceHandler extends Action [$presence->getId()], ); - \triggerPresenceEvent($server, $realtime, $project, $user, 'presences.[presenceId].upsert', $presence); + $triggerPresenceEvent($server, $realtime, $project, $user, 'presences.[presenceId].upsert', $presence); return [ 'type' => 'response', From b2b6fb6b6947f010c38c375ff9ed949a2e539008 Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Mon, 4 May 2026 17:25:39 +0530 Subject: [PATCH 08/20] Enhance validation logic in Realtime message validators. Update error handling to return specific validation error messages and streamline the validation process in SubscribePayloadValidator and UnsubscribePayloadValidator. --- src/Appwrite/Realtime/Message/Dispatcher.php | 10 ++++++- .../Validators/SubscribePayloadValidator.php | 26 +++++++++---------- .../UnsubscribePayloadValidator.php | 17 ++++++------ 3 files changed, 30 insertions(+), 23 deletions(-) diff --git a/src/Appwrite/Realtime/Message/Dispatcher.php b/src/Appwrite/Realtime/Message/Dispatcher.php index ad766309dd..47ba4a6cb8 100644 --- a/src/Appwrite/Realtime/Message/Dispatcher.php +++ b/src/Appwrite/Realtime/Message/Dispatcher.php @@ -117,9 +117,17 @@ class Dispatcher $validator = $validator(); } if (!$validator->isValid($value)) { + // taking the error directly instead of the message attribute from the validator + // to avoid the race condition between coroutines modifying each others static attributes + // as the validator is a static class + $description = $validator->getDescription(); + if (\is_callable([$validator, 'getValidationError'])) { + $description = $validator->getValidationError($value) ?? $description; + } + throw new Exception( Exception::REALTIME_MESSAGE_FORMAT_INVALID, - \sprintf('%s: %s', $key, $validator->getDescription()) + \sprintf('%s: %s', $key, $description) ); } } diff --git a/src/Appwrite/Realtime/Message/Validators/SubscribePayloadValidator.php b/src/Appwrite/Realtime/Message/Validators/SubscribePayloadValidator.php index 5e59f39935..d3c9a4cc37 100644 --- a/src/Appwrite/Realtime/Message/Validators/SubscribePayloadValidator.php +++ b/src/Appwrite/Realtime/Message/Validators/SubscribePayloadValidator.php @@ -6,11 +6,9 @@ use Utopia\Validator; class SubscribePayloadValidator extends Validator { - private string $message = 'Payload is not valid.'; - public function getDescription(): string { - return $this->message; + return 'Payload is not valid.'; } public function isArray(): bool @@ -24,33 +22,33 @@ class SubscribePayloadValidator extends Validator } public function isValid(mixed $value): bool + { + return $this->getValidationError($value) === null; + } + + public function getValidationError(mixed $value): ?string { if (!\is_array($value) || !\array_is_list($value)) { - $this->message = 'Payload is not valid.'; - return false; + return 'Payload is not valid.'; } foreach ($value as $payload) { if (!\is_array($payload)) { - $this->message = 'Each subscribe payload must be an object.'; - return false; + return 'Each subscribe payload must be an object.'; } if (!\array_key_exists('channels', $payload)) { - $this->message = 'channels is not present in payload.'; - return false; + return 'channels is not present in payload.'; } if (!\is_array($payload['channels']) || !\array_is_list($payload['channels'])) { - $this->message = 'channels is not a valid array.'; - return false; + return 'channels is not a valid array.'; } if (\array_key_exists('queries', $payload) && (!\is_array($payload['queries']) || !\array_is_list($payload['queries'])) ) { - $this->message = 'queries is not a valid array.'; - return false; + return 'queries is not a valid array.'; } } - return true; + return null; } } diff --git a/src/Appwrite/Realtime/Message/Validators/UnsubscribePayloadValidator.php b/src/Appwrite/Realtime/Message/Validators/UnsubscribePayloadValidator.php index eb1676af06..e3e3742f43 100644 --- a/src/Appwrite/Realtime/Message/Validators/UnsubscribePayloadValidator.php +++ b/src/Appwrite/Realtime/Message/Validators/UnsubscribePayloadValidator.php @@ -6,11 +6,9 @@ use Utopia\Validator; class UnsubscribePayloadValidator extends Validator { - private string $message = 'Payload is not valid.'; - public function getDescription(): string { - return $this->message; + return 'Payload is not valid.'; } public function isArray(): bool @@ -24,10 +22,14 @@ class UnsubscribePayloadValidator extends Validator } public function isValid(mixed $value): bool + { + return $this->getValidationError($value) === null; + } + + public function getValidationError(mixed $value): ?string { if (!\is_array($value) || !\array_is_list($value)) { - $this->message = 'Payload is not valid.'; - return false; + return 'Payload is not valid.'; } foreach ($value as $payload) { @@ -37,11 +39,10 @@ class UnsubscribePayloadValidator extends Validator || !\is_string($payload['subscriptionId']) || $payload['subscriptionId'] === '' ) { - $this->message = 'Each unsubscribe payload must include a non-empty subscriptionId.'; - return false; + return 'Each unsubscribe payload must include a non-empty subscriptionId.'; } } - return true; + return null; } } From 2ed8247fba89329174ae60a0231c698a9b180de0 Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Mon, 4 May 2026 17:39:34 +0530 Subject: [PATCH 09/20] fix graphql tests --- tests/e2e/Services/GraphQL/PresenceTest.php | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/tests/e2e/Services/GraphQL/PresenceTest.php b/tests/e2e/Services/GraphQL/PresenceTest.php index 077c0aa902..d1fb786ac5 100644 --- a/tests/e2e/Services/GraphQL/PresenceTest.php +++ b/tests/e2e/Services/GraphQL/PresenceTest.php @@ -22,7 +22,7 @@ class PresenceTest extends Scope $payload = [ 'query' => <<<'GQL' mutation upsertPresence($presenceId: String!, $userId: String!, $status: String!, $metadata: Json) { - presencesUpsert(presenceId: $presenceId, userId: $userId, status: $status, metadata: $metadata) { + presencesUpsertPresence(presenceId: $presenceId, userId: $userId, status: $status, metadata: $metadata) { _id userId status @@ -45,9 +45,8 @@ class PresenceTest extends Scope 'x-appwrite-project' => $projectId, 'x-appwrite-key' => $apiKey, ], $payload); - $this->assertEquals(200, $response['headers']['status-code']); - $this->assertEquals('online', $response['body']['data']['presencesUpsert']['status']); - $this->assertEquals('graphql', $response['body']['data']['presencesUpsert']['source']); + $this->assertEquals('online', $response['body']['data']['presencesUpsertPresence']['status']); + $this->assertEquals('graphql', $response['body']['data']['presencesUpsertPresence']['source']); } } From d043b4740e41a99f3a92ddda457c1c8fe789c2c3 Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Tue, 5 May 2026 19:11:05 +0530 Subject: [PATCH 10/20] updated --- src/Appwrite/Realtime/Message/Handlers/PresenceHandler.php | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/Appwrite/Realtime/Message/Handlers/PresenceHandler.php b/src/Appwrite/Realtime/Message/Handlers/PresenceHandler.php index a9924fdb1e..a608328c99 100644 --- a/src/Appwrite/Realtime/Message/Handlers/PresenceHandler.php +++ b/src/Appwrite/Realtime/Message/Handlers/PresenceHandler.php @@ -15,7 +15,6 @@ use Utopia\Platform\Action; use Utopia\Validator\ArrayList; use Utopia\Validator\JSON; use Utopia\Validator\Text; -use Utopia\WebSocket\Server; class PresenceHandler extends Action { @@ -29,7 +28,6 @@ class PresenceHandler extends Action ->param('metadata', null, new JSON(), 'Optional metadata payload', true, [], true) ->param('permissions', null, new ArrayList(new Text(2048)), 'Optional permissions list', true) ->inject('connection') - ->inject('server') ->inject('realtime') ->inject('database') ->inject('authorization') @@ -43,7 +41,7 @@ class PresenceHandler extends Action /** * @param array|null $permissions * @param Closure(int, string): void $triggerPresenceUsage - * @param Closure(Server, Realtime, ?Document, User, string, Document): void $triggerPresenceEvent + * @param Closure(?Document, User, string, Document): void $triggerPresenceEvent * @return array */ public function action( @@ -52,7 +50,6 @@ class PresenceHandler extends Action mixed $metadata, ?array $permissions, int $connection, - Server $server, Realtime $realtime, Database $database, Authorization $authorization, @@ -104,7 +101,7 @@ class PresenceHandler extends Action [$presence->getId()], ); - $triggerPresenceEvent($server, $realtime, $project, $user, 'presences.[presenceId].upsert', $presence); + $triggerPresenceEvent($project, $user, 'presences.[presenceId].upsert', $presence); return [ 'type' => 'response', From 5eabeeea209a7ac806d9498e2bb926d9b9e571cd Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Wed, 6 May 2026 12:10:50 +0530 Subject: [PATCH 11/20] refactor: update payload validators to use closures for instantiation and improve error handling --- src/Appwrite/Realtime/Message/Dispatcher.php | 10 +------ .../Message/Handlers/SubscribeHandler.php | 2 +- .../Message/Handlers/UnsubscribeHandler.php | 2 +- .../Validators/SubscribePayloadValidator.php | 28 ++++++++++--------- .../UnsubscribePayloadValidator.php | 17 ++++++----- 5 files changed, 26 insertions(+), 33 deletions(-) diff --git a/src/Appwrite/Realtime/Message/Dispatcher.php b/src/Appwrite/Realtime/Message/Dispatcher.php index 47ba4a6cb8..ad766309dd 100644 --- a/src/Appwrite/Realtime/Message/Dispatcher.php +++ b/src/Appwrite/Realtime/Message/Dispatcher.php @@ -117,17 +117,9 @@ class Dispatcher $validator = $validator(); } if (!$validator->isValid($value)) { - // taking the error directly instead of the message attribute from the validator - // to avoid the race condition between coroutines modifying each others static attributes - // as the validator is a static class - $description = $validator->getDescription(); - if (\is_callable([$validator, 'getValidationError'])) { - $description = $validator->getValidationError($value) ?? $description; - } - throw new Exception( Exception::REALTIME_MESSAGE_FORMAT_INVALID, - \sprintf('%s: %s', $key, $description) + \sprintf('%s: %s', $key, $validator->getDescription()) ); } } diff --git a/src/Appwrite/Realtime/Message/Handlers/SubscribeHandler.php b/src/Appwrite/Realtime/Message/Handlers/SubscribeHandler.php index 0e95d869a6..5de891d6c0 100644 --- a/src/Appwrite/Realtime/Message/Handlers/SubscribeHandler.php +++ b/src/Appwrite/Realtime/Message/Handlers/SubscribeHandler.php @@ -21,7 +21,7 @@ class SubscribeHandler extends Action ->desc('Bulk subscribe to realtime channels') ->label(Dispatcher::LABEL_MESSAGE_TYPE, 'subscribe') ->label(Dispatcher::LABEL_PAYLOAD_SHAPE, Dispatcher::PAYLOAD_SHAPE_LIST) - ->param('items', null, new SubscribePayloadValidator(), 'Subscriptions to add') + ->param('items', null, fn () => new SubscribePayloadValidator(), 'Subscriptions to add') ->inject('connection') ->inject('realtime') ->inject('register') diff --git a/src/Appwrite/Realtime/Message/Handlers/UnsubscribeHandler.php b/src/Appwrite/Realtime/Message/Handlers/UnsubscribeHandler.php index a6e6a38179..4b19f99d4b 100644 --- a/src/Appwrite/Realtime/Message/Handlers/UnsubscribeHandler.php +++ b/src/Appwrite/Realtime/Message/Handlers/UnsubscribeHandler.php @@ -17,7 +17,7 @@ class UnsubscribeHandler extends Action ->desc('Bulk remove subscriptions by id') ->label(Dispatcher::LABEL_MESSAGE_TYPE, 'unsubscribe') ->label(Dispatcher::LABEL_PAYLOAD_SHAPE, Dispatcher::PAYLOAD_SHAPE_LIST) - ->param('items', null, new UnsubscribePayloadValidator(), 'Subscriptions to remove') + ->param('items', null, fn () => new UnsubscribePayloadValidator(), 'Subscriptions to remove') ->inject('connection') ->inject('realtime') ->inject('register') diff --git a/src/Appwrite/Realtime/Message/Validators/SubscribePayloadValidator.php b/src/Appwrite/Realtime/Message/Validators/SubscribePayloadValidator.php index d3c9a4cc37..763a90f49f 100644 --- a/src/Appwrite/Realtime/Message/Validators/SubscribePayloadValidator.php +++ b/src/Appwrite/Realtime/Message/Validators/SubscribePayloadValidator.php @@ -6,9 +6,11 @@ use Utopia\Validator; class SubscribePayloadValidator extends Validator { + protected string $description = 'Payload is not valid.'; + public function getDescription(): string { - return 'Payload is not valid.'; + return $this->description; } public function isArray(): bool @@ -22,33 +24,33 @@ class SubscribePayloadValidator extends Validator } public function isValid(mixed $value): bool - { - return $this->getValidationError($value) === null; - } - - public function getValidationError(mixed $value): ?string { if (!\is_array($value) || !\array_is_list($value)) { - return 'Payload is not valid.'; + $this->description = 'Payload is not valid.'; + return false; } foreach ($value as $payload) { if (!\is_array($payload)) { - return 'Each subscribe payload must be an object.'; + $this->description = 'Each subscribe payload must be an object.'; + return false; } if (!\array_key_exists('channels', $payload)) { - return 'channels is not present in payload.'; + $this->description = 'channels is not present in payload.'; + return false; } if (!\is_array($payload['channels']) || !\array_is_list($payload['channels'])) { - return 'channels is not a valid array.'; + $this->description = 'channels is not a valid array.'; + return false; } if (\array_key_exists('queries', $payload) && (!\is_array($payload['queries']) || !\array_is_list($payload['queries'])) ) { - return 'queries is not a valid array.'; + $this->description = 'queries is not a valid array.'; + return false; } } - return null; + return true; } -} +} \ No newline at end of file diff --git a/src/Appwrite/Realtime/Message/Validators/UnsubscribePayloadValidator.php b/src/Appwrite/Realtime/Message/Validators/UnsubscribePayloadValidator.php index e3e3742f43..91c26ac0a2 100644 --- a/src/Appwrite/Realtime/Message/Validators/UnsubscribePayloadValidator.php +++ b/src/Appwrite/Realtime/Message/Validators/UnsubscribePayloadValidator.php @@ -6,9 +6,11 @@ use Utopia\Validator; class UnsubscribePayloadValidator extends Validator { + protected string $description = 'Payload is not valid.'; + public function getDescription(): string { - return 'Payload is not valid.'; + return $this->description; } public function isArray(): bool @@ -22,14 +24,10 @@ class UnsubscribePayloadValidator extends Validator } public function isValid(mixed $value): bool - { - return $this->getValidationError($value) === null; - } - - public function getValidationError(mixed $value): ?string { if (!\is_array($value) || !\array_is_list($value)) { - return 'Payload is not valid.'; + $this->description = 'Payload is not valid.'; + return false; } foreach ($value as $payload) { @@ -39,10 +37,11 @@ class UnsubscribePayloadValidator extends Validator || !\is_string($payload['subscriptionId']) || $payload['subscriptionId'] === '' ) { - return 'Each unsubscribe payload must include a non-empty subscriptionId.'; + $this->description = 'Each unsubscribe payload must include a non-empty subscriptionId.'; + return false; } } - return null; + return true; } } From 1946ee86b222a5d36292fdf47447c3fe01717437 Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Wed, 6 May 2026 12:20:06 +0530 Subject: [PATCH 12/20] feat: add realtime message handlers for authentication, ping, presence, subscribe, and unsubscribe --- app/realtime.php | 10 +++++----- .../{AuthenticationHandler.php => Authentication.php} | 2 +- .../Message/Handlers/{PingHandler.php => Ping.php} | 2 +- .../Handlers/{PresenceHandler.php => Presence.php} | 10 ++++++---- .../Handlers/{SubscribeHandler.php => Subscribe.php} | 4 ++-- .../{UnsubscribeHandler.php => Unsubscribe.php} | 4 ++-- ...scribePayloadValidator.php => SubscribePayload.php} | 4 ++-- ...ribePayloadValidator.php => UnsubscribePayload.php} | 2 +- 8 files changed, 20 insertions(+), 18 deletions(-) rename src/Appwrite/Realtime/Message/Handlers/{AuthenticationHandler.php => Authentication.php} (98%) rename src/Appwrite/Realtime/Message/Handlers/{PingHandler.php => Ping.php} (94%) rename src/Appwrite/Realtime/Message/Handlers/{PresenceHandler.php => Presence.php} (93%) rename src/Appwrite/Realtime/Message/Handlers/{SubscribeHandler.php => Subscribe.php} (97%) rename src/Appwrite/Realtime/Message/Handlers/{UnsubscribeHandler.php => Unsubscribe.php} (95%) rename src/Appwrite/Realtime/Message/Validators/{SubscribePayloadValidator.php => SubscribePayload.php} (96%) rename src/Appwrite/Realtime/Message/Validators/{UnsubscribePayloadValidator.php => UnsubscribePayload.php} (95%) diff --git a/app/realtime.php b/app/realtime.php index f72609dee8..f20da0291f 100644 --- a/app/realtime.php +++ b/app/realtime.php @@ -11,11 +11,11 @@ use Appwrite\Messaging\Adapter\Realtime; use Appwrite\Network\Validator\Origin; use Appwrite\PubSub\Adapter\Pool as PubSubPool; use Appwrite\Realtime\Message\Dispatcher as MessageDispatcher; -use Appwrite\Realtime\Message\Handlers\AuthenticationHandler; -use Appwrite\Realtime\Message\Handlers\PingHandler; -use Appwrite\Realtime\Message\Handlers\PresenceHandler; -use Appwrite\Realtime\Message\Handlers\SubscribeHandler; -use Appwrite\Realtime\Message\Handlers\UnsubscribeHandler; +use Appwrite\Realtime\Message\Handlers\Authentication as AuthenticationHandler; +use Appwrite\Realtime\Message\Handlers\Ping as PingHandler; +use Appwrite\Realtime\Message\Handlers\Presence as PresenceHandler; +use Appwrite\Realtime\Message\Handlers\Subscribe as SubscribeHandler; +use Appwrite\Realtime\Message\Handlers\Unsubscribe as UnsubscribeHandler; use Appwrite\Usage\Context; use Appwrite\Utopia\Database\Documents\User; use Appwrite\Utopia\Request; diff --git a/src/Appwrite/Realtime/Message/Handlers/AuthenticationHandler.php b/src/Appwrite/Realtime/Message/Handlers/Authentication.php similarity index 98% rename from src/Appwrite/Realtime/Message/Handlers/AuthenticationHandler.php rename to src/Appwrite/Realtime/Message/Handlers/Authentication.php index b6d8616f0b..cdb0fe7bbe 100644 --- a/src/Appwrite/Realtime/Message/Handlers/AuthenticationHandler.php +++ b/src/Appwrite/Realtime/Message/Handlers/Authentication.php @@ -17,7 +17,7 @@ use Utopia\Registry\Registry; use Utopia\Span\Span; use Utopia\Validator\Text; -class AuthenticationHandler extends Action +class Authentication extends Action { public function __construct() { diff --git a/src/Appwrite/Realtime/Message/Handlers/PingHandler.php b/src/Appwrite/Realtime/Message/Handlers/Ping.php similarity index 94% rename from src/Appwrite/Realtime/Message/Handlers/PingHandler.php rename to src/Appwrite/Realtime/Message/Handlers/Ping.php index 98fd6ab10b..4bfcfa7060 100644 --- a/src/Appwrite/Realtime/Message/Handlers/PingHandler.php +++ b/src/Appwrite/Realtime/Message/Handlers/Ping.php @@ -5,7 +5,7 @@ namespace Appwrite\Realtime\Message\Handlers; use Appwrite\Realtime\Message\Dispatcher; use Utopia\Platform\Action; -class PingHandler extends Action +class Ping extends Action { public function __construct() { diff --git a/src/Appwrite/Realtime/Message/Handlers/PresenceHandler.php b/src/Appwrite/Realtime/Message/Handlers/Presence.php similarity index 93% rename from src/Appwrite/Realtime/Message/Handlers/PresenceHandler.php rename to src/Appwrite/Realtime/Message/Handlers/Presence.php index a608328c99..1d373e172c 100644 --- a/src/Appwrite/Realtime/Message/Handlers/PresenceHandler.php +++ b/src/Appwrite/Realtime/Message/Handlers/Presence.php @@ -16,7 +16,7 @@ use Utopia\Validator\ArrayList; use Utopia\Validator\JSON; use Utopia\Validator\Text; -class PresenceHandler extends Action +class Presence extends Action { public function __construct() { @@ -58,6 +58,10 @@ class PresenceHandler extends Action Closure $triggerPresenceUsage, Closure $triggerPresenceEvent, ): array { + if ($project === null || $project->isEmpty()) { + throw new Exception(Exception::REALTIME_POLICY_VIOLATION, 'Presence requires a project context.'); + } + $userId = $realtime->connections[$connection]['userId'] ?? ''; if (empty($userId)) { throw new Exception(Exception::USER_UNAUTHORIZED, 'User must be authorized'); @@ -88,9 +92,7 @@ class PresenceHandler extends Action $presenceId, (string) $user->getSequence(), function () use ($project, $triggerPresenceUsage): void { - if ($project !== null && !$project->isEmpty()) { - $triggerPresenceUsage(1, $project->getId()); - } + $triggerPresenceUsage(1, $project->getId()); }, ); diff --git a/src/Appwrite/Realtime/Message/Handlers/SubscribeHandler.php b/src/Appwrite/Realtime/Message/Handlers/Subscribe.php similarity index 97% rename from src/Appwrite/Realtime/Message/Handlers/SubscribeHandler.php rename to src/Appwrite/Realtime/Message/Handlers/Subscribe.php index 5de891d6c0..c32ad4f702 100644 --- a/src/Appwrite/Realtime/Message/Handlers/SubscribeHandler.php +++ b/src/Appwrite/Realtime/Message/Handlers/Subscribe.php @@ -5,7 +5,7 @@ namespace Appwrite\Realtime\Message\Handlers; use Appwrite\Extend\Exception; use Appwrite\Messaging\Adapter\Realtime; use Appwrite\Realtime\Message\Dispatcher; -use Appwrite\Realtime\Message\Validators\SubscribePayloadValidator; +use Appwrite\Realtime\Message\Validators\SubscribePayload as SubscribePayloadValidator; use Utopia\Database\Exception\Query as QueryException; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Role; @@ -13,7 +13,7 @@ use Utopia\Platform\Action; use Utopia\Registry\Registry; use Utopia\Span\Span; -class SubscribeHandler extends Action +class Subscribe extends Action { public function __construct() { diff --git a/src/Appwrite/Realtime/Message/Handlers/UnsubscribeHandler.php b/src/Appwrite/Realtime/Message/Handlers/Unsubscribe.php similarity index 95% rename from src/Appwrite/Realtime/Message/Handlers/UnsubscribeHandler.php rename to src/Appwrite/Realtime/Message/Handlers/Unsubscribe.php index 4b19f99d4b..469d2145dd 100644 --- a/src/Appwrite/Realtime/Message/Handlers/UnsubscribeHandler.php +++ b/src/Appwrite/Realtime/Message/Handlers/Unsubscribe.php @@ -4,12 +4,12 @@ namespace Appwrite\Realtime\Message\Handlers; use Appwrite\Messaging\Adapter\Realtime; use Appwrite\Realtime\Message\Dispatcher; -use Appwrite\Realtime\Message\Validators\UnsubscribePayloadValidator; +use Appwrite\Realtime\Message\Validators\UnsubscribePayload as UnsubscribePayloadValidator; use Utopia\Platform\Action; use Utopia\Registry\Registry; use Utopia\Span\Span; -class UnsubscribeHandler extends Action +class Unsubscribe extends Action { public function __construct() { diff --git a/src/Appwrite/Realtime/Message/Validators/SubscribePayloadValidator.php b/src/Appwrite/Realtime/Message/Validators/SubscribePayload.php similarity index 96% rename from src/Appwrite/Realtime/Message/Validators/SubscribePayloadValidator.php rename to src/Appwrite/Realtime/Message/Validators/SubscribePayload.php index 763a90f49f..d76955d873 100644 --- a/src/Appwrite/Realtime/Message/Validators/SubscribePayloadValidator.php +++ b/src/Appwrite/Realtime/Message/Validators/SubscribePayload.php @@ -4,7 +4,7 @@ namespace Appwrite\Realtime\Message\Validators; use Utopia\Validator; -class SubscribePayloadValidator extends Validator +class SubscribePayload extends Validator { protected string $description = 'Payload is not valid.'; @@ -53,4 +53,4 @@ class SubscribePayloadValidator extends Validator return true; } -} \ No newline at end of file +} diff --git a/src/Appwrite/Realtime/Message/Validators/UnsubscribePayloadValidator.php b/src/Appwrite/Realtime/Message/Validators/UnsubscribePayload.php similarity index 95% rename from src/Appwrite/Realtime/Message/Validators/UnsubscribePayloadValidator.php rename to src/Appwrite/Realtime/Message/Validators/UnsubscribePayload.php index 91c26ac0a2..fca065dec8 100644 --- a/src/Appwrite/Realtime/Message/Validators/UnsubscribePayloadValidator.php +++ b/src/Appwrite/Realtime/Message/Validators/UnsubscribePayload.php @@ -4,7 +4,7 @@ namespace Appwrite\Realtime\Message\Validators; use Utopia\Validator; -class UnsubscribePayloadValidator extends Validator +class UnsubscribePayload extends Validator { protected string $description = 'Payload is not valid.'; From d2ea6ef2cae97bc023cee291c79fbaad3e622706 Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Wed, 6 May 2026 12:33:42 +0530 Subject: [PATCH 13/20] removed redundant dumps --- app/realtime.php | 1 - 1 file changed, 1 deletion(-) diff --git a/app/realtime.php b/app/realtime.php index f20da0291f..a2a61393ca 100644 --- a/app/realtime.php +++ b/app/realtime.php @@ -409,7 +409,6 @@ $container->set('pools', function ($register) { if (!$container->has('queueForEvents')) { $container->set('queueForEvents', function ($pools) { - var_dump("ce"); return new QueueEvent(new BrokerPool( publisher: $pools->get('publisher') )); From f9c18a64622540d4b566a397994188bdb2950ffe Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Wed, 6 May 2026 13:20:19 +0530 Subject: [PATCH 14/20] updated validator subscribe --- .../Message/Validators/SubscribePayload.php | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/Appwrite/Realtime/Message/Validators/SubscribePayload.php b/src/Appwrite/Realtime/Message/Validators/SubscribePayload.php index d76955d873..da99b8c555 100644 --- a/src/Appwrite/Realtime/Message/Validators/SubscribePayload.php +++ b/src/Appwrite/Realtime/Message/Validators/SubscribePayload.php @@ -2,6 +2,7 @@ namespace Appwrite\Realtime\Message\Validators; +use Appwrite\Utopia\Database\Validator\CustomId; use Utopia\Validator; class SubscribePayload extends Validator @@ -30,11 +31,17 @@ class SubscribePayload extends Validator return false; } + $customId = new CustomId(); + foreach ($value as $payload) { if (!\is_array($payload)) { $this->description = 'Each subscribe payload must be an object.'; return false; } + if (\array_key_exists('subscriptionId', $payload) && !$customId->isValid($payload['subscriptionId'])) { + $this->description = 'subscriptionId is not a valid id.'; + return false; + } if (!\array_key_exists('channels', $payload)) { $this->description = 'channels is not present in payload.'; return false; @@ -43,12 +50,15 @@ class SubscribePayload extends Validator $this->description = 'channels is not a valid array.'; return false; } - if (\array_key_exists('queries', $payload) - && (!\is_array($payload['queries']) || !\array_is_list($payload['queries'])) - ) { - $this->description = 'queries is not a valid array.'; - return false; + foreach ($payload['channels'] as $channel) { + if (!\is_string($channel)) { + $this->description = 'channels must contain only strings.'; + return false; + } } + + // not validating queries here as we will be doing it anyways during the controller level + // kind of expensive validating queries twice as we need to check a lot of cases } return true; From ac80ba270bdbbaf0cf2b57675b2fd81835dd16a3 Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Wed, 6 May 2026 13:24:34 +0530 Subject: [PATCH 15/20] updated queries --- .../Realtime/Message/Validators/SubscribePayload.php | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/Appwrite/Realtime/Message/Validators/SubscribePayload.php b/src/Appwrite/Realtime/Message/Validators/SubscribePayload.php index da99b8c555..3e7e5cec10 100644 --- a/src/Appwrite/Realtime/Message/Validators/SubscribePayload.php +++ b/src/Appwrite/Realtime/Message/Validators/SubscribePayload.php @@ -56,9 +56,12 @@ class SubscribePayload extends Validator return false; } } - - // not validating queries here as we will be doing it anyways during the controller level - // kind of expensive validating queries twice as we need to check a lot of cases + if (\array_key_exists('queries', $payload) + && (!\is_array($payload['queries']) || !\array_is_list($payload['queries'])) + ) { + $this->description = 'queries is not a valid array.'; + return false; + } } return true; From 6290a664e9f4b48fd0152e726adb279bf7c0edcd Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Wed, 6 May 2026 14:16:59 +0530 Subject: [PATCH 16/20] refactor: rename presence methods for consistency and clarity --- src/Appwrite/Platform/Modules/Presences/HTTP/Delete.php | 2 +- src/Appwrite/Platform/Modules/Presences/HTTP/Get.php | 2 +- src/Appwrite/Platform/Modules/Presences/HTTP/Update.php | 2 +- src/Appwrite/Platform/Modules/Presences/HTTP/Upsert.php | 2 +- src/Appwrite/Platform/Modules/Presences/HTTP/XList.php | 2 +- tests/e2e/Services/GraphQL/PresenceTest.php | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Appwrite/Platform/Modules/Presences/HTTP/Delete.php b/src/Appwrite/Platform/Modules/Presences/HTTP/Delete.php index 6963bda7d2..2d3950645f 100644 --- a/src/Appwrite/Platform/Modules/Presences/HTTP/Delete.php +++ b/src/Appwrite/Platform/Modules/Presences/HTTP/Delete.php @@ -39,7 +39,7 @@ class Delete extends PlatformAction ->label('sdk', new Method( namespace: 'presences', group: 'presences', - name: 'deletePresence', + name: 'delete', description: 'Delete a presence log by its unique ID.', auth: [AuthType::ADMIN, AuthType::KEY, AuthType::SESSION, AuthType::JWT], responses: [ diff --git a/src/Appwrite/Platform/Modules/Presences/HTTP/Get.php b/src/Appwrite/Platform/Modules/Presences/HTTP/Get.php index 058cb2fa6f..6c6f02e1ab 100644 --- a/src/Appwrite/Platform/Modules/Presences/HTTP/Get.php +++ b/src/Appwrite/Platform/Modules/Presences/HTTP/Get.php @@ -33,7 +33,7 @@ class Get extends PlatformAction ->label('sdk', new Method( namespace: 'presences', group: 'presences', - name: 'getPresence', + name: 'get', description: 'Get a presence log by its unique ID.', auth: [AuthType::ADMIN, AuthType::KEY, AuthType::SESSION, AuthType::JWT], responses: [ diff --git a/src/Appwrite/Platform/Modules/Presences/HTTP/Update.php b/src/Appwrite/Platform/Modules/Presences/HTTP/Update.php index 336264730d..f59e85c0ed 100644 --- a/src/Appwrite/Platform/Modules/Presences/HTTP/Update.php +++ b/src/Appwrite/Platform/Modules/Presences/HTTP/Update.php @@ -50,7 +50,7 @@ class Update extends PlatformAction new Method( namespace: 'presences', group: 'presences', - name: 'updatePresence', + name: 'update', description: 'Update a presence log by its unique ID.', auth: [AuthType::SESSION], responses: [ diff --git a/src/Appwrite/Platform/Modules/Presences/HTTP/Upsert.php b/src/Appwrite/Platform/Modules/Presences/HTTP/Upsert.php index 0be1c58402..e4a6e20da0 100644 --- a/src/Appwrite/Platform/Modules/Presences/HTTP/Upsert.php +++ b/src/Appwrite/Platform/Modules/Presences/HTTP/Upsert.php @@ -73,7 +73,7 @@ class Upsert extends PlatformAction new Method( namespace: 'presences', group: 'presences', - name: 'upsertPresence', + name: 'upsert', description: 'Create or update a presence log by its unique ID.', auth: [AuthType::KEY, AuthType::JWT, AuthType::ADMIN], responses: [ diff --git a/src/Appwrite/Platform/Modules/Presences/HTTP/XList.php b/src/Appwrite/Platform/Modules/Presences/HTTP/XList.php index 94710715cc..19883181a5 100644 --- a/src/Appwrite/Platform/Modules/Presences/HTTP/XList.php +++ b/src/Appwrite/Platform/Modules/Presences/HTTP/XList.php @@ -43,7 +43,7 @@ class XList extends PlatformAction ->label('sdk', new Method( namespace: 'presences', group: 'presences', - name: 'listPresences', + name: 'list', description: 'List presence logs.', auth: [AuthType::ADMIN, AuthType::KEY, AuthType::SESSION, AuthType::JWT], responses: [ diff --git a/tests/e2e/Services/GraphQL/PresenceTest.php b/tests/e2e/Services/GraphQL/PresenceTest.php index d1fb786ac5..7fa5474e83 100644 --- a/tests/e2e/Services/GraphQL/PresenceTest.php +++ b/tests/e2e/Services/GraphQL/PresenceTest.php @@ -22,7 +22,7 @@ class PresenceTest extends Scope $payload = [ 'query' => <<<'GQL' mutation upsertPresence($presenceId: String!, $userId: String!, $status: String!, $metadata: Json) { - presencesUpsertPresence(presenceId: $presenceId, userId: $userId, status: $status, metadata: $metadata) { + presencesUpsert(presenceId: $presenceId, userId: $userId, status: $status, metadata: $metadata) { _id userId status From 63e226c7612030abdf6b904df78a59deba8450e5 Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Wed, 6 May 2026 14:50:40 +0530 Subject: [PATCH 17/20] updated Co-authored-by: Copilot --- src/Appwrite/Platform/Modules/Presences/HTTP/Upsert.php | 2 +- tests/e2e/Services/GraphQL/PresenceTest.php | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Appwrite/Platform/Modules/Presences/HTTP/Upsert.php b/src/Appwrite/Platform/Modules/Presences/HTTP/Upsert.php index e4a6e20da0..65a184a805 100644 --- a/src/Appwrite/Platform/Modules/Presences/HTTP/Upsert.php +++ b/src/Appwrite/Platform/Modules/Presences/HTTP/Upsert.php @@ -52,7 +52,7 @@ class Upsert extends PlatformAction new Method( namespace: 'presences', group: 'presences', - name: 'upsertPresence', + name: 'upsert', description: 'Create or update a presence log by its unique ID.', auth: [AuthType::SESSION], responses: [ diff --git a/tests/e2e/Services/GraphQL/PresenceTest.php b/tests/e2e/Services/GraphQL/PresenceTest.php index 7fa5474e83..6087b19bde 100644 --- a/tests/e2e/Services/GraphQL/PresenceTest.php +++ b/tests/e2e/Services/GraphQL/PresenceTest.php @@ -21,7 +21,7 @@ class PresenceTest extends Scope $payload = [ 'query' => <<<'GQL' - mutation upsertPresence($presenceId: String!, $userId: String!, $status: String!, $metadata: Json) { + mutation upsert($presenceId: String!, $userId: String!, $status: String!, $metadata: Json) { presencesUpsert(presenceId: $presenceId, userId: $userId, status: $status, metadata: $metadata) { _id userId @@ -46,7 +46,7 @@ class PresenceTest extends Scope 'x-appwrite-key' => $apiKey, ], $payload); $this->assertEquals(200, $response['headers']['status-code']); - $this->assertEquals('online', $response['body']['data']['presencesUpsertPresence']['status']); - $this->assertEquals('graphql', $response['body']['data']['presencesUpsertPresence']['source']); + $this->assertEquals('online', $response['body']['data']['presencesUpsert']['status']); + $this->assertEquals('graphql', $response['body']['data']['presencesUpsert']['source']); } } From 6679d02a3558997e125dee24e25e399411db2f06 Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Thu, 7 May 2026 11:48:45 +0530 Subject: [PATCH 18/20] refactor: rename connection to connectionId for consistency across handlers --- app/realtime.php | 2 +- .../Message/Handlers/Authentication.php | 22 +++++++++---------- .../Realtime/Message/Handlers/Presence.php | 10 ++++----- .../Realtime/Message/Handlers/Subscribe.php | 14 ++++++------ .../Realtime/Message/Handlers/Unsubscribe.php | 10 ++++----- 5 files changed, 29 insertions(+), 29 deletions(-) diff --git a/app/realtime.php b/app/realtime.php index a2a61393ca..a0572c70ff 100644 --- a/app/realtime.php +++ b/app/realtime.php @@ -1218,7 +1218,7 @@ $server->onMessage(function (int $connection, string $message) use ($container, // while globally-registered services (pools, queueForRealtime, ...) remain reachable // via the parent. $messageContainer = new Container($container); - $messageContainer->set('connection', fn () => $connection); + $messageContainer->set('connectionId', fn () => $connection); $messageContainer->set('server', fn () => $server); $messageContainer->set('realtime', fn () => $realtime); $messageContainer->set('register', fn () => $register); diff --git a/src/Appwrite/Realtime/Message/Handlers/Authentication.php b/src/Appwrite/Realtime/Message/Handlers/Authentication.php index cdb0fe7bbe..f738d84a23 100644 --- a/src/Appwrite/Realtime/Message/Handlers/Authentication.php +++ b/src/Appwrite/Realtime/Message/Handlers/Authentication.php @@ -25,7 +25,7 @@ class Authentication extends Action ->desc('Authenticate the connection with a session token') ->label(Dispatcher::LABEL_MESSAGE_TYPE, 'authentication') ->param('session', '', new Text(2048), 'Encoded session token') - ->inject('connection') + ->inject('connectionId') ->inject('realtime') ->inject('database') ->inject('register') @@ -38,7 +38,7 @@ class Authentication extends Action */ public function action( string $session, - int $connection, + int $connectionId, Realtime $realtime, Database $database, Registry $register, @@ -63,16 +63,16 @@ class Authentication extends Action $roles = $user->getRoles($database->getAuthorization()); - $authorization = $realtime->connections[$connection]['authorization'] ?? null; - $projectId = $realtime->connections[$connection]['projectId'] ?? null; + $authorization = $realtime->connections[$connectionId]['authorization'] ?? null; + $projectId = $realtime->connections[$connectionId]['projectId'] ?? null; // Capture the pre-auth userId before unsubscribe() clears the connection entry, // so we can rebind any account channels that were stored under it. - $previousUserId = $realtime->connections[$connection]['userId'] ?? ''; + $previousUserId = $realtime->connections[$connectionId]['userId'] ?? ''; - $subscriptionsBefore = \count($realtime->getSubscriptionMetadata($connection)); - $meta = $realtime->getSubscriptionMetadata($connection); + $subscriptionsBefore = \count($realtime->getSubscriptionMetadata($connectionId)); + $meta = $realtime->getSubscriptionMetadata($connectionId); - $realtime->unsubscribe($connection); + $realtime->unsubscribe($connectionId); if (!empty($projectId)) { foreach ($meta as $subscriptionId => $subscription) { @@ -85,7 +85,7 @@ class Authentication extends Action $realtime->subscribe( $projectId, - $connection, + $connectionId, $subscriptionId, $roles, $channels, @@ -96,10 +96,10 @@ class Authentication extends Action } if ($authorization !== null) { - $realtime->connections[$connection]['authorization'] = $authorization; + $realtime->connections[$connectionId]['authorization'] = $authorization; } - $subscriptionsAfter = \count($realtime->getSubscriptionMetadata($connection)); + $subscriptionsAfter = \count($realtime->getSubscriptionMetadata($connectionId)); $subscriptionDelta = $subscriptionsAfter - $subscriptionsBefore; if ($subscriptionDelta !== 0) { $register->get('telemetry.workerSubscriptionCounter') diff --git a/src/Appwrite/Realtime/Message/Handlers/Presence.php b/src/Appwrite/Realtime/Message/Handlers/Presence.php index 1d373e172c..fbab6ec70e 100644 --- a/src/Appwrite/Realtime/Message/Handlers/Presence.php +++ b/src/Appwrite/Realtime/Message/Handlers/Presence.php @@ -27,7 +27,7 @@ class Presence extends Action ->param('presenceId', 'unique()', new Text(36), 'Presence document ID', true) ->param('metadata', null, new JSON(), 'Optional metadata payload', true, [], true) ->param('permissions', null, new ArrayList(new Text(2048)), 'Optional permissions list', true) - ->inject('connection') + ->inject('connectionId') ->inject('realtime') ->inject('database') ->inject('authorization') @@ -49,7 +49,7 @@ class Presence extends Action string $presenceId, mixed $metadata, ?array $permissions, - int $connection, + int $connectionId, Realtime $realtime, Database $database, Authorization $authorization, @@ -62,7 +62,7 @@ class Presence extends Action throw new Exception(Exception::REALTIME_POLICY_VIOLATION, 'Presence requires a project context.'); } - $userId = $realtime->connections[$connection]['userId'] ?? ''; + $userId = $realtime->connections[$connectionId]['userId'] ?? ''; if (empty($userId)) { throw new Exception(Exception::USER_UNAUTHORIZED, 'User must be authorized'); } @@ -98,8 +98,8 @@ class Presence extends Action $presence->removeAttribute('hostname'); - $realtime->connections[$connection]['presences'] = \array_merge( - $realtime->connections[$connection]['presences'] ?? [], + $realtime->connections[$connectionId]['presences'] = \array_merge( + $realtime->connections[$connectionId]['presences'] ?? [], [$presence->getId()], ); diff --git a/src/Appwrite/Realtime/Message/Handlers/Subscribe.php b/src/Appwrite/Realtime/Message/Handlers/Subscribe.php index c32ad4f702..76a4e5d3b8 100644 --- a/src/Appwrite/Realtime/Message/Handlers/Subscribe.php +++ b/src/Appwrite/Realtime/Message/Handlers/Subscribe.php @@ -22,7 +22,7 @@ class Subscribe extends Action ->label(Dispatcher::LABEL_MESSAGE_TYPE, 'subscribe') ->label(Dispatcher::LABEL_PAYLOAD_SHAPE, Dispatcher::PAYLOAD_SHAPE_LIST) ->param('items', null, fn () => new SubscribePayloadValidator(), 'Subscriptions to add') - ->inject('connection') + ->inject('connectionId') ->inject('realtime') ->inject('register') ->inject('projectId') @@ -35,16 +35,16 @@ class Subscribe extends Action */ public function action( array $items, - int $connection, + int $connectionId, Realtime $realtime, Registry $register, ?string $projectId, ): array { - $roles = $realtime->connections[$connection]['roles'] ?? [Role::guests()->toString()]; - $userId = $realtime->connections[$connection]['userId'] ?? ''; + $roles = $realtime->connections[$connectionId]['roles'] ?? [Role::guests()->toString()]; + $userId = $realtime->connections[$connectionId]['userId'] ?? ''; $parsedPayloads = []; - $subscriptionsBefore = \count($realtime->getSubscriptionMetadata($connection)); + $subscriptionsBefore = \count($realtime->getSubscriptionMetadata($connectionId)); foreach ($items as $payload) { $subscriptionId = \array_key_exists('subscriptionId', $payload) @@ -72,7 +72,7 @@ class Subscribe extends Action foreach ($parsedPayloads as $parsedPayload) { $realtime->subscribe( $projectId, - $connection, + $connectionId, $parsedPayload['subscriptionId'], $roles, $parsedPayload['convertedChannels'], @@ -80,7 +80,7 @@ class Subscribe extends Action ); } - $subscriptionsAfter = \count($realtime->getSubscriptionMetadata($connection)); + $subscriptionsAfter = \count($realtime->getSubscriptionMetadata($connectionId)); $subscriptionDelta = $subscriptionsAfter - $subscriptionsBefore; $subscriptionsRequested = \count($parsedPayloads); diff --git a/src/Appwrite/Realtime/Message/Handlers/Unsubscribe.php b/src/Appwrite/Realtime/Message/Handlers/Unsubscribe.php index 469d2145dd..1e23a40a7f 100644 --- a/src/Appwrite/Realtime/Message/Handlers/Unsubscribe.php +++ b/src/Appwrite/Realtime/Message/Handlers/Unsubscribe.php @@ -18,7 +18,7 @@ class Unsubscribe extends Action ->label(Dispatcher::LABEL_MESSAGE_TYPE, 'unsubscribe') ->label(Dispatcher::LABEL_PAYLOAD_SHAPE, Dispatcher::PAYLOAD_SHAPE_LIST) ->param('items', null, fn () => new UnsubscribePayloadValidator(), 'Subscriptions to remove') - ->inject('connection') + ->inject('connectionId') ->inject('realtime') ->inject('register') ->callback($this->action(...)); @@ -30,22 +30,22 @@ class Unsubscribe extends Action */ public function action( array $items, - int $connection, + int $connectionId, Realtime $realtime, Registry $register, ): array { - $subscriptionsBefore = \count($realtime->getSubscriptionMetadata($connection)); + $subscriptionsBefore = \count($realtime->getSubscriptionMetadata($connectionId)); $unsubscribeResults = []; foreach ($items as $payload) { $subscriptionId = $payload['subscriptionId']; $unsubscribeResults[] = [ 'subscriptionId' => $subscriptionId, - 'removed' => $realtime->unsubscribeSubscription($connection, $subscriptionId), + 'removed' => $realtime->unsubscribeSubscription($connectionId, $subscriptionId), ]; } - $subscriptionsAfter = \count($realtime->getSubscriptionMetadata($connection)); + $subscriptionsAfter = \count($realtime->getSubscriptionMetadata($connectionId)); $subscriptionDelta = $subscriptionsAfter - $subscriptionsBefore; $subscriptionsRequested = \count($items); $subscriptionsRemoved = \count(\array_filter( From ce07c6ffd5830821be602f7cb1a71a40868584e5 Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Thu, 7 May 2026 12:24:42 +0530 Subject: [PATCH 19/20] added type error to the subscribe handler --- src/Appwrite/Realtime/Message/Handlers/Subscribe.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Appwrite/Realtime/Message/Handlers/Subscribe.php b/src/Appwrite/Realtime/Message/Handlers/Subscribe.php index 76a4e5d3b8..8620a121b5 100644 --- a/src/Appwrite/Realtime/Message/Handlers/Subscribe.php +++ b/src/Appwrite/Realtime/Message/Handlers/Subscribe.php @@ -57,6 +57,8 @@ class Subscribe extends Action $convertedQueries = Realtime::convertQueries($queries); } catch (QueryException $e) { throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Invalid query: ' . $e->getMessage()); + } catch (\TypeError $e) { + throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Invalid query: query elements must be strings.'); } $convertedChannels = \array_keys(Realtime::convertChannels($payload['channels'], $userId)); From ec8d48327c2e9dd642fd2b5a03270b394acd7a8c Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Thu, 7 May 2026 12:34:34 +0530 Subject: [PATCH 20/20] reverted type error as query exception only thown --- src/Appwrite/Realtime/Message/Handlers/Subscribe.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/Appwrite/Realtime/Message/Handlers/Subscribe.php b/src/Appwrite/Realtime/Message/Handlers/Subscribe.php index 8620a121b5..76a4e5d3b8 100644 --- a/src/Appwrite/Realtime/Message/Handlers/Subscribe.php +++ b/src/Appwrite/Realtime/Message/Handlers/Subscribe.php @@ -57,8 +57,6 @@ class Subscribe extends Action $convertedQueries = Realtime::convertQueries($queries); } catch (QueryException $e) { throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Invalid query: ' . $e->getMessage()); - } catch (\TypeError $e) { - throw new Exception(Exception::REALTIME_MESSAGE_FORMAT_INVALID, 'Invalid query: query elements must be strings.'); } $convertedChannels = \array_keys(Realtime::convertChannels($payload['channels'], $userId));