1use std::sync::Arc;
13use std::time::{Duration, Instant};
14
15use differential_dataflow::operators::arrange::{Arrange, Arranged, TraceAgent};
16use differential_dataflow::trace::TraceReader;
17use differential_dataflow::trace::implementations::ord_neu::OrdValBatcher;
18use differential_dataflow::{AsCollection, Hashable, VecCollection};
19use mz_persist_client::operators::shard_source::SnapshotMode;
20use mz_repr::{Datum, Diff, GlobalId, Row, Timestamp};
21use mz_row_spine::{ArcOrdValBuilder, ArcOrdValSpine};
22use mz_storage_operators::persist_source;
23use mz_storage_types::controller::CollectionMetadata;
24use mz_storage_types::errors::DataflowError;
25use mz_storage_types::sinks::{StorageSinkConnection, StorageSinkDesc};
26use mz_timely_util::builder_async::PressOnDropButton;
27use timely::dataflow::operators::Leave;
28use timely::dataflow::{Scope, StreamVec};
29use tracing::warn;
30
31use crate::healthcheck::HealthStatusMessage;
32use crate::storage_state::StorageState;
33
34pub(crate) type SinkTrace = TraceAgent<ArcOrdValSpine<Option<Row>, Row, Timestamp, Diff>>;
38
39pub(crate) type SinkBatchStream<'scope> =
47 StreamVec<'scope, Timestamp, <SinkTrace as TraceReader>::Batch>;
48
49pub(crate) fn render_sink<'scope>(
53 scope: Scope<'scope, ()>,
54 storage_state: &mut StorageState,
55 sink_id: GlobalId,
56 sink: &StorageSinkDesc<CollectionMetadata, mz_repr::Timestamp>,
57) -> (
58 StreamVec<'scope, (), HealthStatusMessage>,
59 Vec<PressOnDropButton>,
60) {
61 let snapshot_mode = if sink.with_snapshot {
62 SnapshotMode::Include
63 } else {
64 SnapshotMode::Exclude
65 };
66
67 let error_handler = storage_state.error_handler("storage_sink", sink_id);
68
69 let name = format!("{sink_id}-sinks");
70 let outer_scope = scope.clone();
71
72 scope.scoped(&name, |scope| {
73 let mut tokens = vec![];
74 let sink_render = get_sink_render_for(&sink.connection);
75
76 let (ok_collection, err_collection, persist_tokens) = persist_source::persist_source(
77 scope,
78 sink.from,
79 Arc::clone(&storage_state.persist_clients),
80 &storage_state.txns_ctx,
81 sink.from_storage_metadata.clone(),
82 None,
83 Some(sink.as_of.clone()),
84 snapshot_mode,
85 timely::progress::Antichain::new(),
86 None,
87 None,
88 async {},
89 error_handler,
90 );
91 tokens.extend(persist_tokens);
92
93 let batches = arrange_sink_input(&*sink_render, ok_collection.as_collection());
94 let key_is_synthetic = sink_render.get_key_indices().is_none()
95 && sink_render.get_relation_key_indices().is_none();
96
97 let (health, sink_tokens) = sink_render.render_sink(
98 storage_state,
99 sink,
100 sink_id,
101 batches,
102 key_is_synthetic,
103 err_collection.as_collection(),
104 );
105 tokens.extend(sink_tokens);
106 (health.leave(outer_scope), tokens)
107 })
108}
109
110fn arrange_sink_input<'scope>(
123 sink_render: &dyn SinkRender<'scope>,
124 collection: VecCollection<'scope, Timestamp, Row, Diff>,
125) -> SinkBatchStream<'scope> {
126 let key_indices = sink_render
127 .get_key_indices()
128 .or_else(|| sink_render.get_relation_key_indices())
129 .map(|k| k.to_vec());
130
131 let keyed = match key_indices {
132 None => collection.map(|row| (Some(Row::pack(Some(Datum::UInt64(row.hashed())))), row)),
133 Some(key_indices) => {
134 let mut datum_vec = mz_repr::DatumVec::new();
135 collection.map(move |row| {
136 let key = {
139 let datums = datum_vec.borrow_with(&row);
140 Row::pack(key_indices.iter().map(|&idx| datums[idx].clone()))
141 };
142 (Some(key), row)
143 })
144 }
145 };
146
147 #[allow(clippy::disallowed_methods)]
150 let Arranged {stream, trace: _} = keyed.arrange_named::<OrdValBatcher<_, _, _, _>, ArcOrdValBuilder<_, _, _, _>, ArcOrdValSpine<_, _, _, _>>("Arrange Sink");
151 stream
152}
153
154pub(crate) struct PkViolationWarner {
166 sink_id: GlobalId,
167 from_id: GlobalId,
168 last_warning: Instant,
169 current: Option<(u64, Timestamp)>,
170 count: usize,
171}
172
173impl PkViolationWarner {
174 pub fn new(sink_id: GlobalId, from_id: GlobalId) -> Self {
175 Self {
176 sink_id,
177 from_id,
178 last_warning: Instant::now(),
179 current: None,
180 count: 0,
181 }
182 }
183
184 pub fn observe(&mut self, key: &Option<Row>, time: Timestamp) {
188 let hash = key.as_ref().map(|k| k.hashed()).unwrap_or(u64::MAX);
192 let same = self.current == Some((hash, time));
193 if !same {
194 self.flush();
195 self.current = Some((hash, time));
196 }
197 self.count += 1;
198 }
199
200 pub fn flush(&mut self) {
203 if self.count > 1 {
204 let now = Instant::now();
205 if now.duration_since(self.last_warning) >= Duration::from_secs(10) {
206 self.last_warning = now;
207 warn!(
208 sink_id = ?self.sink_id,
209 from_id = ?self.from_id,
210 "primary key error: expected at most one update per key and timestamp; \
211 this can happen when the configured sink key is not a primary key of \
212 the sinked relation"
213 );
214 }
215 }
216 self.current = None;
217 self.count = 0;
218 }
219}
220
221pub(crate) trait SinkRender<'scope> {
223 fn get_key_indices(&self) -> Option<&[usize]>;
226
227 fn get_relation_key_indices(&self) -> Option<&[usize]>;
230
231 fn render_sink(
241 &self,
242 storage_state: &mut StorageState,
243 sink: &StorageSinkDesc<CollectionMetadata, Timestamp>,
244 sink_id: GlobalId,
245 batches: SinkBatchStream<'scope>,
246 key_is_synthetic: bool,
247 err_collection: VecCollection<'scope, Timestamp, DataflowError, Diff>,
248 ) -> (
249 StreamVec<'scope, Timestamp, HealthStatusMessage>,
250 Vec<PressOnDropButton>,
251 );
252}
253
254fn get_sink_render_for<'scope>(connection: &StorageSinkConnection) -> Box<dyn SinkRender<'scope>> {
255 match connection {
256 StorageSinkConnection::Kafka(connection) => Box::new(connection.clone()),
257 StorageSinkConnection::Iceberg(connection) => Box::new(connection.clone()),
258 }
259}