Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(capture): outputs layer owns the failover policy (#81243)

Paweł Ledwońc1e0e1834a92
diff --git a/rust/capture/OUTPUTS_REFACTOR_PLAN.md b/rust/capture/OUTPUTS_REFACTOR_PLAN.md
index 4abe831b4616..5529c43111c8 100644
--- a/rust/capture/OUTPUTS_REFACTOR_PLAN.md
+++ b/rust/capture/OUTPUTS_REFACTOR_PLAN.md
@@ -36,12 +36,13 @@ sinks → single backend: wrap payload into wire record (topic/key v
## Starting point
-Steps 1–3 land together with this doc: the routing golden oracle, the pure `route()`, and the `OutputRegistry` with its startup completeness check. Production call sites still publish through the v0 `Event` trait (`send` / `send_batch`); the v1 stack (`CAPTURE_V1_SINKS`, opt-in) still runs its own serialize-then-publish pipeline with a per-event response model. The v1 `PreparedEvent { uuid, destination, payload: Bytes, headers, partition_key }` is the shape our output→sink handoff adopts.
+Steps 1–3 land together with this doc: the routing golden oracle, the pure `route()`, and the `TopicTable` with its startup completeness check. Production call sites still publish through the v0 `Event` trait (`send` / `send_batch`); the v1 stack (`CAPTURE_V1_SINKS`, opt-in) still runs its own serialize-then-publish pipeline with a per-event response model. The v1 `PreparedEvent { uuid, destination, payload: Bytes, headers, partition_key }` is the shape our output→sink handoff adopts.
### Vocabulary rules
- An event's **Address** is a lane of its pipeline (lanes typed per pipeline — `AnalyticsLane`, `AiLane`, `SessionReplayLane`, `BasicLane` — so invalid pairs are unrepresentable), or an admin **custom redirect** that carries its own topic outside the lane model. Pipeline and lane kind are projections; construction goes through `resolve`. Never reintroduce a flat destination enum that conflates pipeline and lane.
-- **Output** = the addressed destination: targets + selection policy + serializer. **OutputTable** = the `(Pipeline, Lane)` → output mapping with the per-mode completeness check. The Step-3 `OutputRegistry` (output → topic) is absorbed into the table's targets.
+- **Output** = the addressed destination: targets + selection policy + serializer. **OutputRegistry** = the `(Pipeline, Lane)` → output mapping with the per-mode completeness check. The Step-3 **TopicTable** (destination → topic) is absorbed into the registry's targets.
+- **Destination** = a routed topic slot (`AnalyticsMain`, `Dlq`, `AiEvents`, `Custom`). One word across both stacks: v0's `sinks::registry::Destination` and v1's `v1::sinks::types::Destination` are the same concept and converge at Step 20. Never name a backend policy tree an `Output` *and* a routed topic an `Output`.
- **Sink** = backend mechanism. Kafka, S3, print, noop. Nothing else is a sink; a thing that picks between sinks is an output policy.
- **Serializer** = format × envelope. Formats and envelopes compose; neither knows about sinks or outputs.
@@ -68,10 +69,10 @@ The `assert_routing` suite pins topic + partition key + every stamped header + t
The decision is the target `Output` plus the customer-facing `OrderingGuarantee` the sink realizes as a partition key; side effects are implied by the target rather than carried as decision data, the AI overflow valve rides in as an explicit argument to keep the function pure, and a replay decision with no session id is rejected rather than returned unrealizable.
This is the function Step 5 hoists out of the sink into lane resolution.
-#### Step 3 · `OutputRegistry` + startup completeness check
+#### Step 3 · `TopicTable` + startup completeness check
-One output→topic wiring point plus refuse-to-boot on a blank topic, gated behind `CAPTURE_OUTPUTS_COMPLETENESS_CHECK_ENABLED` (default off; see Step 9's arming precondition).
-Step 7 absorbs it into the `OutputTable`; the mode-scoped demand is folded in at Step 9, where `(Pipeline, Lane)` makes the per-mode reachable set explicit.
+One destination→topic wiring point plus refuse-to-boot on a blank topic, gated behind `CAPTURE_OUTPUTS_COMPLETENESS_CHECK_ENABLED` (default off; see Step 9's arming precondition).
+Step 7 absorbs it into the `OutputRegistry`; the mode-scoped demand is folded in at Step 9, where `(Pipeline, Lane)` makes the per-mode reachable set explicit.
### Stage B — the two new seams (no caller-visible change)
@@ -111,18 +112,19 @@ Step 7 absorbs it into the `OutputTable`; the mode-scoped demand is folded in at
- **Goal.** New `outputs` module — the produce surface, with multi-target policy ownership from day one:
- `Output`: a single backend, or a policy composing two *outputs* — today `failover` (health-gated Kafka→S3: skip primary while the advisory handle is unhealthy, re-publish the batch on a retriable failure, fatal never fails over). Targets are outputs themselves, so a future policy (a split for the next cluster migration) composes over pairs the way the old composites did. Policies operate on *events*, before prep — each target resolves topics and serializes for itself, exactly like the old per-sink `send_batch` paths, so parity is structural.
- - Leaves run the dance internally via the `pub(crate)` `Prepare` trait (prep → publish → fold); no caller ever sees a two-phase protocol.
- - `OutputTable`: the `(pipeline, lane)` → output handle the state holds; degenerate today (one deployment-wide output; per-lane topics resolve in prep via the `OutputRegistry`).
+ - Leaves run the dance internally via the `pub(crate)` `PublishEvents` trait (prep → publish → fold); no caller ever sees a two-phase protocol.
+ - `OutputRegistry`: the `(pipeline, lane)` → output handle the state holds; degenerate today (one deployment-wide output; per-lane topics resolve in prep via the `TopicTable`).
- `setup::create_output` builds the policy tree from the same config; **`FallbackSink` is deleted**, its tests re-expressed on `Output` with assertions preserved (+ a new fatal-no-failover case).
- Call sites are untouched: the table serves them through a transitional `Event` facade (which records `capture_event_batch_size`, where the old sink impls recorded it). Migration is Step 8.
-- **Files.** `rust/capture/src/outputs.rs` (new); `rust/capture/src/setup.rs`; `rust/capture/src/sinks/{mod,s3,print,noop,test_sink}.rs` (mechanism + `Prepare` impls); `fallback.rs` deleted.
+ - The facade is the only `dyn Event` the production call sites see, so the per-sink `Event` impls on s3, print, and noop are deleted here rather than rewired onto `PublishEvents`. `Event` survives only where callers still need it: the Kafka bridge and `MockSink`, both consumed by tests that Step 8 retypes.
+- **Files.** `rust/capture/src/outputs.rs` (new); `rust/capture/src/setup.rs`; `rust/capture/src/sinks/{mod,s3,print,noop,test_sink}.rs` (mechanism + `PublishEvents` impls); `fallback.rs` deleted.
- **Parity proof.** Goldens + all integration suites unmodified. Known metrics-only deltas, accepted: the batch-size histogram now records on the fallback-to-S3 path (it silently didn't before), and print/noop single sends record it (they didn't).
- **Risk / rollback.** Medium. Revert.
- **Size.** L.
#### Step 8 · Call sites migrate to the table; `Event` retired
-- **Goal.** All four call sites (`events/analytics.rs`, `ai_endpoint.rs`, `otel/mod.rs`, `events/recordings.rs`) publish via `OutputTable::publish`, recording `capture_event_batch_size` at the call site; `State` and test mocks retype; then delete the v0 `Event` trait, the outputs facade, the Kafka `Event` bridge, and the single-event `kafka_send` path.
+- **Goal.** All four call sites (`events/analytics.rs`, `ai_endpoint.rs`, `otel/mod.rs`, `events/recordings.rs`) publish via `OutputRegistry::publish`, recording `capture_event_batch_size` at the call site; `State` and test mocks retype; then delete the v0 `Event` trait, the outputs facade, the Kafka `Event` bridge, and the single-event `kafka_send` path.
- **Parity proof.** All endpoint/integration suites green; grep proves `Event` call-site-free before the deletion half.
- **Size.** M/L. May split into per-call-site commits if the diff grows.
@@ -130,7 +132,7 @@ Step 7 absorbs it into the `OutputTable`; the mode-scoped demand is folded in at
#### Step 9 · Mode-scoped registry completeness
-- **Goal.** `OutputRegistry::check_complete` scopes its demand per `CaptureMode`: an Events/Ai pod demands the analytics family, a Recordings pod main/replay-overflow/dlq only.
+- **Goal.** `TopicTable::check_complete` scopes its demand per `CaptureMode`: an Events/Ai pod demands the analytics family, a Recordings pod main/replay-overflow/dlq only.
- **Arming precondition.** `CAPTURE_OUTPUTS_COMPLETENESS_CHECK_ENABLED` stays off in every deployment until this step lands and the chart env is audited for explicitly-blank topic values.
The mode-blind check demands every registered topic on every pod, so a recordings or import deployment that sets an analytics topic to `""` would crashloop the fleet at boot, not degrade.
- **Parity proof.** Per-mode refusal + anti-over-demand tests.
@@ -150,9 +152,9 @@ Step 7 absorbs it into the `OutputTable`; the mode-scoped demand is folded in at
### Stage E — prep hoists up; sinks become pure transport
-#### Step 12 · Prep hoists into the outputs layer; `Prepare` retired
+#### Step 12 · Prep hoists into the outputs layer; `PublishEvents` retired
-- **Goal.** Sinks take prepared payloads as input, full stop. `PrepSpec` (registry + per-destination serializers) moves payload assembly — lane resolution, serialization, header stamps, topic and partition key, and the scatter-gather batch prep — into the outputs layer; the `(pipeline, lane)` → output bridge and the `OutputRegistry` move with it (`outputs::registry`). The `Prepare` trait is deleted; every backend (Kafka, S3, print, noop) preps identically via its output's spec, and the Kafka sink is reduced to producer + enqueue + ack drain. The boot completeness check moves to `setup::create_output`.
+- **Goal.** Sinks take prepared payloads as input, full stop. `PrepSpec` (registry + per-destination serializers) moves payload assembly — lane resolution, serialization, header stamps, topic and partition key, and the scatter-gather batch prep — into the outputs layer; the `(pipeline, lane)` → output bridge and the `TopicTable` move with it (`outputs::topics`). The `PublishEvents` trait is deleted; every backend (Kafka, S3, print, noop) preps identically via its output's spec, and the Kafka sink is reduced to producer + enqueue + ack drain. The boot completeness check moves to `setup::create_output`.
- **Test posture change (deliberate).** Capturing mocks intercept *published payloads*, not `ProcessedEvent`s, so ~60 assertions that read metadata stamps migrate to wire-level outcomes: topic, partition key, headers, and payload bytes (deserialized for content checks). The declarative `ExpectedEvent` checkers recompute the expected record from the same expectations, so test bodies stay put. Wire-level assertions also pin a semantic the metadata-level ones couldn't see: replay events redirected to dlq/custom topics partition on the event key, not the session id.
- **Known deltas, accepted:** print/noop deployments run the real prep path (lane effects and their counters included), and prep can fail there (e.g. `MissingSessionId`) where the old passthrough couldn't. The prep histograms keep their `capture_kafka_*` names for dashboard continuity.
- **Files.** `outputs/mod.rs`, `outputs/registry.rs` (moved), `sinks/*`, `setup.rs`, all capturing test mocks.
@@ -238,11 +240,11 @@ The hold window is per-shard and bounded by one producer flush — that is the "
When all steps land, the five strata hold:
- **Pipelines and lanes.** `pipeline::resolve` is the one lane decision (dlq > custom > historical > overflow > main), pure over `ProcessedEventMetadata`; `Pipeline`/`Lane` are the event's address.
-- **Outputs are the produce surface.** Every pipeline publishes through the `OutputTable`; the `Output` policy tree (single | failover) owns all multi-target behavior, composing the way the old sink composites did. The v0 `Event` trait and `FallbackSink` are gone; `SplitKafkaSink` already is, deleted with the retired AI secondary-cluster routing.
+- **Outputs are the produce surface.** Every pipeline publishes through the `OutputRegistry`; the `Output` policy tree (single | failover) owns all multi-target behavior, composing the way the old sink composites did. The v0 `Event` trait and `FallbackSink` are gone; `SplitKafkaSink` already is, deleted with the retired AI secondary-cluster routing.
- **Serialization is a seam.** Format × envelope per destination, with content headers carrying encoding coexistence (the lz4 replay design, generalized); a protobuf cutover is an output-level config change.
- **Sinks are mechanism, and own their namespace.** Payloads carry the abstract `Address`; each sink realizes it in its own namespace at publish time (Kafka: its per-cluster topic table — the swappable seam a repartitioning coordinator plugs into; S3: the buffer path; print/noop: trivially). Sinks make no routing decisions; a failover pair can share one prepared batch because payloads are target-agnostic. Serialization stays output-level (a consumer contract, shared across targets).
- **Breaker failover is dark-launched** behind `CAPTURE_FAILOVER_ENABLED` as the failover output's autonomous mode.
-- **v1 resolves topics through the shared `OutputRegistry`** via `Destination::as_output`. The v1 `Sink`/`Router` trait convergence stays gated on the per-event response model.
+- **v1 resolves topics through the shared `TopicTable`** via `Destination::as_output`. The v1 `Sink`/`Router` trait convergence stays gated on the per-event response model.
## Agent conventions
@@ -263,17 +265,17 @@ When all steps land, the five strata hold:
| 0 · This plan doc | done | `docs(capture): outputs refactor plan and progress tracker` |
| 1 · Routing golden oracle | done | `test(capture): consolidate routing golden oracle with headers and counters` |
| 2 · Pure `route()` | done | `refactor(capture): extract pure route() from prepare_record` |
-| 3 · `OutputRegistry` + completeness | done | `refactor(capture): output registry with startup completeness check` |
+| 3 · `TopicTable` + completeness | done | `refactor(capture): output registry with startup completeness check` |
| 4 · Serialization layer | done | `refactor(capture): serialization layer behind one seam` |
| 5 · `Pipeline` + `Lane`; lane resolution | done | `refactor(capture): lane decision moves to the pipeline layer` |
| 6 · Kafka sink → backend mechanism | done | `refactor(capture): narrow the kafka sink to backend mechanism over prepared payloads` |
-| 7 · Outputs layer with policies; composites retired | pending | `feat(capture): outputs layer owns the failover policy` |
+| 7 · Outputs layer with policies; composites retired | done | `feat(capture): outputs layer owns the failover policy` |
| 8a · Call sites on the table | pending | `refactor(capture): call sites publish through outputs` |
| 8b · `Event` retired | pending | `refactor(capture): retire v0 Event trait` |
| 9 · Mode-scoped completeness | pending | `refactor(capture): mode-scoped output registry completeness` |
| 10 · Breaker mode (dark) | pending | `feat(capture): breaker-driven failover mode (dark)` |
| 11 · v1 convergence | pending | `refactor(capture): v1 resolves through shared pipeline/lane strata` |
-| 12 · Prep hoist; `Prepare` retired | pending | `refactor(capture): hoist prep into outputs; sinks take prepared payloads only` |
+| 12 · Prep hoist; `PublishEvents` retired | pending | `refactor(capture): hoist prep into outputs; sinks take prepared payloads only` |
| 13 · Typed addresses; AI pipeline | pending | `refactor(capture): typed per-pipeline lanes; custom redirects and the ai stream become addresses` |
| 14 · Sinks realize namespaces | pending | `refactor(capture): payloads carry addresses; sinks realize them in their own namespace` |
| 15 · Per-mode output tables | pending | `feat(capture): per-mode output tables; handlers bound by publish capabilities` |
diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rs
index 01ad1093c3e6..71821afd6634 100644
--- a/rust/capture/src/config.rs
+++ b/rust/capture/src/config.rs
@@ -503,7 +503,7 @@ pub struct KafkaConfig {
#[envconfig(default = "none")]
pub kafka_replay_envelope_compression: EnvelopeCompression,
/// Refuse to boot when a registered output resolves to an empty topic
- /// name (see `OutputRegistry::check_complete`). Config-only — the broker
+ /// name (see `TopicTable::check_complete`). Config-only — the broker
/// is never probed, so topic autocreation on first publish is unaffected.
/// Opt-in (default off) so deployments that deliberately blank a topic
/// they never produce to keep booting; arm it per deployment once its
diff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rs
index 4529114c7f1d..3375c2150e8e 100644
--- a/rust/capture/src/events/analytics.rs
+++ b/rust/capture/src/events/analytics.rs
@@ -1458,7 +1458,7 @@ mod tests {
"only the under-budget AI event must reach the sink"
);
let topics = test_topics();
- let ai_topic = topics.topic_for(&crate::sinks::registry::Output::AiMain);
+ let ai_topic = topics.topic_for(&crate::sinks::registry::Destination::AiMain);
assert_eq!(
records[0].topic, ai_topic,
"the surviving record must be on the AI lane"
@@ -1797,7 +1797,7 @@ mod tests {
"only the under-budget event must reach the sink under Ai mode"
);
let topics = test_topics();
- let ai_topic = topics.topic_for(&crate::sinks::registry::Output::AiMain);
+ let ai_topic = topics.topic_for(&crate::sinks::registry::Destination::AiMain);
assert_eq!(
records[0].topic, ai_topic,
"an allowlisted AI event diverts to the AI lane under Ai mode too"
diff --git a/rust/capture/src/lib.rs b/rust/capture/src/lib.rs
index ecf44577a4c2..b42cf97f6972 100644
--- a/rust/capture/src/lib.rs
+++ b/rust/capture/src/lib.rs
@@ -12,6 +12,7 @@ pub mod log_util;
pub mod metrics_middleware;
pub mod ordering;
pub mod otel;
+pub mod outputs;
/// Cross-path parity suite for the v0 and v1 overflow / rate-limit matrix.
#[cfg(test)]
mod overflow_parity;
diff --git a/rust/capture/src/outputs.rs b/rust/capture/src/outputs.rs
new file mode 100644
index 000000000000..02dbdbead4eb
--- /dev/null
+++ b/rust/capture/src/outputs.rs
@@ -0,0 +1,388 @@
+//! The outputs layer: the produce surface above the sinks.
+//!
+//! An [`Output`] is a published-to destination: either a single backend
+//! leaf, or a policy composing two child outputs. Today the one policy is
+//! failover (health-gated Kafka primary with an S3 secondary). Policies
+//! operate on *events*, before any payload prep, so each target resolves
+//! topics and serializes for itself.
+
+use async_trait::async_trait;
+use metrics::{counter, gauge, histogram};
+use tracing::instrument;
+use tracing::log::error;
+
+use crate::api::CaptureError;
+use crate::sinks::Event;
+use crate::v0_request::ProcessedEvent;
+
+/// The leaf produce contract: run prep, publish, and fold internally and
+/// report the v0 whole-request result, so no caller sees a two-phase
+/// protocol.
+#[async_trait]
+pub(crate) trait PublishEvents: Send + Sync {
+ async fn publish_one(&self, event: ProcessedEvent) -> Result<(), CaptureError>;
+
+ async fn publish_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError>;
+
+ fn flush(&self) -> Result<(), anyhow::Error> {
+ Ok(())
+ }
+}
+
+pub struct Output {
+ inner: Inner,
+}
+
+enum Inner {
+ Single(Box<dyn PublishEvents>),
+ Failover(Failover),
+}
+
+impl Output {
+ pub(crate) fn single<L: PublishEvents + 'static>(leaf: L) -> Self {
+ Self {
+ inner: Inner::Single(Box::new(leaf)),
+ }
+ }
+
+ /// Health-gated failover over two outputs. While the advisory handle
+ /// reports unhealthy the primary is skipped entirely; without a handle
+ /// the primary is always tried first. A retriable primary failure
+ /// re-publishes the batch on the fallback. Any other error is final:
+ /// a non-retryable error is a property of the event, not the backend,
+ /// so the fallback would reject it too.
+ pub(crate) fn failover(
+ primary: Output,
+ fallback: Output,
+ advisory_handle: Option<lifecycle::Handle>,
+ ) -> Self {
+ if advisory_handle.is_some() {
+ gauge!("capture_primary_sink_health").set(1.0);
+ }
+ Self {
+ inner: Inner::Failover(Failover {
+ primary: Box::new(primary),
+ fallback: Box::new(fallback),
+ advisory_handle,
+ }),
+ }
+ }
+}
+
+// `async_trait` boxes these futures, which is what lets the failover arm
+// recurse into its child outputs without building an infinitely-sized
+// future type.
+#[async_trait]
+impl PublishEvents for Output {
+ async fn publish_one(&self, event: ProcessedEvent) -> Result<(), CaptureError> {
+ match &self.inner {
+ Inner::Single(leaf) => leaf.publish_one(event).await,
+ Inner::Failover(failover) => failover.publish_one(event).await,
+ }
+ }
+
+ async fn publish_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {
+ match &self.inner {
+ Inner::Single(leaf) => leaf.publish_batch(events).await,
+ Inner::Failover(failover) => failover.publish_batch(events).await,
+ }
+ }
+
+ fn flush(&self) -> Result<(), anyhow::Error> {
+ match &self.inner {
+ Inner::Single(leaf) => leaf.flush(),
+ Inner::Failover(failover) => failover.flush(),
+ }
+ }
+}
+
+struct Failover {
+ primary: Box<Output>,
+ fallback: Box<Output>,
+ advisory_handle: Option<lifecycle::Handle>,
+}
+
+impl Failover {
+ fn primary_is_healthy(&self) -> bool {
+ self.advisory_handle
+ .as_ref()
+ .map(|h| h.is_healthy())
+ .unwrap_or(true)
+ }
+
+ #[instrument(skip_all)]
+ async fn publish_one(&self, event: ProcessedEvent) -> Result<(), CaptureError> {
+ let healthy = self.primary_is_healthy();
+ gauge!("capture_primary_sink_health").set(if healthy { 1.0 } else { 0.0 });
+
+ if healthy {
+ match self.primary.publish_one(event.clone()).await {
+ Ok(()) => Ok(()),
+ Err(CaptureError::RetryableSinkError) => {
+ error!("Primary output failed, falling back");
+ counter!("capture_fallback_sink_failovers_total").increment(1);
+ self.fallback.publish_one(event).await
+ }
+ Err(e) => Err(e),
+ }
+ } else {
+ counter!("capture_fallback_sink_failovers_total").increment(1);
+ self.fallback.publish_one(event).await
+ }
+ }
+
+ #[instrument(skip_all)]
+ async fn publish_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {
+ let healthy = self.primary_is_healthy();
+ gauge!("capture_primary_sink_health").set(if healthy { 1.0 } else { 0.0 });
+
+ if healthy {
+ match self.primary.publish_batch(events.clone()).await {
+ Ok(()) => Ok(()),
+ Err(CaptureError::RetryableSinkError) => {
+ error!("Primary output failed, falling back");
+ counter!("capture_fallback_sink_failovers_total").increment(1);
+ self.fallback.publish_batch(events).await
+ }
+ Err(e) => Err(e),
+ }
+ } else {
+ counter!("capture_fallback_sink_failovers_total").increment(1);
+ self.fallback.publish_batch(events).await
+ }
+ }
+
+ fn flush(&self) -> Result<(), anyhow::Error> {
+ self.primary.flush()
+ }
+}
+
+/// The (pipeline, lane) → output map the deployment state holds.
+/// Degenerate today: one deployment-wide output serves every address, and
+/// per-lane topics resolve during prep via the [`TopicTable`].
+///
+/// [`TopicTable`]: crate::sinks::registry::TopicTable
+pub struct OutputRegistry {
+ output: Output,
+}
+
+impl OutputRegistry {
+ pub fn new(output: Output) -> Self {
+ Self { output }
+ }
+}
+
+/// Transitional facade serving the `Event` call sites from the registry.
+#[async_trait]
+impl Event for OutputRegistry {
+ async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {
+ histogram!("capture_event_batch_size").record(1.0);
+ self.output.publish_one(event).await
+ }
+
+ async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {
+ histogram!("capture_event_batch_size").record(events.len() as f64);
+ self.output.publish_batch(events).await
+ }
+
+ fn flush(&self) -> Result<(), anyhow::Error> {
+ self.output.flush()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::sinks::test_sink::MockSink;
+ use crate::utils::uuid_v7_from_datetime;
+ use crate::v0_request::{DataType, ProcessedEventMetadata};
+ use common_types::CapturedEvent;
+ use std::time::Duration;
+
+ struct FailLeaf(CaptureError);
+
+ #[async_trait]
+ impl PublishEvents for FailLeaf {
+ async fn publish_one(&self, _event: ProcessedEvent) -> Result<(), CaptureError> {
+ Err(self.0.clone())
+ }
+
+ async fn publish_batch(&self, _events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {
+ Err(self.0.clone())
+ }
+ }
+
+ fn test_event() -> ProcessedEvent {
+ let timestamp = chrono::DateTime::parse_from_rfc3339("2024-01-01T00:00:00Z")
+ .unwrap()
+ .with_timezone(&chrono::Utc);
+ ProcessedEvent {
+ event: CapturedEvent {
+ uuid: uuid_v7_from_datetime(timestamp),
+ distinct_id: "test_id".to_string(),
+ session_id: None,
+ ip: "127.0.0.1".to_string(),
+ data: "test data".to_string(),
+ now: "2024-01-01T00:00:00Z".to_string(),
+ sent_at: None,
+ token: "test_token".to_string(),
+ event: "test_event".to_string(),
+ timestamp,
+ is_cookieless_mode: false,
+ historical_migration: false,
+ },
+ metadata: ProcessedEventMetadata {
+ data_type: DataType::AnalyticsMain,
+ session_id: None,
+ computed_timestamp: None,
+ event_name: "test_event".to_string(),
+ force_overflow: false,
+ skip_person_processing: false,
+ redirect_to_dlq: false,
+ redirect_to_topic: None,
+ skip_heatmap_processing: false,
+ overflow_reason: None,
+ distinct_id_truncated_from: None,
+ },
+ }
+ }
+
+ #[tokio::test]
+ async fn failover_republishes_on_retriable_primary_failure() {
+ let fallback = MockSink::new();
+ let output = Output::failover(
+ Output::single(FailLeaf(CaptureError::RetryableSinkError)),
+ Output::single(fallback.clone()),
+ None,
+ );
+
+ output
+ .publish_one(test_event())
+ .await
+ .expect("Failed to send event");
+
+ let batch = vec![test_event(), test_event()];
+ output
+ .publish_batch(batch)
+ .await
+ .expect("Failed to send batch");
+
+ assert_eq!(fallback.get_events().len(), 3);
+ }
+
+ #[tokio::test]
+ async fn failover_reports_the_error_when_both_targets_fail() {
+ let output = Output::failover(
+ Output::single(FailLeaf(CaptureError::RetryableSinkError)),
+ Output::single(FailLeaf(CaptureError::RetryableSinkError)),
+ None,
+ );
+
+ assert!(matches!(
+ output.publish_one(test_event()).await,
+ Err(CaptureError::RetryableSinkError)
+ ));
+
+ let batch = vec![test_event(), test_event()];
+ assert!(matches!(
+ output.publish_batch(batch).await,
+ Err(CaptureError::RetryableSinkError)
+ ));
+ }
+
+ #[tokio::test]
+ async fn fatal_primary_error_does_not_fail_over() {
+ let fallback = MockSink::new();
+ let output = Output::failover(
+ Output::single(FailLeaf(CaptureError::NonRetryableSinkError)),
+ Output::single(fallback.clone()),
+ None,
+ );
+
+ assert!(matches!(
+ output.publish_one(test_event()).await,
+ Err(CaptureError::NonRetryableSinkError)
+ ));
+ assert!(matches!(
+ output.publish_batch(vec![test_event()]).await,
+ Err(CaptureError::NonRetryableSinkError)
+ ));
+
+ assert!(
+ fallback.get_events().is_empty(),
+ "a fatal primary error must not reach the fallback"
+ );
+ }
+
+ #[tokio::test]
+ async fn advisory_handle_controls_primary_health() {
+ let mut manager = lifecycle::Manager::builder("test")
+ .with_trap_signals(false)
+ .with_prestop_check(false)
+ .with_health_poll_interval(Duration::from_millis(50))
+ .build();
+
+ let kafka_handle = manager.register(
+ "kafka-advisory",
+ lifecycle::ComponentOptions::new()
+ .with_liveness_deadline(Duration::from_millis(200))
+ .is_advisory(true),
+ );
+ let _s3_handle = manager.register(
+ "s3-sink",
+ lifecycle::ComponentOptions::new().with_liveness_deadline(Duration::from_millis(200)),
+ );
+
+ let _monitor = manager.monitor_background();
+
+ let primary = MockSink::new();
+ let fallback = MockSink::new();
+ let output = Output::failover(
+ Output::single(primary.clone()),
+ Output::single(fallback.clone()),
+ Some(kafka_handle.clone()),
+ );
+
+ kafka_handle.report_healthy();
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ output.publish_one(test_event()).await.unwrap();
+ assert_eq!(
+ (primary.get_events().len(), fallback.get_events().len()),
+ (1, 0),
+ "primary should serve while the kafka advisory reports healthy"
+ );
+
+ // Let the advisory handle's deadline expire without calling report_healthy
+ tokio::time::sleep(Duration::from_millis(400)).await;
+ output.publish_one(test_event()).await.unwrap();
+ assert_eq!(
+ (primary.get_events().len(), fallback.get_events().len()),
+ (1, 1),
+ "fallback should serve when the kafka advisory deadline expires"
+ );
+
+ kafka_handle.report_healthy();
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ output.publish_one(test_event()).await.unwrap();
+ assert_eq!(
+ (primary.get_events().len(), fallback.get_events().len()),
+ (2, 1),
+ "primary should recover when the kafka advisory reports healthy again"
+ );
+ }
+
+ #[tokio::test]
+ async fn registry_facade_serves_event_call_sites() {
+ let leaf = MockSink::new();
+ let registry = OutputRegistry::new(Output::single(leaf.clone()));
+
+ registry.send(test_event()).await.unwrap();
+ registry
+ .send_batch(vec![test_event(), test_event()])
+ .await
+ .unwrap();
+
+ assert_eq!(leaf.get_events().len(), 3);
+ registry.flush().unwrap();
+ }
+}
diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rs
index 9034b3c0509c..24bd247ed569 100644
--- a/rust/capture/src/setup.rs
+++ b/rust/capture/src/setup.rs
@@ -16,13 +16,13 @@ use tracing::{info, warn};
use crate::config::{CaptureMode, Config};
use crate::event_restrictions::{EventRestrictionService, Pipeline, RedisRestrictionsRepository};
use crate::global_rate_limiter::{ai_byte_limit_window, GlobalRateLimiter};
+use crate::outputs::{Output, OutputRegistry};
use crate::prometheus::setup_metrics_recorder;
use crate::quota_limiters::{
is_exception_event, is_llm_event, is_survey_event, CaptureQuotaLimiter,
};
use crate::router;
use crate::router::BATCH_BODY_SIZE;
-use crate::sinks::fallback::FallbackSink;
use crate::sinks::kafka::KafkaSink;
use crate::sinks::noop::NoOpSink;
use crate::sinks::print::PrintSink;
@@ -571,11 +571,20 @@ async fn create_sink(
sink_handle: Option<lifecycle::Handle>,
advisory_handle: Option<lifecycle::Handle>,
) -> anyhow::Result<Box<dyn Event + Send + Sync>> {
+ let output = create_output(config, sink_handle, advisory_handle).await?;
+ Ok(Box::new(OutputRegistry::new(output)))
+}
+
+async fn create_output(
+ config: &Config,
+ sink_handle: Option<lifecycle::Handle>,
+ advisory_handle: Option<lifecycle::Handle>,
+) -> anyhow::Result<Output> {
if config.print_sink {
- Ok(Box::new(PrintSink {}))
+ Ok(Output::single(PrintSink {}))
} else if config.noop_sink {
info!("NoOpSink enabled, events will be silently dropped");
- Ok(Box::new(NoOpSink::new()))
+ Ok(Output::single(NoOpSink::new()))
} else if config.s3_fallback_enabled {
let s3_handle = sink_handle.expect("sink lifecycle handle required for S3 fallback");
let kafka_handle = advisory_handle.expect("kafka advisory handle required for fallback");
@@ -596,17 +605,17 @@ async fn create_sink(
.await
.expect("failed to create S3 sink");
- Ok(Box::new(FallbackSink::new_with_advisory(
- kafka_sink,
- s3_sink,
- kafka_handle,
- )))
+ Ok(Output::failover(
+ Output::single(kafka_sink),
+ Output::single(s3_sink),
+ Some(kafka_handle),
+ ))
} else {
let kafka_sink = KafkaSink::new(config.kafka.clone(), sink_handle)
.await
.context("failed to start Kafka sink")?;
- Ok(Box::new(kafka_sink))
+ Ok(Output::single(kafka_sink))
}
}
@@ -1218,7 +1227,7 @@ mod tests {
}
/// A blank output topic makes `create_sink` refuse to boot in every capture
- /// mode — the misconfig fails fast at startup (via the `OutputRegistry`
+ /// mode — the misconfig fails fast at startup (via the `TopicTable`
/// completeness check inside `KafkaSink::new`) rather than at first produce.
#[rstest::rstest]
#[case(CaptureMode::Events)]
diff --git a/rust/capture/src/sinks/fallback.rs b/rust/capture/src/sinks/fallback.rs
deleted file mode 100644
index ba888de867a3..000000000000
--- a/rust/capture/src/sinks/fallback.rs
+++ /dev/null
@@ -1,285 +0,0 @@
-use crate::api::CaptureError;
-use crate::sinks::Event;
-use crate::v0_request::ProcessedEvent;
-
-use async_trait::async_trait;
-use metrics::{counter, gauge};
-use std::sync::Arc;
-use tracing::instrument;
-use tracing::log::error;
-
-pub struct FallbackSink {
- primary: Arc<Box<dyn Event + Send + Sync + 'static>>,
- fallback: Arc<Box<dyn Event + Send + Sync + 'static>>,
- advisory_handle: Option<lifecycle::Handle>,
-}
-
-/// FallbackSink attempts to send events to the primary sink, and if it fails,
-/// it will send events to the fallback sink. When an advisory lifecycle handle
-/// is provided, it skips the primary entirely while the handle reports unhealthy.
-impl FallbackSink {
- pub fn new<P, F>(primary: P, fallback: F) -> Self
- where
- P: Event + Send + Sync + 'static,
- F: Event + Send + Sync + 'static,
- {
- Self {
- primary: Arc::new(Box::new(primary)),
- fallback: Arc::new(Box::new(fallback)),
- advisory_handle: None,
- }
- }
-
- pub fn new_with_advisory<P, F>(
- primary: P,
- fallback: F,
- advisory_handle: lifecycle::Handle,
- ) -> Self
- where
- P: Event + Send + Sync + 'static,
- F: Event + Send + Sync + 'static,
- {
- gauge!("capture_primary_sink_health").set(1.0);
- Self {
- primary: Arc::new(Box::new(primary)),
- fallback: Arc::new(Box::new(fallback)),
- advisory_handle: Some(advisory_handle),
- }
- }
-
- fn primary_is_healthy(&self) -> bool {
- self.advisory_handle
- .as_ref()
- .map(|h| h.is_healthy())
- .unwrap_or(true)
- }
-}
-
-#[async_trait]
-impl Event for FallbackSink {
- #[instrument(skip_all)]
- async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {
- let healthy = self.primary_is_healthy();
- gauge!("capture_primary_sink_health").set(if healthy { 1.0 } else { 0.0 });
-
- if healthy {
- match self.primary.send(event.clone()).await {
- Ok(_) => Ok(()),
- Err(CaptureError::RetryableSinkError) => {
- error!("Primary sink failed, falling back");
- counter!("capture_fallback_sink_failovers_total").increment(1);
- self.fallback.send(event).await
- }
- Err(e) => Err(e),
- }
- } else {
- counter!("capture_fallback_sink_failovers_total").increment(1);
- self.fallback.send(event).await
- }
- }
-
- #[instrument(skip_all)]
- async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {
- let healthy = self.primary_is_healthy();
- gauge!("capture_primary_sink_health").set(if healthy { 1.0 } else { 0.0 });
-
- if healthy {
- match self.primary.send_batch(events.clone()).await {
- Ok(_) => Ok(()),
- Err(CaptureError::RetryableSinkError) => {
- error!("Primary sink failed, falling back");
- counter!("capture_fallback_sink_failovers_total").increment(1);
- self.fallback.send_batch(events).await
- }
- Err(e) => Err(e),
- }
- } else {
- counter!("capture_fallback_sink_failovers_total").increment(1);
- self.fallback.send_batch(events).await
- }
- }
-
- fn flush(&self) -> Result<(), anyhow::Error> {
- self.primary.flush()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::sinks::print::PrintSink;
- use crate::utils::uuid_v7_from_datetime;
- use crate::v0_request::{DataType, ProcessedEventMetadata};
- use common_types::CapturedEvent;
- use std::time::Duration;
-
- #[derive(Clone)]
- pub struct FailSink {}
-
- #[async_trait]
- impl Event for FailSink {
- async fn send(&self, _event: ProcessedEvent) -> Result<(), CaptureError> {
- Err(CaptureError::RetryableSinkError)
- }
- async fn send_batch(&self, _events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {
- Err(CaptureError::RetryableSinkError)
- }
- }
-
- #[tokio::test]
- async fn test_fallback_sink() {
- let fail_sink = FailSink {};
- let print_sink = PrintSink {};
-
- let fallback_sink = FallbackSink::new(fail_sink, print_sink);
-
- // Create test event
- let timestamp = chrono::DateTime::parse_from_rfc3339("2024-01-01T00:00:00Z")
- .unwrap()
- .with_timezone(&chrono::Utc);
- let event = ProcessedEvent {
- event: CapturedEvent {
- uuid: uuid_v7_from_datetime(timestamp),
- distinct_id: "test_id".to_string(),
- session_id: None,
- ip: "127.0.0.1".to_string(),
- data: "test data".to_string(),
- now: "2024-01-01T00:00:00Z".to_string(),
- sent_at: None,
- token: "test_token".to_string(),
- event: "test_event".to_string(),
- timestamp,
- is_cookieless_mode: false,
- historical_migration: false,
- },
- metadata: ProcessedEventMetadata {
- data_type: DataType::AnalyticsMain,
- session_id: None,
- computed_timestamp: None,
- event_name: "test_event".to_string(),
- force_overflow: false,
- skip_person_processing: false,
- redirect_to_dlq: false,
- redirect_to_topic: None,
- skip_heatmap_processing: false,
- overflow_reason: None,
- distinct_id_truncated_from: None,
- },
- };
-
- // Should fail over to print sink
- fallback_sink
- .send(event.clone())
- .await
- .expect("Failed to send event");
-
- // Test batch
- let batch = vec![event.clone(), event.clone()];
- fallback_sink
- .send_batch(batch)
- .await
- .expect("Failed to send batch");
- }
-
- #[tokio::test]
- async fn test_fallback_sink_fail() {
- let fail_sink = FailSink {};
- let fallback_sink = FallbackSink::new(fail_sink.clone(), fail_sink);
-
- // Create test event
- let timestamp = chrono::DateTime::parse_from_rfc3339("2024-01-01T00:00:00Z")
- .unwrap()
- .with_timezone(&chrono::Utc);
- let event = ProcessedEvent {
- event: CapturedEvent {
- uuid: uuid_v7_from_datetime(timestamp),
- distinct_id: "test_id".to_string(),
- session_id: None,
- ip: "127.0.0.1".to_string(),
- data: "test data".to_string(),
- now: "2024-01-01T00:00:00Z".to_string(),
- sent_at: None,
- token: "test_token".to_string(),
- event: "test_event".to_string(),
- timestamp,
- is_cookieless_mode: false,
- historical_migration: false,
- },
- metadata: ProcessedEventMetadata {
- data_type: DataType::AnalyticsMain,
- session_id: None,
- computed_timestamp: None,
- event_name: "test_event".to_string(),
- force_overflow: false,
- skip_person_processing: false,
- redirect_to_dlq: false,
- redirect_to_topic: None,
- skip_heatmap_processing: false,
- overflow_reason: None,
- distinct_id_truncated_from: None,
- },
- };
-
- // Should fail over to print sink
-
- assert!(matches!(
- fallback_sink.send(event.clone()).await,
- Err(CaptureError::RetryableSinkError)
- ));
-
- // Test batch
- let batch = vec![event.clone(), event.clone()];
- assert!(matches!(
- fallback_sink.send_batch(batch).await,
- Err(CaptureError::RetryableSinkError)
- ));
- }
-
- #[tokio::test]
- async fn test_advisory_handle_controls_primary_health() {
- let mut manager = lifecycle::Manager::builder("test")
- .with_trap_signals(false)
- .with_prestop_check(false)
- .with_health_poll_interval(Duration::from_millis(50))
- .build();
-
- let kafka_handle = manager.register(
- "kafka-advisory",
- lifecycle::ComponentOptions::new()
- .with_liveness_deadline(Duration::from_millis(200))
- .is_advisory(true),
- );
- let _s3_handle = manager.register(
- "s3-sink",
- lifecycle::ComponentOptions::new().with_liveness_deadline(Duration::from_millis(200)),
- );
-
- let _monitor = manager.monitor_background();
-
- let sink =
- FallbackSink::new_with_advisory(PrintSink {}, PrintSink {}, kafka_handle.clone());
-
- // Advisory handle starts healthy
- kafka_handle.report_healthy();
- tokio::time::sleep(Duration::from_millis(100)).await;
- assert!(
- sink.primary_is_healthy(),
- "primary should be healthy when kafka advisory reports healthy"
- );
-
- // Let the advisory handle's deadline expire without calling report_healthy
- tokio::time::sleep(Duration::from_millis(400)).await;
- assert!(
- !sink.primary_is_healthy(),
- "primary should be unhealthy when kafka advisory deadline expires"
- );
-
- // Recovery: report healthy again
- kafka_handle.report_healthy();
- tokio::time::sleep(Duration::from_millis(100)).await;
- assert!(
- sink.primary_is_healthy(),
- "primary should recover when kafka advisory reports healthy again"
- );
- }
-}
diff --git a/rust/capture/src/sinks/kafka.rs b/rust/capture/src/sinks/kafka.rs
index 10449fd26002..3fa38d829709 100644
--- a/rust/capture/src/sinks/kafka.rs
+++ b/rust/capture/src/sinks/kafka.rs
@@ -20,10 +20,11 @@
use crate::api::CaptureError;
use crate::config::{EnvelopeCompression, KafkaConfig};
use crate::ordering::OrderingGuarantee;
+use crate::outputs::PublishEvents;
use crate::pipeline::{self, Address, Lane, Pipeline};
use crate::serialization::Serializer;
use crate::sinks::producer::{KafkaProducer, ProduceRecord};
-use crate::sinks::registry::{Output, OutputRegistry};
+use crate::sinks::registry::{Destination, TopicTable};
use crate::sinks::sink::{fold_results, Outcome, PreparedPayload, Sink, SinkResult};
use crate::sinks::Event;
use crate::v0_request::{DataType, ProcessedEvent};
@@ -184,7 +185,7 @@ impl rdkafka::ClientContext for KafkaContext {
/// is cloned once per spawned prep task.
pub struct KafkaSinkBase<P: KafkaProducer> {
producer: Arc<P>,
- topics: Arc<OutputRegistry>,
+ topics: Arc<TopicTable>,
replay_envelope_compression: EnvelopeCompression,
}
@@ -198,7 +199,7 @@ impl<P: KafkaProducer> Clone for KafkaSinkBase<P> {
}
}
-/// Map a lane address to the sink's configured [`Output`]. The sink owns
+/// Map a lane address to the sink's configured [`Destination`]. The sink owns
/// this mapping only until the outputs layer exists to own the address →
/// output table. Every `(pipeline, lane)` pair is spelled out so that a new
/// lane, or a change making an unbacked pair reachable, has to visit this
@@ -206,22 +207,22 @@ impl<P: KafkaProducer> Clone for KafkaSinkBase<P> {
/// [`pipeline::resolve`] never produces — no output backs it, and the caller
/// dlqs the event (the typed-per-pipeline-lanes step makes these pairs
/// unrepresentable).
-fn lane_output(pipeline: Pipeline, lane: Lane) -> Option<Output> {
+fn lane_output(pipeline: Pipeline, lane: Lane) -> Option<Destination> {
match (pipeline, lane) {
- (Pipeline::Analytics, Lane::Main) => Some(Output::AnalyticsMain),
- (Pipeline::Analytics, Lane::Overflow) => Some(Output::AnalyticsOverflow),
- (Pipeline::Analytics, Lane::Historical) => Some(Output::AnalyticsHistorical),
- (Pipeline::Ai, Lane::Main) => Some(Output::AiMain),
- (Pipeline::Ai, Lane::Overflow) => Some(Output::AiOverflow),
+ (Pipeline::Analytics, Lane::Main) => Some(Destination::AnalyticsMain),
+ (Pipeline::Analytics, Lane::Overflow) => Some(Destination::AnalyticsOverflow),
+ (Pipeline::Analytics, Lane::Historical) => Some(Destination::AnalyticsHistorical),
+ (Pipeline::Ai, Lane::Main) => Some(Destination::AiMain),
+ (Pipeline::Ai, Lane::Overflow) => Some(Destination::AiOverflow),
(Pipeline::Ai, Lane::Historical) => None,
- (Pipeline::Warnings, Lane::Main) => Some(Output::ClientWarningsMain),
+ (Pipeline::Warnings, Lane::Main) => Some(Destination::ClientWarningsMain),
(Pipeline::Warnings, Lane::Overflow | Lane::Historical) => None,
- (Pipeline::Heatmaps, Lane::Main) => Some(Output::HeatmapsMain),
+ (Pipeline::Heatmaps, Lane::Main) => Some(Destination::HeatmapsMain),
(Pipeline::Heatmaps, Lane::Overflow | Lane::Historical) => None,
- (Pipeline::ErrorTracking, Lane::Main) => Some(Output::ErrorTrackingMain),
+ (Pipeline::ErrorTracking, Lane::Main) => Some(Destination::ErrorTrackingMain),
(Pipeline::ErrorTracking, Lane::Overflow | Lane::Historical) => None,
- (Pipeline::Replay, Lane::Main) => Some(Output::SessionReplayMain),
- (Pipeline::Replay, Lane::Overflow) => Some(Output::SessionReplayOverflow),
+ (Pipeline::Replay, Lane::Main) => Some(Destination::SessionReplayMain),
+ (Pipeline::Replay, Lane::Overflow) => Some(Destination::SessionReplayOverflow),
(Pipeline::Replay, Lane::Historical) => None,
}
}
@@ -249,7 +250,7 @@ impl KafkaSink {
// here, at startup, instead of at first produce. Config-only, so it
// runs before the producer is built and the broker is pinged — the
// refusal is instant, not one connect attempt later.
- let registry = OutputRegistry::from(&config);
+ let registry = TopicTable::from(&config);
if config.outputs_completeness_check_enabled {
registry.check_complete()?;
} else {
@@ -388,7 +389,7 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
/// Create a new KafkaSinkBase with a custom producer (useful for testing).
/// No limiters — the sink is a mechanism layer; overflow stamping happens
/// upstream in the pipeline. See the module header for details.
- pub fn with_producer(producer: P, topics: OutputRegistry) -> Self {
+ pub fn with_producer(producer: P, topics: TopicTable) -> Self {
Self {
producer: Arc::new(producer),
topics: Arc::new(topics),
@@ -399,7 +400,7 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
/// Same as `with_producer` but with envelope compression enabled. Used in tests.
pub fn with_producer_and_compression(
producer: P,
- topics: OutputRegistry,
+ topics: TopicTable,
replay_envelope_compression: EnvelopeCompression,
) -> Self {
Self {
@@ -420,14 +421,6 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
/// pure mechanism. DLQ and custom-topic redirects take priority over
/// overflow routing.
///
- /// Prep lives in this file rather than the outputs layer because it
- /// reads state the sink still owns (the topic registry, the replay
- /// envelope setting). Keeping it off the `Sink` trait is what matters
- /// for the layering: callers above can prep and publish as separate
- /// phases. The prep hoist (step 12 of
- /// `rust/capture/OUTPUTS_REFACTOR_PLAN.md`) moves the assembly and that
- /// state up; drop this note when it lands.
- ///
/// Not `async`: there are no await points, and keeping it
/// synchronous lets `prepare_batch`'s serial fast path call it inline
/// without any runtime indirection.
@@ -480,7 +473,7 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
let target = match decision.address {
Address::Dlq => {
dlq_reroute_effects(&mut headers, "event_restriction");
- Output::Dlq
+ Destination::Dlq
}
Address::Custom(topic) => {
counter!(
@@ -488,7 +481,7 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
&[("reason", "event_restriction")]
)
.increment(1);
- Output::Custom(topic)
+ Destination::Custom(topic)
}
Address::Lane { pipeline, lane } => match lane_output(pipeline, lane) {
Some(output) => output,
@@ -501,7 +494,7 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
debug_assert!(false, "no output backs ({pipeline:?}, {lane:?})");
error!("no output backs ({pipeline:?}, {lane:?}), publishing to the dlq");
dlq_reroute_effects(&mut headers, "unbacked_lane");
- Output::Dlq
+ Destination::Dlq
}
},
};
@@ -733,8 +726,27 @@ impl<P: KafkaProducer + 'static> Sink for KafkaSinkBase<P> {
}
#[async_trait]
-impl<P: KafkaProducer + 'static> Event for KafkaSinkBase<P> {
+impl<P: KafkaProducer + 'static> PublishEvents for KafkaSinkBase<P> {
+ #[instrument(skip_all)]
+ async fn publish_one(&self, event: ProcessedEvent) -> Result<(), CaptureError> {
+ self.kafka_send(event)?
+ .instrument(info_span!("ack_wait_one"))
+ .await
+ }
+
#[instrument(skip_all)]
+ async fn publish_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {
+ let payloads = self.prepare_batch(events).await?;
+ fold_results(self.publish(payloads).await)
+ }
+
+ fn flush(&self) -> Result<(), anyhow::Error> {
+ Sink::flush(self)
+ }
+}
+
+#[async_trait]
+impl<P: KafkaProducer + 'static> Event for KafkaSinkBase<P> {
async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {
let ack_future = self.kafka_send(event)?;
histogram!("capture_event_batch_size").record(1.0);
@@ -744,15 +756,13 @@ impl<P: KafkaProducer + 'static> Event for KafkaSinkBase<P> {
/// The v0 bridge onto the mechanism seam: prep, publish, fold. The
/// per-event results collapse to the whole-request `CaptureError` the
/// `Event` callers expect.
- #[instrument(skip_all)]
async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {
// Record the batch-size histogram up front so the distribution is a
// faithful view of batches submitted, not only those that succeeded.
// Matches the single-event `send` path which records before any await.
histogram!("capture_event_batch_size").record(events.len() as f64);
- let payloads = self.prepare_batch(events).await?;
- fold_results(self.publish(payloads).await)
+ PublishEvents::publish_batch(self, events).await
}
fn flush(&self) -> Result<(), anyhow::Error> {
diff --git a/rust/capture/src/sinks/mod.rs b/rust/capture/src/sinks/mod.rs
index 1b6e44ee96a6..d39284d78e48 100644
--- a/rust/capture/src/sinks/mod.rs
+++ b/rust/capture/src/sinks/mod.rs
@@ -2,7 +2,6 @@ use async_trait::async_trait;
use crate::{api::CaptureError, v0_request::ProcessedEvent};
-pub mod fallback;
pub mod kafka;
pub mod noop;
pub mod print;
@@ -37,5 +36,3 @@ impl<T: Event + ?Sized + Send + Sync> Event for Box<T> {
(**self).flush()
}
}
-
-pub use fallback::FallbackSink;
diff --git a/rust/capture/src/sinks/noop.rs b/rust/capture/src/sinks/noop.rs
index 65a2815eacb2..085021d91566 100644
--- a/rust/capture/src/sinks/noop.rs
+++ b/rust/capture/src/sinks/noop.rs
@@ -1,8 +1,8 @@
use async_trait::async_trait;
-use metrics::{counter, histogram};
+use metrics::counter;
use crate::api::CaptureError;
-use crate::sinks::Event;
+use crate::outputs::PublishEvents;
use crate::v0_request::ProcessedEvent;
#[derive(Default)]
@@ -15,13 +15,13 @@ impl NoOpSink {
}
#[async_trait]
-impl Event for NoOpSink {
- async fn send(&self, _event: ProcessedEvent) -> Result<(), CaptureError> {
+impl PublishEvents for NoOpSink {
+ async fn publish_one(&self, _event: ProcessedEvent) -> Result<(), CaptureError> {
counter!("capture_events_ingested_total").increment(1);
Ok(())
}
- async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {
- histogram!("capture_event_batch_size").record(events.len() as f64);
+
+ async fn publish_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {
counter!("capture_events_ingested_total").increment(events.len() as u64);
Ok(())
}
diff --git a/rust/capture/src/sinks/print.rs b/rust/capture/src/sinks/print.rs
index c4d73d1cc0f2..c11925c349eb 100644
--- a/rust/capture/src/sinks/print.rs
+++ b/rust/capture/src/sinks/print.rs
@@ -1,27 +1,27 @@
use async_trait::async_trait;
-use metrics::{counter, histogram};
+use metrics::counter;
use tracing::log::info;
use crate::api::CaptureError;
-use crate::sinks::Event;
+use crate::outputs::PublishEvents;
use crate::v0_request::ProcessedEvent;
pub struct PrintSink {}
#[async_trait]
-impl Event for PrintSink {
- async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {
+impl PublishEvents for PrintSink {
+ async fn publish_one(&self, event: ProcessedEvent) -> Result<(), CaptureError> {
info!("single event: {:?}", event);
counter!("capture_events_ingested_total").increment(1);
Ok(())
}
- async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {
+
+ async fn publish_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {
let span = tracing::span!(tracing::Level::INFO, "batch of events");
let _enter = span.enter();
- histogram!("capture_event_batch_size").record(events.len() as f64);
counter!("capture_events_ingested_total").increment(events.len() as u64);
for event in events {
info!("event: {event:?}");
diff --git a/rust/capture/src/sinks/registry.rs b/rust/capture/src/sinks/registry.rs
index 2d6c3d0b8bd6..5177bfd21494 100644
--- a/rust/capture/src/sinks/registry.rs
+++ b/rust/capture/src/sinks/registry.rs
@@ -1,7 +1,7 @@
-//! Output registry — the topic-completeness surface.
+//! Destination registry — the topic-completeness surface.
//!
-//! Binds every fixed routing [`Output`] variant to its configured Kafka topic
-//! and provides a startup completeness check ([`OutputRegistry::check_complete`])
+//! Binds every fixed routing [`Destination`] variant to its configured Kafka topic
+//! and provides a startup completeness check ([`TopicTable::check_complete`])
//! that refuses to boot when any fixed output resolves to an empty topic. This
//! is the single place the output→topic wiring lives, so adding an output is a
//! one-place change: the `topic_for` and `is_required` matches are
@@ -19,13 +19,13 @@ use crate::config::KafkaConfig;
/// Which configured output a routing decision selects, named **pipeline +
/// lane** — the vocabulary the refactor converges on (typed per-pipeline
/// lanes; see the plan doc). The sink resolves each output to a concrete
-/// topic string against the [`OutputRegistry`]; distinct outputs may share a
+/// topic string against the [`TopicTable`]; distinct outputs may share a
/// topic (analytics main and session-replay main both resolve the
/// deployment's main topic today). Mirrors v1's `Destination` split — the
/// convergence target when the v1 stack folds onto this registry (see the
/// plan doc).
#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum Output {
+pub enum Destination {
AnalyticsMain,
AnalyticsOverflow,
AnalyticsHistorical,
@@ -48,20 +48,20 @@ pub enum Output {
Custom(String),
}
-impl Output {
+impl Destination {
/// Every registered always-required output. `check_complete` walks this so
/// a newly added output is caught at boot rather than at first produce.
- const REGISTERED: [Output; 10] = [
- Output::AnalyticsMain,
- Output::AnalyticsOverflow,
- Output::AnalyticsHistorical,
- Output::ClientWarningsMain,
- Output::HeatmapsMain,
- Output::SessionReplayMain,
- Output::SessionReplayOverflow,
- Output::Dlq,
- Output::ErrorTrackingMain,
- Output::AiMain,
+ const REGISTERED: [Destination; 10] = [
+ Destination::AnalyticsMain,
+ Destination::AnalyticsOverflow,
+ Destination::AnalyticsHistorical,
+ Destination::ClientWarningsMain,
+ Destination::HeatmapsMain,
+ Destination::SessionReplayMain,
+ Destination::SessionReplayOverflow,
+ Destination::Dlq,
+ Destination::ErrorTrackingMain,
+ Destination::AiMain,
];
/// Whether this output participates in the boot completeness check.
@@ -73,19 +73,19 @@ impl Output {
#[cfg(test)]
fn is_required(&self) -> bool {
match self {
- Output::AnalyticsMain
- | Output::AnalyticsOverflow
- | Output::AnalyticsHistorical
- | Output::ClientWarningsMain
- | Output::HeatmapsMain
- | Output::SessionReplayMain
- | Output::SessionReplayOverflow
- | Output::Dlq
- | Output::ErrorTrackingMain
- | Output::AiMain => true,
+ Destination::AnalyticsMain
+ | Destination::AnalyticsOverflow
+ | Destination::AnalyticsHistorical
+ | Destination::ClientWarningsMain
+ | Destination::HeatmapsMain
+ | Destination::SessionReplayMain
+ | Destination::SessionReplayOverflow
+ | Destination::Dlq
+ | Destination::ErrorTrackingMain
+ | Destination::AiMain => true,
// The opt-in AI overflow valve and per-event custom topics sit
// outside the check.
- Output::AiOverflow | Output::Custom(_) => false,
+ Destination::AiOverflow | Destination::Custom(_) => false,
}
}
@@ -93,26 +93,26 @@ impl Output {
/// "custom" so admin topic names never leak into error messages.
fn name(&self) -> &'static str {
match self {
- Output::AnalyticsMain => "analytics-main",
- Output::AnalyticsOverflow => "analytics-overflow",
- Output::AnalyticsHistorical => "analytics-historical",
- Output::ClientWarningsMain => "clientwarnings-main",
- Output::HeatmapsMain => "heatmaps-main",
- Output::SessionReplayMain => "sessionreplay-main",
- Output::SessionReplayOverflow => "sessionreplay-overflow",
- Output::Dlq => "dlq",
- Output::ErrorTrackingMain => "errortracking-main",
- Output::AiMain => "ai-main",
- Output::AiOverflow => "ai-overflow",
- Output::Custom(_) => "custom",
+ Destination::AnalyticsMain => "analytics-main",
+ Destination::AnalyticsOverflow => "analytics-overflow",
+ Destination::AnalyticsHistorical => "analytics-historical",
+ Destination::ClientWarningsMain => "clientwarnings-main",
+ Destination::HeatmapsMain => "heatmaps-main",
+ Destination::SessionReplayMain => "sessionreplay-main",
+ Destination::SessionReplayOverflow => "sessionreplay-overflow",
+ Destination::Dlq => "dlq",
+ Destination::ErrorTrackingMain => "errortracking-main",
+ Destination::AiMain => "ai-main",
+ Destination::AiOverflow => "ai-overflow",
+ Destination::Custom(_) => "custom",
}
}
}
/// The one place output→topic wiring lives. Holds the configured topic for every
-/// fixed [`Output`] variant. Cheap to clone; the sink holds it behind an `Arc`.
+/// fixed [`Destination`] variant. Cheap to clone; the sink holds it behind an `Arc`.
#[derive(Clone, Debug)]
-pub struct OutputRegistry {
+pub struct TopicTable {
pub(crate) main: String,
pub(crate) overflow: String,
pub(crate) historical: String,
@@ -121,40 +121,40 @@ pub struct OutputRegistry {
pub(crate) replay_overflow: String,
pub(crate) dlq: String,
pub(crate) error_tracking: String,
- /// Dedicated topic for `Output::AiMain` (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`,
+ /// Dedicated topic for `Destination::AiMain` (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`,
/// required with a default).
pub(crate) ai_events: String,
/// Overflow topic for the AI lane. Unset means the AI overflow valve is
- /// unarmed and routing never selects `Output::AiOverflow`.
+ /// unarmed and routing never selects `Destination::AiOverflow`.
pub(crate) ai_events_overflow: Option<String>,
}
-impl OutputRegistry {
+impl TopicTable {
/// Resolve an output to its topic. Fixed outputs read the registered topic;
/// `Custom` returns its inline, admin-supplied topic.
- pub fn topic_for<'a>(&'a self, output: &'a Output) -> &'a str {
+ pub fn topic_for<'a>(&'a self, output: &'a Destination) -> &'a str {
match output {
- Output::AnalyticsMain | Output::SessionReplayMain => &self.main,
- Output::AnalyticsOverflow => &self.overflow,
- Output::AnalyticsHistorical => &self.historical,
- Output::ClientWarningsMain => &self.client_ingestion_warning,
- Output::HeatmapsMain => &self.heatmaps,
- Output::SessionReplayOverflow => &self.replay_overflow,
- Output::Dlq => &self.dlq,
- Output::ErrorTrackingMain => &self.error_tracking,
- Output::AiMain => &self.ai_events,
- Output::AiOverflow => match self.ai_events_overflow.as_deref() {
+ Destination::AnalyticsMain | Destination::SessionReplayMain => &self.main,
+ Destination::AnalyticsOverflow => &self.overflow,
+ Destination::AnalyticsHistorical => &self.historical,
+ Destination::ClientWarningsMain => &self.client_ingestion_warning,
+ Destination::HeatmapsMain => &self.heatmaps,
+ Destination::SessionReplayOverflow => &self.replay_overflow,
+ Destination::Dlq => &self.dlq,
+ Destination::ErrorTrackingMain => &self.error_tracking,
+ Destination::AiMain => &self.ai_events,
+ Destination::AiOverflow => match self.ai_events_overflow.as_deref() {
Some(topic) if !topic.is_empty() => topic,
// Unreachable: routing only selects this output when the
// valve is armed, i.e. exactly when the topic is set.
_ => &self.ai_events,
},
- Output::Custom(topic) => topic,
+ Destination::Custom(topic) => topic,
}
}
/// Whether the AI overflow valve is armed: the AI overflow topic is wired,
- /// so routing may select `Output::AiOverflow`.
+ /// so routing may select `Destination::AiOverflow`.
pub fn ai_events_overflow_armed(&self) -> bool {
self.ai_events_overflow
.as_deref()
@@ -167,7 +167,7 @@ impl OutputRegistry {
/// (it carries its own topic per event), as is the opt-in `AiOverflow`
/// valve (unset means routing never selects it).
pub fn check_complete(&self) -> anyhow::Result<()> {
- for output in &Output::REGISTERED {
+ for output in &Destination::REGISTERED {
anyhow::ensure!(
!self.topic_for(output).is_empty(),
"output '{}' resolves to an empty Kafka topic; every non-custom \
@@ -179,7 +179,7 @@ impl OutputRegistry {
}
}
-impl From<&KafkaConfig> for OutputRegistry {
+impl From<&KafkaConfig> for TopicTable {
fn from(config: &KafkaConfig) -> Self {
Self {
main: config.kafka_topic.clone(),
@@ -196,12 +196,12 @@ impl From<&KafkaConfig> for OutputRegistry {
}
}
-/// Shared `OutputRegistry` fixture for tests across the capture crate. Used by
+/// Shared `TopicTable` fixture for tests across the capture crate. Used by
/// sink-side routing tests and pipeline-to-sink E2E tests so every test site
/// asserts against the same canonical topic names.
#[cfg(test)]
-pub(crate) fn test_topics() -> OutputRegistry {
- OutputRegistry {
+pub(crate) fn test_topics() -> TopicTable {
+ TopicTable {
main: "events_plugin_ingestion".to_string(),
overflow: "events_plugin_ingestion_overflow".to_string(),
historical: "events_plugin_ingestion_historical".to_string(),
@@ -221,18 +221,18 @@ mod tests {
use rstest::rstest;
#[rstest]
- #[case(Output::AnalyticsMain, "events_plugin_ingestion")]
- #[case(Output::SessionReplayMain, "events_plugin_ingestion")]
- #[case(Output::AnalyticsOverflow, "events_plugin_ingestion_overflow")]
- #[case(Output::AnalyticsHistorical, "events_plugin_ingestion_historical")]
- #[case(Output::ClientWarningsMain, "client_ingestion_warning")]
- #[case(Output::HeatmapsMain, "heatmaps")]
- #[case(Output::SessionReplayOverflow, "replay_overflow")]
- #[case(Output::Dlq, "events_plugin_ingestion_dlq")]
- #[case(Output::ErrorTrackingMain, "error_tracking_events")]
- #[case(Output::AiMain, "ai_events")]
- #[case(Output::AiOverflow, "ai_events_overflow")]
- fn topic_for_resolves_registered_outputs(#[case] output: Output, #[case] expected: &str) {
+ #[case(Destination::AnalyticsMain, "events_plugin_ingestion")]
+ #[case(Destination::SessionReplayMain, "events_plugin_ingestion")]
+ #[case(Destination::AnalyticsOverflow, "events_plugin_ingestion_overflow")]
+ #[case(Destination::AnalyticsHistorical, "events_plugin_ingestion_historical")]
+ #[case(Destination::ClientWarningsMain, "client_ingestion_warning")]
+ #[case(Destination::HeatmapsMain, "heatmaps")]
+ #[case(Destination::SessionReplayOverflow, "replay_overflow")]
+ #[case(Destination::Dlq, "events_plugin_ingestion_dlq")]
+ #[case(Destination::ErrorTrackingMain, "error_tracking_events")]
+ #[case(Destination::AiMain, "ai_events")]
+ #[case(Destination::AiOverflow, "ai_events_overflow")]
+ fn topic_for_resolves_registered_outputs(#[case] output: Destination, #[case] expected: &str) {
assert_eq!(test_topics().topic_for(&output), expected);
}
@@ -240,7 +240,7 @@ mod tests {
fn topic_for_custom_returns_inline_topic() {
let registry = test_topics();
assert_eq!(
- registry.topic_for(&Output::Custom("admin_topic".to_string())),
+ registry.topic_for(&Destination::Custom("admin_topic".to_string())),
"admin_topic"
);
}
@@ -253,7 +253,7 @@ mod tests {
registry.ai_events_overflow = None;
assert!(registry.check_complete().is_ok());
assert!(!registry.ai_events_overflow_armed());
- assert_eq!(registry.topic_for(&Output::AiMain), "ai_events");
+ assert_eq!(registry.topic_for(&Destination::AiMain), "ai_events");
}
#[test]
@@ -269,22 +269,22 @@ mod tests {
#[test]
fn registered_is_exactly_the_required_outputs() {
let all = [
- Output::AnalyticsMain,
- Output::AnalyticsOverflow,
- Output::AnalyticsHistorical,
- Output::ClientWarningsMain,
- Output::HeatmapsMain,
- Output::SessionReplayMain,
- Output::SessionReplayOverflow,
- Output::Dlq,
- Output::ErrorTrackingMain,
- Output::AiMain,
- Output::AiOverflow,
- Output::Custom("t".to_string()),
+ Destination::AnalyticsMain,
+ Destination::AnalyticsOverflow,
+ Destination::AnalyticsHistorical,
+ Destination::ClientWarningsMain,
+ Destination::HeatmapsMain,
+ Destination::SessionReplayMain,
+ Destination::SessionReplayOverflow,
+ Destination::Dlq,
+ Destination::ErrorTrackingMain,
+ Destination::AiMain,
+ Destination::AiOverflow,
+ Destination::Custom("t".to_string()),
];
for output in &all {
assert_eq!(
- Output::REGISTERED.contains(output),
+ Destination::REGISTERED.contains(output),
output.is_required(),
"'{}' must be in REGISTERED exactly when it is required",
output.name()
@@ -295,18 +295,18 @@ mod tests {
/// Every registered output, blanked one at a time, must fail the check and
/// the error must name the offending output.
#[rstest]
- #[case("analytics-main", |r: &mut OutputRegistry| r.main.clear())]
- #[case("analytics-overflow", |r: &mut OutputRegistry| r.overflow.clear())]
- #[case("analytics-historical", |r: &mut OutputRegistry| r.historical.clear())]
- #[case("clientwarnings-main", |r: &mut OutputRegistry| r.client_ingestion_warning.clear())]
- #[case("heatmaps-main", |r: &mut OutputRegistry| r.heatmaps.clear())]
- #[case("sessionreplay-overflow", |r: &mut OutputRegistry| r.replay_overflow.clear())]
- #[case("dlq", |r: &mut OutputRegistry| r.dlq.clear())]
- #[case("errortracking-main", |r: &mut OutputRegistry| r.error_tracking.clear())]
- #[case("ai-main", |r: &mut OutputRegistry| r.ai_events.clear())]
+ #[case("analytics-main", |r: &mut TopicTable| r.main.clear())]
+ #[case("analytics-overflow", |r: &mut TopicTable| r.overflow.clear())]
+ #[case("analytics-historical", |r: &mut TopicTable| r.historical.clear())]
+ #[case("clientwarnings-main", |r: &mut TopicTable| r.client_ingestion_warning.clear())]
+ #[case("heatmaps-main", |r: &mut TopicTable| r.heatmaps.clear())]
+ #[case("sessionreplay-overflow", |r: &mut TopicTable| r.replay_overflow.clear())]
+ #[case("dlq", |r: &mut TopicTable| r.dlq.clear())]
+ #[case("errortracking-main", |r: &mut TopicTable| r.error_tracking.clear())]
+ #[case("ai-main", |r: &mut TopicTable| r.ai_events.clear())]
fn check_complete_rejects_empty_topic(
#[case] output_name: &str,
- #[case] blank: fn(&mut OutputRegistry),
+ #[case] blank: fn(&mut TopicTable),
) {
let mut registry = test_topics();
blank(&mut registry);
diff --git a/rust/capture/src/sinks/s3.rs b/rust/capture/src/sinks/s3.rs
index 65d3cab44e51..955a31d34d64 100644
--- a/rust/capture/src/sinks/s3.rs
+++ b/rust/capture/src/sinks/s3.rs
@@ -17,7 +17,7 @@ use tracing::instrument;
use tracing::log::{debug, error, info};
use crate::api::CaptureError;
-use crate::sinks::Event;
+use crate::outputs::PublishEvents;
const FLUSH_INTERVAL: Duration = Duration::from_secs(1);
const HEALTH_INTERVAL: Duration = Duration::from_secs(10);
@@ -274,9 +274,9 @@ impl Inner {
}
#[async_trait]
-impl Event for S3Sink {
+impl PublishEvents for S3Sink {
#[instrument(skip_all)]
- async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {
+ async fn publish_one(&self, event: ProcessedEvent) -> Result<(), CaptureError> {
let mut buffer = self.inner.buffer.lock().await;
buffer.add_event(event)?;
let mut rx = buffer.tx.subscribe();
@@ -287,7 +287,7 @@ impl Event for S3Sink {
}
#[instrument(skip_all)]
- async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {
+ async fn publish_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {
let mut buffer = self.inner.buffer.lock().await;
for event in events {
buffer.add_event(event)?;
@@ -376,13 +376,15 @@ mod tests {
// Test single event
let event = create_test_event();
- sink.send(event.clone())
+ sink.publish_one(event.clone())
.await
- .expect("Failed to send event");
+ .expect("Failed to publish event");
// Test batch
let batch = vec![event.clone(), event.clone()];
- sink.send_batch(batch).await.expect("Failed to send batch");
+ sink.publish_batch(batch)
+ .await
+ .expect("Failed to publish batch");
}
#[tokio::test]
@@ -399,6 +401,8 @@ mod tests {
metadata: create_test_event().metadata,
};
- sink.send(event).await.expect("Failed to send large event");
+ sink.publish_one(event)
+ .await
+ .expect("Failed to publish large event");
}
}
diff --git a/rust/capture/src/sinks/test_sink.rs b/rust/capture/src/sinks/test_sink.rs
index 00bc743ce9a1..2c2c2e860c90 100644
--- a/rust/capture/src/sinks/test_sink.rs
+++ b/rust/capture/src/sinks/test_sink.rs
@@ -10,6 +10,7 @@
//! the sink before wrapping in `Arc<dyn Event>`)
use crate::api::CaptureError;
+use crate::outputs::PublishEvents;
use crate::sinks::Event;
use crate::v0_request::ProcessedEvent;
use async_trait::async_trait;
@@ -42,3 +43,16 @@ impl Event for MockSink {
Ok(())
}
}
+
+#[async_trait]
+impl PublishEvents for MockSink {
+ async fn publish_one(&self, event: ProcessedEvent) -> Result<(), CaptureError> {
+ self.events.lock().unwrap().push(event);
+ Ok(())
+ }
+
+ async fn publish_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {
+ self.events.lock().unwrap().extend(events);
+ Ok(())
+ }
+}
diff --git a/rust/capture/src/v1/test_utils.rs b/rust/capture/src/v1/test_utils.rs
index ad8620cbb196..05e43d89e592 100644
--- a/rust/capture/src/v1/test_utils.rs
+++ b/rust/capture/src/v1/test_utils.rs
@@ -675,6 +675,7 @@ use limiters::token_dropper::TokenDropper;
use crate::config::CaptureMode;
use crate::event_restrictions::EventRestrictionService;
use crate::global_rate_limiter::GlobalRateLimiter;
+use crate::outputs::{Output, OutputRegistry};
use crate::quota_limiters::CaptureQuotaLimiter;
use crate::router::{self, HistoricalConfig};
use crate::sinks;
@@ -915,8 +916,9 @@ impl TestStateBuilder {
let v1_router = v1_sinks::Router::new(SinkName::Msk, sinks_map);
// Legacy sink — no-op since V1 tests go through v1_sink_router
- let legacy_sink: Arc<dyn sinks::Event + Send + Sync> =
- Arc::new(crate::sinks::noop::NoOpSink::new());
+ let legacy_sink: Arc<dyn sinks::Event + Send + Sync> = Arc::new(OutputRegistry::new(
+ Output::single(crate::sinks::noop::NoOpSink::new()),
+ ));
let timesource: Arc<dyn TimeSource + Send + Sync> = Arc::new(crate::time::SystemTime {});
diff --git a/rust/capture/tests/integration_person_processing_matrix.rs b/rust/capture/tests/integration_person_processing_matrix.rs
index 99b3efd14d3a..837e69cbd4ed 100644
--- a/rust/capture/tests/integration_person_processing_matrix.rs
+++ b/rust/capture/tests/integration_person_processing_matrix.rs
@@ -45,7 +45,7 @@ use capture::quota_limiters::CaptureQuotaLimiter;
use capture::router::router;
use capture::sinks::kafka::KafkaSinkBase;
use capture::sinks::producer::MockKafkaProducer;
-use capture::sinks::registry::OutputRegistry;
+use capture::sinks::registry::TopicTable;
use capture::time::TimeSource;
use capture::v1::router::{router as v1_router, RouterConfig as V1RouterConfig};
use capture::v1::test_utils::TestStateBuilder;
@@ -226,7 +226,7 @@ async fn run_v0(inputs: Inputs, distinct_ids: &[&str]) -> Batch {
let service = build_restrictions(inputs).await;
let producer = MockKafkaProducer::new();
- let sink = KafkaSinkBase::with_producer(producer.clone(), OutputRegistry::from(&cfg.kafka));
+ let sink = KafkaSinkBase::with_producer(producer.clone(), TopicTable::from(&cfg.kafka));
let quota_limiter =
CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));