1use std::collections::{BTreeMap, BTreeSet};
36use std::sync::{Arc, Mutex};
37use std::time::Duration;
38
39use mz_build_info::BuildInfo;
40use mz_cluster_client::client::ClusterReplicaLocation;
41use mz_cluster_client::metrics::ControllerMetrics;
42use mz_cluster_client::{ReplicaId, WallclockLagFn};
43use mz_compute_types::ComputeInstanceId;
44use mz_compute_types::config::ComputeReplicaConfig;
45use mz_compute_types::dataflows::DataflowDescription;
46use mz_compute_types::dyncfgs::COMPUTE_REPLICA_EXPIRATION_OFFSET;
47use mz_dyncfg::ConfigSet;
48use mz_expr::RowSetFinishing;
49use mz_ore::cast::CastFrom;
50use mz_ore::collections::CollectionExt;
51use mz_ore::metrics::MetricsRegistry;
52use mz_ore::now::NowFn;
53use mz_ore::tracing::OpenTelemetryContext;
54use mz_persist_types::PersistLocation;
55use mz_repr::{Datum, GlobalId, RelationDesc, Row, TimestampManipulation};
56use mz_storage_client::controller::StorageController;
57use mz_storage_types::dyncfgs::ORE_OVERFLOWING_BEHAVIOR;
58use mz_storage_types::read_holds::ReadHold;
59use mz_storage_types::read_policy::ReadPolicy;
60use mz_storage_types::time_dependence::{TimeDependence, TimeDependenceError};
61use prometheus::proto::LabelPair;
62use serde::{Deserialize, Serialize};
63use timely::PartialOrder;
64use timely::progress::{Antichain, Timestamp};
65use tokio::sync::{mpsc, oneshot};
66use tokio::time::{self, MissedTickBehavior};
67use uuid::Uuid;
68
69use crate::controller::error::{
70 CollectionLookupError, CollectionMissing, CollectionUpdateError, DataflowCreationError,
71 HydrationCheckBadTarget, InstanceExists, InstanceMissing, PeekError, ReadPolicyError,
72 ReplicaCreationError, ReplicaDropError,
73};
74use crate::controller::instance::{Instance, SharedCollectionState};
75use crate::controller::introspection::{IntrospectionUpdates, spawn_introspection_sink};
76use crate::controller::replica::ReplicaConfig;
77use crate::logging::{LogVariant, LoggingConfig};
78use crate::metrics::ComputeControllerMetrics;
79use crate::protocol::command::{ComputeParameters, PeekTarget};
80use crate::protocol::response::{PeekResponse, SubscribeBatch};
81
82mod introspection;
83mod replica;
84mod sequential_hydration;
85
86pub mod error;
87pub mod instance;
88
89pub(crate) type StorageCollections<T> = Arc<
90 dyn mz_storage_client::storage_collections::StorageCollections<Timestamp = T> + Send + Sync,
91>;
92
93pub trait ComputeControllerTimestamp: TimestampManipulation + Into<Datum<'static>> + Sync {}
96
97impl ComputeControllerTimestamp for mz_repr::Timestamp {}
98
99#[derive(Debug)]
101pub enum ComputeControllerResponse<T> {
102 PeekNotification(Uuid, PeekNotification, OpenTelemetryContext),
104 SubscribeResponse(GlobalId, SubscribeBatch<T>),
106 CopyToResponse(GlobalId, Result<u64, anyhow::Error>),
117 FrontierUpper {
122 id: GlobalId,
124 upper: Antichain<T>,
126 },
127}
128
129#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
131pub enum PeekNotification {
132 Success {
134 rows: u64,
136 result_size: u64,
138 },
139 Error(String),
141 Canceled,
143}
144
145impl PeekNotification {
146 fn new(peek_response: &PeekResponse, offset: usize, limit: Option<usize>) -> Self {
149 match peek_response {
150 PeekResponse::Rows(rows) => {
151 let num_rows = u64::cast_from(rows.count(offset, limit));
152 let result_size = u64::cast_from(rows.byte_len());
153
154 tracing::trace!(?num_rows, ?result_size, "inline peek result");
155
156 Self::Success {
157 rows: num_rows,
158 result_size,
159 }
160 }
161 PeekResponse::Stashed(stashed_response) => {
162 let rows = stashed_response.num_rows(offset, limit);
163 let result_size = stashed_response.size_bytes();
164
165 tracing::trace!(?rows, ?result_size, "stashed peek result");
166
167 Self::Success {
168 rows: u64::cast_from(rows),
169 result_size: u64::cast_from(result_size),
170 }
171 }
172 PeekResponse::Error(err) => Self::Error(err.clone()),
173 PeekResponse::Canceled => Self::Canceled,
174 }
175 }
176}
177
178pub struct ComputeController<T: ComputeControllerTimestamp> {
180 instances: BTreeMap<ComputeInstanceId, InstanceState<T>>,
181 instance_workload_classes: Arc<Mutex<BTreeMap<ComputeInstanceId, Option<String>>>>,
185 build_info: &'static BuildInfo,
186 storage_collections: StorageCollections<T>,
188 initialized: bool,
190 read_only: bool,
196 config: ComputeParameters,
198 peek_stash_persist_location: PersistLocation,
200 stashed_response: Option<ComputeControllerResponse<T>>,
202 metrics: ComputeControllerMetrics,
204 now: NowFn,
206 wallclock_lag: WallclockLagFn<T>,
208 dyncfg: Arc<ConfigSet>,
213
214 response_rx: mpsc::UnboundedReceiver<ComputeControllerResponse<T>>,
216 response_tx: mpsc::UnboundedSender<ComputeControllerResponse<T>>,
218 introspection_rx: Option<mpsc::UnboundedReceiver<IntrospectionUpdates>>,
223 introspection_tx: mpsc::UnboundedSender<IntrospectionUpdates>,
225
226 maintenance_ticker: tokio::time::Interval,
228 maintenance_scheduled: bool,
230}
231
232impl<T: ComputeControllerTimestamp> ComputeController<T> {
233 pub fn new(
235 build_info: &'static BuildInfo,
236 storage_collections: StorageCollections<T>,
237 read_only: bool,
238 metrics_registry: &MetricsRegistry,
239 peek_stash_persist_location: PersistLocation,
240 controller_metrics: ControllerMetrics,
241 now: NowFn,
242 wallclock_lag: WallclockLagFn<T>,
243 ) -> Self {
244 let (response_tx, response_rx) = mpsc::unbounded_channel();
245 let (introspection_tx, introspection_rx) = mpsc::unbounded_channel();
246
247 let mut maintenance_ticker = time::interval(Duration::from_secs(1));
248 maintenance_ticker.set_missed_tick_behavior(MissedTickBehavior::Skip);
249
250 let instance_workload_classes = Arc::new(Mutex::new(BTreeMap::<
251 ComputeInstanceId,
252 Option<String>,
253 >::new()));
254
255 metrics_registry.register_postprocessor({
259 let instance_workload_classes = Arc::clone(&instance_workload_classes);
260 move |metrics| {
261 let instance_workload_classes = instance_workload_classes
262 .lock()
263 .expect("lock poisoned")
264 .iter()
265 .map(|(id, workload_class)| (id.to_string(), workload_class.clone()))
266 .collect::<BTreeMap<String, Option<String>>>();
267 for metric in metrics {
268 'metric: for metric in metric.mut_metric() {
269 for label in metric.get_label() {
270 if label.name() == "instance_id" {
271 if let Some(workload_class) = instance_workload_classes
272 .get(label.value())
273 .cloned()
274 .flatten()
275 {
276 let mut label = LabelPair::default();
277 label.set_name("workload_class".into());
278 label.set_value(workload_class.clone());
279
280 let mut labels = metric.take_label();
281 labels.push(label);
282 metric.set_label(labels);
283 }
284 continue 'metric;
285 }
286 }
287 }
288 }
289 }
290 });
291
292 let metrics = ComputeControllerMetrics::new(metrics_registry, controller_metrics);
293
294 Self {
295 instances: BTreeMap::new(),
296 instance_workload_classes,
297 build_info,
298 storage_collections,
299 initialized: false,
300 read_only,
301 config: Default::default(),
302 peek_stash_persist_location,
303 stashed_response: None,
304 metrics,
305 now,
306 wallclock_lag,
307 dyncfg: Arc::new(mz_dyncfgs::all_dyncfgs()),
308 response_rx,
309 response_tx,
310 introspection_rx: Some(introspection_rx),
311 introspection_tx,
312 maintenance_ticker,
313 maintenance_scheduled: false,
314 }
315 }
316
317 pub fn start_introspection_sink(
322 &mut self,
323 storage_controller: &dyn StorageController<Timestamp = T>,
324 ) {
325 if let Some(rx) = self.introspection_rx.take() {
326 spawn_introspection_sink(rx, storage_controller);
327 }
328 }
329
330 pub fn instance_exists(&self, id: ComputeInstanceId) -> bool {
332 self.instances.contains_key(&id)
333 }
334
335 fn instance(&self, id: ComputeInstanceId) -> Result<&InstanceState<T>, InstanceMissing> {
337 self.instances.get(&id).ok_or(InstanceMissing(id))
338 }
339
340 pub fn instance_client(
342 &self,
343 id: ComputeInstanceId,
344 ) -> Result<instance::Client<T>, InstanceMissing> {
345 self.instance(id).map(|instance| instance.client.clone())
346 }
347
348 fn instance_mut(
350 &mut self,
351 id: ComputeInstanceId,
352 ) -> Result<&mut InstanceState<T>, InstanceMissing> {
353 self.instances.get_mut(&id).ok_or(InstanceMissing(id))
354 }
355
356 pub fn collection_ids(
358 &self,
359 instance_id: ComputeInstanceId,
360 ) -> Result<impl Iterator<Item = GlobalId> + '_, InstanceMissing> {
361 let instance = self.instance(instance_id)?;
362 let ids = instance.collections.keys().copied();
363 Ok(ids)
364 }
365
366 pub fn collection_frontiers(
371 &self,
372 collection_id: GlobalId,
373 instance_id: Option<ComputeInstanceId>,
374 ) -> Result<CollectionFrontiers<T>, CollectionLookupError> {
375 let collection = match instance_id {
376 Some(id) => self.instance(id)?.collection(collection_id)?,
377 None => self
378 .instances
379 .values()
380 .find_map(|i| i.collections.get(&collection_id))
381 .ok_or(CollectionMissing(collection_id))?,
382 };
383
384 Ok(collection.frontiers())
385 }
386
387 pub fn collection_reverse_dependencies(
389 &self,
390 instance_id: ComputeInstanceId,
391 id: GlobalId,
392 ) -> Result<impl Iterator<Item = GlobalId> + '_, InstanceMissing> {
393 let instance = self.instance(instance_id)?;
394 let collections = instance.collections.iter();
395 let ids = collections
396 .filter_map(move |(cid, c)| c.compute_dependencies.contains(&id).then_some(*cid));
397 Ok(ids)
398 }
399
400 pub async fn collection_hydrated(
406 &self,
407 instance_id: ComputeInstanceId,
408 collection_id: GlobalId,
409 ) -> Result<bool, anyhow::Error> {
410 let instance = self.instance(instance_id)?;
411
412 let res = instance
413 .call_sync(move |i| i.collection_hydrated(collection_id))
414 .await?;
415
416 Ok(res)
417 }
418
419 pub fn collections_hydrated_for_replicas(
426 &self,
427 instance_id: ComputeInstanceId,
428 replicas: Vec<ReplicaId>,
429 exclude_collections: BTreeSet<GlobalId>,
430 ) -> Result<oneshot::Receiver<bool>, anyhow::Error> {
431 let instance = self.instance(instance_id)?;
432
433 if instance.replicas.is_empty() && !replicas.iter().any(|id| instance.replicas.contains(id))
435 {
436 return Err(HydrationCheckBadTarget(replicas).into());
437 }
438
439 let (tx, rx) = oneshot::channel();
440 instance.call(move |i| {
441 let result = i
442 .collections_hydrated_on_replicas(Some(replicas), &exclude_collections)
443 .expect("validated");
444 let _ = tx.send(result);
445 });
446
447 Ok(rx)
448 }
449
450 pub async fn dump(&self) -> Result<serde_json::Value, anyhow::Error> {
454 let Self {
461 instances,
462 instance_workload_classes,
463 build_info: _,
464 storage_collections: _,
465 initialized,
466 read_only,
467 config: _,
468 peek_stash_persist_location: _,
469 stashed_response,
470 metrics: _,
471 now: _,
472 wallclock_lag: _,
473 dyncfg: _,
474 response_rx: _,
475 response_tx: _,
476 introspection_rx: _,
477 introspection_tx: _,
478 maintenance_ticker: _,
479 maintenance_scheduled,
480 } = self;
481
482 let mut instances_dump = BTreeMap::new();
483 for (id, instance) in instances {
484 let dump = instance.dump().await?;
485 instances_dump.insert(id.to_string(), dump);
486 }
487
488 let instance_workload_classes: BTreeMap<_, _> = instance_workload_classes
489 .lock()
490 .expect("lock poisoned")
491 .iter()
492 .map(|(id, wc)| (id.to_string(), format!("{wc:?}")))
493 .collect();
494
495 Ok(serde_json::json!({
496 "instances": instances_dump,
497 "instance_workload_classes": instance_workload_classes,
498 "initialized": initialized,
499 "read_only": read_only,
500 "stashed_response": format!("{stashed_response:?}"),
501 "maintenance_scheduled": maintenance_scheduled,
502 }))
503 }
504}
505
506impl<T> ComputeController<T>
507where
508 T: ComputeControllerTimestamp,
509{
510 pub fn create_instance(
512 &mut self,
513 id: ComputeInstanceId,
514 arranged_logs: BTreeMap<LogVariant, GlobalId>,
515 workload_class: Option<String>,
516 ) -> Result<(), InstanceExists> {
517 if self.instances.contains_key(&id) {
518 return Err(InstanceExists(id));
519 }
520
521 let mut collections = BTreeMap::new();
522 let mut logs = Vec::with_capacity(arranged_logs.len());
523 for (&log, &id) in &arranged_logs {
524 let collection = Collection::new_log();
525 let shared = collection.shared.clone();
526 collections.insert(id, collection);
527 logs.push((log, id, shared));
528 }
529
530 let client = instance::Client::spawn(
531 id,
532 self.build_info,
533 Arc::clone(&self.storage_collections),
534 self.peek_stash_persist_location.clone(),
535 logs,
536 self.metrics.for_instance(id),
537 self.now.clone(),
538 self.wallclock_lag.clone(),
539 Arc::clone(&self.dyncfg),
540 self.response_tx.clone(),
541 self.introspection_tx.clone(),
542 self.read_only,
543 );
544
545 let instance = InstanceState::new(client, collections);
546 self.instances.insert(id, instance);
547
548 self.instance_workload_classes
549 .lock()
550 .expect("lock poisoned")
551 .insert(id, workload_class.clone());
552
553 let instance = self.instances.get_mut(&id).expect("instance just added");
554 if self.initialized {
555 instance.call(Instance::initialization_complete);
556 }
557
558 let mut config_params = self.config.clone();
559 config_params.workload_class = Some(workload_class);
560 instance.call(|i| i.update_configuration(config_params));
561
562 Ok(())
563 }
564
565 pub fn update_instance_workload_class(
567 &mut self,
568 id: ComputeInstanceId,
569 workload_class: Option<String>,
570 ) -> Result<(), InstanceMissing> {
571 let _ = self.instance(id)?;
573
574 self.instance_workload_classes
575 .lock()
576 .expect("lock poisoned")
577 .insert(id, workload_class);
578
579 self.update_configuration(Default::default());
581
582 Ok(())
583 }
584
585 pub fn drop_instance(&mut self, id: ComputeInstanceId) {
591 if let Some(instance) = self.instances.remove(&id) {
592 instance.call(|i| i.shutdown());
593 }
594
595 self.instance_workload_classes
596 .lock()
597 .expect("lock poisoned")
598 .remove(&id);
599 }
600
601 pub fn dyncfg(&self) -> &Arc<ConfigSet> {
603 &self.dyncfg
604 }
605
606 pub fn update_configuration(&mut self, config_params: ComputeParameters) {
608 config_params.dyncfg_updates.apply(&self.dyncfg);
610
611 let instance_workload_classes = self
612 .instance_workload_classes
613 .lock()
614 .expect("lock poisoned");
615
616 for (id, instance) in self.instances.iter_mut() {
619 let mut params = config_params.clone();
620 params.workload_class = Some(instance_workload_classes[id].clone());
621 instance.call(|i| i.update_configuration(params));
622 }
623
624 let overflowing_behavior = ORE_OVERFLOWING_BEHAVIOR.get(&self.dyncfg);
625 match overflowing_behavior.parse() {
626 Ok(behavior) => mz_ore::overflowing::set_behavior(behavior),
627 Err(err) => {
628 tracing::error!(
629 err,
630 overflowing_behavior,
631 "Invalid value for ore_overflowing_behavior"
632 );
633 }
634 }
635
636 self.config.update(config_params);
638 }
639
640 pub fn initialization_complete(&mut self) {
646 self.initialized = true;
647 for instance in self.instances.values_mut() {
648 instance.call(Instance::initialization_complete);
649 }
650 }
651
652 pub async fn ready(&mut self) {
660 if self.stashed_response.is_some() {
661 return;
663 }
664 if self.maintenance_scheduled {
665 return;
667 }
668
669 tokio::select! {
670 resp = self.response_rx.recv() => {
671 let resp = resp.expect("`self.response_tx` not dropped");
672 self.stashed_response = Some(resp);
673 }
674 _ = self.maintenance_ticker.tick() => {
675 self.maintenance_scheduled = true;
676 },
677 }
678 }
679
680 pub fn add_replica_to_instance(
682 &mut self,
683 instance_id: ComputeInstanceId,
684 replica_id: ReplicaId,
685 location: ClusterReplicaLocation,
686 config: ComputeReplicaConfig,
687 ) -> Result<(), ReplicaCreationError> {
688 use ReplicaCreationError::*;
689
690 let instance = self.instance(instance_id)?;
691
692 if instance.replicas.contains(&replica_id) {
694 return Err(ReplicaExists(replica_id));
695 }
696
697 let (enable_logging, interval) = match config.logging.interval {
698 Some(interval) => (true, interval),
699 None => (false, Duration::from_secs(1)),
700 };
701
702 let expiration_offset = COMPUTE_REPLICA_EXPIRATION_OFFSET.get(&self.dyncfg);
703
704 let replica_config = ReplicaConfig {
705 location,
706 logging: LoggingConfig {
707 interval,
708 enable_logging,
709 log_logging: config.logging.log_logging,
710 index_logs: Default::default(),
711 },
712 grpc_client: self.config.grpc_client.clone(),
713 expiration_offset: (!expiration_offset.is_zero()).then_some(expiration_offset),
714 };
715
716 let instance = self.instance_mut(instance_id).expect("validated");
717 instance.replicas.insert(replica_id);
718
719 instance.call(move |i| {
720 i.add_replica(replica_id, replica_config, None)
721 .expect("validated")
722 });
723
724 Ok(())
725 }
726
727 pub fn drop_replica(
729 &mut self,
730 instance_id: ComputeInstanceId,
731 replica_id: ReplicaId,
732 ) -> Result<(), ReplicaDropError> {
733 use ReplicaDropError::*;
734
735 let instance = self.instance_mut(instance_id)?;
736
737 if !instance.replicas.contains(&replica_id) {
739 return Err(ReplicaMissing(replica_id));
740 }
741
742 instance.replicas.remove(&replica_id);
743
744 instance.call(move |i| i.remove_replica(replica_id).expect("validated"));
745
746 Ok(())
747 }
748
749 pub fn create_dataflow(
755 &mut self,
756 instance_id: ComputeInstanceId,
757 mut dataflow: DataflowDescription<mz_compute_types::plan::Plan<T>, (), T>,
758 subscribe_target_replica: Option<ReplicaId>,
759 ) -> Result<(), DataflowCreationError> {
760 use DataflowCreationError::*;
761
762 let instance = self.instance(instance_id)?;
763
764 if let Some(replica_id) = subscribe_target_replica {
766 if !instance.replicas.contains(&replica_id) {
767 return Err(ReplicaMissing(replica_id));
768 }
769 }
770
771 let as_of = dataflow.as_of.as_ref().ok_or(MissingAsOf)?;
773 if as_of.is_empty() && dataflow.subscribe_ids().next().is_some() {
774 return Err(EmptyAsOfForSubscribe);
775 }
776 if as_of.is_empty() && dataflow.copy_to_ids().next().is_some() {
777 return Err(EmptyAsOfForCopyTo);
778 }
779
780 let storage_ids = dataflow.imported_source_ids().collect();
782 let mut import_read_holds = self.storage_collections.acquire_read_holds(storage_ids)?;
783 for id in dataflow.imported_index_ids() {
784 let read_hold = instance.acquire_read_hold(id)?;
785 import_read_holds.push(read_hold);
786 }
787 for hold in &import_read_holds {
788 if PartialOrder::less_than(as_of, hold.since()) {
789 return Err(SinceViolation(hold.id()));
790 }
791 }
792
793 for id in dataflow.persist_sink_ids() {
795 if self.storage_collections.check_exists(id).is_err() {
796 return Err(CollectionMissing(id));
797 }
798 }
799 let time_dependence = self
800 .determine_time_dependence(instance_id, &dataflow)
801 .expect("must exist");
802
803 let instance = self.instance_mut(instance_id).expect("validated");
804
805 let mut shared_collection_state = BTreeMap::new();
806 for id in dataflow.export_ids() {
807 let shared = SharedCollectionState::new(as_of.clone());
808 let collection = Collection {
809 write_only: dataflow.sink_exports.contains_key(&id),
810 compute_dependencies: dataflow.imported_index_ids().collect(),
811 shared: shared.clone(),
812 time_dependence: time_dependence.clone(),
813 };
814 instance.collections.insert(id, collection);
815 shared_collection_state.insert(id, shared);
816 }
817
818 dataflow.time_dependence = time_dependence;
819
820 instance.call(move |i| {
821 i.create_dataflow(
822 dataflow,
823 import_read_holds,
824 subscribe_target_replica,
825 shared_collection_state,
826 )
827 .expect("validated")
828 });
829
830 Ok(())
831 }
832
833 pub fn drop_collections(
836 &mut self,
837 instance_id: ComputeInstanceId,
838 collection_ids: Vec<GlobalId>,
839 ) -> Result<(), CollectionUpdateError> {
840 let instance = self.instance_mut(instance_id)?;
841
842 for id in &collection_ids {
844 instance.collection(*id)?;
845 }
846
847 for id in &collection_ids {
848 instance.collections.remove(id);
849 }
850
851 instance.call(|i| i.drop_collections(collection_ids).expect("validated"));
852
853 Ok(())
854 }
855
856 pub fn peek(
858 &self,
859 instance_id: ComputeInstanceId,
860 peek_target: PeekTarget,
861 literal_constraints: Option<Vec<Row>>,
862 uuid: Uuid,
863 timestamp: T,
864 result_desc: RelationDesc,
865 finishing: RowSetFinishing,
866 map_filter_project: mz_expr::SafeMfpPlan,
867 target_replica: Option<ReplicaId>,
868 peek_response_tx: oneshot::Sender<PeekResponse>,
869 ) -> Result<(), PeekError> {
870 use PeekError::*;
871
872 let instance = self.instance(instance_id)?;
873
874 if let Some(replica_id) = target_replica {
876 if !instance.replicas.contains(&replica_id) {
877 return Err(ReplicaMissing(replica_id));
878 }
879 }
880
881 let read_hold = match &peek_target {
883 PeekTarget::Index { id } => instance.acquire_read_hold(*id)?,
884 PeekTarget::Persist { id, .. } => self
885 .storage_collections
886 .acquire_read_holds(vec![*id])?
887 .into_element(),
888 };
889 if !read_hold.since().less_equal(×tamp) {
890 return Err(SinceViolation(peek_target.id()));
891 }
892
893 instance.call(move |i| {
894 i.peek(
895 peek_target,
896 literal_constraints,
897 uuid,
898 timestamp,
899 result_desc,
900 finishing,
901 map_filter_project,
902 read_hold,
903 target_replica,
904 peek_response_tx,
905 )
906 .expect("validated")
907 });
908
909 Ok(())
910 }
911
912 pub fn cancel_peek(
922 &self,
923 instance_id: ComputeInstanceId,
924 uuid: Uuid,
925 reason: PeekResponse,
926 ) -> Result<(), InstanceMissing> {
927 self.instance(instance_id)?
928 .call(move |i| i.cancel_peek(uuid, reason));
929 Ok(())
930 }
931
932 pub fn set_read_policy(
944 &self,
945 instance_id: ComputeInstanceId,
946 policies: Vec<(GlobalId, ReadPolicy<T>)>,
947 ) -> Result<(), ReadPolicyError> {
948 use ReadPolicyError::*;
949
950 let instance = self.instance(instance_id)?;
951
952 for (id, _) in &policies {
954 let collection = instance.collection(*id)?;
955 if collection.write_only {
956 return Err(WriteOnlyCollection(*id));
957 }
958 }
959
960 self.instance(instance_id)?
961 .call(|i| i.set_read_policy(policies).expect("validated"));
962
963 Ok(())
964 }
965
966 pub fn acquire_read_hold(
968 &self,
969 instance_id: ComputeInstanceId,
970 collection_id: GlobalId,
971 ) -> Result<ReadHold<T>, CollectionUpdateError> {
972 let read_hold = self
973 .instance(instance_id)?
974 .acquire_read_hold(collection_id)?;
975 Ok(read_hold)
976 }
977
978 fn determine_time_dependence(
980 &self,
981 instance_id: ComputeInstanceId,
982 dataflow: &DataflowDescription<mz_compute_types::plan::Plan<T>, (), T>,
983 ) -> Result<Option<TimeDependence>, TimeDependenceError> {
984 let is_continual_task = dataflow.continual_task_ids().next().is_some();
986 if is_continual_task {
987 return Ok(None);
988 }
989
990 let instance = self
991 .instance(instance_id)
992 .map_err(|err| TimeDependenceError::InstanceMissing(err.0))?;
993 let mut time_dependencies = Vec::new();
994
995 for id in dataflow.imported_index_ids() {
996 let dependence = instance
997 .get_time_dependence(id)
998 .map_err(|err| TimeDependenceError::CollectionMissing(err.0))?;
999 time_dependencies.push(dependence);
1000 }
1001
1002 'source: for id in dataflow.imported_source_ids() {
1003 for instance in self.instances.values() {
1007 if let Ok(dependence) = instance.get_time_dependence(id) {
1008 time_dependencies.push(dependence);
1009 continue 'source;
1010 }
1011 }
1012
1013 time_dependencies.push(self.storage_collections.determine_time_dependence(id)?);
1015 }
1016
1017 Ok(TimeDependence::merge(
1018 time_dependencies,
1019 dataflow.refresh_schedule.as_ref(),
1020 ))
1021 }
1022
1023 #[mz_ore::instrument(level = "debug")]
1025 pub fn process(&mut self) -> Option<ComputeControllerResponse<T>> {
1026 if self.maintenance_scheduled {
1028 self.maintain();
1029 self.maintenance_scheduled = false;
1030 }
1031
1032 self.stashed_response.take()
1034 }
1035
1036 #[mz_ore::instrument(level = "debug")]
1037 fn maintain(&mut self) {
1038 for instance in self.instances.values_mut() {
1040 instance.call(Instance::maintain);
1041 }
1042 }
1043
1044 pub fn allow_writes(
1048 &mut self,
1049 instance_id: ComputeInstanceId,
1050 collection_id: GlobalId,
1051 ) -> Result<(), CollectionUpdateError> {
1052 if self.read_only {
1053 tracing::debug!("Skipping allow_writes in read-only mode");
1054 return Ok(());
1055 }
1056
1057 let instance = self.instance_mut(instance_id)?;
1058
1059 instance.collection(collection_id)?;
1061
1062 instance.call(move |i| i.allow_writes(collection_id).expect("validated"));
1063
1064 Ok(())
1065 }
1066}
1067
1068#[derive(Debug)]
1069struct InstanceState<T: ComputeControllerTimestamp> {
1070 client: instance::Client<T>,
1071 replicas: BTreeSet<ReplicaId>,
1072 collections: BTreeMap<GlobalId, Collection<T>>,
1073}
1074
1075impl<T: ComputeControllerTimestamp> InstanceState<T> {
1076 fn new(client: instance::Client<T>, collections: BTreeMap<GlobalId, Collection<T>>) -> Self {
1077 Self {
1078 client,
1079 replicas: Default::default(),
1080 collections,
1081 }
1082 }
1083
1084 fn collection(&self, id: GlobalId) -> Result<&Collection<T>, CollectionMissing> {
1085 self.collections.get(&id).ok_or(CollectionMissing(id))
1086 }
1087
1088 fn call<F>(&self, f: F)
1094 where
1095 F: FnOnce(&mut Instance<T>) + Send + 'static,
1096 {
1097 self.client.call(f).expect("instance not dropped")
1098 }
1099
1100 async fn call_sync<F, R>(&self, f: F) -> R
1106 where
1107 F: FnOnce(&mut Instance<T>) -> R + Send + 'static,
1108 R: Send + 'static,
1109 {
1110 self.client
1111 .call_sync(f)
1112 .await
1113 .expect("instance not dropped")
1114 }
1115
1116 pub fn acquire_read_hold(&self, id: GlobalId) -> Result<ReadHold<T>, CollectionMissing> {
1118 let collection = self.collection(id)?;
1128 let since = collection.shared.lock_read_capabilities(|caps| {
1129 let since = caps.frontier().to_owned();
1130 caps.update_iter(since.iter().map(|t| (t.clone(), 1)));
1131 since
1132 });
1133
1134 let hold = ReadHold::new(id, since, self.client.read_hold_tx());
1135 Ok(hold)
1136 }
1137
1138 fn get_time_dependence(
1140 &self,
1141 id: GlobalId,
1142 ) -> Result<Option<TimeDependence>, CollectionMissing> {
1143 Ok(self.collection(id)?.time_dependence.clone())
1144 }
1145
1146 pub async fn dump(&self) -> Result<serde_json::Value, anyhow::Error> {
1148 let Self {
1150 client: _,
1151 replicas,
1152 collections,
1153 } = self;
1154
1155 let instance = self.call_sync(|i| i.dump()).await?;
1156 let replicas: Vec<_> = replicas.iter().map(|id| id.to_string()).collect();
1157 let collections: BTreeMap<_, _> = collections
1158 .iter()
1159 .map(|(id, c)| (id.to_string(), format!("{c:?}")))
1160 .collect();
1161
1162 Ok(serde_json::json!({
1163 "instance": instance,
1164 "replicas": replicas,
1165 "collections": collections,
1166 }))
1167 }
1168}
1169
1170#[derive(Debug)]
1171struct Collection<T> {
1172 write_only: bool,
1173 compute_dependencies: BTreeSet<GlobalId>,
1174 shared: SharedCollectionState<T>,
1175 time_dependence: Option<TimeDependence>,
1178}
1179
1180impl<T: Timestamp> Collection<T> {
1181 fn new_log() -> Self {
1182 let as_of = Antichain::from_elem(T::minimum());
1183 Self {
1184 write_only: false,
1185 compute_dependencies: Default::default(),
1186 shared: SharedCollectionState::new(as_of),
1187 time_dependence: Some(TimeDependence::default()),
1188 }
1189 }
1190
1191 fn frontiers(&self) -> CollectionFrontiers<T> {
1192 let read_frontier = self
1193 .shared
1194 .lock_read_capabilities(|c| c.frontier().to_owned());
1195 let write_frontier = self.shared.lock_write_frontier(|f| f.clone());
1196 CollectionFrontiers {
1197 read_frontier,
1198 write_frontier,
1199 }
1200 }
1201}
1202
1203#[derive(Clone, Debug)]
1205pub struct CollectionFrontiers<T> {
1206 pub read_frontier: Antichain<T>,
1208 pub write_frontier: Antichain<T>,
1210}
1211
1212impl<T: Timestamp> Default for CollectionFrontiers<T> {
1213 fn default() -> Self {
1214 Self {
1215 read_frontier: Antichain::from_elem(T::minimum()),
1216 write_frontier: Antichain::from_elem(T::minimum()),
1217 }
1218 }
1219}