refactor(abuse): remove projection worker stage

go
codex 1 week ago
parent e58839ea3c
commit 977895f6e5

@ -3,35 +3,26 @@
namespace App\Command;
use App\Services\Cloud\CloudAbuseObservationIngestService;
use App\Services\Cloud\CloudAbuseProjectionService;
use App\Services\Cloud\CloudAbuseRetentionService;
use App\Services\Cloud\CloudRuntimeHeartbeat;
/**
* Independent, observe-only network-abuse monitor.
*
* Collection and projection deliberately stay outside cloud_jobs: every host
* call is read-only and every database write is an idempotent telemetry or
* read-model update. No lifecycle, billing, firewall or task mutation belongs
* in this loop.
* Collection deliberately stays outside cloud_jobs: every host call is
* read-only and every database write is an atomic telemetry/read-model
* update. No lifecycle, billing, firewall or task mutation belongs here.
*/
final class CloudAbuseMonitor
{
private const PROJECTION_BURST = 64;
private const RETENTION_INTERVAL_SECONDS = 300;
private const IDLE_SLEEP_MICROSECONDS = 1_000_000;
private const SAFE_PROJECTION_DIAGNOSTICS = [
'instance_deleted',
'instance_owner_changed',
'projection_receipt_baseline_reset',
];
/**
* Injectable objects and clock keep the command testable without turning
* the production services into interfaces solely for the command layer.
*
* @param null|object $ingest must expose tick() and observationErrors()
* @param null|object $projection must expose tick() and observationErrors()
* @param null|object $retention must expose prune()
* @param null|callable():int $clock
* @param null|callable(int):void $sleep
@ -40,7 +31,6 @@ final class CloudAbuseMonitor
array $argv = [],
?CloudRuntimeHeartbeat $heartbeat = null,
?object $ingest = null,
?object $projection = null,
?object $retention = null,
?callable $clock = null,
?callable $sleep = null
@ -51,20 +41,17 @@ final class CloudAbuseMonitor
$once
);
$ingest ??= new CloudAbuseObservationIngestService();
$projection ??= new CloudAbuseProjectionService();
$retention ??= new CloudAbuseRetentionService();
$clock ??= static fn (): int => time();
$sleep ??= static function (int $microseconds): void {
usleep($microseconds);
};
self::assertWorker($ingest, ['tick', 'observationErrors']);
self::assertWorker($projection, ['tick', 'observationErrors']);
self::assertWorker($retention, ['prune']);
$nextRetentionAt = 0;
$unresolved = [
'collection' => '',
'projection' => '',
'retention' => '',
];
try {
@ -83,29 +70,6 @@ final class CloudAbuseMonitor
self::writeFailure('collection', $error);
}
$heartbeat->busy('abuse_monitor_projection');
try {
$projectionFailed = false;
for ($projected = 0;
$projected < self::PROJECTION_BURST;
$projected++
) {
if ($projection->tick() !== true) {
break;
}
$worked = true;
$projectionFailed = self::hasProjectionFailure(
$projection->observationErrors()
) || $projectionFailed;
}
$unresolved['projection'] = $projectionFailed
? 'abuse_monitor_projection_failed' : '';
} catch (\Throwable $error) {
$unresolved['projection'] =
'abuse_monitor_projection_failed';
self::writeFailure('projection', $error);
}
$now = $clock();
if (!is_int($now) || $now < 1) {
throw new \LogicException(
@ -180,19 +144,4 @@ final class CloudAbuseMonitor
);
}
/** @param list<mixed> $diagnostics */
private static function hasProjectionFailure(array $diagnostics): bool
{
foreach ($diagnostics as $diagnostic) {
if (!is_string($diagnostic)
|| !in_array(
$diagnostic,
self::SAFE_PROJECTION_DIAGNOSTICS,
true
)) {
return true;
}
}
return false;
}
}

@ -31,7 +31,6 @@ final class CloudRuntimeHeartbeat
'storage_publication_tick' => '对象存储业务目录最终化',
'storage_health_probe' => '对象存储健康探测',
'abuse_monitor_ingest' => '网络观测采集',
'abuse_monitor_projection' => '网络风险投影',
'abuse_monitor_retention' => '网络观测保留清理',
'traffic_sync' => '流量同步',
'traffic_settlement_compaction' => '流量结算压缩',
@ -53,7 +52,6 @@ final class CloudRuntimeHeartbeat
'storage_publication_failed',
'storage_health_failed', 'storage_backend_unhealthy',
'abuse_monitor_collection_failed',
'abuse_monitor_projection_failed',
'abuse_monitor_retention_failed',
'abuse_monitor_runtime_failed',
'traffic_sync_failed', 'runtime_status_sync_failed',

@ -41,7 +41,7 @@ try {
public int $ticks = 0;
public function tick(): bool
{
$this->ticks++;
++$this->ticks;
return true;
}
public function observationErrors(): array
@ -49,25 +49,13 @@ try {
return [];
}
};
$projection = new class {
public int $ticks = 0;
public function tick(): bool
{
$this->ticks++;
return $this->ticks <= 2;
}
public function observationErrors(): array
{
return [];
}
};
$retention = new class {
public int $runs = 0;
public function prune(): array
{
$this->runs++;
return ['terminal_outboxes' => 0, 'samples' => 1,
'baselines' => 0, 'receipts' => 0, 'findings' => 0];
++$this->runs;
return ['daily_summaries' => 1, 'resolved_findings' => 0,
'alert_events' => 0, 'deliveries' => 0];
}
};
$heartbeat = CloudRuntimeHeartbeat::start(
@ -80,7 +68,6 @@ try {
['cloudAbuseMonitor', '--once'],
$heartbeat,
$ingest,
$projection,
$retention,
static fn (): int => $now,
static function (int $_microseconds): void {
@ -96,13 +83,12 @@ try {
);
$assert($status === 0
&& $ingest->ticks === 1
&& $projection->ticks === 3
&& $retention->runs === 1
&& $record['kind'] === 'abuse_monitor'
&& $record['state'] === 'stopped'
&& $record['last_success'] === $now
&& $record['unresolved_error'] === false,
'Observe-only worker did not drain its bounded burst cleanly.');
'Direct observe-only worker did not complete cleanly.');
$failureDirectory = $temporary . '-failure';
mkdir($failureDirectory, 0700, true);
@ -116,21 +102,11 @@ try {
return ['network_observation_collection_failed'];
}
};
$idleProjection = new class {
public function tick(): bool
{
return false;
}
public function observationErrors(): array
{
return [];
}
};
$idleRetention = new class {
public function prune(): array
{
return ['terminal_outboxes' => 0, 'samples' => 0,
'baselines' => 0, 'receipts' => 0, 'findings' => 0];
return ['daily_summaries' => 0, 'resolved_findings' => 0,
'alert_events' => 0, 'deliveries' => 0];
}
};
$failedHeartbeat = CloudRuntimeHeartbeat::start(
@ -143,7 +119,6 @@ try {
['cloudAbuseMonitor', '--once'],
$failedHeartbeat,
$failedIngest,
$idleProjection,
$idleRetention,
static fn (): int => $now
);
@ -161,11 +136,12 @@ try {
&& $failedRecord['last_error']
=== 'abuse_monitor_collection_failed'
&& $failedRecord['unresolved_error'] === true,
'A caught collection failure was falsely projected healthy.');
'A caught collection failure was falsely reported healthy.');
$cleanup($failureDirectory);
$safeDirectory = $temporary . '-safe-projection';
mkdir($safeDirectory, 0700, true);
// A successful zero-work retry must clear a prior retention warning.
$recoveryDirectory = $temporary . '-retention-recovery';
mkdir($recoveryDirectory, 0700, true);
$idleIngest = new class {
public function tick(): bool
{
@ -176,92 +152,6 @@ try {
return [];
}
};
$safeProjection = new class {
public int $ticks = 0;
public function tick(): bool
{
return ++$this->ticks === 1;
}
public function observationErrors(): array
{
return $this->ticks === 1
? ['instance_deleted'] : [];
}
};
$safeHeartbeat = CloudRuntimeHeartbeat::start(
'abuse_monitor',
true,
$safeDirectory,
static fn (): int => $now
);
$safeStatus = CloudAbuseMonitor::run(
['cloudAbuseMonitor', '--once'],
$safeHeartbeat,
$idleIngest,
$safeProjection,
$idleRetention,
static fn (): int => $now
);
$safeFiles = iterator_to_array(new FilesystemIterator($safeDirectory));
$safeRecord = json_decode(
file_get_contents(reset($safeFiles)->getPathname()),
true,
16,
JSON_THROW_ON_ERROR
);
$assert($safeStatus === 0
&& $safeRecord['unresolved_error'] === false,
'A safely converged projection discard raised a worker failure.');
$cleanup($safeDirectory);
$conflictDirectory = $temporary . '-projection-conflict';
mkdir($conflictDirectory, 0700, true);
$conflictProjection = new class {
public int $ticks = 0;
public function tick(): bool
{
return ++$this->ticks === 1;
}
public function observationErrors(): array
{
return $this->ticks === 1
? ['projection_order_conflict'] : [];
}
};
$conflictHeartbeat = CloudRuntimeHeartbeat::start(
'abuse_monitor',
true,
$conflictDirectory,
static fn (): int => $now
);
$conflictStatus = CloudAbuseMonitor::run(
['cloudAbuseMonitor', '--once'],
$conflictHeartbeat,
$idleIngest,
$conflictProjection,
$idleRetention,
static fn (): int => $now
);
$conflictFiles = iterator_to_array(
new FilesystemIterator($conflictDirectory)
);
$conflictRecord = json_decode(
file_get_contents(reset($conflictFiles)->getPathname()),
true,
16,
JSON_THROW_ON_ERROR
);
$assert($conflictStatus === 1
&& $conflictRecord['last_error']
=== 'abuse_monitor_projection_failed'
&& $conflictRecord['unresolved_error'] === true,
'A projection ordering conflict was silently treated as safe.');
$cleanup($conflictDirectory);
// A stage clears its own warning after a successful zero-work retry; it
// must not depend on unrelated collection or projection work.
$recoveryDirectory = $temporary . '-retention-recovery';
mkdir($recoveryDirectory, 0700, true);
$recoveringRetention = new class {
public int $runs = 0;
public function prune(): array
@ -269,8 +159,8 @@ try {
if (++$this->runs === 1) {
throw new RuntimeException('simulated retention outage');
}
return ['terminal_outboxes' => 0, 'samples' => 0,
'baselines' => 0, 'receipts' => 0, 'findings' => 0];
return ['daily_summaries' => 0, 'resolved_findings' => 0,
'alert_events' => 0, 'deliveries' => 0];
}
};
$recoveryNow = $now;
@ -288,7 +178,6 @@ try {
['cloudAbuseMonitor'],
$recoveryHeartbeat,
$idleIngest,
$idleProjection,
$recoveringRetention,
static function () use (&$recoveryNow): int {
return $recoveryNow;
@ -316,7 +205,7 @@ try {
$assert($row['state'] === 'idle'
&& $row['unresolved_error'] === false
&& $row['last_success'] === $recoveryNow - 301,
'Successful zero-work retention did not clear its warning.');
'Successful zero-work retention did not clear warning.');
throw new RuntimeException('stop daemon fixture');
}
);
@ -340,18 +229,19 @@ try {
$deployment = $read('docs/DEPLOYMENT.md');
$assert(str_contains($xcat, "'cloudAbuseMonitor'")
&& str_contains($xcat, 'CloudAbuseMonitor::run')
&& str_contains($command, 'PROJECTION_BURST = 64')
&& str_contains($command, 'CloudAbuseObservationIngestService')
&& str_contains($command, 'CloudAbuseProjectionService')
&& str_contains($command, 'CloudAbuseRetentionService')
&& !str_contains($command, 'CloudAbuseProjectionService')
&& !str_contains($command, 'PROJECTION_BURST')
&& !str_contains($command, "table('cloud_jobs')")
&& !str_contains($command, 'CloudJob'),
'Monitor command is unreachable, unbounded, or coupled to jobs.');
'Monitor command retained projection or job-queue coupling.');
$assert(str_contains($heartbeatSource, "'abuse_monitor'")
&& str_contains($heartbeatSource, "'abuse_monitor_ingest'")
&& !str_contains($heartbeatSource, 'abuse_monitor_projection')
&& str_contains($runtime,
"'abuse_monitor' => '网络滥用监测'"),
'Runtime observation does not expose the independent monitor.');
'Runtime observation retained a projection phase.');
$assert(str_contains($unit,
'ExecStart=/usr/bin/php /home/virt-cloud/web/xcat cloudAbuseMonitor')
&& str_contains($unit, 'NoNewPrivileges=true')
@ -359,9 +249,9 @@ try {
&& str_contains($unit, 'LimitCORE=0')
&& str_contains($deployment,
'virt-cloud-abuse-monitor.service'),
'Monitor systemd isolation or deployment documentation is incomplete.');
'Monitor systemd isolation or deployment docs are incomplete.');
} finally {
$cleanup($temporary);
}
echo "Observe-only abuse monitor worker contract tests passed.\n";
echo "Direct abuse monitor worker contract tests passed.\n";

@ -121,13 +121,13 @@ try {
$checks($directory)['storage_health']['message'],
'对象存储健康探测'
), 'Object storage health probes did not receive an isolated runtime phase.');
$abuseMonitor->busy('abuse_monitor_projection');
$abuseMonitor->busy('abuse_monitor_ingest');
$assert(str_contains(
$checks($directory)['abuse_monitor']['message'],
'网络风险投影'
), 'Abuse projection did not receive an isolated runtime phase.');
'网络观测采集'
), 'Abuse collection did not receive an isolated runtime phase.');
$now++;
$abuseMonitor->error('abuse_monitor_projection_failed');
$abuseMonitor->error('abuse_monitor_collection_failed');
$assert($checks($directory)['abuse_monitor']['status'] === 'warning',
'Abuse-monitor failure was not preserved as a stable warning.');

Loading…
Cancel
Save