Step 7.4 feat: implement none strict-priority and buffered sender loops
This commit is contained in:
parent
5a45180cdd
commit
5e2e255943
|
|
@ -0,0 +1,224 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg width="1600" height="1180" viewBox="0 0 1600 1180" xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="title desc">
|
||||
<title id="title">Linux Event Agent Architecture</title>
|
||||
<desc id="desc">Block diagram of a Linux event agent with collectors, command coordinator, executors, director, cache, derivator, outbox, senders, transports, CLI, config, and observability.</desc>
|
||||
|
||||
<defs>
|
||||
<style>
|
||||
.title { font: 700 28px Arial, Helvetica, sans-serif; fill: #111; }
|
||||
.subtitle { font: 500 14px Arial, Helvetica, sans-serif; fill: #333; }
|
||||
.section { font: 700 18px Arial, Helvetica, sans-serif; fill: #111; }
|
||||
.label { font: 600 14px Arial, Helvetica, sans-serif; fill: #111; }
|
||||
.small { font: 12px Arial, Helvetica, sans-serif; fill: #222; }
|
||||
.tiny { font: 11px Arial, Helvetica, sans-serif; fill: #333; }
|
||||
.box { stroke: #1f2937; stroke-width: 1.5; rx: 12; ry: 12; }
|
||||
.group { stroke: #6b7280; stroke-width: 1.5; stroke-dasharray: 6 5; rx: 18; ry: 18; fill: none; }
|
||||
.arrow { stroke: #374151; stroke-width: 2; fill: none; marker-end: url(#arrow); }
|
||||
.arrowThin { stroke: #4b5563; stroke-width: 1.5; fill: none; marker-end: url(#arrow); }
|
||||
.note { fill: #fff; stroke: #9ca3af; stroke-width: 1.2; rx: 10; ry: 10; }
|
||||
</style>
|
||||
<marker id="arrow" markerWidth="10" markerHeight="10" refX="9" refY="5" orient="auto" markerUnits="strokeWidth">
|
||||
<path d="M0,0 L10,5 L0,10 z" fill="#374151"/>
|
||||
</marker>
|
||||
</defs>
|
||||
|
||||
<rect x="0" y="0" width="1600" height="1180" fill="#ffffff"/>
|
||||
|
||||
<text x="800" y="42" text-anchor="middle" class="title">Linux Event Agent — Architecture Block Diagram</text>
|
||||
<text x="800" y="68" text-anchor="middle" class="subtitle">Collectors + Command Coordinator + Executors + Director + In-memory Cache + Derivator + Outbox + Senders</text>
|
||||
|
||||
<rect x="40" y="95" width="1520" height="90" class="group"/>
|
||||
<text x="60" y="122" class="section">Configuration and runtime context</text>
|
||||
|
||||
<rect x="70" y="135" width="180" height="34" class="box" fill="#eef6ff"/>
|
||||
<text x="160" y="157" text-anchor="middle" class="label">.env</text>
|
||||
|
||||
<rect x="280" y="135" width="220" height="34" class="box" fill="#eef6ff"/>
|
||||
<text x="390" y="157" text-anchor="middle" class="label">TOML config</text>
|
||||
|
||||
<rect x="530" y="135" width="220" height="34" class="box" fill="#eef6ff"/>
|
||||
<text x="640" y="157" text-anchor="middle" class="label">Protocol Buffers v1</text>
|
||||
|
||||
<rect x="780" y="135" width="220" height="34" class="box" fill="#eef6ff"/>
|
||||
<text x="890" y="157" text-anchor="middle" class="label">Linux runtime</text>
|
||||
|
||||
<rect x="1030" y="135" width="240" height="34" class="box" fill="#eef6ff"/>
|
||||
<text x="1150" y="157" text-anchor="middle" class="label">Policies / rules / task schedule</text>
|
||||
|
||||
<rect x="1300" y="135" width="220" height="34" class="box" fill="#eef6ff"/>
|
||||
<text x="1410" y="157" text-anchor="middle" class="label">CLI / operator context</text>
|
||||
|
||||
<rect x="40" y="220" width="520" height="365" class="group"/>
|
||||
<text x="60" y="247" class="section">Ingestion plane — Collectors</text>
|
||||
|
||||
<rect x="70" y="278" width="210" height="64" class="box" fill="#ecfdf5"/>
|
||||
<text x="175" y="302" text-anchor="middle" class="label">JournalCollector</text>
|
||||
<text x="175" y="323" text-anchor="middle" class="small">systemd journal</text>
|
||||
|
||||
<rect x="310" y="278" width="210" height="64" class="box" fill="#ecfdf5"/>
|
||||
<text x="415" y="302" text-anchor="middle" class="label">DbusCollector</text>
|
||||
<text x="415" y="323" text-anchor="middle" class="small">system bus / signals</text>
|
||||
|
||||
<rect x="70" y="366" width="210" height="64" class="box" fill="#ecfdf5"/>
|
||||
<text x="175" y="390" text-anchor="middle" class="label">WpaCtrlCollector</text>
|
||||
<text x="175" y="411" text-anchor="middle" class="small">wpa_supplicant ctrl_iface</text>
|
||||
|
||||
<rect x="310" y="366" width="210" height="64" class="box" fill="#ecfdf5"/>
|
||||
<text x="415" y="390" text-anchor="middle" class="label">NavigationCollector</text>
|
||||
<text x="415" y="411" text-anchor="middle" class="small">adapter / future source</text>
|
||||
|
||||
<rect x="90" y="468" width="410" height="84" class="box" fill="#f7fee7"/>
|
||||
<text x="295" y="492" text-anchor="middle" class="label">Collector pipeline</text>
|
||||
<text x="295" y="514" text-anchor="middle" class="small">prefilter → validation → normalization(proto v1) → marking</text>
|
||||
<text x="295" y="535" text-anchor="middle" class="tiny">all collectors emit canonical EventEnvelope into Director</text>
|
||||
|
||||
<rect x="600" y="220" width="420" height="240" class="group"/>
|
||||
<text x="620" y="247" class="section">Control plane initiators</text>
|
||||
|
||||
<rect x="635" y="278" width="110" height="58" class="box" fill="#fff7ed"/>
|
||||
<text x="690" y="312" text-anchor="middle" class="label">CLI</text>
|
||||
|
||||
<rect x="758" y="278" width="110" height="58" class="box" fill="#fff7ed"/>
|
||||
<text x="813" y="312" text-anchor="middle" class="label">Scheduler</text>
|
||||
|
||||
<rect x="881" y="278" width="110" height="58" class="box" fill="#fff7ed"/>
|
||||
<text x="936" y="312" text-anchor="middle" class="label">Derivator</text>
|
||||
|
||||
<rect x="650" y="372" width="320" height="58" class="box" fill="#fffbeb"/>
|
||||
<text x="810" y="396" text-anchor="middle" class="label">CommandRequest</text>
|
||||
<text x="810" y="417" text-anchor="middle" class="small">operator / scheduled / derived actions</text>
|
||||
|
||||
<rect x="1060" y="220" width="500" height="365" class="group"/>
|
||||
<text x="1080" y="247" class="section">Control execution plane</text>
|
||||
|
||||
<rect x="1090" y="278" width="210" height="70" class="box" fill="#fef2f2"/>
|
||||
<text x="1195" y="302" text-anchor="middle" class="label">CommandCoordinator</text>
|
||||
<text x="1195" y="323" text-anchor="middle" class="small">priority / exclusivity / dedup / cooldown</text>
|
||||
|
||||
<rect x="1325" y="278" width="200" height="70" class="box" fill="#fef2f2"/>
|
||||
<text x="1425" y="302" text-anchor="middle" class="label">ExecutorRouter</text>
|
||||
<text x="1425" y="323" text-anchor="middle" class="small">command type → executor</text>
|
||||
|
||||
<rect x="1090" y="385" width="130" height="64" class="box" fill="#fee2e2"/>
|
||||
<text x="1155" y="409" text-anchor="middle" class="label">WpaCtrlExecutor</text>
|
||||
<text x="1155" y="430" text-anchor="middle" class="tiny">scan/status/add_network/...</text>
|
||||
|
||||
<rect x="1240" y="385" width="130" height="64" class="box" fill="#fee2e2"/>
|
||||
<text x="1305" y="409" text-anchor="middle" class="label">SystemExecutor</text>
|
||||
<text x="1305" y="430" text-anchor="middle" class="tiny">set_regdomain</text>
|
||||
|
||||
<rect x="1390" y="385" width="130" height="64" class="box" fill="#fee2e2"/>
|
||||
<text x="1455" y="409" text-anchor="middle" class="label">DbusExecutor</text>
|
||||
<text x="1455" y="430" text-anchor="middle" class="tiny">future / optional</text>
|
||||
|
||||
<rect x="1170" y="487" width="280" height="58" class="box" fill="#fff1f2"/>
|
||||
<text x="1310" y="511" text-anchor="middle" class="label">Command result event</text>
|
||||
<text x="1310" y="532" text-anchor="middle" class="small">accepted / rejected / started / succeeded / failed</text>
|
||||
|
||||
<rect x="40" y="625" width="1520" height="385" class="group"/>
|
||||
<text x="60" y="652" class="section">Core event runtime</text>
|
||||
|
||||
<rect x="660" y="685" width="280" height="90" class="box" fill="#ede9fe"/>
|
||||
<text x="800" y="714" text-anchor="middle" class="label">Director</text>
|
||||
<text x="800" y="738" text-anchor="middle" class="small">route canonical events</text>
|
||||
<text x="800" y="759" text-anchor="middle" class="tiny">to cache / outbox / derivator-interest</text>
|
||||
|
||||
<rect x="100" y="700" width="340" height="82" class="box" fill="#eff6ff"/>
|
||||
<text x="270" y="729" text-anchor="middle" class="label">Core Cache</text>
|
||||
<text x="270" y="752" text-anchor="middle" class="small">bounded in-memory ring buffer</text>
|
||||
|
||||
<rect x="100" y="812" width="340" height="82" class="box" fill="#eff6ff"/>
|
||||
<text x="270" y="841" text-anchor="middle" class="label">Secondary indexes</text>
|
||||
<text x="270" y="864" text-anchor="middle" class="small">by interface / type / source / ssid</text>
|
||||
|
||||
<rect x="470" y="812" width="260" height="82" class="box" fill="#eff6ff"/>
|
||||
<text x="600" y="841" text-anchor="middle" class="label">Payload store</text>
|
||||
<text x="600" y="864" text-anchor="middle" class="small">payload arena / refs</text>
|
||||
|
||||
<rect x="1030" y="700" width="260" height="82" class="box" fill="#f0fdf4"/>
|
||||
<text x="1160" y="729" text-anchor="middle" class="label">Outbox</text>
|
||||
<text x="1160" y="752" text-anchor="middle" class="small">bounded in-memory queue</text>
|
||||
|
||||
<rect x="520" y="915" width="300" height="72" class="box" fill="#faf5ff"/>
|
||||
<text x="670" y="943" text-anchor="middle" class="label">Derivator</text>
|
||||
<text x="670" y="965" text-anchor="middle" class="small">reads cache windows, emits derived events</text>
|
||||
|
||||
<rect x="1030" y="812" width="220" height="64" class="box" fill="#dcfce7"/>
|
||||
<text x="1140" y="836" text-anchor="middle" class="label">Sender types</text>
|
||||
<text x="1140" y="857" text-anchor="middle" class="small">none / strict_priority / buffered</text>
|
||||
|
||||
<rect x="1290" y="812" width="220" height="64" class="box" fill="#dcfce7"/>
|
||||
<text x="1400" y="836" text-anchor="middle" class="label">Transports</text>
|
||||
<text x="1400" y="857" text-anchor="middle" class="small">drop / webhook</text>
|
||||
|
||||
<rect x="1260" y="915" width="270" height="72" class="box" fill="#ecfccb"/>
|
||||
<text x="1395" y="943" text-anchor="middle" class="label">External sink</text>
|
||||
<text x="1395" y="965" text-anchor="middle" class="small">webhook POST / synthetic drop</text>
|
||||
|
||||
<rect x="40" y="1035" width="1520" height="110" class="group"/>
|
||||
<text x="60" y="1062" class="section">Observability and operations</text>
|
||||
|
||||
<rect x="80" y="1085" width="220" height="38" class="box" fill="#f9fafb"/>
|
||||
<text x="190" y="1108" text-anchor="middle" class="label">CLI inspection</text>
|
||||
|
||||
<rect x="340" y="1085" width="250" height="38" class="box" fill="#f9fafb"/>
|
||||
<text x="465" y="1108" text-anchor="middle" class="label">Status / stats / cache / outbox</text>
|
||||
|
||||
<rect x="630" y="1085" width="250" height="38" class="box" fill="#f9fafb"/>
|
||||
<text x="755" y="1108" text-anchor="middle" class="label">Command / task control</text>
|
||||
|
||||
<rect x="920" y="1085" width="260" height="38" class="box" fill="#f9fafb"/>
|
||||
<text x="1050" y="1108" text-anchor="middle" class="label">Counters / watermarks / health</text>
|
||||
|
||||
<rect x="1220" y="1085" width="280" height="38" class="box" fill="#f9fafb"/>
|
||||
<text x="1360" y="1108" text-anchor="middle" class="label">Operator-visible runtime introspection</text>
|
||||
|
||||
<line x1="175" y1="342" x2="175" y2="468" class="arrowThin"/>
|
||||
<line x1="415" y1="342" x2="415" y2="468" class="arrowThin"/>
|
||||
<line x1="175" y1="430" x2="175" y2="468" class="arrowThin"/>
|
||||
<line x1="415" y1="430" x2="415" y2="468" class="arrowThin"/>
|
||||
<line x1="500" y1="510" x2="660" y2="730" class="arrow"/>
|
||||
|
||||
<line x1="690" y1="336" x2="810" y2="372" class="arrowThin"/>
|
||||
<line x1="813" y1="336" x2="810" y2="372" class="arrowThin"/>
|
||||
<line x1="936" y1="336" x2="810" y2="372" class="arrowThin"/>
|
||||
|
||||
<line x1="970" y1="401" x2="1090" y2="313" class="arrow"/>
|
||||
<line x1="1300" y1="313" x2="1325" y2="313" class="arrowThin"/>
|
||||
|
||||
<line x1="1425" y1="348" x2="1155" y2="385" class="arrowThin"/>
|
||||
<line x1="1425" y1="348" x2="1305" y2="385" class="arrowThin"/>
|
||||
<line x1="1425" y1="348" x2="1455" y2="385" class="arrowThin"/>
|
||||
|
||||
<line x1="1155" y1="449" x2="1170" y2="516" class="arrowThin"/>
|
||||
<line x1="1305" y1="449" x2="1310" y2="487" class="arrowThin"/>
|
||||
<line x1="1455" y1="449" x2="1450" y2="516" class="arrowThin"/>
|
||||
|
||||
<line x1="1170" y1="545" x2="940" y2="730" class="arrow"/>
|
||||
|
||||
<line x1="800" y1="775" x2="270" y2="700" class="arrow"/>
|
||||
<line x1="800" y1="775" x2="1160" y2="700" class="arrow"/>
|
||||
<line x1="270" y1="782" x2="270" y2="812" class="arrowThin"/>
|
||||
<line x1="440" y1="853" x2="470" y2="853" class="arrowThin"/>
|
||||
|
||||
<line x1="670" y1="915" x2="670" y2="812" class="arrowThin"/>
|
||||
<line x1="820" y1="951" x2="1090" y2="401" class="arrowThin"/>
|
||||
<line x1="820" y1="930" x2="800" y2="775" class="arrow"/>
|
||||
|
||||
<line x1="1160" y1="782" x2="1140" y2="812" class="arrowThin"/>
|
||||
<line x1="1250" y1="844" x2="1290" y2="844" class="arrowThin"/>
|
||||
<line x1="1400" y1="876" x2="1395" y2="915" class="arrow"/>
|
||||
|
||||
<line x1="1410" y1="169" x2="690" y2="278" class="arrowThin"/>
|
||||
<line x1="1150" y1="169" x2="1090" y2="313" class="arrowThin"/>
|
||||
<line x1="390" y1="169" x2="295" y2="468" class="arrowThin"/>
|
||||
<line x1="640" y1="169" x2="800" y2="685" class="arrowThin"/>
|
||||
|
||||
<rect x="560" y="560" width="420" height="50" class="note"/>
|
||||
<text x="770" y="582" text-anchor="middle" class="small">Canonical event path:</text>
|
||||
<text x="770" y="600" text-anchor="middle" class="tiny">collectors and command results both enter Director as EventEnvelope</text>
|
||||
|
||||
<rect x="1030" y="610" width="430" height="50" class="note"/>
|
||||
<text x="1245" y="632" text-anchor="middle" class="small">Unified control path:</text>
|
||||
<text x="1245" y="650" text-anchor="middle" class="tiny">CLI / Scheduler / Derivator → CommandCoordinator → Executors → result event → Director</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 13 KiB |
|
|
@ -1,6 +1,16 @@
|
|||
"""Outbox draining and transport sender logic."""
|
||||
|
||||
from .batcher import BatchBuilder, BatchBuilderResult
|
||||
from .loops import (
|
||||
BufferedSenderLoop,
|
||||
ImmediateSenderLoop,
|
||||
NoneSenderLoop,
|
||||
SenderLoopBase,
|
||||
SenderLoopResult,
|
||||
SenderLoopStatsSnapshot,
|
||||
StrictPrioritySenderLoop,
|
||||
build_sender_loop,
|
||||
)
|
||||
from .outbox import (
|
||||
OutboxEnqueueResult,
|
||||
OutboxItem,
|
||||
|
|
@ -21,7 +31,10 @@ from .transports import DropTransport, TransportBase, TransportIdentity, Transpo
|
|||
__all__ = [
|
||||
"BatchBuilder",
|
||||
"BatchBuilderResult",
|
||||
"BufferedSenderLoop",
|
||||
"DropTransport",
|
||||
"ImmediateSenderLoop",
|
||||
"NoneSenderLoop",
|
||||
"OutboxEnqueueResult",
|
||||
"OutboxItem",
|
||||
"OutboxOverflowPolicy",
|
||||
|
|
@ -29,12 +42,17 @@ __all__ = [
|
|||
"OutboxQueueStats",
|
||||
"SenderBufferedConfig",
|
||||
"SenderComposition",
|
||||
"SenderLoopBase",
|
||||
"SenderLoopResult",
|
||||
"SenderLoopStatsSnapshot",
|
||||
"SenderRuntimeConfig",
|
||||
"SenderType",
|
||||
"StrictPrioritySenderLoop",
|
||||
"TransportBase",
|
||||
"TransportIdentity",
|
||||
"TransportResult",
|
||||
"TransportType",
|
||||
"WebhookTransport",
|
||||
"WebhookTransportConfig",
|
||||
]
|
||||
"build_sender_loop",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,295 @@
|
|||
"""Sender loop implementations for immediate and buffered draining."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from time import monotonic_ns
|
||||
from typing import Iterable
|
||||
|
||||
from ..cache import CacheAPI
|
||||
from .batcher import BatchBuilder, BatchBuilderResult
|
||||
from .outbox import OutboxItem, OutboxQueue
|
||||
from .sender_types import SenderRuntimeConfig, SenderType, TransportType
|
||||
from .transports import DropTransport, TransportBase, TransportResult, WebhookTransport
|
||||
|
||||
|
||||
@dataclass(slots=True, frozen=True)
|
||||
class SenderLoopResult:
|
||||
sender_type: SenderType
|
||||
transport_type: TransportType
|
||||
flushed: bool
|
||||
skipped: bool
|
||||
reason: str
|
||||
batch_result: BatchBuilderResult | None = None
|
||||
transport_result: TransportResult | None = None
|
||||
acknowledged_seq_nos: tuple[int, ...] = ()
|
||||
|
||||
@property
|
||||
def success(self) -> bool:
|
||||
return self.transport_result.ok if self.transport_result is not None else False
|
||||
|
||||
@property
|
||||
def item_count(self) -> int:
|
||||
if self.batch_result is None:
|
||||
return 0
|
||||
return self.batch_result.count
|
||||
|
||||
|
||||
@dataclass(slots=True, frozen=True)
|
||||
class SenderLoopStatsSnapshot:
|
||||
run_total: int
|
||||
flush_total: int
|
||||
ack_total: int
|
||||
send_success_total: int
|
||||
send_failed_total: int
|
||||
skipped_total: int
|
||||
last_batch_size: int
|
||||
last_transport_status_code: int
|
||||
last_transport_reason: str
|
||||
last_error: str
|
||||
|
||||
|
||||
class SenderLoopBase(ABC):
|
||||
def __init__(
|
||||
self,
|
||||
config: SenderRuntimeConfig,
|
||||
*,
|
||||
cache: CacheAPI,
|
||||
outbox: OutboxQueue,
|
||||
transport: TransportBase,
|
||||
) -> None:
|
||||
self.config = config
|
||||
self.cache = cache
|
||||
self.outbox = outbox
|
||||
self.transport = transport
|
||||
self.batch_builder = BatchBuilder(cache)
|
||||
self._run_total = 0
|
||||
self._flush_total = 0
|
||||
self._ack_total = 0
|
||||
self._send_success_total = 0
|
||||
self._send_failed_total = 0
|
||||
self._skipped_total = 0
|
||||
self._last_batch_size = 0
|
||||
self._last_transport_status_code = 0
|
||||
self._last_transport_reason = ""
|
||||
self._last_error = ""
|
||||
|
||||
@property
|
||||
def sender_type(self) -> SenderType:
|
||||
return self.config.sender_type
|
||||
|
||||
@property
|
||||
def transport_type(self) -> TransportType:
|
||||
return self.config.transport_type
|
||||
|
||||
def stats(self) -> SenderLoopStatsSnapshot:
|
||||
return SenderLoopStatsSnapshot(
|
||||
run_total=self._run_total,
|
||||
flush_total=self._flush_total,
|
||||
ack_total=self._ack_total,
|
||||
send_success_total=self._send_success_total,
|
||||
send_failed_total=self._send_failed_total,
|
||||
skipped_total=self._skipped_total,
|
||||
last_batch_size=self._last_batch_size,
|
||||
last_transport_status_code=self._last_transport_status_code,
|
||||
last_transport_reason=self._last_transport_reason,
|
||||
last_error=self._last_error,
|
||||
)
|
||||
|
||||
def _dispatch(
|
||||
self,
|
||||
items: Iterable[OutboxItem],
|
||||
*,
|
||||
batch_id: str = "",
|
||||
created_at: datetime | None = None,
|
||||
) -> SenderLoopResult:
|
||||
self._run_total += 1
|
||||
selected = tuple(items)
|
||||
if not selected:
|
||||
self._skipped_total += 1
|
||||
self._last_batch_size = 0
|
||||
self._last_transport_status_code = 0
|
||||
self._last_transport_reason = "outbox empty"
|
||||
return SenderLoopResult(
|
||||
sender_type=self.sender_type,
|
||||
transport_type=self.transport_type,
|
||||
flushed=False,
|
||||
skipped=True,
|
||||
reason="outbox empty",
|
||||
)
|
||||
|
||||
batch_result = self.batch_builder.build(
|
||||
selected,
|
||||
batch_id=batch_id,
|
||||
created_at=created_at or datetime.now(timezone.utc),
|
||||
include_json=True,
|
||||
)
|
||||
payload = batch_result.json or ""
|
||||
transport_result = self.transport.send(payload, content_type="application/json")
|
||||
self._last_batch_size = batch_result.count
|
||||
self._last_transport_status_code = transport_result.status_code
|
||||
self._last_transport_reason = transport_result.reason
|
||||
self._flush_total += 1
|
||||
|
||||
if transport_result.ok:
|
||||
acknowledged = self._acknowledge(selected)
|
||||
self._send_success_total += 1
|
||||
return SenderLoopResult(
|
||||
sender_type=self.sender_type,
|
||||
transport_type=self.transport_type,
|
||||
flushed=True,
|
||||
skipped=False,
|
||||
reason="delivered",
|
||||
batch_result=batch_result,
|
||||
transport_result=transport_result,
|
||||
acknowledged_seq_nos=acknowledged,
|
||||
)
|
||||
|
||||
self._send_failed_total += 1
|
||||
self._last_error = transport_result.reason
|
||||
return SenderLoopResult(
|
||||
sender_type=self.sender_type,
|
||||
transport_type=self.transport_type,
|
||||
flushed=True,
|
||||
skipped=False,
|
||||
reason=transport_result.reason,
|
||||
batch_result=batch_result,
|
||||
transport_result=transport_result,
|
||||
)
|
||||
|
||||
def _acknowledge(self, items: Iterable[OutboxItem]) -> tuple[int, ...]:
|
||||
acked: list[int] = []
|
||||
for item in items:
|
||||
removed = self.outbox.remove(item.seq_no)
|
||||
if removed is not None:
|
||||
acked.append(int(item.seq_no))
|
||||
self._ack_total += len(acked)
|
||||
return tuple(acked)
|
||||
|
||||
|
||||
class ImmediateSenderLoop(SenderLoopBase):
|
||||
def run_once(
|
||||
self,
|
||||
*,
|
||||
now_mono_ns_value: int | None = None,
|
||||
batch_id: str = "",
|
||||
created_at: datetime | None = None,
|
||||
) -> SenderLoopResult:
|
||||
del now_mono_ns_value
|
||||
return self._dispatch(
|
||||
self.outbox.items(),
|
||||
batch_id=batch_id,
|
||||
created_at=created_at,
|
||||
)
|
||||
|
||||
|
||||
class NoneSenderLoop(ImmediateSenderLoop):
|
||||
def __init__(
|
||||
self,
|
||||
config: SenderRuntimeConfig,
|
||||
*,
|
||||
cache: CacheAPI,
|
||||
outbox: OutboxQueue,
|
||||
transport: TransportBase | None = None,
|
||||
) -> None:
|
||||
super().__init__(
|
||||
config.with_sender_type(SenderType.NONE),
|
||||
cache=cache,
|
||||
outbox=outbox,
|
||||
transport=transport or DropTransport(),
|
||||
)
|
||||
|
||||
|
||||
class StrictPrioritySenderLoop(ImmediateSenderLoop):
|
||||
def __init__(
|
||||
self,
|
||||
config: SenderRuntimeConfig,
|
||||
*,
|
||||
cache: CacheAPI,
|
||||
outbox: OutboxQueue,
|
||||
transport: TransportBase | None = None,
|
||||
) -> None:
|
||||
super().__init__(
|
||||
config.with_sender_type(SenderType.STRICT_PRIORITY),
|
||||
cache=cache,
|
||||
outbox=outbox,
|
||||
transport=transport or WebhookTransport(config.webhook),
|
||||
)
|
||||
|
||||
|
||||
class BufferedSenderLoop(SenderLoopBase):
|
||||
def __init__(
|
||||
self,
|
||||
config: SenderRuntimeConfig,
|
||||
*,
|
||||
cache: CacheAPI,
|
||||
outbox: OutboxQueue,
|
||||
transport: TransportBase | None = None,
|
||||
) -> None:
|
||||
super().__init__(
|
||||
config.with_sender_type(SenderType.BUFFERED),
|
||||
cache=cache,
|
||||
outbox=outbox,
|
||||
transport=transport or WebhookTransport(config.webhook),
|
||||
)
|
||||
|
||||
def run_once(
|
||||
self,
|
||||
*,
|
||||
now_mono_ns_value: int | None = None,
|
||||
batch_id: str = "",
|
||||
created_at: datetime | None = None,
|
||||
) -> SenderLoopResult:
|
||||
now = monotonic_ns() if now_mono_ns_value is None else now_mono_ns_value
|
||||
items = self.outbox.items()
|
||||
if not items:
|
||||
return self._dispatch((), batch_id=batch_id, created_at=created_at)
|
||||
|
||||
batch_max_events = max(1, int(self.config.buffered.batch_max_events))
|
||||
if len(items) < batch_max_events and not self._flush_due(items, now):
|
||||
self._run_total += 1
|
||||
self._skipped_total += 1
|
||||
self._last_batch_size = 0
|
||||
self._last_transport_status_code = 0
|
||||
self._last_transport_reason = "buffer not ready"
|
||||
return SenderLoopResult(
|
||||
sender_type=self.sender_type,
|
||||
transport_type=self.transport_type,
|
||||
flushed=False,
|
||||
skipped=True,
|
||||
reason="buffer not ready",
|
||||
)
|
||||
|
||||
return self._dispatch(
|
||||
items[:batch_max_events],
|
||||
batch_id=batch_id,
|
||||
created_at=created_at,
|
||||
)
|
||||
|
||||
def _flush_due(self, items: Iterable[OutboxItem], now_mono_ns_value: int) -> bool:
|
||||
flush_ms = max(0, int(self.config.buffered.batch_flush_ms))
|
||||
if flush_ms <= 0:
|
||||
return True
|
||||
oldest_enqueue = min(item.enqueue_mono_ns for item in items)
|
||||
return (now_mono_ns_value - oldest_enqueue) >= flush_ms * 1_000_000
|
||||
|
||||
|
||||
def build_sender_loop(
|
||||
config: SenderRuntimeConfig,
|
||||
*,
|
||||
cache: CacheAPI,
|
||||
outbox: OutboxQueue,
|
||||
transport: TransportBase | None = None,
|
||||
) -> SenderLoopBase:
|
||||
composition = config.composition()
|
||||
if not composition.is_supported():
|
||||
raise ValueError(", ".join(composition.validate()))
|
||||
if config.sender_type == SenderType.NONE:
|
||||
return NoneSenderLoop(config, cache=cache, outbox=outbox, transport=transport)
|
||||
if config.sender_type == SenderType.STRICT_PRIORITY:
|
||||
return StrictPrioritySenderLoop(config, cache=cache, outbox=outbox, transport=transport)
|
||||
if config.sender_type == SenderType.BUFFERED:
|
||||
return BufferedSenderLoop(config, cache=cache, outbox=outbox, transport=transport)
|
||||
raise ValueError(f"unsupported sender type: {config.sender_type.value}")
|
||||
|
|
@ -5,5 +5,7 @@ from pathlib import Path
|
|||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SRC = ROOT / "src"
|
||||
if str(SRC) not in sys.path:
|
||||
sys.path.insert(0, str(SRC))
|
||||
for path in (ROOT, SRC):
|
||||
text = str(path)
|
||||
if text not in sys.path:
|
||||
sys.path.insert(0, text)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,168 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from agent.cache import build_default_cache
|
||||
from agent.core import EventRecord
|
||||
from agent.core.enums import EventKind, PayloadKind, Severity, SourceKind
|
||||
from agent.sender import (
|
||||
BufferedSenderLoop,
|
||||
NoneSenderLoop,
|
||||
SenderBufferedConfig,
|
||||
SenderRuntimeConfig,
|
||||
SenderType,
|
||||
StrictPrioritySenderLoop,
|
||||
TransportBase,
|
||||
TransportIdentity,
|
||||
TransportResult,
|
||||
TransportType,
|
||||
build_sender_loop,
|
||||
)
|
||||
from agent.sender.outbox import OutboxQueue
|
||||
|
||||
|
||||
class RecordingTransport(TransportBase):
|
||||
def __init__(self, *, transport_type: TransportType = TransportType.WEBHOOK, ok: bool = True) -> None:
|
||||
super().__init__(TransportIdentity(name="recording", transport_type=transport_type, enabled=True))
|
||||
self.ok = ok
|
||||
self.calls: list[dict[str, object]] = []
|
||||
|
||||
def send(self, payload, *, content_type: str | None = None, headers=None) -> TransportResult:
|
||||
del headers
|
||||
self.calls.append({"payload": payload, "content_type": content_type})
|
||||
body = (
|
||||
payload.encode("utf-8")
|
||||
if isinstance(payload, str)
|
||||
else bytes(payload)
|
||||
if isinstance(payload, (bytes, bytearray, memoryview))
|
||||
else str(payload).encode("utf-8")
|
||||
)
|
||||
return TransportResult(
|
||||
ok=self.ok,
|
||||
status_code=202 if self.ok else 500,
|
||||
reason="accepted" if self.ok else "failed",
|
||||
bytes_sent=len(body),
|
||||
url="recording://",
|
||||
content_type=content_type or "",
|
||||
)
|
||||
|
||||
|
||||
def _make_queue_item(cache, outbox: OutboxQueue, *, event_id: int, priority: int, enqueue_mono_ns: int):
|
||||
record = cache.append(
|
||||
EventRecord(
|
||||
event_id=event_id,
|
||||
source_kind=SourceKind.APPLICATION,
|
||||
payload_kind=PayloadKind.UNSPECIFIED,
|
||||
event_kind=EventKind.RAW,
|
||||
severity=Severity.INFO,
|
||||
event_type_id=1,
|
||||
source_instance_id=1,
|
||||
observed_mono_ns=enqueue_mono_ns,
|
||||
observed_wall_ns=enqueue_mono_ns,
|
||||
ingested_mono_ns=enqueue_mono_ns,
|
||||
)
|
||||
)
|
||||
result = outbox.enqueue(
|
||||
int(record.seq_no),
|
||||
int(record.event_id),
|
||||
priority=priority,
|
||||
enqueue_mono_ns=enqueue_mono_ns,
|
||||
)
|
||||
assert result.accepted is True
|
||||
assert result.item is not None
|
||||
return record, result.item
|
||||
|
||||
|
||||
def test_none_sender_loop_emulates_success_and_clears_outbox() -> None:
|
||||
cache = build_default_cache(ring_capacity=8, payload_capacity_items=8, payload_capacity_bytes=4096)
|
||||
outbox = OutboxQueue(4)
|
||||
_make_queue_item(cache, outbox, event_id=11, priority=5, enqueue_mono_ns=100)
|
||||
loop = NoneSenderLoop(SenderRuntimeConfig(sender_type=SenderType.NONE, transport_type=TransportType.DROP), cache=cache, outbox=outbox)
|
||||
|
||||
result = loop.run_once()
|
||||
|
||||
assert result.skipped is False
|
||||
assert result.success is True
|
||||
assert result.batch_result is not None
|
||||
assert result.batch_result.count == 1
|
||||
assert json.loads(result.batch_result.json or "{}")["events"]
|
||||
assert result.acknowledged_seq_nos == (1,)
|
||||
assert len(outbox) == 0
|
||||
assert loop.stats().send_success_total == 1
|
||||
|
||||
|
||||
def test_strict_priority_sender_loop_drains_items_in_outbox_priority_order() -> None:
|
||||
cache = build_default_cache(ring_capacity=8, payload_capacity_items=8, payload_capacity_bytes=4096)
|
||||
outbox = OutboxQueue(4)
|
||||
_, low_item = _make_queue_item(cache, outbox, event_id=21, priority=1, enqueue_mono_ns=100)
|
||||
_, high_item = _make_queue_item(cache, outbox, event_id=22, priority=9, enqueue_mono_ns=110)
|
||||
transport = RecordingTransport(transport_type=TransportType.WEBHOOK)
|
||||
loop = StrictPrioritySenderLoop(
|
||||
SenderRuntimeConfig(sender_type=SenderType.STRICT_PRIORITY, transport_type=TransportType.WEBHOOK),
|
||||
cache=cache,
|
||||
outbox=outbox,
|
||||
transport=transport,
|
||||
)
|
||||
|
||||
result = loop.run_once()
|
||||
|
||||
assert result.success is True
|
||||
assert result.batch_result is not None
|
||||
assert [item.seq_no for item in result.batch_result.outbox_items] == [high_item.seq_no, low_item.seq_no]
|
||||
assert len(transport.calls) == 1
|
||||
assert transport.calls[0]["content_type"] == "application/json"
|
||||
assert len(outbox) == 0
|
||||
assert loop.stats().ack_total == 2
|
||||
|
||||
|
||||
def test_buffered_sender_loop_waits_until_flush_time_and_then_drains() -> None:
|
||||
cache = build_default_cache(ring_capacity=8, payload_capacity_items=8, payload_capacity_bytes=4096)
|
||||
outbox = OutboxQueue(4)
|
||||
_make_queue_item(cache, outbox, event_id=31, priority=4, enqueue_mono_ns=1_000_000_000)
|
||||
transport = RecordingTransport(transport_type=TransportType.WEBHOOK)
|
||||
loop = BufferedSenderLoop(
|
||||
SenderRuntimeConfig(
|
||||
sender_type=SenderType.BUFFERED,
|
||||
transport_type=TransportType.WEBHOOK,
|
||||
buffered=SenderBufferedConfig(batch_max_events=2, batch_flush_ms=500, retry_base_ms=100, retry_max_ms=1000),
|
||||
),
|
||||
cache=cache,
|
||||
outbox=outbox,
|
||||
transport=transport,
|
||||
)
|
||||
|
||||
skipped = loop.run_once(now_mono_ns_value=1_000_100_000)
|
||||
flushed = loop.run_once(now_mono_ns_value=1_500_600_000)
|
||||
|
||||
assert skipped.skipped is True
|
||||
assert skipped.reason == "buffer not ready"
|
||||
assert len(transport.calls) == 1
|
||||
assert flushed.success is True
|
||||
assert len(outbox) == 0
|
||||
|
||||
|
||||
def test_build_sender_loop_selects_expected_implementation() -> None:
|
||||
cache = build_default_cache(ring_capacity=4, payload_capacity_items=4, payload_capacity_bytes=1024)
|
||||
outbox = OutboxQueue(2)
|
||||
|
||||
none_loop = build_sender_loop(
|
||||
SenderRuntimeConfig(sender_type=SenderType.NONE, transport_type=TransportType.DROP),
|
||||
cache=cache,
|
||||
outbox=outbox,
|
||||
)
|
||||
strict_loop = build_sender_loop(
|
||||
SenderRuntimeConfig(sender_type=SenderType.STRICT_PRIORITY, transport_type=TransportType.WEBHOOK),
|
||||
cache=cache,
|
||||
outbox=outbox,
|
||||
transport=RecordingTransport(transport_type=TransportType.WEBHOOK),
|
||||
)
|
||||
buffered_loop = build_sender_loop(
|
||||
SenderRuntimeConfig(sender_type=SenderType.BUFFERED, transport_type=TransportType.WEBHOOK),
|
||||
cache=cache,
|
||||
outbox=outbox,
|
||||
transport=RecordingTransport(transport_type=TransportType.WEBHOOK),
|
||||
)
|
||||
|
||||
assert isinstance(none_loop, NoneSenderLoop)
|
||||
assert isinstance(strict_loop, StrictPrioritySenderLoop)
|
||||
assert isinstance(buffered_loop, BufferedSenderLoop)
|
||||
Loading…
Reference in New Issue