pub struct Spaces { /* private fields */ }
Expand description

This is the set of all current DnaHash spaces for all cells installed on this conductor.

Implementations§

Create a new empty set of DnaHash spaces.

Examples found in repository?
src/sweettest/sweet_conductor.rs (lines 97-100)
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
    pub async fn new(
        handle: ConductorHandle,
        env_dir: TestDir,
        config: ConductorConfig,
    ) -> SweetConductor {
        // Automatically add a test app interface
        handle
            .add_test_app_interface(AppInterfaceId::default())
            .await
            .expect("Couldn't set up test app interface");

        // Get a stream of all signals since conductor startup
        let signal_stream = handle.signal_broadcaster().subscribe_merged();

        // XXX: this is a bit wonky.
        // We create a Spaces instance here purely because it's easier to initialize
        // the per-space databases this way. However, we actually use the TestEnvs
        // to actually access those databases.
        // As a TODO, we can remove the need for TestEnvs in sweettest or have
        // some other better integration between the two.
        let spaces = Spaces::new(&ConductorConfig {
            environment_path: env_dir.to_path_buf().into(),
            ..Default::default()
        })
        .unwrap();

        let keystore = handle.keystore().clone();

        Self {
            handle: Some(SweetConductorHandle(handle)),
            db_dir: env_dir,
            keystore,
            spaces,
            config,
            dnas: Vec::new(),
            signal_stream: Some(Box::new(signal_stream)),
        }
    }
More examples
Hide additional examples
src/conductor/conductor/builder.rs (line 105)
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
    pub async fn build(self) -> ConductorResult<ConductorHandle> {
        tracing::info!(?self.config);

        let keystore = if let Some(keystore) = self.keystore {
            keystore
        } else {
            pub(crate) fn warn_no_encryption() {
                #[cfg(not(feature = "db-encryption"))]
                {
                    const MSG: &str = "WARNING: running without local db encryption";
                    eprintln!("{}", MSG);
                    println!("{}", MSG);
                    tracing::warn!("{}", MSG);
                }
            }
            let get_passphrase = || -> ConductorResult<sodoken::BufRead> {
                match self.passphrase {
                    None => Err(
                        one_err::OneErr::new("passphrase required for lair keystore api").into(),
                    ),
                    Some(p) => Ok(p),
                }
            };
            match &self.config.keystore {
                KeystoreConfig::DangerTestKeystore => spawn_test_keystore().await?,
                KeystoreConfig::LairServer { connection_url } => {
                    warn_no_encryption();
                    let passphrase = get_passphrase()?;
                    spawn_lair_keystore(connection_url.clone(), passphrase).await?
                }
                KeystoreConfig::LairServerInProc { lair_root } => {
                    warn_no_encryption();
                    let mut keystore_config_path = lair_root.clone().unwrap_or_else(|| {
                        let mut p: std::path::PathBuf = self.config.environment_path.clone().into();
                        p.push("keystore");
                        p
                    });
                    keystore_config_path.push("lair-keystore-config.yaml");
                    let passphrase = get_passphrase()?;
                    spawn_lair_keystore_in_proc(keystore_config_path, passphrase).await?
                }
            }
        };

        let Self {
            ribosome_store,
            config,
            ..
        } = self;

        let ribosome_store = RwShare::new(ribosome_store);

        let spaces = Spaces::new(&config)?;
        let tag = spaces.get_state().await?.tag().clone();

        let network_config = config.network.clone().unwrap_or_default();
        let (cert_digest, cert, cert_priv_key) =
            keystore.get_or_create_tls_cert_by_tag(tag.0).await?;
        let tls_config =
            holochain_p2p::kitsune_p2p::dependencies::kitsune_p2p_types::tls::TlsConfig {
                cert,
                cert_priv_key,
                cert_digest,
            };
        let strat = ArqStrat::from_params(network_config.tuning_params.gossip_redundancy_target);

        let host = KitsuneHostImpl::new(
            spaces.clone(),
            ribosome_store.clone(),
            network_config.tuning_params.clone(),
            strat,
        );

        let (holochain_p2p, p2p_evt) =
            holochain_p2p::spawn_holochain_p2p(network_config, tls_config, host).await?;

        let (post_commit_sender, post_commit_receiver) =
            tokio::sync::mpsc::channel(POST_COMMIT_CHANNEL_BOUND);

        let conductor = Conductor::new(
            config.clone(),
            ribosome_store,
            keystore,
            holochain_p2p,
            spaces,
            post_commit_sender,
        );

        let shutting_down = conductor.shutting_down.clone();

        #[cfg(any(test, feature = "test_utils"))]
        let conductor = Self::update_fake_state(self.state, conductor).await?;

        // Create handle
        let handle: ConductorHandle = Arc::new(conductor);

        {
            let handle = handle.clone();
            tokio::task::spawn(async move {
                while !shutting_down.load(std::sync::atomic::Ordering::Relaxed) {
                    tokio::time::sleep(std::time::Duration::from_secs(60)).await;
                    if let Err(e) = handle.prune_p2p_agents_db().await {
                        tracing::error!("failed to prune p2p_agents_db: {:?}", e);
                    }
                }
            });
        }

        Self::finish(
            handle,
            config,
            p2p_evt,
            post_commit_receiver,
            self.no_print_setup,
        )
        .await
    }

    pub(crate) fn spawn_post_commit(
        conductor_handle: ConductorHandle,
        receiver: tokio::sync::mpsc::Receiver<PostCommitArgs>,
    ) {
        let receiver_stream = tokio_stream::wrappers::ReceiverStream::new(receiver);
        tokio::task::spawn(receiver_stream.for_each_concurrent(
            POST_COMMIT_CONCURRENT_LIMIT,
            move |post_commit_args| {
                let conductor_handle = conductor_handle.clone();
                async move {
                    let PostCommitArgs {
                        host_access,
                        invocation,
                        cell_id,
                    } = post_commit_args;
                    match conductor_handle.clone().get_ribosome(cell_id.dna_hash()) {
                        Ok(ribosome) => {
                            if let Err(e) = tokio::task::spawn_blocking(move || {
                                if let Err(e) = ribosome.run_post_commit(host_access, invocation) {
                                    tracing::error!(?e);
                                }
                            })
                            .await
                            {
                                tracing::error!(?e);
                            }
                        }
                        Err(e) => {
                            tracing::error!(?e);
                        }
                    }
                }
            },
        ));
    }

    pub(crate) async fn finish(
        conductor: ConductorHandle,
        conductor_config: ConductorConfig,
        p2p_evt: holochain_p2p::event::HolochainP2pEventReceiver,
        post_commit_receiver: tokio::sync::mpsc::Receiver<PostCommitArgs>,
        no_print_setup: bool,
    ) -> ConductorResult<ConductorHandle> {
        conductor
            .clone()
            .start_scheduler(holochain_zome_types::schedule::SCHEDULER_INTERVAL)
            .await;

        tokio::task::spawn(p2p_event_task(p2p_evt, conductor.clone()));

        Self::spawn_post_commit(conductor.clone(), post_commit_receiver);

        let configs = conductor_config.admin_interfaces.unwrap_or_default();
        let cell_startup_errors = conductor.clone().initialize_conductor(configs).await?;

        // TODO: This should probably be emitted over the admin interface
        if !cell_startup_errors.is_empty() {
            error!(
                msg = "Failed to create the following active apps",
                ?cell_startup_errors
            );
        }

        if !no_print_setup {
            conductor.print_setup();
        }

        Ok(conductor)
    }

    /// Pass a test keystore in, to ensure that generated test agents
    /// are actually available for signing (especially for tryorama compat)
    pub fn with_keystore(mut self, keystore: MetaLairClient) -> Self {
        self.keystore = Some(keystore);
        self
    }

    #[cfg(any(test, feature = "test_utils"))]
    /// Sets some fake conductor state for tests
    pub fn fake_state(mut self, state: ConductorState) -> Self {
        self.state = Some(state);
        self
    }

    #[cfg(any(test, feature = "test_utils"))]
    pub(crate) async fn update_fake_state(
        state: Option<ConductorState>,
        conductor: Conductor,
    ) -> ConductorResult<Conductor> {
        if let Some(state) = state {
            conductor.update_state(move |_| Ok(state)).await?;
        }
        Ok(conductor)
    }

    /// Build a Conductor with a test environment
    #[cfg(any(test, feature = "test_utils"))]
    pub async fn test(
        mut self,
        env_path: &std::path::Path,
        extra_dnas: &[DnaFile],
    ) -> ConductorResult<ConductorHandle> {
        let keystore = self.keystore.unwrap_or_else(test_keystore);
        self.config.environment_path = env_path.to_path_buf().into();

        let spaces = Spaces::new(&self.config)?;

        let network_config = self.config.network.clone().unwrap_or_default();
        let tuning_params = network_config.tuning_params.clone();
        let strat = ArqStrat::from_params(tuning_params.gossip_redundancy_target);

        let ribosome_store = RwShare::new(self.ribosome_store);
        let host =
            KitsuneHostImpl::new(spaces.clone(), ribosome_store.clone(), tuning_params, strat);

        let (holochain_p2p, p2p_evt) =
                holochain_p2p::spawn_holochain_p2p(network_config, holochain_p2p::kitsune_p2p::dependencies::kitsune_p2p_types::tls::TlsConfig::new_ephemeral().await.unwrap(), host)
                    .await?;

        let (post_commit_sender, post_commit_receiver) =
            tokio::sync::mpsc::channel(POST_COMMIT_CHANNEL_BOUND);

        let conductor = Conductor::new(
            self.config.clone(),
            ribosome_store,
            keystore,
            holochain_p2p,
            spaces,
            post_commit_sender,
        );

        let conductor = Self::update_fake_state(self.state, conductor).await?;

        // Create handle
        let handle: ConductorHandle = Arc::new(conductor);

        // Install extra DNAs, in particular:
        // the ones with InlineZomes will not be registered in the Wasm DB
        // and cannot be automatically loaded on conductor restart.

        for dna_file in extra_dnas {
            handle
                .register_dna(dna_file.clone())
                .await
                .expect("Could not install DNA");
        }

        Self::finish(
            handle,
            self.config,
            p2p_evt,
            post_commit_receiver,
            self.no_print_setup,
        )
        .await
    }

Get the holochain conductor state

Examples found in repository?
src/conductor/conductor.rs (line 1739)
1738
1739
1740
        pub(crate) async fn get_state(&self) -> ConductorResult<ConductorState> {
            self.spaces.get_state().await
        }
More examples
Hide additional examples
src/conductor/conductor/builder.rs (line 106)
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
    pub async fn build(self) -> ConductorResult<ConductorHandle> {
        tracing::info!(?self.config);

        let keystore = if let Some(keystore) = self.keystore {
            keystore
        } else {
            pub(crate) fn warn_no_encryption() {
                #[cfg(not(feature = "db-encryption"))]
                {
                    const MSG: &str = "WARNING: running without local db encryption";
                    eprintln!("{}", MSG);
                    println!("{}", MSG);
                    tracing::warn!("{}", MSG);
                }
            }
            let get_passphrase = || -> ConductorResult<sodoken::BufRead> {
                match self.passphrase {
                    None => Err(
                        one_err::OneErr::new("passphrase required for lair keystore api").into(),
                    ),
                    Some(p) => Ok(p),
                }
            };
            match &self.config.keystore {
                KeystoreConfig::DangerTestKeystore => spawn_test_keystore().await?,
                KeystoreConfig::LairServer { connection_url } => {
                    warn_no_encryption();
                    let passphrase = get_passphrase()?;
                    spawn_lair_keystore(connection_url.clone(), passphrase).await?
                }
                KeystoreConfig::LairServerInProc { lair_root } => {
                    warn_no_encryption();
                    let mut keystore_config_path = lair_root.clone().unwrap_or_else(|| {
                        let mut p: std::path::PathBuf = self.config.environment_path.clone().into();
                        p.push("keystore");
                        p
                    });
                    keystore_config_path.push("lair-keystore-config.yaml");
                    let passphrase = get_passphrase()?;
                    spawn_lair_keystore_in_proc(keystore_config_path, passphrase).await?
                }
            }
        };

        let Self {
            ribosome_store,
            config,
            ..
        } = self;

        let ribosome_store = RwShare::new(ribosome_store);

        let spaces = Spaces::new(&config)?;
        let tag = spaces.get_state().await?.tag().clone();

        let network_config = config.network.clone().unwrap_or_default();
        let (cert_digest, cert, cert_priv_key) =
            keystore.get_or_create_tls_cert_by_tag(tag.0).await?;
        let tls_config =
            holochain_p2p::kitsune_p2p::dependencies::kitsune_p2p_types::tls::TlsConfig {
                cert,
                cert_priv_key,
                cert_digest,
            };
        let strat = ArqStrat::from_params(network_config.tuning_params.gossip_redundancy_target);

        let host = KitsuneHostImpl::new(
            spaces.clone(),
            ribosome_store.clone(),
            network_config.tuning_params.clone(),
            strat,
        );

        let (holochain_p2p, p2p_evt) =
            holochain_p2p::spawn_holochain_p2p(network_config, tls_config, host).await?;

        let (post_commit_sender, post_commit_receiver) =
            tokio::sync::mpsc::channel(POST_COMMIT_CHANNEL_BOUND);

        let conductor = Conductor::new(
            config.clone(),
            ribosome_store,
            keystore,
            holochain_p2p,
            spaces,
            post_commit_sender,
        );

        let shutting_down = conductor.shutting_down.clone();

        #[cfg(any(test, feature = "test_utils"))]
        let conductor = Self::update_fake_state(self.state, conductor).await?;

        // Create handle
        let handle: ConductorHandle = Arc::new(conductor);

        {
            let handle = handle.clone();
            tokio::task::spawn(async move {
                while !shutting_down.load(std::sync::atomic::Ordering::Relaxed) {
                    tokio::time::sleep(std::time::Duration::from_secs(60)).await;
                    if let Err(e) = handle.prune_p2p_agents_db().await {
                        tracing::error!("failed to prune p2p_agents_db: {:?}", e);
                    }
                }
            });
        }

        Self::finish(
            handle,
            config,
            p2p_evt,
            post_commit_receiver,
            self.no_print_setup,
        )
        .await
    }

Update the internal state with a pure function mapping old state to new

Examples found in repository?
src/conductor/conductor.rs (line 1747)
1743
1744
1745
1746
1747
1748
        pub(crate) async fn update_state<F: Send>(&self, f: F) -> ConductorResult<ConductorState>
        where
            F: FnOnce(ConductorState) -> ConductorResult<ConductorState> + 'static,
        {
            self.spaces.update_state(f).await
        }
More examples
Hide additional examples
src/conductor/space.rs (line 188)
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
    pub async fn get_state(&self) -> ConductorResult<ConductorState> {
        let state = self
            .conductor_db
            .async_reader(|txn| {
                let state = txn
                    .query_row("SELECT blob FROM ConductorState WHERE id = 1", [], |row| {
                        row.get("blob")
                    })
                    .optional()?;
                match state {
                    Some(state) => ConductorResult::Ok(Some(from_blob(state)?)),
                    None => ConductorResult::Ok(None),
                }
            })
            .await?;

        match state {
            Some(state) => Ok(state),
            // update_state will again try to read the state. It's a little
            // inefficient in the infrequent case where we haven't saved the
            // state yet, but more atomic, so worth it.
            None => self.update_state(Ok).await,
        }
    }

Update the internal state with a pure function mapping old state to new, which may also produce an output value which will be the output of this function

Examples found in repository?
src/conductor/space.rs (line 197)
193
194
195
196
197
198
199
    pub async fn update_state<F: Send>(&self, f: F) -> ConductorResult<ConductorState>
    where
        F: FnOnce(ConductorState) -> ConductorResult<ConductorState> + 'static,
    {
        let (state, _) = self.update_state_prime(|s| Ok((f(s)?, ()))).await?;
        Ok(state)
    }
More examples
Hide additional examples
src/conductor/conductor.rs (line 1762)
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
        pub(crate) async fn update_state_prime<F, O>(
            &self,
            f: F,
        ) -> ConductorResult<(ConductorState, O)>
        where
            F: FnOnce(ConductorState) -> ConductorResult<(ConductorState, O)> + Send + 'static,
            O: Send + 'static,
        {
            self.check_running()?;
            self.spaces.update_state_prime(f).await
        }

Get something from every space

Examples found in repository?
src/sweettest/sweet_conductor.rs (line 475)
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
    pub async fn exchange_peer_info(conductors: impl IntoIterator<Item = &Self>) {
        let mut all = Vec::new();
        for c in conductors.into_iter() {
            for env in c.spaces.get_from_spaces(|s| s.p2p_agents_db.clone()) {
                all.push(env.clone());
            }
        }
        crate::conductor::p2p_agent_store::exchange_peer_info(all).await;
    }

    /// Let each conductor know about each others' agents so they can do networking
    pub async fn exchange_peer_info_sampled(
        conductors: impl IntoIterator<Item = &Self>,
        rng: &mut StdRng,
        s: usize,
    ) {
        let mut all = Vec::new();
        for c in conductors.into_iter() {
            for env in c.spaces.get_from_spaces(|s| s.p2p_agents_db.clone()) {
                all.push(env.clone());
            }
        }
        let connectivity = covering(rng, all.len(), s);
        crate::conductor::p2p_agent_store::exchange_peer_info_sparse(all, connectivity).await;
    }
More examples
Hide additional examples
src/sweettest/sweet_conductor_batch.rs (line 139)
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
    pub async fn reveal_peer_info(&self, observer: usize, seen: usize) {
        let observer_conductor = &self.0[observer];
        let mut observer_envs = Vec::new();
        for env in observer_conductor
            .spaces
            .get_from_spaces(|s| s.p2p_agents_db.clone())
        {
            observer_envs.push(env.clone());
        }

        let seen_conductor = &self.0[seen];
        let mut seen_envs = Vec::new();
        for env in seen_conductor
            .spaces
            .get_from_spaces(|s| s.p2p_agents_db.clone())
        {
            seen_envs.push(env.clone());
        }

        crate::conductor::p2p_agent_store::reveal_peer_info(observer_envs, seen_envs).await;
    }
src/conductor/conductor.rs (line 811)
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
        pub async fn get_agent_infos(
            &self,
            cell_id: Option<CellId>,
        ) -> ConductorApiResult<Vec<AgentInfoSigned>> {
            match cell_id {
                Some(c) => {
                    let (d, a) = c.into_dna_and_agent();
                    let db = self.p2p_agents_db(&d);
                    Ok(get_single_agent_info(db.into(), d, a)
                        .await?
                        .map(|a| vec![a])
                        .unwrap_or_default())
                }
                None => {
                    let mut out = Vec::new();
                    // collecting so the mutex lock can close
                    let envs = self.spaces.get_from_spaces(|s| s.p2p_agents_db.clone());
                    for db in envs {
                        out.append(&mut all_agent_infos(db.into()).await?);
                    }
                    Ok(out)
                }
            }
        }

Get the space if it exists or create it if it doesn’t.

Examples found in repository?
src/conductor/conductor.rs (line 2063)
2062
2063
2064
        pub(crate) fn get_or_create_space(&self, dna_hash: &DnaHash) -> ConductorResult<Space> {
            self.spaces.get_or_create_space(dna_hash)
        }
More examples
Hide additional examples
src/sweettest/sweet_conductor.rs (line 251)
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
    async fn setup_app_3_create_sweet_app(
        &self,
        installed_app_id: &str,
        agent: AgentPubKey,
        dna_hashes: impl Iterator<Item = DnaHash>,
    ) -> ConductorApiResult<SweetApp> {
        let mut sweet_cells = Vec::new();
        for dna_hash in dna_hashes {
            // Initialize per-space databases
            let _space = self.spaces.get_or_create_space(&dna_hash)?;

            // Create and add the SweetCell
            sweet_cells.push(self.get_sweet_cell(CellId::new(dna_hash, agent.clone()))?);
        }

        Ok(SweetApp::new(installed_app_id.into(), sweet_cells))
    }

Get the cache database (this will create the space if it doesn’t already exist).

Get the authored database (this will create the space if it doesn’t already exist).

Examples found in repository?
src/conductor/conductor.rs (line 2070)
2066
2067
2068
2069
2070
2071
        pub(crate) fn get_or_create_authored_db(
            &self,
            dna_hash: &DnaHash,
        ) -> ConductorResult<DbWrite<DbKindAuthored>> {
            self.spaces.authored_db(dna_hash)
        }

Get the dht database (this will create the space if it doesn’t already exist).

Examples found in repository?
src/conductor/conductor.rs (line 2077)
2073
2074
2075
2076
2077
2078
        pub(crate) fn get_or_create_dht_db(
            &self,
            dna_hash: &DnaHash,
        ) -> ConductorResult<DbWrite<DbKindDht>> {
            self.spaces.dht_db(dna_hash)
        }
More examples
Hide additional examples
src/conductor/kitsune_host_impl.rs (line 115)
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
    fn query_region_set(
        &self,
        space: Arc<kitsune_p2p::KitsuneSpace>,
        dht_arc_set: Arc<holochain_p2p::dht_arc::DhtArcSet>,
    ) -> KitsuneHostResult<holochain_p2p::dht::region_set::RegionSetLtcs> {
        let dna_hash = DnaHash::from_kitsune(&space);
        async move {
            let topology = self.get_topology(space.clone()).await?;
            let db = self.spaces.dht_db(&dna_hash)?;
            let region_set =
                query_region_set::query_region_set(db, topology.clone(), &self.strat, dht_arc_set)
                    .await?;
            Ok(region_set)
        }
        .boxed()
        .into()
    }

    fn query_size_limited_regions(
        &self,
        space: Arc<kitsune_p2p::KitsuneSpace>,
        size_limit: u32,
        regions: Vec<holochain_p2p::dht::region::Region>,
    ) -> KitsuneHostResult<Vec<holochain_p2p::dht::region::Region>> {
        let dna_hash = DnaHash::from_kitsune(&space);
        async move {
            let topology = self.get_topology(space).await?;
            let db = self.spaces.dht_db(&dna_hash)?;
            Ok(query_size_limited_regions::query_size_limited_regions(
                db, topology, regions, size_limit,
            )
            .await?)
        }
        .boxed()
        .into()
    }

    fn query_op_hashes_by_region(
        &self,
        space: Arc<kitsune_p2p::KitsuneSpace>,
        region: holochain_p2p::dht::region::RegionCoords,
    ) -> KitsuneHostResult<Vec<OpHashSized>> {
        let dna_hash = DnaHash::from_kitsune(&space);
        async move {
            let db = self.spaces.dht_db(&dna_hash)?;
            let topology = self.get_topology(space).await?;
            let bounds = region.to_bounds(&topology);
            Ok(query_region_op_hashes::query_region_op_hashes(db.clone(), bounds).await?)
        }
        .boxed()
        .into()
    }

    fn get_topology(&self, space: Arc<kitsune_p2p::KitsuneSpace>) -> KitsuneHostResult<Topology> {
        let dna_hash = DnaHash::from_kitsune(&space);
        let dna_def = self
            .ribosome_store
            .share_mut(|ds| ds.get_dna_def(&dna_hash))
            .ok_or(DnaError::DnaMissing(dna_hash));
        let cutoff = self.tuning_params.danger_gossip_recent_threshold();
        async move { Ok(dna_def?.topology(cutoff)) }.boxed().into()
    }

    fn op_hash(&self, op_data: KOpData) -> KitsuneHostResult<KOpHash> {
        use holochain_p2p::DhtOpHashExt;

        async move {
            let op = holochain_p2p::WireDhtOpData::decode(op_data.0.clone())?;

            let op_hash = DhtOpHash::with_data_sync(&op.op_data).into_kitsune();

            Ok(op_hash)
        }
        .boxed()
        .into()
    }

    fn check_op_data(
        &self,
        space: Arc<kitsune_p2p::KitsuneSpace>,
        op_hash_list: Vec<KOpHash>,
        context: Option<kitsune_p2p::dependencies::kitsune_p2p_fetch::FetchContext>,
    ) -> KitsuneHostResult<Vec<bool>> {
        use holochain_p2p::{DhtOpHashExt, FetchContextExt};
        use rusqlite::ToSql;

        async move {
            let db = self.spaces.dht_db(&DnaHash::from_kitsune(&space))?;
            let results = db
                .async_commit(move |txn| {
                    let mut out = Vec::new();
                    for op_hash in op_hash_list {
                        let op_hash = DhtOpHash::from_kitsune(&op_hash);
                        match txn.query_row(
                            "SELECT 1 FROM DhtOp WHERE hash = ?",
                            [&op_hash],
                            |_row| Ok(()),
                        ) {
                            Ok(_) => {
                                // might be tempted to remove this given we
                                // are currently reflecting publishes,
                                // but we still need this for the delegate
                                // broadcast case.
                                if let Some(context) = context {
                                    if context.has_request_validation_receipt() {
                                        txn.execute(
                                            "UPDATE DhtOp SET require_receipt = ? WHERE DhtOp.hash = ?",
                                            [&true as &dyn ToSql, &op_hash as &dyn ToSql],
                                        )?;
                                    }
                                }
                                out.push(true)
                            }
                            Err(_) => out.push(false),
                        }
                    }
                    holochain_sqlite::prelude::DatabaseResult::Ok(out)
                })
                .await?;

            Ok(results)
        }
        .boxed()
        .into()
    }
src/conductor/space.rs (line 422)
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
    pub async fn handle_fetch_op_regions(
        &self,
        dna_hash: &DnaHash,
        topology: Topology,
        dht_arc_set: DhtArcSet,
    ) -> ConductorResult<RegionSetLtcs> {
        let sql = holochain_sqlite::sql::sql_cell::FETCH_OP_REGION;
        let max_chunks = ArqStrat::default().max_chunks();
        let arq_set = ArqBoundsSet::new(
            dht_arc_set
                .intervals()
                .into_iter()
                .map(|i| {
                    let len = i.length();
                    let (pow, _) = power_and_count_from_length(&topology.space, len, max_chunks);
                    ArqBounds::from_interval_rounded(&topology, pow, i).0
                })
                .collect(),
        );
        let times = TelescopingTimes::historical(&topology);
        let coords = RegionCoordSetLtcs::new(times, arq_set);
        let coords_clone = coords.clone();
        let db = self.dht_db(dna_hash)?;
        db.async_reader(move |txn| {
            let mut stmt = txn.prepare_cached(sql).map_err(DatabaseError::from)?;
            Ok(coords_clone.into_region_set(|(_, coords)| {
                let bounds = coords.to_bounds(&topology);
                let (x0, x1) = bounds.x;
                let (t0, t1) = bounds.t;
                stmt.query_row(
                    named_params! {
                        ":storage_start_loc": x0,
                        ":storage_end_loc": x1,
                        ":timestamp_min": t0,
                        ":timestamp_max": t1,
                    },
                    |row| {
                        let total_action_size: f64 = row.get("total_action_size")?;
                        let total_entry_size: f64 = row.get("total_entry_size")?;
                        let size = total_action_size + total_entry_size;
                        Ok(RegionData {
                            hash: RegionHash::from_vec(row.get("xor_hash")?)
                                .expect("region hash must be 32 bytes"),
                            size: size.min(u32::MAX as f64) as u32,
                            count: row.get("count")?,
                        })
                    },
                )
            })?)
        })
        .await
    }

Get the peer database (this will create the space if it doesn’t already exist).

Examples found in repository?
src/conductor/kitsune_host_impl.rs (line 60)
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
    fn peer_extrapolated_coverage(
        &self,
        space: std::sync::Arc<kitsune_p2p::KitsuneSpace>,
        dht_arc_set: holochain_p2p::dht_arc::DhtArcSet,
    ) -> KitsuneHostResult<Vec<f64>> {
        async move {
            let db = self.spaces.p2p_agents_db(&DnaHash::from_kitsune(&space))?;
            use holochain_sqlite::db::AsP2pAgentStoreConExt;
            let permit = db.conn_permit().await;
            let task = tokio::task::spawn_blocking(move || {
                let mut conn = db.with_permit(permit)?;
                conn.p2p_extrapolated_coverage(dht_arc_set)
            })
            .await;
            Ok(task??)
        }
        .boxed()
        .into()
    }

    fn record_metrics(
        &self,
        space: std::sync::Arc<kitsune_p2p::KitsuneSpace>,
        records: Vec<kitsune_p2p::event::MetricRecord>,
    ) -> KitsuneHostResult<()> {
        async move {
            let db = self.spaces.p2p_metrics_db(&DnaHash::from_kitsune(&space))?;
            use holochain_sqlite::db::AsP2pMetricStoreConExt;
            let permit = db.conn_permit().await;
            let task = tokio::task::spawn_blocking(move || {
                let mut conn = db.with_permit(permit)?;
                conn.p2p_log_metrics(records)
            })
            .await;
            Ok(task??)
        }
        .boxed()
        .into()
    }

    fn get_agent_info_signed(
        &self,
        GetAgentInfoSignedEvt { space, agent }: GetAgentInfoSignedEvt,
    ) -> KitsuneHostResult<Option<AgentInfoSigned>> {
        let dna_hash = DnaHash::from_kitsune(&space);
        let db = self.spaces.p2p_agents_db(&dna_hash);
        async move {
            Ok(super::p2p_agent_store::get_agent_info_signed(db?.into(), space, agent).await?)
        }
        .boxed()
        .into()
    }
More examples
Hide additional examples
src/conductor/conductor.rs (line 835)
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
        pub(crate) async fn prune_p2p_agents_db(&self) -> ConductorResult<()> {
            use holochain_p2p::AgentPubKeyExt;

            let mut space_to_agents = HashMap::new();

            for cell in self.running_cells.share_ref(|c| {
                <Result<_, one_err::OneErr>>::Ok(c.keys().cloned().collect::<Vec<_>>())
            })? {
                space_to_agents
                    .entry(cell.dna_hash().clone())
                    .or_insert_with(Vec::new)
                    .push(cell.agent_pubkey().to_kitsune());
            }

            for (space, agents) in space_to_agents {
                let db = self.spaces.p2p_agents_db(&space)?;
                p2p_prune(&db, agents).await?;
            }

            Ok(())
        }

        pub(crate) async fn network_info(
            &self,
            dnas: &[DnaHash],
        ) -> ConductorResult<Vec<NetworkInfo>> {
            futures::future::join_all(dnas.iter().map(|dna| async move {
                let d = self.holochain_p2p.get_diagnostics(dna.clone()).await?;
                let fetch_queue_info = d.fetch_queue.info([dna.to_kitsune()].into_iter().collect());
                ConductorResult::Ok(NetworkInfo { fetch_queue_info })
            }))
            .await
            .into_iter()
            .collect::<Result<Vec<_>, _>>()
        }

        #[instrument(skip(self))]
        pub(crate) async fn dispatch_holochain_p2p_event(
            &self,
            event: holochain_p2p::event::HolochainP2pEvent,
        ) -> ConductorApiResult<()> {
            use HolochainP2pEvent::*;
            let dna_hash = event.dna_hash().clone();
            trace!(dispatch_event = ?event);
            match event {
                PutAgentInfoSigned {
                    peer_data, respond, ..
                } => {
                    let sender = self.p2p_batch_sender(&dna_hash);
                    let (result_sender, response) = tokio::sync::oneshot::channel();
                    let _ = sender
                        .send(P2pBatch {
                            peer_data,
                            result_sender,
                        })
                        .await;
                    let res = match response.await {
                        Ok(r) => r.map_err(holochain_p2p::HolochainP2pError::other),
                        Err(e) => Err(holochain_p2p::HolochainP2pError::other(e)),
                    };
                    respond.respond(Ok(async move { res }.boxed().into()));
                }
                QueryAgentInfoSigned {
                    kitsune_space,
                    agents,
                    respond,
                    ..
                } => {
                    let db = { self.p2p_agents_db(&dna_hash) };
                    let res = list_all_agent_info(db.into(), kitsune_space)
                        .await
                        .map(|infos| match agents {
                            Some(agents) => infos
                                .into_iter()
                                .filter(|info| agents.contains(&info.agent))
                                .collect(),
                            None => infos,
                        })
                        .map_err(holochain_p2p::HolochainP2pError::other);
                    respond.respond(Ok(async move { res }.boxed().into()));
                }
                QueryGossipAgents {
                    since_ms,
                    until_ms,
                    arc_set,
                    respond,
                    ..
                } => {
                    use holochain_sqlite::db::AsP2pAgentStoreConExt;
                    let db = { self.p2p_agents_db(&dna_hash) };
                    let permit = db.conn_permit().await;
                    let res = tokio::task::spawn_blocking(move || {
                        let mut conn = db.with_permit(permit)?;
                        conn.p2p_gossip_query_agents(since_ms, until_ms, (*arc_set).clone())
                    })
                    .await;
                    let res = res
                        .map_err(holochain_p2p::HolochainP2pError::other)
                        .and_then(|r| r.map_err(holochain_p2p::HolochainP2pError::other));
                    respond.respond(Ok(async move { res }.boxed().into()));
                }
                QueryAgentInfoSignedNearBasis {
                    kitsune_space,
                    basis_loc,
                    limit,
                    respond,
                    ..
                } => {
                    let db = { self.p2p_agents_db(&dna_hash) };
                    let res = list_all_agent_info_signed_near_basis(
                        db.into(),
                        kitsune_space,
                        basis_loc,
                        limit,
                    )
                    .await
                    .map_err(holochain_p2p::HolochainP2pError::other);
                    respond.respond(Ok(async move { res }.boxed().into()));
                }
                QueryPeerDensity {
                    kitsune_space,
                    dht_arc,
                    respond,
                    ..
                } => {
                    let cutoff = self
                        .get_config()
                        .network
                        .clone()
                        .unwrap_or_default()
                        .tuning_params
                        .danger_gossip_recent_threshold();
                    let topo = self
                        .get_dna_def(&dna_hash)
                        .ok_or_else(|| DnaError::DnaMissing(dna_hash.clone()))?
                        .topology(cutoff);
                    let db = { self.p2p_agents_db(&dna_hash) };
                    let res = query_peer_density(db.into(), topo, kitsune_space, dht_arc)
                        .await
                        .map_err(holochain_p2p::HolochainP2pError::other);
                    respond.respond(Ok(async move { res }.boxed().into()));
                }
                SignNetworkData {
                    respond,
                    to_agent,
                    data,
                    ..
                } => {
                    let signature = to_agent.sign_raw(self.keystore(), data.into()).await?;
                    respond.respond(Ok(async move { Ok(signature) }.boxed().into()));
                }
                HolochainP2pEvent::CallRemote { .. }
                | CountersigningSessionNegotiation { .. }
                | Get { .. }
                | GetMeta { .. }
                | GetLinks { .. }
                | GetAgentActivity { .. }
                | MustGetAgentActivity { .. }
                | ValidationReceiptReceived { .. } => {
                    let cell_id =
                        CellId::new(event.dna_hash().clone(), event.target_agents().clone());
                    let cell = self.cell_by_id(&cell_id)?;
                    cell.handle_holochain_p2p_event(event).await?;
                }
                Publish {
                    dna_hash,
                    respond,
                    request_validation_receipt,
                    countersigning_session,
                    ops,
                    ..
                } => {
                    async {
                        let res = self
                            .spaces
                            .handle_publish(
                                &dna_hash,
                                request_validation_receipt,
                                countersigning_session,
                                ops,
                            )
                            .await
                            .map_err(holochain_p2p::HolochainP2pError::other);
                        respond.respond(Ok(async move { res }.boxed().into()));
                    }
                    .instrument(debug_span!("handle_publish"))
                    .await;
                }
                FetchOpData {
                    respond,
                    query,
                    dna_hash,
                    ..
                } => {
                    async {
                        let res = self
                            .spaces
                            .handle_fetch_op_data(&dna_hash, query)
                            .await
                            .map_err(holochain_p2p::HolochainP2pError::other);
                        respond.respond(Ok(async move { res }.boxed().into()));
                    }
                    .instrument(debug_span!("handle_fetch_op_data"))
                    .await;
                }

                HolochainP2pEvent::QueryOpHashes {
                    dna_hash,
                    window,
                    max_ops,
                    include_limbo,
                    arc_set,
                    respond,
                    ..
                } => {
                    let res = self
                        .spaces
                        .handle_query_op_hashes(&dna_hash, arc_set, window, max_ops, include_limbo)
                        .await
                        .map_err(holochain_p2p::HolochainP2pError::other);

                    respond.respond(Ok(async move { res }.boxed().into()));
                }
            }
            Ok(())
        }

        /// Invoke a zome function on a Cell
        pub async fn call_zome(&self, call: ZomeCall) -> ConductorApiResult<ZomeCallResult> {
            let cell = self.cell_by_id(&call.cell_id)?;
            Ok(cell.call_zome(call, None).await?)
        }

        pub(crate) async fn call_zome_with_workspace(
            &self,
            call: ZomeCall,
            workspace_lock: SourceChainWorkspace,
        ) -> ConductorApiResult<ZomeCallResult> {
            debug!(cell_id = ?call.cell_id);
            let cell = self.cell_by_id(&call.cell_id)?;
            Ok(cell.call_zome(call, Some(workspace_lock)).await?)
        }
    }
}

/// Methods related to app installation and management
mod app_impls {

    use super::*;
    impl Conductor {
        pub(crate) async fn install_app(
            self: Arc<Self>,
            installed_app_id: InstalledAppId,
            cell_data: Vec<(InstalledCell, Option<MembraneProof>)>,
        ) -> ConductorResult<()> {
            crate::conductor::conductor::genesis_cells(
                self.clone(),
                cell_data
                    .iter()
                    .map(|(c, p)| (c.as_id().clone(), p.clone()))
                    .collect(),
            )
            .await?;

            let cell_data = cell_data.into_iter().map(|(c, _)| c);
            let app = InstalledAppCommon::new_legacy(installed_app_id, cell_data)?;

            // Update the db
            let _ = self.add_disabled_app_to_db(app).await?;

            Ok(())
        }

        /// Install DNAs and set up Cells as specified by an AppBundle
        pub async fn install_app_bundle(
            self: Arc<Self>,
            payload: InstallAppPayload,
        ) -> ConductorResult<StoppedApp> {
            let InstallAppPayload {
                source,
                agent_key,
                installed_app_id,
                membrane_proofs,
                network_seed,
            } = payload;

            let bundle: AppBundle = {
                let original_bundle = source.resolve().await?;
                if let Some(network_seed) = network_seed {
                    let mut manifest = original_bundle.manifest().to_owned();
                    manifest.set_network_seed(network_seed);
                    AppBundle::from(original_bundle.into_inner().update_manifest(manifest)?)
                } else {
                    original_bundle
                }
            };

            let installed_app_id =
                installed_app_id.unwrap_or_else(|| bundle.manifest().app_name().to_owned());
            let ops = bundle
                .resolve_cells(agent_key.clone(), DnaGamut::placeholder(), membrane_proofs)
                .await?;

            let cells_to_create = ops.cells_to_create();

            for (dna, _) in ops.dnas_to_register {
                self.clone().register_dna(dna).await?;
            }

            crate::conductor::conductor::genesis_cells(self.clone(), cells_to_create).await?;

            let roles = ops.role_assignments;
            let app = InstalledAppCommon::new(installed_app_id, agent_key, roles)?;

            // Update the db
            let stopped_app = self.add_disabled_app_to_db(app).await?;

            Ok(stopped_app)
        }

        /// Uninstall an app
        #[tracing::instrument(skip(self))]
        pub async fn uninstall_app(
            self: Arc<Self>,
            installed_app_id: &InstalledAppId,
        ) -> ConductorResult<()> {
            let self_clone = self.clone();
            let app = self.remove_app_from_db(installed_app_id).await?;
            tracing::debug!(msg = "Removed app from db.", app = ?app);

            // Remove cells which may now be dangling due to the removed app
            self_clone
                .process_app_status_fx(AppStatusFx::SpinDown, None)
                .await?;
            Ok(())
        }

        /// List active AppIds
        pub async fn list_running_apps(&self) -> ConductorResult<Vec<InstalledAppId>> {
            let state = self.get_state().await?;
            Ok(state.running_apps().map(|(id, _)| id).cloned().collect())
        }

        /// List Apps with their information
        pub async fn list_apps(
            &self,
            status_filter: Option<AppStatusFilter>,
        ) -> ConductorResult<Vec<AppInfo>> {
            use AppStatusFilter::*;
            let conductor_state = self.get_state().await?;

            let apps_ids: Vec<&String> = match status_filter {
                Some(Enabled) => conductor_state.enabled_apps().map(|(id, _)| id).collect(),
                Some(Disabled) => conductor_state.disabled_apps().map(|(id, _)| id).collect(),
                Some(Running) => conductor_state.running_apps().map(|(id, _)| id).collect(),
                Some(Stopped) => conductor_state.stopped_apps().map(|(id, _)| id).collect(),
                Some(Paused) => conductor_state.paused_apps().map(|(id, _)| id).collect(),
                None => conductor_state.installed_apps().keys().collect(),
            };

            let app_infos: Vec<AppInfo> = apps_ids
                .into_iter()
                .map(|app_id| self.get_app_info_inner(app_id, &conductor_state))
                .collect::<Result<Vec<_>, _>>()?
                .into_iter()
                .flatten()
                .collect();

            Ok(app_infos)
        }

        /// Get the IDs of all active installed Apps which use this Cell
        pub async fn list_running_apps_for_dependent_cell_id(
            &self,
            cell_id: &CellId,
        ) -> ConductorResult<HashSet<InstalledAppId>> {
            Ok(self
                .get_state()
                .await?
                .running_apps()
                .filter(|(_, v)| v.all_cells().any(|i| i == cell_id))
                .map(|(k, _)| k)
                .cloned()
                .collect())
        }

        /// Find the ID of the first active installed App which uses this Cell
        pub async fn find_cell_with_role_alongside_cell(
            &self,
            cell_id: &CellId,
            role_name: &RoleName,
        ) -> ConductorResult<Option<CellId>> {
            Ok(self
                .get_state()
                .await?
                .running_apps()
                .find(|(_, running_app)| running_app.all_cells().any(|i| i == cell_id))
                .and_then(|(_, running_app)| {
                    running_app
                        .into_common()
                        .role(role_name)
                        .ok()
                        .map(|role| role.cell_id())
                        .cloned()
                }))
        }

        /// Get the IDs of all active installed Apps which use this Dna
        pub async fn list_running_apps_for_dependent_dna_hash(
            &self,
            dna_hash: &DnaHash,
        ) -> ConductorResult<HashSet<InstalledAppId>> {
            Ok(self
                .get_state()
                .await?
                .running_apps()
                .filter(|(_, v)| v.all_cells().any(|i| i.dna_hash() == dna_hash))
                .map(|(k, _)| k)
                .cloned()
                .collect())
        }

        /// Get info about an installed App, regardless of status
        pub async fn get_app_info(
            &self,
            installed_app_id: &InstalledAppId,
        ) -> ConductorResult<Option<AppInfo>> {
            let state = self.get_state().await?;
            let maybe_app_info = self.get_app_info_inner(installed_app_id, &state)?;
            Ok(maybe_app_info)
        }

        fn get_app_info_inner(
            &self,
            app_id: &InstalledAppId,
            state: &ConductorState,
        ) -> ConductorResult<Option<AppInfo>> {
            match state.installed_apps().get(app_id) {
                None => Ok(None),
                Some(app) => {
                    let dna_definitions = self.get_dna_definitions(app)?;
                    Ok(Some(AppInfo::from_installed_app(app, &dna_definitions)))
                }
            }
        }
    }
}

/// Methods related to cell access
mod cell_impls {
    use super::*;
    impl Conductor {
        pub(crate) fn cell_by_id(&self, cell_id: &CellId) -> ConductorResult<Arc<Cell>> {
            let cell = self
                .running_cells
                .share_ref(|c| c.get(cell_id).map(|i| i.cell.clone()))
                .ok_or_else(|| ConductorError::CellMissing(cell_id.clone()))?;
            Ok(cell)
        }

        /// Iterator over only the cells which are fully running. Generally used
        /// to handle conductor interface requests
        pub fn running_cell_ids(&self) -> HashSet<CellId> {
            self.running_cells.share_ref(|c| {
                c.iter()
                    .filter_map(|(id, item)| {
                        if item.is_running() {
                            Some(id.clone())
                        } else {
                            None
                        }
                    })
                    .collect()
            })
        }

        /// List CellIds for Cells which match a status filter
        pub fn list_cell_ids(&self, filter: Option<CellStatusFilter>) -> Vec<CellId> {
            self.running_cells.share_ref(|cells| {
                cells
                    .iter()
                    .filter_map(|(id, cell)| {
                        let matches = filter
                            .as_ref()
                            .map(|status| cell.status == *status)
                            .unwrap_or(true);
                        if matches {
                            Some(id)
                        } else {
                            None
                        }
                    })
                    .cloned()
                    .collect()
            })
        }
    }
}

/// Methods related to clone cell management
mod clone_cell_impls {
    use super::*;

    impl Conductor {
        /// Create a new cell in an existing app based on an existing DNA.
        ///
        /// # Returns
        ///
        /// A struct with the created cell's clone id and cell id.
        pub async fn create_clone_cell(
            self: Arc<Self>,
            payload: CreateCloneCellPayload,
        ) -> ConductorResult<InstalledCell> {
            let CreateCloneCellPayload {
                app_id,
                role_name,
                modifiers,
                membrane_proof,
                name,
            } = payload;
            if !modifiers.has_some_option_set() {
                return Err(ConductorError::CloneCellError(
                    "neither network_seed nor properties nor origin_time provided for clone cell"
                        .to_string(),
                ));
            }
            let state = self.get_state().await?;
            let app = state.get_app(&app_id)?;
            app.provisioned_cells()
                .find(|(app_role_name, _)| **app_role_name == role_name)
                .ok_or_else(|| {
                    ConductorError::CloneCellError(
                        "no base cell found for provided role id".to_string(),
                    )
                })?;

            // add cell to app
            let installed_clone_cell = self
                .add_clone_cell_to_app(
                    app_id.clone(),
                    role_name.clone(),
                    modifiers.serialized()?,
                    name,
                )
                .await?;

            // run genesis on cloned cell
            let cells = vec![(installed_clone_cell.as_id().clone(), membrane_proof)];
            crate::conductor::conductor::genesis_cells(self.clone(), cells).await?;
            self.create_and_add_initialized_cells_for_running_apps(Some(&app_id))
                .await?;
            Ok(installed_clone_cell)
        }

        /// Disable a clone cell.
        pub(crate) async fn disable_clone_cell(
            &self,
            DisableCloneCellPayload {
                app_id,
                clone_cell_id,
            }: &DisableCloneCellPayload,
        ) -> ConductorResult<()> {
            let (_, removed_cell_id) = self
                .update_state_prime({
                    let app_id = app_id.to_owned();
                    let clone_cell_id = clone_cell_id.to_owned();
                    move |mut state| {
                        let app = state.get_app_mut(&app_id)?;
                        let clone_id = app.get_clone_id(&clone_cell_id)?;
                        let cell_id = app.get_clone_cell_id(&clone_cell_id)?;
                        app.disable_clone_cell(&clone_id)?;
                        Ok((state, cell_id))
                    }
                })
                .await?;
            self.remove_cells(&[removed_cell_id]).await;
            Ok(())
        }

        /// Enable a disabled clone cell.
        pub async fn enable_clone_cell(
            self: Arc<Self>,
            payload: &EnableCloneCellPayload,
        ) -> ConductorResult<InstalledCell> {
            let (_, enabled_cell) = self
                .update_state_prime({
                    let app_id = payload.app_id.to_owned();
                    let clone_cell_id = payload.clone_cell_id.to_owned();
                    move |mut state| {
                        let app = state.get_app_mut(&app_id)?;
                        let clone_id = app.get_disabled_clone_id(&clone_cell_id)?;
                        let enabled_cell = app.enable_clone_cell(&clone_id)?;
                        Ok((state, enabled_cell))
                    }
                })
                .await?;

            self.create_and_add_initialized_cells_for_running_apps(Some(&payload.app_id))
                .await?;
            Ok(enabled_cell)
        }

        /// Delete a clone cell.
        pub(crate) async fn delete_clone_cell(
            &self,
            DeleteCloneCellPayload {
                app_id,
                clone_cell_id,
            }: &DeleteCloneCellPayload,
        ) -> ConductorResult<()> {
            self.update_state_prime({
                let app_id = app_id.clone();
                let clone_cell_id = clone_cell_id.clone();
                move |mut state| {
                    let app = state.get_app_mut(&app_id)?;
                    let clone_id = app.get_disabled_clone_id(&clone_cell_id)?;
                    app.delete_clone_cell(&clone_id)?;
                    Ok((state, ()))
                }
            })
            .await?;
            self.remove_dangling_cells().await?;
            Ok(())
        }
    }
}

/// Methods related to management of app and cell status
mod app_status_impls {
    use super::*;

    impl Conductor {
        /// Adjust which cells are present in the Conductor (adding and removing as
        /// needed) to match the current reality of all app statuses.
        /// - If a Cell is used by at least one Running app, then ensure it is added
        /// - If a Cell is used by no running apps, then ensure it is removed.
        #[tracing::instrument(skip(self))]
        pub async fn reconcile_cell_status_with_app_status(
            self: Arc<Self>,
        ) -> ConductorResult<CellStartupErrors> {
            self.remove_dangling_cells().await?;

            let results = self
                .create_and_add_initialized_cells_for_running_apps(None)
                .await?;
            Ok(results)
        }

        /// Enable an app
        #[tracing::instrument(skip(self))]
        pub async fn enable_app(
            self: Arc<Self>,
            app_id: InstalledAppId,
        ) -> ConductorResult<(InstalledApp, CellStartupErrors)> {
            let (app, delta) = self
                .transition_app_status(app_id.clone(), AppStatusTransition::Enable)
                .await?;
            let errors = self
                .process_app_status_fx(delta, Some(vec![app_id.to_owned()].into_iter().collect()))
                .await?;
            Ok((app, errors))
        }

        /// Disable an app
        #[tracing::instrument(skip(self))]
        pub async fn disable_app(
            self: Arc<Self>,
            app_id: InstalledAppId,
            reason: DisabledAppReason,
        ) -> ConductorResult<InstalledApp> {
            let (app, delta) = self
                .transition_app_status(app_id.clone(), AppStatusTransition::Disable(reason))
                .await?;
            self.process_app_status_fx(delta, Some(vec![app_id.to_owned()].into_iter().collect()))
                .await?;
            Ok(app)
        }

        /// Start an app
        #[tracing::instrument(skip(self))]
        pub async fn start_app(
            self: Arc<Self>,
            app_id: InstalledAppId,
        ) -> ConductorResult<InstalledApp> {
            let (app, delta) = self
                .transition_app_status(app_id.clone(), AppStatusTransition::Start)
                .await?;
            self.process_app_status_fx(delta, Some(vec![app_id.to_owned()].into_iter().collect()))
                .await?;
            Ok(app)
        }

        /// Register an app as disabled in the database
        pub(crate) async fn add_disabled_app_to_db(
            &self,
            app: InstalledAppCommon,
        ) -> ConductorResult<StoppedApp> {
            let (_, stopped_app) = self
                .update_state_prime(move |mut state| {
                    let stopped_app = state.add_app(app)?;
                    Ok((state, stopped_app))
                })
                .await?;
            Ok(stopped_app)
        }

        /// Transition an app's status to a new state.
        #[tracing::instrument(skip(self))]
        pub(crate) async fn transition_app_status(
            &self,
            app_id: InstalledAppId,
            transition: AppStatusTransition,
        ) -> ConductorResult<(InstalledApp, AppStatusFx)> {
            Ok(self
                .update_state_prime(move |mut state| {
                    let (app, delta) = state.transition_app_status(&app_id, transition)?.clone();
                    let app = app.clone();
                    Ok((state, (app, delta)))
                })
                .await?
                .1)
        }

        /// Pause an app
        #[tracing::instrument(skip(self))]
        #[cfg(any(test, feature = "test_utils"))]
        pub async fn pause_app(
            self: Arc<Self>,
            app_id: InstalledAppId,
            reason: PausedAppReason,
        ) -> ConductorResult<InstalledApp> {
            let (app, delta) = self
                .transition_app_status(app_id.clone(), AppStatusTransition::Pause(reason))
                .await?;
            self.process_app_status_fx(delta, Some(vec![app_id.clone()].into_iter().collect()))
                .await?;
            Ok(app)
        }

        /// Create any Cells which are missing for any running apps, then initialize
        /// and join them. (Joining could take a while.)
        pub(crate) async fn create_and_add_initialized_cells_for_running_apps(
            self: Arc<Self>,
            app_id: Option<&InstalledAppId>,
        ) -> ConductorResult<CellStartupErrors> {
            let results = self.clone().create_cells_for_running_apps(app_id).await?;
            let (new_cells, errors): (Vec<_>, Vec<_>) =
                results.into_iter().partition(Result::is_ok);

            let new_cells = new_cells
                .into_iter()
                // We can unwrap the successes because of the partition
                .map(Result::unwrap)
                .collect();

            let errors = errors
                .into_iter()
                // throw away the non-Debug types which will be unwrapped away anyway
                .map(|r| r.map(|_| ()))
                // We can unwrap the errors because of the partition
                .map(Result::unwrap_err)
                .collect();

            // Add the newly created cells to the Conductor with the PendingJoin
            // status, and start their workflow loops
            self.add_and_initialize_cells(new_cells);

            // Join these newly created cells to the network
            // (as well as any others which need joining)
            self.join_all_pending_cells().await;

            Ok(errors)
        }

        /// Attempt to join all PendingJoin cells to the kitsune network.
        /// Returns the cells which were joined during this call.
        ///
        /// NB: this could take as long as JOIN_NETWORK_TIMEOUT, which is significant.
        ///   Be careful to only await this future if it's important that cells be
        ///   joined before proceeding.
        pub(crate) async fn join_all_pending_cells(&self) -> Vec<CellId> {
            // Join the network but ignore errors because the
            // space retries joining all cells every 5 minutes.

            use holochain_p2p::AgentPubKeyExt;

            let tasks = self
            .mark_pending_cells_as_joining()
            .into_iter()
            .map(|(cell_id, cell)| async move {
                let p2p_agents_db = cell.p2p_agents_db().clone();
                let kagent = cell_id.agent_pubkey().to_kitsune();
                let agent_info = match p2p_agents_db.async_reader(move |tx| {
                    tx.p2p_get_agent(&kagent)
                }).await {
                    Ok(maybe_info) => maybe_info,
                    _ => None,
                };
                let maybe_initial_arc = agent_info.map(|i| i.storage_arc);
                let network = cell.holochain_p2p_dna().clone();
                match tokio::time::timeout(JOIN_NETWORK_TIMEOUT, network.join(cell_id.agent_pubkey().clone(), maybe_initial_arc)).await {
                    Ok(Err(e)) => {
                        tracing::info!(error = ?e, cell_id = ?cell_id, "Error while trying to join the network");
                        Err(cell_id)
                    }
                    Err(_) => {
                        tracing::info!(cell_id = ?cell_id, "Timed out trying to join the network");
                        Err(cell_id)
                    }
                    Ok(Ok(_)) => Ok(cell_id),
                }
            });

            let maybes: Vec<_> = futures::stream::iter(tasks)
                .buffer_unordered(100)
                .collect()
                .await;

            let (cell_ids, failed_joins): (Vec<_>, Vec<_>) =
                maybes.into_iter().partition(Result::is_ok);

            // These unwraps are both safe because of the partition.
            let cell_ids: Vec<_> = cell_ids.into_iter().map(Result::unwrap).collect();
            let failed_joins: Vec<_> = failed_joins.into_iter().map(Result::unwrap_err).collect();

            // Update the status of the cells which were able to join the network
            // (may or may not be all cells which were added)
            self.update_cell_status(cell_ids.as_slice(), CellStatus::Joined);

            self.update_cell_status(failed_joins.as_slice(), CellStatus::PendingJoin);

            cell_ids
        }

        /// Adjust app statuses (via state transitions) to match the current
        /// reality of which Cells are present in the conductor.
        /// - Do not change state for Disabled apps. For all others:
        /// - If an app is Paused but all of its (required) Cells are on,
        ///     then set it to Running
        /// - If an app is Running but at least one of its (required) Cells are off,
        ///     then set it to Paused
        pub(crate) async fn reconcile_app_status_with_cell_status(
            &self,
            app_ids: Option<HashSet<InstalledAppId>>,
        ) -> ConductorResult<AppStatusFx> {
            use AppStatus::*;
            use AppStatusTransition::*;

            let running_cells: HashSet<CellId> = self.running_cell_ids();
            let (_, delta) = self
                .update_state_prime(move |mut state| {
                    #[allow(deprecated)]
                    let apps = state.installed_apps_mut().iter_mut().filter(|(id, _)| {
                        app_ids
                            .as_ref()
                            .map(|ids| ids.contains(&**id))
                            .unwrap_or(true)
                    });
                    let delta = apps
                        .into_iter()
                        .map(|(_app_id, app)| {
                            match app.status().clone() {
                                Running => {
                                    // If not all required cells are running, pause the app
                                    let missing: Vec<_> = app
                                        .required_cells()
                                        .filter(|id| !running_cells.contains(id))
                                        .collect();
                                    if !missing.is_empty() {
                                        let reason = PausedAppReason::Error(format!(
                                            "Some cells are missing / not able to run: {:#?}",
                                            missing
                                        ));
                                        app.status.transition(Pause(reason))
                                    } else {
                                        AppStatusFx::NoChange
                                    }
                                }
                                Paused(_) => {
                                    // If all required cells are now running, restart the app
                                    if app.required_cells().all(|id| running_cells.contains(id)) {
                                        app.status.transition(Start)
                                    } else {
                                        AppStatusFx::NoChange
                                    }
                                }
                                Disabled(_) => {
                                    // Disabled status should never automatically change.
                                    AppStatusFx::NoChange
                                }
                            }
                        })
                        .fold(AppStatusFx::default(), AppStatusFx::combine);
                    Ok((state, delta))
                })
                .await?;
            Ok(delta)
        }

        /// Change the CellStatus of the given Cells in the Conductor.
        /// Silently ignores Cells that don't exist.
        pub(crate) fn update_cell_status(&self, cell_ids: &[CellId], status: CellStatus) {
            for cell_id in cell_ids {
                self.running_cells.share_mut(|cells| {
                    if let Some(mut cell) = cells.get_mut(cell_id) {
                        cell.status = status.clone();
                    }
                });
            }
        }
    }
}

/// Methods related to management of Conductor state
mod state_impls {
    use super::*;

    impl Conductor {
        pub(crate) async fn get_state(&self) -> ConductorResult<ConductorState> {
            self.spaces.get_state().await
        }

        /// Update the internal state with a pure function mapping old state to new
        pub(crate) async fn update_state<F: Send>(&self, f: F) -> ConductorResult<ConductorState>
        where
            F: FnOnce(ConductorState) -> ConductorResult<ConductorState> + 'static,
        {
            self.spaces.update_state(f).await
        }

        /// Update the internal state with a pure function mapping old state to new,
        /// which may also produce an output value which will be the output of
        /// this function
        pub(crate) async fn update_state_prime<F, O>(
            &self,
            f: F,
        ) -> ConductorResult<(ConductorState, O)>
        where
            F: FnOnce(ConductorState) -> ConductorResult<(ConductorState, O)> + Send + 'static,
            O: Send + 'static,
        {
            self.check_running()?;
            self.spaces.update_state_prime(f).await
        }

        /// Sends a JoinHandle to the TaskManager task to be managed
        pub(crate) async fn manage_task(&self, handle: ManagedTaskAdd) -> ConductorResult<()> {
            self.task_manager
                .share_ref(|tm| {
                    tm.as_ref()
                        .expect("Task manager not initialized")
                        .task_add_sender()
                        .clone()
                })
                .send(handle)
                .await
                .map_err(|e| ConductorError::SubmitTaskError(format!("{}", e)))
        }
    }
}

/// Methods related to zome function scheduling
mod scheduler_impls {
    use super::*;

    impl Conductor {
        pub(super) fn set_scheduler(&self, join_handle: tokio::task::JoinHandle<()>) {
            let mut scheduler = self.scheduler.lock();
            if let Some(existing_join_handle) = &*scheduler {
                existing_join_handle.abort();
            }
            *scheduler = Some(join_handle);
        }

        /// Start the scheduler. None is not an option.
        /// Calling this will:
        /// - Delete/unschedule all ephemeral scheduled functions GLOBALLY
        /// - Add an interval that runs IN ADDITION to previous invocations
        /// So ideally this would be called ONCE per conductor lifecyle ONLY.
        pub(crate) async fn start_scheduler(self: Arc<Self>, interval_period: std::time::Duration) {
            // Clear all ephemeral cruft in all cells before starting a scheduler.
            let cell_arcs = {
                let mut cell_arcs = vec![];
                for cell_id in self.running_cell_ids() {
                    if let Ok(cell_arc) = self.cell_by_id(&cell_id) {
                        cell_arcs.push(cell_arc);
                    }
                }
                cell_arcs
            };
            let tasks = cell_arcs
                .into_iter()
                .map(|cell_arc| cell_arc.delete_all_ephemeral_scheduled_fns());
            futures::future::join_all(tasks).await;

            let scheduler_handle = self.clone();
            self.set_scheduler(tokio::task::spawn(async move {
                let mut interval = tokio::time::interval(interval_period);
                loop {
                    interval.tick().await;
                    scheduler_handle
                        .clone()
                        .dispatch_scheduled_fns(Timestamp::now())
                        .await;
                }
            }));
        }

        /// The scheduler wants to dispatch any functions that are due.
        pub(crate) async fn dispatch_scheduled_fns(self: Arc<Self>, now: Timestamp) {
            let cell_arcs = {
                let mut cell_arcs = vec![];
                for cell_id in self.running_cell_ids() {
                    if let Ok(cell_arc) = self.cell_by_id(&cell_id) {
                        cell_arcs.push(cell_arc);
                    }
                }
                cell_arcs
            };

            let tasks = cell_arcs
                .into_iter()
                .map(|cell_arc| cell_arc.dispatch_scheduled_fns(now));
            futures::future::join_all(tasks).await;
        }
    }
}

/// Miscellaneous methods
mod misc_impls {
    use holochain_zome_types::builder;

    use super::*;

    impl Conductor {
        /// Grant a zome call capability for a cell
        pub async fn grant_zome_call_capability(
            &self,
            payload: GrantZomeCallCapabilityPayload,
        ) -> ConductorApiResult<()> {
            let GrantZomeCallCapabilityPayload { cell_id, cap_grant } = payload;

            let source_chain = SourceChain::new(
                self.get_authored_db(cell_id.dna_hash())?,
                self.get_dht_db(cell_id.dna_hash())?,
                self.get_dht_db_cache(cell_id.dna_hash())?,
                self.keystore.clone(),
                cell_id.agent_pubkey().clone(),
            )
            .await?;

            let cap_grant_entry = Entry::CapGrant(cap_grant);
            let entry_hash = EntryHash::with_data_sync(&cap_grant_entry);
            let action_builder = builder::Create {
                entry_type: EntryType::CapGrant,
                entry_hash,
            };

            source_chain
                .put_weightless(
                    action_builder,
                    Some(cap_grant_entry),
                    ChainTopOrdering::default(),
                )
                .await?;

            let cell = self.cell_by_id(&cell_id)?;
            source_chain.flush(cell.holochain_p2p_dna()).await?;

            Ok(())
        }

        /// Create a JSON dump of the cell's state
        pub async fn dump_cell_state(&self, cell_id: &CellId) -> ConductorApiResult<String> {
            let cell = self.cell_by_id(cell_id)?;
            let authored_db = cell.authored_db();
            let dht_db = cell.dht_db();
            let space = cell_id.dna_hash();
            let p2p_agents_db = self.p2p_agents_db(space);

            let peer_dump =
                p2p_agent_store::dump_state(p2p_agents_db.into(), Some(cell_id.clone())).await?;
            let source_chain_dump = source_chain::dump_state(
                authored_db.clone().into(),
                cell_id.agent_pubkey().clone(),
            )
            .await?;

            let out = JsonDump {
                peer_dump,
                source_chain_dump,
                integration_dump: integration_dump(&dht_db.clone().into()).await?,
            };
            // Add summary
            let summary = out.to_string();
            let out = (out, summary);
            Ok(serde_json::to_string_pretty(&out)?)
        }

        /// Create a comprehensive structured dump of a cell's state
        pub async fn dump_full_cell_state(
            &self,
            cell_id: &CellId,
            dht_ops_cursor: Option<u64>,
        ) -> ConductorApiResult<FullStateDump> {
            let authored_db = self.get_or_create_authored_db(cell_id.dna_hash())?;
            let dht_db = self.get_or_create_dht_db(cell_id.dna_hash())?;
            let dna_hash = cell_id.dna_hash();
            let p2p_agents_db = self.spaces.p2p_agents_db(dna_hash)?;

            let peer_dump =
                p2p_agent_store::dump_state(p2p_agents_db.into(), Some(cell_id.clone())).await?;
            let source_chain_dump =
                source_chain::dump_state(authored_db.into(), cell_id.agent_pubkey().clone())
                    .await?;

            let out = FullStateDump {
                peer_dump,
                source_chain_dump,
                integration_dump: full_integration_dump(&dht_db, dht_ops_cursor).await?,
            };
            Ok(out)
        }

        /// JSON dump of network metrics
        pub async fn dump_network_metrics(
            &self,
            dna_hash: Option<DnaHash>,
        ) -> ConductorApiResult<String> {
            use holochain_p2p::HolochainP2pSender;
            self.holochain_p2p()
                .dump_network_metrics(dna_hash)
                .await
                .map_err(crate::conductor::api::error::ConductorApiError::other)
        }

        /// Add signed agent info to the conductor
        pub async fn add_agent_infos(
            &self,
            agent_infos: Vec<AgentInfoSigned>,
        ) -> ConductorApiResult<()> {
            let mut space_map = HashMap::new();
            for agent_info_signed in agent_infos {
                let space = agent_info_signed.space.clone();
                space_map
                    .entry(space)
                    .or_insert_with(Vec::new)
                    .push(agent_info_signed);
            }
            for (space, agent_infos) in space_map {
                let db = self.p2p_agents_db(&DnaHash::from_kitsune(&space));
                inject_agent_infos(db, agent_infos.iter()).await?;
            }
            Ok(())
        }

        /// Inject records into a source chain for a cell.
        /// If the records form a chain segment that can be "grafted" onto the existing chain, it will be.
        /// Otherwise, a new chain will be formed using the specified records.
        pub async fn graft_records_onto_source_chain(
            self: Arc<Self>,
            cell_id: CellId,
            validate: bool,
            records: Vec<Record>,
        ) -> ConductorApiResult<()> {
            graft_records_onto_source_chain::graft_records_onto_source_chain(
                self, cell_id, validate, records,
            )
            .await
        }

        /// Update coordinator zomes on an existing dna.
        pub async fn update_coordinators(
            &self,
            hash: &DnaHash,
            coordinator_zomes: CoordinatorZomes,
            wasms: Vec<wasm::DnaWasm>,
        ) -> ConductorResult<()> {
            // Note this isn't really concurrent safe. It would be a race condition to update the
            // same dna concurrently.
            let mut ribosome = self
                .ribosome_store()
                .share_ref(|d| match d.get_ribosome(hash) {
                    Some(dna) => Ok(dna),
                    None => Err(DnaError::DnaMissing(hash.to_owned())),
                })?;
            let _old_wasms = ribosome
                .dna_file
                .update_coordinators(coordinator_zomes.clone(), wasms.clone())
                .await?;

            // Add new wasm code to db.
            self.put_wasm_code(
                ribosome.dna_def().clone(),
                wasms.into_iter(),
                Vec::with_capacity(0),
            )
            .await?;

            // Update RibosomeStore.
            self.ribosome_store()
                .share_mut(|d| d.add_ribosome(ribosome));

            // TODO: Remove old wasm code? (Maybe this needs to be done on restart as it could be in use).

            Ok(())
        }
    }
}

/// Pure accessor methods
mod accessor_impls {
    use super::*;

    impl Conductor {
        pub(crate) fn ribosome_store(&self) -> &RwShare<RibosomeStore> {
            &self.ribosome_store
        }

        pub(crate) fn get_queue_consumer_workflows(&self) -> QueueConsumerMap {
            self.spaces.queue_consumer_map.clone()
        }

        /// Access to the signal broadcast channel, to create
        /// new subscriptions
        pub fn signal_broadcaster(&self) -> SignalBroadcaster {
            let senders = self
                .app_interfaces
                .share_ref(|ai| ai.values().map(|i| i.signal_tx()).cloned().collect());
            SignalBroadcaster::new(senders)
        }

        /// Instantiate a Ribosome for use with a DNA
        pub(crate) fn get_ribosome(&self, dna_hash: &DnaHash) -> ConductorResult<RealRibosome> {
            self.ribosome_store
                .share_ref(|d| match d.get_ribosome(dna_hash) {
                    Some(r) => Ok(r),
                    None => Err(DnaError::DnaMissing(dna_hash.to_owned()).into()),
                })
        }

        /// Get a dna space or create it if one doesn't exist.
        pub(crate) fn get_or_create_space(&self, dna_hash: &DnaHash) -> ConductorResult<Space> {
            self.spaces.get_or_create_space(dna_hash)
        }

        pub(crate) fn get_or_create_authored_db(
            &self,
            dna_hash: &DnaHash,
        ) -> ConductorResult<DbWrite<DbKindAuthored>> {
            self.spaces.authored_db(dna_hash)
        }

        pub(crate) fn get_or_create_dht_db(
            &self,
            dna_hash: &DnaHash,
        ) -> ConductorResult<DbWrite<DbKindDht>> {
            self.spaces.dht_db(dna_hash)
        }

        pub(crate) fn p2p_agents_db(&self, hash: &DnaHash) -> DbWrite<DbKindP2pAgents> {
            self.spaces
                .p2p_agents_db(hash)
                .expect("failed to open p2p_agent_store database")
        }

Get the peer database (this will create the space if it doesn’t already exist).

Examples found in repository?
src/conductor/conductor.rs (line 2097)
2095
2096
2097
2098
2099
        pub(crate) fn p2p_metrics_db(&self, hash: &DnaHash) -> DbWrite<DbKindP2pMetrics> {
            self.spaces
                .p2p_metrics_db(hash)
                .expect("failed to open p2p_metrics_store database")
        }
More examples
Hide additional examples
src/conductor/kitsune_host_impl.rs (line 80)
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
    fn record_metrics(
        &self,
        space: std::sync::Arc<kitsune_p2p::KitsuneSpace>,
        records: Vec<kitsune_p2p::event::MetricRecord>,
    ) -> KitsuneHostResult<()> {
        async move {
            let db = self.spaces.p2p_metrics_db(&DnaHash::from_kitsune(&space))?;
            use holochain_sqlite::db::AsP2pMetricStoreConExt;
            let permit = db.conn_permit().await;
            let task = tokio::task::spawn_blocking(move || {
                let mut conn = db.with_permit(permit)?;
                conn.p2p_log_metrics(records)
            })
            .await;
            Ok(task??)
        }
        .boxed()
        .into()
    }

Get the batch sender (this will create the space if it doesn’t already exist).

Examples found in repository?
src/conductor/conductor.rs (line 2091)
2086
2087
2088
2089
2090
2091
2092
2093
        pub(crate) fn p2p_batch_sender(
            &self,
            hash: &DnaHash,
        ) -> tokio::sync::mpsc::Sender<P2pBatch> {
            self.spaces
                .p2p_batch_sender(hash)
                .expect("failed to get p2p_batch_sender")
        }

the network module is requesting a list of dht op hashes Get the DhtOpHashes and authored timestamps for a given time window.

The network module needs info about various groupings (“regions”) of ops

Note that this always includes all ops regardless of integration status. This is to avoid the degenerate case of freshly joining a network, and having several new peers gossiping with you at once about the same regions. If we calculate our region hash only by integrated ops, we will experience mismatches for a large number of ops repeatedly until we have integrated those ops. Note that when sending ops we filter out ops in limbo.

The network module is requesting the content for dht ops

The network module is requesting the content for dht ops

The network module is requesting the content for dht ops

we are receiving a “publish” event from the network

Get the recent_threshold based on the kitsune network config

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
TODO: once 1.33.0 is the minimum supported compiler version, remove Any::type_id_compat and use StdAny::type_id instead. https://github.com/rust-lang/rust/issues/27745
The archived version of the pointer metadata for this type.
Converts some archived metadata to the pointer metadata for itself.
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Deserializes using the given deserializer

Returns the argument unchanged.

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Attaches the current Context to this type, returning a WithContext wrapper. Read more
Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The alignment of pointer.
The type for initializers.
Initializes a with the given initializer. Read more
Dereferences the given pointer. Read more
Mutably dereferences the given pointer. Read more
Drops the object pointed to by the given pointer. Read more
The type for metadata in pointers and references to Self.
Should always be Self
The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Checks if self is actually part of its subset T (and can be converted to it).
Use with care! Same as self.to_subset but without any property checks. Always succeeds.
The inclusion map: converts self to the equivalent element of its superset.
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
upcast ref
upcast mut ref
upcast boxed dyn
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more