From 2ce39768c3f913633beda3be450dbc250a4462bf Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Wed, 15 Apr 2026 13:38:34 +0530 Subject: [PATCH] added delete of presence on disconnect --- app/realtime.php | 25 +++++++++++++++++++++ src/Appwrite/Messaging/Adapter/Realtime.php | 4 +++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/app/realtime.php b/app/realtime.php index 28581b5e53..9b1de14a2f 100644 --- a/app/realtime.php +++ b/app/realtime.php @@ -1166,6 +1166,8 @@ $server->onMessage(function (int $connection, string $message) use ($server, $re $presence->removeAttribute('hostname'); + $realtime->connections[$connection]['presences'] = array_merge($realtime->connections[$connection]['presences'] ?? [], [$presence->getId()]); + $responsePayload = json_encode([ 'type' => 'response', 'data' => [ @@ -1228,6 +1230,29 @@ $server->onClose(function (int $connection) use ($realtime, $stats, $register) { $register->get('telemetry.connectionCounter')->add(-1); $projectId = $realtime->connections[$connection]['projectId']; + $presenceIds = $realtime->connections[$connection]['presences'] ?? []; + + if ( + !empty($presenceIds) + && $projectId !== 'console' + ) { + /** @var string[] $presenceIds */ + $presenceIds = \array_values(\array_unique(\array_filter($presenceIds, fn (mixed $id): bool => \is_string($id) && $id !== ''))); + + if (!empty($presenceIds)) { + $consoleDB = getConsoleDB(); + $project = $consoleDB->getAuthorization()->skip(fn () => $consoleDB->getDocument('projects', $projectId)); + + if (!$project->isEmpty()) { + $dbForProject = getProjectDB($project); + $dbForProject->deleteDocuments('presenceLogs', [ + Query::equal('$id', $presenceIds), + ], onError: function (Throwable $th) { + // Swallow errors to avoid breaking disconnect cleanup + }); + } + } + } triggerStats([ METRIC_REALTIME_CONNECTIONS => -1, diff --git a/src/Appwrite/Messaging/Adapter/Realtime.php b/src/Appwrite/Messaging/Adapter/Realtime.php index f1d806bcc5..d5ac905fd1 100644 --- a/src/Appwrite/Messaging/Adapter/Realtime.php +++ b/src/Appwrite/Messaging/Adapter/Realtime.php @@ -22,6 +22,7 @@ class Realtime extends MessagingAdapter * 'roles' -> [ROLE_x, ROLE_Y] * 'userId' -> [USER_ID] * 'channels' -> [CHANNEL_NAME_X, CHANNEL_NAME_Y, CHANNEL_NAME_Z] + * 'presences' -> [PRESENCE_ID_1, PRESENCE_ID_2, ...] */ public array $connections = []; @@ -120,7 +121,8 @@ class Realtime extends MessagingAdapter 'projectId' => $projectId, 'roles' => $roles, 'userId' => $userId ?? ($this->connections[$identifier]['userId'] ?? ''), - 'channels' => $channels + 'channels' => $channels, + 'presences' => $this->connections[$identifier]['presences'] ?? [] ]; }