mz_compute_client/controller/
instance_client.rs1use std::sync::Arc;
17
18use mz_build_info::BuildInfo;
19use mz_cluster_client::WallclockLagFn;
20use mz_compute_types::ComputeInstanceId;
21use mz_dyncfg::ConfigSet;
22use mz_expr::RowSetFinishing;
23use mz_ore::now::NowFn;
24use mz_ore::tracing::OpenTelemetryContext;
25use mz_persist_types::PersistLocation;
26use mz_repr::{GlobalId, RelationDesc, Row, Timestamp};
27use mz_storage_types::read_holds::{self, ReadHold};
28use thiserror::Error;
29use timely::progress::{Antichain, ChangeBatch};
30use tokio::sync::mpsc::error::SendError;
31use tokio::sync::{mpsc, oneshot};
32use tracing::debug_span;
33use uuid::Uuid;
34
35use crate::controller::error::CollectionMissing;
36use crate::controller::instance::{Command, Instance, SharedCollectionState};
37use crate::controller::peek_lifecycle::PeekLifecycle;
38use crate::controller::{
39 ComputeControllerResponse, IntrospectionUpdates, ReplicaId, StorageCollections,
40};
41use crate::logging::LogVariant;
42use crate::metrics::InstanceMetrics;
43use crate::protocol::command::PeekTarget;
44use crate::protocol::response::PeekResponse;
45
46#[derive(Error, Debug)]
48#[error("the instance has shut down")]
49pub struct InstanceShutDown;
50
51#[derive(Error, Debug)]
53pub enum PeekError {
54 #[error("replica does not exist: {0}")]
56 ReplicaMissing(ReplicaId),
57 #[error("read hold ID does not match peeked collection: {0}")]
59 ReadHoldIdMismatch(GlobalId),
60 #[error("insufficient read hold provided: {0}")]
62 ReadHoldInsufficient(GlobalId),
63 #[error("the instance has shut down")]
65 InstanceShutDown,
66}
67
68impl From<InstanceShutDown> for PeekError {
69 fn from(_error: InstanceShutDown) -> Self {
70 Self::InstanceShutDown
71 }
72}
73
74#[derive(Error, Debug)]
76pub enum AcquireReadHoldsError {
77 #[error("collection does not exist: {0}")]
79 CollectionMissing(GlobalId),
80 #[error("the instance has shut down")]
82 InstanceShutDown,
83}
84
85impl From<CollectionMissing> for AcquireReadHoldsError {
86 fn from(error: CollectionMissing) -> Self {
87 Self::CollectionMissing(error.0)
88 }
89}
90
91impl From<InstanceShutDown> for AcquireReadHoldsError {
92 fn from(_error: InstanceShutDown) -> Self {
93 Self::InstanceShutDown
94 }
95}
96
97#[derive(Clone, derivative::Derivative)]
99#[derivative(Debug)]
100pub struct InstanceClient {
101 command_tx: mpsc::UnboundedSender<Command>,
103 #[derivative(Debug = "ignore")]
105 read_hold_tx: read_holds::ChangeTx,
106}
107
108impl InstanceClient {
109 pub(super) fn read_hold_tx(&self) -> read_holds::ChangeTx {
110 Arc::clone(&self.read_hold_tx)
111 }
112
113 pub(super) fn call<F>(&self, f: F) -> Result<(), InstanceShutDown>
116 where
117 F: FnOnce(&mut Instance) + Send + 'static,
118 {
119 let otel_ctx = OpenTelemetryContext::obtain();
120 self.command_tx
121 .send(Box::new(move |instance| {
122 let _span = debug_span!("instance_client::call").entered();
123 otel_ctx.attach_as_parent();
124
125 f(instance)
126 }))
127 .map_err(|_send_error| InstanceShutDown)
128 }
129
130 pub(super) async fn call_sync<F, R>(&self, f: F) -> Result<R, InstanceShutDown>
133 where
134 F: FnOnce(&mut Instance) -> R + Send + 'static,
135 R: Send + 'static,
136 {
137 let (tx, rx) = oneshot::channel();
138 let otel_ctx = OpenTelemetryContext::obtain();
139 self.command_tx
140 .send(Box::new(move |instance| {
141 let _span = debug_span!("instance_client::call_sync").entered();
142 otel_ctx.attach_as_parent();
143 let result = f(instance);
144 let _ = tx.send(result);
145 }))
146 .map_err(|_send_error| InstanceShutDown)?;
147
148 rx.await.map_err(|_| InstanceShutDown)
149 }
150
151 pub(super) fn spawn(
152 id: ComputeInstanceId,
153 build_info: &'static BuildInfo,
154 storage: StorageCollections,
155 peek_stash_persist_location: PersistLocation,
156 arranged_logs: Vec<(LogVariant, GlobalId, SharedCollectionState)>,
157 metrics: InstanceMetrics,
158 now: NowFn,
159 wallclock_lag: WallclockLagFn<Timestamp>,
160 dyncfg: Arc<ConfigSet>,
161 response_tx: mpsc::UnboundedSender<ComputeControllerResponse>,
162 introspection_tx: mpsc::UnboundedSender<IntrospectionUpdates>,
163 read_only: bool,
164 ) -> Self {
165 let (command_tx, command_rx) = mpsc::unbounded_channel();
166
167 let read_hold_tx: read_holds::ChangeTx = {
168 let command_tx = command_tx.clone();
169 Arc::new(move |id, change: ChangeBatch<_>| {
170 let cmd: Command = {
171 let change = change.clone();
172 Box::new(move |i| i.apply_read_hold_change(id, change))
173 };
174 command_tx.send(cmd).map_err(|_| SendError((id, change)))
175 })
176 };
177
178 mz_ore::task::spawn(
179 || format!("compute-instance-{id}"),
180 Instance::new(
181 build_info,
182 storage,
183 peek_stash_persist_location,
184 arranged_logs,
185 metrics,
186 now,
187 wallclock_lag,
188 dyncfg,
189 command_rx,
190 response_tx,
191 Arc::clone(&read_hold_tx),
192 introspection_tx,
193 read_only,
194 )
195 .run(),
196 );
197
198 Self {
199 command_tx,
200 read_hold_tx,
201 }
202 }
203
204 pub async fn acquire_read_holds_and_collection_write_frontiers(
207 &self,
208 ids: Vec<GlobalId>,
209 ) -> Result<Vec<(GlobalId, ReadHold, Antichain<Timestamp>)>, AcquireReadHoldsError> {
210 self.call_sync(move |i| {
211 let mut result = Vec::new();
212 for id in ids.into_iter() {
213 result.push((
214 id,
215 i.acquire_read_hold(id)?,
216 i.collection_write_frontier(id)?,
217 ));
218 }
219 Ok(result)
220 })
221 .await?
222 }
223
224 pub async fn peek(
233 &self,
234 peek_target: PeekTarget,
235 literal_constraints: Option<Vec<Row>>,
236 uuid: Uuid,
237 timestamp: Timestamp,
238 result_desc: RelationDesc,
239 finishing: RowSetFinishing,
240 map_filter_project: mz_expr::SafeMfpPlan,
241 target_read_hold: ReadHold,
242 target_replica: Option<ReplicaId>,
243 peek_response_tx: oneshot::Sender<PeekResponse>,
244 lifecycle: Option<Arc<PeekLifecycle>>,
245 ) -> Result<(), PeekError> {
246 let issue = self.peek_command(
247 peek_target,
248 literal_constraints,
249 uuid,
250 timestamp,
251 result_desc,
252 finishing,
253 map_filter_project,
254 target_read_hold,
255 target_replica,
256 peek_response_tx,
257 lifecycle,
258 );
259 self.call_sync(issue).await?
260 }
261
262 pub(super) fn peek_command(
265 &self,
266 peek_target: PeekTarget,
267 literal_constraints: Option<Vec<Row>>,
268 uuid: Uuid,
269 timestamp: Timestamp,
270 result_desc: RelationDesc,
271 finishing: RowSetFinishing,
272 map_filter_project: mz_expr::SafeMfpPlan,
273 target_read_hold: ReadHold,
274 target_replica: Option<ReplicaId>,
275 peek_response_tx: oneshot::Sender<PeekResponse>,
276 lifecycle: Option<Arc<PeekLifecycle>>,
277 ) -> impl FnOnce(&mut Instance) -> Result<(), PeekError> + Send + 'static {
278 let client = self.clone();
279 move |i| {
280 let mut response_tx = Some(peek_response_tx);
281 let issue = || {
282 i.peek(
283 peek_target,
284 literal_constraints,
285 uuid,
286 timestamp,
287 result_desc,
288 finishing,
289 map_filter_project,
290 target_read_hold,
291 target_replica,
292 response_tx.take().expect("peek issued once"),
293 lifecycle.clone(),
294 )
295 };
296 let Some(lifecycle) = &lifecycle else {
297 return issue();
298 };
299 let retired = lifecycle.issue(issue, move |reason| {
303 let _ = client.call(move |i| i.cancel_peek(uuid, reason));
305 })?;
306 if let Some(response) = retired {
307 let _ = response_tx
308 .take()
309 .expect("retired peek was not issued")
310 .send(response);
311 }
312 Ok(())
313 }
314 }
315}
316
317#[cfg(test)]
318mod tests {
319 use std::sync::Arc;
320 use std::task::Poll;
321
322 use mz_expr::{MapFilterProject, RowSetFinishing, SafeMfpPlan};
323 use mz_repr::{GlobalId, RelationDesc, Timestamp};
324 use mz_storage_types::read_holds::ReadHold;
325 use timely::progress::Antichain;
326 use tokio::sync::{mpsc, oneshot};
327 use uuid::Uuid;
328
329 use crate::controller::PeekNotification;
330 use crate::controller::instance::tests::peek_test_instance;
331 use crate::controller::peek_lifecycle::PeekLifecycle;
332 use crate::protocol::command::PeekTarget;
333 use crate::protocol::response::{PeekError, PeekResponse};
334
335 use super::InstanceClient;
336
337 #[mz_ore::test(tokio::test)]
338 async fn cancellation_before_instance_processes_issue_delivers_result() {
339 for response in [
340 PeekResponse::Canceled,
341 PeekResponse::Error(PeekError::unstructured("dependency dropped")),
342 ] {
343 let (mut instance, mut coordinator) = peek_test_instance();
344 let (command_tx, mut command_rx) = mpsc::unbounded_channel();
345 let client = InstanceClient {
346 command_tx,
347 read_hold_tx: Arc::new(|_, _| Ok(())),
348 };
349 let (retired_tx, mut retired_rx) = oneshot::channel();
350 let lifecycle = Arc::new(PeekLifecycle::new(move |outcome| {
351 retired_tx.send(outcome).unwrap();
352 }));
353 let (result_tx, result_rx) = oneshot::channel();
354 let hold = ReadHold::new(
356 GlobalId::User(2),
357 Antichain::from_elem(Timestamp::MIN),
358 Arc::new(|_, _| Ok(())),
359 );
360 let peek = client.peek(
361 PeekTarget::Index {
362 id: GlobalId::User(1),
363 },
364 None,
365 Uuid::new_v4(),
366 Timestamp::MIN,
367 RelationDesc::empty(),
368 RowSetFinishing::trivial(0),
369 SafeMfpPlan::from_mfp(MapFilterProject::new(0)),
370 hold,
371 None,
372 result_tx,
373 Some(Arc::clone(&lifecycle)),
374 );
375 futures::pin_mut!(peek);
376 assert!(matches!(futures::poll!(&mut peek), Poll::Pending));
377 let issue = command_rx.try_recv().expect("issue queued");
378 lifecycle.cancel(response.clone());
379 assert_eq!(retired_rx.try_recv().unwrap(), PeekNotification::Canceled);
380 issue(&mut instance);
381 peek.await
382 .expect("canceled issue succeeds without validation");
383 assert_eq!(result_rx.await.unwrap(), response);
384 assert!(
385 command_rx.try_recv().is_err(),
386 "unissued peek needs no cancel command"
387 );
388 assert!(coordinator.try_recv().is_err());
389 }
390 }
391}