Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions src/ActiveSync/Ops/DeviceLogPathResolver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

declare(strict_types=1);

/**
* Copyright 2026 The Horde Project (http://www.horde.org/)
*
* See the enclosed file LICENSE for license information (LGPL). If you
* did not receive this file, see http://www.horde.org/licenses/lgpl21.
*
* @author Torben Dannhauer <torben@dannhauer.de>
* @category Horde
* @copyright 2026 The Horde Project
* @license http://www.horde.org/licenses/lgpl21 LGPL 2.1
* @package Core
*/

namespace Horde\Core\ActiveSync\Ops;

use Horde\Util\HordeString;

final class DeviceLogPathResolver
{
public function __construct(
private readonly ?string $loggingType,
private readonly ?string $loggingPath
) {
}

public function resolve(string $deviceId): ?string
{
if ($this->loggingType !== 'perdevice'
|| $this->loggingPath === null
|| $this->loggingPath === '') {
return null;
}

return rtrim($this->loggingPath, '/')
. '/'
. HordeString::upper($deviceId)
. '.txt';
}
}
46 changes: 46 additions & 0 deletions src/ActiveSync/Ops/FleetSnapshot.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

declare(strict_types=1);

/**
* Copyright 2026 The Horde Project (http://www.horde.org/)
*
* See the enclosed file LICENSE for license information (LGPL). If you
* did not receive this file, see http://www.horde.org/licenses/lgpl21.
*
* @author Torben Dannhauer <torben@dannhauer.de>
* @category Horde
* @copyright 2026 The Horde Project
* @license http://www.horde.org/licenses/lgpl21 LGPL 2.1
* @package Core
*/

namespace Horde\Core\ActiveSync\Ops;

use Horde\ActiveSync\Ops\DeviceHealth;
use Horde\ActiveSync\Ops\FleetSummary;

final class FleetSnapshot
{
/**
* @param DeviceHealth[] $devices
*/
public function __construct(
public readonly FleetSummary $summary,
public readonly array $devices,
public readonly int $asOf
) {
}

public function toArray(): array
{
return [
'summary' => $this->summary->toArray(),
'devices' => array_map(
static fn (DeviceHealth $device): array => $device->toArray(),
$this->devices
),
'asOf' => $this->asOf,
];
}
}
73 changes: 73 additions & 0 deletions src/ActiveSync/Ops/SnapshotCriteria.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

declare(strict_types=1);

/**
* Copyright 2026 The Horde Project (http://www.horde.org/)
*
* See the enclosed file LICENSE for license information (LGPL). If you
* did not receive this file, see http://www.horde.org/licenses/lgpl21.
*
* @author Torben Dannhauer <torben@dannhauer.de>
* @category Horde
* @copyright 2026 The Horde Project
* @license http://www.horde.org/licenses/lgpl21 LGPL 2.1
* @package Core
*/

namespace Horde\Core\ActiveSync\Ops;

use Horde\ActiveSync\Ops\HealthOptions;
use Horde\ActiveSync\Ops\HealthStatus;
use InvalidArgumentException;

final class SnapshotCriteria
{
public const SORT_AGE = 'age';
public const SORT_USER = 'user';
public const SORT_HEALTH = 'health';
public const SORT_DEVICE = 'device';

public function __construct(
public readonly ?string $user = null,
public readonly ?string $deviceId = null,
public readonly ?int $activeWithin = null,
public readonly ?string $healthMin = null,
public readonly bool $stuckOnly = false,
public readonly int $limit = 100,
public readonly string $sort = self::SORT_AGE
) {
if ($healthMin !== null && !HealthStatus::isValid($healthMin)) {
throw new InvalidArgumentException(
sprintf('Unknown health status: %s', $healthMin)
);
}

if (!in_array($sort, [
self::SORT_AGE,
self::SORT_USER,
self::SORT_HEALTH,
self::SORT_DEVICE,
], true)) {
throw new InvalidArgumentException(
sprintf('Unknown snapshot sort: %s', $sort)
);
}

if ($limit < 0) {
throw new InvalidArgumentException('Snapshot limit cannot be negative.');
}
}

public function toHealthOptions(int $now): HealthOptions
{
if ($this->activeWithin === null) {
return new HealthOptions(now: $now);
}

return new HealthOptions(
now: $now,
activeWithin: $this->activeWithin
);
}
}
181 changes: 181 additions & 0 deletions src/ActiveSync/Ops/SnapshotService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
<?php

declare(strict_types=1);

/**
* Copyright 2026 The Horde Project (http://www.horde.org/)
*
* See the enclosed file LICENSE for license information (LGPL). If you
* did not receive this file, see http://www.horde.org/licenses/lgpl21.
*
* @author Torben Dannhauer <torben@dannhauer.de>
* @category Horde
* @copyright 2026 The Horde Project
* @license http://www.horde.org/licenses/lgpl21 LGPL 2.1
* @package Core
*/

namespace Horde\Core\ActiveSync\Ops;

use Closure;
use Horde\ActiveSync\Ops\DeviceHealth;
use Horde\ActiveSync\Ops\DeviceHealthFactory;
use Horde\ActiveSync\Ops\FleetSummary;
use Horde\ActiveSync\Ops\HealthEvaluator;
use Horde\ActiveSync\Ops\HealthOptions;
use Horde\ActiveSync\Ops\HealthStatus;
use Horde_ActiveSync_State_Base;
use Horde_Exception;
use Horde_Exception_NotFound;
use Horde_Log_Logger;

final class SnapshotService
{
private readonly Closure $factoryBuilder;
private readonly Closure $clock;

public function __construct(
private readonly Horde_ActiveSync_State_Base $state,
private readonly DeviceLogPathResolver $logPaths,
private readonly ?Horde_Log_Logger $logger = null,
?callable $factoryBuilder = null,
?callable $clock = null
) {
$this->factoryBuilder = Closure::fromCallable(
$factoryBuilder
?? static fn (HealthOptions $options): DeviceHealthFactory =>
new DeviceHealthFactory(new HealthEvaluator($options))
);
$this->clock = Closure::fromCallable($clock ?? time(...));
}

public function summary(SnapshotCriteria $criteria): FleetSummary
{
return $this->fleet($criteria)->summary;
}

public function fleet(SnapshotCriteria $criteria): FleetSnapshot
{
$now = ($this->clock)();
$factory = ($this->factoryBuilder)($criteria->toHealthOptions($now));
$filter = $criteria->deviceId === null
? []
: ['device_id' => $criteria->deviceId];
$devices = [];

foreach ($this->state->listDevices($criteria->user, $filter) as $row) {
$deviceId = (string) ($row['device_id'] ?? '');
$user = (string) ($row['device_user'] ?? '');

try {
$cache = $this->state->getSyncCache($deviceId, $user);
} catch (Horde_Exception $e) {
$this->logger?->warn($e);
continue;
}

// SyncCache timestamp is the fleet activity proxy. Loading the
// separate last-sync timestamp per row would add another query.
$health = $factory
->fromRow($row, $cache, null)
->withLogPath($this->logPaths->resolve($deviceId));

if (!$this->matches($health, $criteria)) {
continue;
}

$devices[] = $health;
}

$summary = FleetSummary::fromDevices($devices, $now);
$this->sort($devices, $criteria->sort);

if ($criteria->limit > 0) {
$devices = array_slice($devices, 0, $criteria->limit);
}

return new FleetSnapshot($summary, $devices, $now);
}

public function device(string $user, string $deviceId): DeviceHealth
{
foreach ($this->state->listDevices(
$user,
['device_id' => $deviceId]
) as $row) {
if ((string) ($row['device_id'] ?? '') !== $deviceId
|| (string) ($row['device_user'] ?? '') !== $user) {
continue;
}

$cache = $this->state->getSyncCache($deviceId, $user);
$lastSync = $this->state->getLastSyncTimestamp($deviceId, $user);
$now = ($this->clock)();
$factory = ($this->factoryBuilder)(
(new SnapshotCriteria())->toHealthOptions($now)
);

return $factory
->fromRow($row, $cache, $lastSync)
->withLogPath($this->logPaths->resolve($deviceId));
}

throw new Horde_Exception_NotFound(
sprintf('ActiveSync device %s was not found for %s.', $deviceId, $user)
);
}

private function matches(
DeviceHealth $health,
SnapshotCriteria $criteria
): bool {
if ($criteria->healthMin !== null
&& HealthStatus::rank($health->status)
< HealthStatus::rank($criteria->healthMin)) {
return false;
}

return !$criteria->stuckOnly || $health->isStuck();
}

/**
* @param DeviceHealth[] $devices
*/
private function sort(array &$devices, string $sort): void
{
usort(
$devices,
match ($sort) {
SnapshotCriteria::SORT_USER =>
static fn (DeviceHealth $a, DeviceHealth $b): int =>
strnatcasecmp($a->user, $b->user)
?: strnatcasecmp($a->deviceId, $b->deviceId),
SnapshotCriteria::SORT_HEALTH =>
static fn (DeviceHealth $a, DeviceHealth $b): int =>
HealthStatus::rank($b->status)
<=> HealthStatus::rank($a->status)
?: self::compareAge($a, $b),
SnapshotCriteria::SORT_DEVICE =>
static fn (DeviceHealth $a, DeviceHealth $b): int =>
strnatcasecmp($a->deviceId, $b->deviceId),
default =>
static fn (DeviceHealth $a, DeviceHealth $b): int =>
self::compareAge($a, $b),
}
);
}

private static function compareAge(
DeviceHealth $a,
DeviceHealth $b
): int {
if ($a->ageSeconds === null) {
return $b->ageSeconds === null ? 0 : 1;
}
if ($b->ageSeconds === null) {
return -1;
}

return $a->ageSeconds <=> $b->ageSeconds;
}
}
3 changes: 3 additions & 0 deletions src/DefaultInjectorBindings.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

namespace Horde\Core;

use Horde\Core\ActiveSync\Ops\SnapshotService;
use Horde\Core\Api\ApiRegistry;
use Horde\Core\Auth\AuthService;
use Horde\Core\Config\ConfigLoader;
Expand All @@ -26,6 +27,7 @@
use Horde\Core\Config\State;
use Horde\Core\Config\StateFactory;
use Horde\Core\Editor\TinymcePageBinder;
use Horde\Core\Factory\ActiveSyncOpsSnapshotFactory;
use Horde\Core\Factory\ApiRegistryFactory;
use Horde\Core\Factory\ApplicationServiceFactory;
use Horde\Core\Factory\AuthBaseFactory;
Expand Down Expand Up @@ -171,6 +173,7 @@ public function register(Injector $injector): void
'Horde_ActiveSyncBackend' => 'Horde_Core_Factory_ActiveSyncBackend',
'Horde_ActiveSyncServer' => 'Horde_Core_Factory_ActiveSyncServer',
'Horde_ActiveSyncState' => 'Horde_Core_Factory_ActiveSyncState',
SnapshotService::class => ActiveSyncOpsSnapshotFactory::class,
'Horde_Alarm' => 'Horde_Core_Factory_Alarm',
'Horde_Browser' => 'Horde_Core_Factory_Browser',
'Horde_Cache' => 'Horde_Core_Factory_Cache',
Expand Down
Loading
Loading