-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathActiveConnections.php
More file actions
84 lines (75 loc) · 2.15 KB
/
ActiveConnections.php
File metadata and controls
84 lines (75 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\ServerInfo;
use OCP\IDBConnection;
class ActiveConnections {
public function __construct(
private IDBConnection $db,
) {
}
/**
* Approximate active sessions/connections by counting auth tokens
* with recent activity. Each token corresponds to one client (browser
* tab, mobile app, desktop client, etc.).
*
* @return array{
* last5min: int,
* last1h: int,
* totalTokens: int,
* byType: array<string, int>
* }
*/
public function getActiveConnections(): array {
try {
return [
'last5min' => $this->countSince(time() - 300),
'last1h' => $this->countSince(time() - 3600),
'totalTokens' => $this->countTotal(),
'byType' => $this->byType(),
];
} catch (\Throwable) {
return ['last5min' => 0, 'last1h' => 0, 'totalTokens' => 0, 'byType' => []];
}
}
private function countSince(int $ts): int {
$qb = $this->db->getQueryBuilder();
$qb->select($qb->func()->count('id'))
->from('authtoken')
->where($qb->expr()->gte('last_activity', $qb->createNamedParameter($ts)));
$result = $qb->executeQuery();
$count = (int)$result->fetchOne();
$result->closeCursor();
return $count;
}
private function countTotal(): int {
$qb = $this->db->getQueryBuilder();
$qb->select($qb->func()->count('id'))->from('authtoken');
$result = $qb->executeQuery();
$count = (int)$result->fetchOne();
$result->closeCursor();
return $count;
}
/**
* @return array<string, int>
*/
private function byType(): array {
$qb = $this->db->getQueryBuilder();
$qb->select('type')
->selectAlias($qb->func()->count('id'), 'count')
->from('authtoken')
->where($qb->expr()->gte('last_activity', $qb->createNamedParameter(time() - 3600)))
->groupBy('type');
$result = $qb->executeQuery();
$out = ['session' => 0, 'permanent' => 0];
while (($row = $result->fetch()) !== false) {
$type = (int)($row['type'] ?? 0) === 0 ? 'session' : 'permanent';
$out[$type] = (int)($row['count'] ?? 0);
}
$result->closeCursor();
return $out;
}
}