pub struct Conductor {
pub config: ConductorConfig,
/* private fields */
}
Expand description
A Conductor is a group of Cells
Fields§
§config: ConductorConfig
The config used to create this Conductor
Implementations§
source§impl Conductor
impl Conductor
Methods used by the ConductorHandle
sourcepub fn check_running(&self) -> ConductorResult<()>
pub fn check_running(&self) -> ConductorResult<()>
A gate to put at the top of public functions to ensure that work is not attempted after a shutdown has been issued
Examples found in repository?
More examples
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
async fn handle_request(
&self,
request: Result<Self::ApiRequest, SerializedBytesError>,
) -> InterfaceResult<Self::ApiResponse> {
{
self.conductor_handle
.check_running()
.map_err(Box::new)
.map_err(InterfaceError::RequestHandler)?;
}
match request {
Ok(request) => Ok(AppInterfaceApi::handle_app_request(self, request).await),
Err(e) => Ok(AppResponse::Error(SerializationError::from(e).into())),
}
}
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
async fn handle_request(
&self,
request: Result<Self::ApiRequest, SerializedBytesError>,
) -> InterfaceResult<Self::ApiResponse> {
// Don't hold the read across both awaits
{
self.conductor_handle
.check_running()
.map_err(Box::new)
.map_err(InterfaceError::RequestHandler)?;
}
match request {
Ok(request) => Ok(AdminInterfaceApi::handle_admin_request(self, request).await),
Err(e) => Ok(AdminResponse::Error(SerializationError::from(e).into())),
}
}
sourcepub fn shutdown(&self)
pub fn shutdown(&self)
Broadcasts the shutdown signal to all managed tasks.
To actually wait for these tasks to complete, be sure to
take_shutdown_handle
to await for completion.
Examples found in repository?
More examples
511 512 513 514 515 516 517 518 519 520 521 522 523
fn drop(&mut self) {
if let Some(handle) = self.handle.take() {
tokio::task::spawn(async move {
// Shutdown the conductor
if let Some(shutdown) = handle.take_shutdown_handle() {
handle.shutdown();
if let Err(e) = shutdown.await {
tracing::warn!("Failed to join conductor shutdown task: {:?}", e);
}
}
});
}
}
sourcepub fn take_shutdown_handle(&self) -> Option<JoinHandle<TaskManagerResult>>
pub fn take_shutdown_handle(&self) -> Option<JoinHandle<TaskManagerResult>>
Return the handle which waits for the task manager task to complete
Examples found in repository?
More examples
511 512 513 514 515 516 517 518 519 520 521 522 523
fn drop(&mut self) {
if let Some(handle) = self.handle.take() {
tokio::task::spawn(async move {
// Shutdown the conductor
if let Some(shutdown) = handle.take_shutdown_handle() {
handle.shutdown();
if let Err(e) = shutdown.await {
tracing::warn!("Failed to join conductor shutdown task: {:?}", e);
}
}
});
}
}
source§impl Conductor
impl Conductor
sourcepub async fn add_app_interface(
self: Arc<Self>,
port: Either<u16, AppInterfaceId>
) -> ConductorResult<u16>
pub async fn add_app_interface(
self: Arc<Self>,
port: Either<u16, AppInterfaceId>
) -> ConductorResult<u16>
Spawn a new app interface task, register it with the TaskManager, and modify the conductor accordingly, based on the config passed in which is just a networking port number (or 0 to auto-select one). Returns the given or auto-chosen port number if giving an Ok Result
Examples found in repository?
More examples
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
sourcepub fn get_arbitrary_admin_websocket_port(&self) -> Option<u16>
pub fn get_arbitrary_admin_websocket_port(&self) -> Option<u16>
Returns a port which is guaranteed to have a websocket listener with an Admin interface on it. Useful for specifying port 0 and letting the OS choose a free port.
sourcepub async fn list_app_interfaces(&self) -> ConductorResult<Vec<u16>>
pub async fn list_app_interfaces(&self) -> ConductorResult<Vec<u16>>
Give a list of networking ports taken up as running app interface tasks
Examples found in repository?
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
source§impl Conductor
impl Conductor
sourcepub fn list_dnas(&self) -> Vec<DnaHash> ⓘ
pub fn list_dnas(&self) -> Vec<DnaHash> ⓘ
Get the list of hashes of installed Dnas in this Conductor
Examples found in repository?
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
sourcepub fn get_dna_def(&self, hash: &DnaHash) -> Option<DnaDef>
pub fn get_dna_def(&self, hash: &DnaHash) -> Option<DnaDef>
Get a DnaDef
from the RibosomeStore
Examples found in repository?
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
pub async fn spawn_queue_consumer_tasks(
cell_id: CellId,
network: HolochainP2pDna,
space: &Space,
conductor_handle: ConductorHandle,
task_sender: sync::mpsc::Sender<ManagedTaskAdd>,
stop: sync::broadcast::Sender<()>,
) -> (QueueTriggers, InitialQueueTriggers) {
let Space {
authored_db,
dht_db,
cache_db: cache,
dht_query_cache,
..
} = space;
let keystore = conductor_handle.keystore().clone();
let dna_hash = Arc::new(cell_id.dna_hash().clone());
let queue_consumer_map = conductor_handle.get_queue_consumer_workflows();
// Publish
let (tx_publish, handle) = spawn_publish_dht_ops_consumer(
cell_id.agent_pubkey().clone(),
authored_db.clone(),
conductor_handle.clone(),
stop.subscribe(),
Box::new(network.clone()),
);
task_sender
.send(ManagedTaskAdd::cell_critical(
handle,
cell_id.clone(),
"publish_dht_ops_consumer",
))
.await
.expect("Failed to manage workflow handle");
// Validation Receipt
// One per space.
let (tx_receipt, handle) =
queue_consumer_map.spawn_once_validation_receipt(dna_hash.clone(), || {
spawn_validation_receipt_consumer(
dna_hash.clone(),
dht_db.clone(),
conductor_handle.clone(),
stop.subscribe(),
network.clone(),
)
});
if let Some(handle) = handle {
task_sender
.send(ManagedTaskAdd::cell_critical(
handle,
cell_id.clone(),
"validation_receipt_consumer",
))
.await
.expect("Failed to manage workflow handle");
}
// Integration
// One per space.
let (tx_integration, handle) =
queue_consumer_map.spawn_once_integration(dna_hash.clone(), || {
spawn_integrate_dht_ops_consumer(
dna_hash.clone(),
dht_db.clone(),
dht_query_cache.clone(),
stop.subscribe(),
tx_receipt.clone(),
network.clone(),
)
});
if let Some(handle) = handle {
task_sender
.send(ManagedTaskAdd::cell_critical(
handle,
cell_id.clone(),
"integrate_dht_ops_consumer",
))
.await
.expect("Failed to manage workflow handle");
}
let dna_def = conductor_handle
.get_dna_def(&*dna_hash)
.expect("Dna must be in store");
// App validation
// One per space.
let (tx_app, handle) = queue_consumer_map.spawn_once_app_validation(dna_hash.clone(), || {
spawn_app_validation_consumer(
dna_hash.clone(),
AppValidationWorkspace::new(
authored_db.clone().into(),
dht_db.clone(),
space.dht_query_cache.clone(),
cache.clone(),
keystore.clone(),
Arc::new(dna_def),
),
conductor_handle.clone(),
stop.subscribe(),
tx_integration.clone(),
network.clone(),
dht_query_cache.clone(),
)
});
if let Some(handle) = handle {
task_sender
.send(ManagedTaskAdd::cell_critical(
handle,
cell_id.clone(),
"app_validation_consumer",
))
.await
.expect("Failed to manage workflow handle");
}
let dna_def = conductor_handle
.get_dna_def(&*dna_hash)
.expect("Dna must be in store");
// Sys validation
// One per space.
let (tx_sys, handle) = queue_consumer_map.spawn_once_sys_validation(dna_hash.clone(), || {
spawn_sys_validation_consumer(
SysValidationWorkspace::new(
authored_db.clone().into(),
dht_db.clone().into(),
dht_query_cache.clone(),
cache.clone(),
Arc::new(dna_def),
),
space.clone(),
conductor_handle.clone(),
stop.subscribe(),
tx_app.clone(),
network.clone(),
)
});
if let Some(handle) = handle {
task_sender
.send(ManagedTaskAdd::cell_critical(
handle,
cell_id.clone(),
"sys_validation_consumer",
))
.await
.expect("Failed to manage workflow handle");
}
let (tx_cs, handle) = queue_consumer_map.spawn_once_countersigning(dna_hash.clone(), || {
spawn_countersigning_consumer(
space.clone(),
stop.subscribe(),
network.clone(),
tx_sys.clone(),
)
});
if let Some(handle) = handle {
task_sender
.send(ManagedTaskAdd::cell_critical(
handle,
cell_id.clone(),
"countersigning_consumer",
))
.await
.expect("Failed to manage workflow handle");
}
(
QueueTriggers {
sys_validation: tx_sys.clone(),
publish_dht_ops: tx_publish.clone(),
countersigning: tx_cs,
integrate_dht_ops: tx_integration.clone(),
},
InitialQueueTriggers::new(tx_sys, tx_publish, tx_app, tx_integration, tx_receipt),
)
}
More examples
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
sourcepub fn get_dna_file(&self, hash: &DnaHash) -> Option<DnaFile>
pub fn get_dna_file(&self, hash: &DnaHash) -> Option<DnaFile>
Get a DnaFile
from the RibosomeStore
Examples found in repository?
More examples
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
pub async fn genesis<Ribosome>(
id: CellId,
conductor_handle: ConductorHandle,
authored_db: DbWrite<DbKindAuthored>,
dht_db: DbWrite<DbKindDht>,
dht_db_cache: DhtDbQueryCache,
ribosome: Ribosome,
membrane_proof: Option<MembraneProof>,
chc: Option<ChcImpl>,
) -> CellResult<()>
where
Ribosome: RibosomeT + 'static,
{
// get the dna
let dna_file = conductor_handle
.get_dna_file(id.dna_hash())
.ok_or_else(|| DnaError::DnaMissing(id.dna_hash().to_owned()))?;
let conductor_api = CellConductorApi::new(conductor_handle.clone(), id.clone());
// run genesis
let workspace = GenesisWorkspace::new(authored_db, dht_db)
.map_err(ConductorApiError::from)
.map_err(Box::new)?;
// exit early if genesis has already run
if workspace.has_genesis(id.agent_pubkey().clone()).await? {
return Ok(());
}
let args = GenesisWorkflowArgs::new(
dna_file,
id.agent_pubkey().clone(),
membrane_proof,
ribosome,
dht_db_cache,
chc,
);
genesis_workflow(workspace, conductor_api, args)
.await
.map_err(ConductorApiError::from)
.map_err(Box::new)?;
if let Some(trigger) = conductor_handle
.get_queue_consumer_workflows()
.integration_trigger(Arc::new(id.dna_hash().clone()))
{
trigger.trigger(&"genesis");
}
Ok(())
}
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
sourcepub fn get_entry_def(&self, key: &EntryDefBufferKey) -> Option<EntryDef>
pub fn get_entry_def(&self, key: &EntryDefBufferKey) -> Option<EntryDef>
Get an EntryDef
from the EntryDefBufferKey
Examples found in repository?
More examples
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
pub(crate) async fn get_entry_def(
entry_def_index: EntryDefIndex,
zome: IntegrityZomeDef,
dna_hash: &DnaHash,
conductor_handle: &Conductor,
) -> EntryDefStoreResult<Option<EntryDef>> {
// Try to get the entry def from the entry def store
let key = EntryDefBufferKey::new(zome, entry_def_index);
let entry_def = conductor_handle.get_entry_def(&key);
let ribosome = conductor_handle
.get_ribosome(dna_hash)
.map_err(|_| EntryDefStoreError::DnaFileMissing(dna_hash.clone()))?;
// If it's not found run the ribosome and get the entry defs
match &entry_def {
Some(_) => Ok(entry_def),
None => Ok(get_entry_defs(ribosome)
.await?
.into_iter()
.find(
|(
EntryDefBufferKey {
entry_def_position, ..
},
_,
)| *entry_def_position == entry_def_index,
)
.map(|(_, v)| v)),
}
}
sourcepub fn get_dna_definitions(
&self,
app: &InstalledApp
) -> ConductorResult<HashMap<CellId, DnaDefHashed>>
pub fn get_dna_definitions(
&self,
app: &InstalledApp
) -> ConductorResult<HashMap<CellId, DnaDefHashed>>
Create a hash map of all existing DNA definitions, mapped to cell ids.
Examples found in repository?
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
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)))
}
}
}
More examples
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
sourcepub fn root_db_dir(&self) -> &DatabaseRootPath
pub fn root_db_dir(&self) -> &DatabaseRootPath
Get the root environment directory.
sourcepub fn keystore(&self) -> &MetaLairClient
pub fn keystore(&self) -> &MetaLairClient
Get the keystore.
Examples found in repository?
More examples
47 48 49 50 51 52 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
pub async fn new(
cell_id: &CellId,
handle: &ConductorHandle,
dna_file: &DnaFile,
chc: Option<ChcImpl>,
) -> Self {
let authored_db = handle.get_authored_db(cell_id.dna_hash()).unwrap();
let dht_db = handle.get_dht_db(cell_id.dna_hash()).unwrap();
let dht_db_cache = handle.get_dht_db_cache(cell_id.dna_hash()).unwrap();
let cache = handle.get_cache_db(cell_id).unwrap();
let keystore = handle.keystore().clone();
let network = handle
.holochain_p2p()
.to_dna(cell_id.dna_hash().clone(), chc);
let triggers = handle.get_cell_triggers(cell_id).unwrap();
let cell_conductor_api = CellConductorApi::new(handle.clone(), cell_id.clone());
let ribosome = handle.get_ribosome(dna_file.dna_hash()).unwrap();
let signal_tx = handle.signal_broadcaster();
CellHostFnCaller {
cell_id: cell_id.clone(),
authored_db,
dht_db,
dht_db_cache,
cache,
ribosome,
network,
keystore,
signal_tx,
triggers,
cell_conductor_api,
}
}
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
pub async fn call_from_fallible<I, O, F>(
&self,
provenance: &AgentPubKey,
cap_secret: Option<CapSecret>,
zome: &SweetZome,
fn_name: F,
payload: I,
) -> ConductorApiResult<O>
where
FunctionName: From<F>,
I: Serialize + std::fmt::Debug,
O: serde::de::DeserializeOwned + std::fmt::Debug,
{
let payload = ExternIO::encode(payload).expect("Couldn't serialize payload");
let now = Timestamp::now();
let (nonce, expires_at) = fresh_nonce(now)?;
let call_unsigned = ZomeCallUnsigned {
cell_id: zome.cell_id().clone(),
zome_name: zome.name().clone(),
fn_name: fn_name.into(),
cap_secret,
provenance: provenance.clone(),
payload,
nonce,
expires_at,
};
let call = ZomeCall::try_from_unsigned_zome_call(self.keystore(), call_unsigned).await?;
let response = self.0.call_zome(call).await;
match response {
Ok(Ok(response)) => Ok(unwrap_to!(response => ZomeCallResponse::Ok)
.decode()
.expect("Couldn't deserialize zome call output")),
Ok(Err(error)) => Err(ConductorApiError::Other(Box::new(error))),
Err(error) => Err(error),
}
}
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)),
}
}
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
pub async fn create_for_zome(
cell_id: &CellId,
handle: &ConductorHandle,
dna_file: &DnaFile,
zome_index: usize,
) -> HostFnCaller {
let authored_db = handle.get_authored_db(cell_id.dna_hash()).unwrap();
let dht_db = handle.get_dht_db(cell_id.dna_hash()).unwrap();
let dht_db_cache = handle.get_dht_db_cache(cell_id.dna_hash()).unwrap();
let cache = handle.get_cache_db(cell_id).unwrap();
let keystore = handle.keystore().clone();
let network = handle
.holochain_p2p()
.to_dna(cell_id.dna_hash().clone(), None);
let zome_path = (
cell_id.clone(),
dna_file
.dna()
.integrity_zomes
.get(zome_index)
.unwrap()
.0
.clone(),
)
.into();
let ribosome = handle.get_ribosome(dna_file.dna_hash()).unwrap();
let signal_tx = handle.signal_broadcaster();
let call_zome_handle =
CellConductorApi::new(handle.clone(), cell_id.clone()).into_call_zome_handle();
HostFnCaller {
authored_db,
dht_db,
dht_db_cache,
cache,
ribosome,
zome_path,
network,
keystore,
signal_tx,
call_zome_handle,
}
}
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 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
pub(crate) async fn graft_records_onto_source_chain(
handle: ConductorHandle,
cell_id: CellId,
validate: bool,
records: Vec<Record>,
) -> ConductorApiResult<()> {
// Get or create the space for this cell.
// Note: This doesn't require the cell be installed.
let space = handle.get_or_create_space(cell_id.dna_hash())?;
let chc = None;
let network = handle
.holochain_p2p()
.to_dna(cell_id.dna_hash().clone(), chc);
let source_chain: SourceChain = space
.source_chain(handle.keystore().clone(), cell_id.agent_pubkey().clone())
.await?;
let existing = source_chain
.query(ChainQueryFilter::new().descending())
.await?
.into_iter()
.map(|r| r.signed_action)
.collect::<Vec<SignedActionHashed>>();
let graft = ChainGraft::new(existing, records).rebalance();
let chain_top = graft.existing_chain_top();
if validate {
validate_records(handle.clone(), &cell_id, &chain_top, graft.incoming()).await?;
}
// Produce the op lights for each record.
let data = graft
.incoming
.into_iter()
.map(|el| {
let ops = produce_op_lights_from_records(vec![&el])?;
// Check have the same author as cell.
let (sah, entry) = el.into_inner();
if sah.action().author() != cell_id.agent_pubkey() {
return Err(StateMutationError::AuthorsMustMatch);
}
Ok((sah, ops, entry.into_option()))
})
.collect::<StateMutationResult<Vec<_>>>()?;
// Commit the records to the source chain.
let ops_to_integrate = space
.authored_db
.async_commit({
let cell_id = cell_id.clone();
move |txn| {
if let Some((_, seq)) = chain_top {
// Remove records above the grafting position.
//
// NOTES:
// - the chain top may have moved since the grafting call began,
// but it doesn't really matter, since we explicitly want to
// clobber anything beyond the grafting point anyway.
// - if there is an existing fork, there may still be a fork after the
// grafting. A more rigorous approach would thin out the existing
// actions until a single fork is obtained.
txn.execute(
holochain_sqlite::sql::sql_cell::DELETE_ACTIONS_AFTER_SEQ,
rusqlite::named_params! {
":author": cell_id.agent_pubkey(),
":seq": seq
},
)
.map_err(StateMutationError::from)?;
}
let mut ops_to_integrate = Vec::new();
// Commit the records and ops to the authored db.
for (sah, ops, entry) in data {
// Clippy is wrong :(
#[allow(clippy::needless_collect)]
let basis = ops
.iter()
.map(|op| op.dht_basis().clone())
.collect::<Vec<_>>();
ops_to_integrate.extend(
source_chain::put_raw(txn, sah, ops, entry)?
.into_iter()
.zip(basis.into_iter()),
);
}
SourceChainResult::Ok(ops_to_integrate)
}
})
.await?;
// Check which ops need to be integrated.
// Only integrated if a cell is installed.
if handle
.list_cell_ids(Some(CellStatus::Joined))
.contains(&cell_id)
{
holochain_state::integrate::authored_ops_to_dht_db(
&network,
ops_to_integrate,
&space.authored_db,
&space.dht_db,
&space.dht_query_cache,
)
.await?;
}
Ok(())
}
async fn validate_records(
handle: ConductorHandle,
cell_id: &CellId,
chain_top: &Option<(ActionHash, u32)>,
records: &[Record],
) -> ConductorApiResult<()> {
let space = handle.get_or_create_space(cell_id.dna_hash())?;
let ribosome = handle.get_ribosome(cell_id.dna_hash())?;
let chc = None;
let network = handle
.holochain_p2p()
.to_dna(cell_id.dna_hash().clone(), chc);
// Create a raw source chain to validate against because
// genesis may not have been run yet.
let workspace = SourceChainWorkspace::raw_empty(
space.authored_db.clone(),
space.dht_db.clone(),
space.dht_query_cache.clone(),
space.cache_db.clone(),
handle.keystore().clone(),
cell_id.agent_pubkey().clone(),
Arc::new(ribosome.dna_def().as_content().clone()),
)
.await?;
let sc = workspace.source_chain();
// Validate the chain.
crate::core::validate_chain(records.iter().map(|e| e.signed_action()), chain_top)
.map_err(|e| SourceChainError::InvalidCommit(e.to_string()))?;
// Add the records to the source chain so we can validate them.
sc.scratch()
.apply(|scratch| {
for r in records {
holochain_state::prelude::insert_record_scratch(
scratch,
r.clone(),
Default::default(),
);
}
})
.map_err(SourceChainError::from)?;
// Run the individual record validations.
crate::core::workflow::inline_validation(
workspace.clone(),
network.clone(),
handle.clone(),
ribosome,
)
.await?;
Ok(())
}
sourcepub fn holochain_p2p(&self) -> &HolochainP2pRef
pub fn holochain_p2p(&self) -> &HolochainP2pRef
Get a reference to the conductor’s HolochainP2p.
Examples found in repository?
More examples
47 48 49 50 51 52 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
pub async fn new(
cell_id: &CellId,
handle: &ConductorHandle,
dna_file: &DnaFile,
chc: Option<ChcImpl>,
) -> Self {
let authored_db = handle.get_authored_db(cell_id.dna_hash()).unwrap();
let dht_db = handle.get_dht_db(cell_id.dna_hash()).unwrap();
let dht_db_cache = handle.get_dht_db_cache(cell_id.dna_hash()).unwrap();
let cache = handle.get_cache_db(cell_id).unwrap();
let keystore = handle.keystore().clone();
let network = handle
.holochain_p2p()
.to_dna(cell_id.dna_hash().clone(), chc);
let triggers = handle.get_cell_triggers(cell_id).unwrap();
let cell_conductor_api = CellConductorApi::new(handle.clone(), cell_id.clone());
let ribosome = handle.get_ribosome(dna_file.dna_hash()).unwrap();
let signal_tx = handle.signal_broadcaster();
CellHostFnCaller {
cell_id: cell_id.clone(),
authored_db,
dht_db,
dht_db_cache,
cache,
ribosome,
network,
keystore,
signal_tx,
triggers,
cell_conductor_api,
}
}
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
pub async fn create_for_zome(
cell_id: &CellId,
handle: &ConductorHandle,
dna_file: &DnaFile,
zome_index: usize,
) -> HostFnCaller {
let authored_db = handle.get_authored_db(cell_id.dna_hash()).unwrap();
let dht_db = handle.get_dht_db(cell_id.dna_hash()).unwrap();
let dht_db_cache = handle.get_dht_db_cache(cell_id.dna_hash()).unwrap();
let cache = handle.get_cache_db(cell_id).unwrap();
let keystore = handle.keystore().clone();
let network = handle
.holochain_p2p()
.to_dna(cell_id.dna_hash().clone(), None);
let zome_path = (
cell_id.clone(),
dna_file
.dna()
.integrity_zomes
.get(zome_index)
.unwrap()
.0
.clone(),
)
.into();
let ribosome = handle.get_ribosome(dna_file.dna_hash()).unwrap();
let signal_tx = handle.signal_broadcaster();
let call_zome_handle =
CellConductorApi::new(handle.clone(), cell_id.clone()).into_call_zome_handle();
HostFnCaller {
authored_db,
dht_db,
dht_db_cache,
cache,
ribosome,
zome_path,
network,
keystore,
signal_tx,
call_zome_handle,
}
}
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 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
pub(crate) async fn graft_records_onto_source_chain(
handle: ConductorHandle,
cell_id: CellId,
validate: bool,
records: Vec<Record>,
) -> ConductorApiResult<()> {
// Get or create the space for this cell.
// Note: This doesn't require the cell be installed.
let space = handle.get_or_create_space(cell_id.dna_hash())?;
let chc = None;
let network = handle
.holochain_p2p()
.to_dna(cell_id.dna_hash().clone(), chc);
let source_chain: SourceChain = space
.source_chain(handle.keystore().clone(), cell_id.agent_pubkey().clone())
.await?;
let existing = source_chain
.query(ChainQueryFilter::new().descending())
.await?
.into_iter()
.map(|r| r.signed_action)
.collect::<Vec<SignedActionHashed>>();
let graft = ChainGraft::new(existing, records).rebalance();
let chain_top = graft.existing_chain_top();
if validate {
validate_records(handle.clone(), &cell_id, &chain_top, graft.incoming()).await?;
}
// Produce the op lights for each record.
let data = graft
.incoming
.into_iter()
.map(|el| {
let ops = produce_op_lights_from_records(vec![&el])?;
// Check have the same author as cell.
let (sah, entry) = el.into_inner();
if sah.action().author() != cell_id.agent_pubkey() {
return Err(StateMutationError::AuthorsMustMatch);
}
Ok((sah, ops, entry.into_option()))
})
.collect::<StateMutationResult<Vec<_>>>()?;
// Commit the records to the source chain.
let ops_to_integrate = space
.authored_db
.async_commit({
let cell_id = cell_id.clone();
move |txn| {
if let Some((_, seq)) = chain_top {
// Remove records above the grafting position.
//
// NOTES:
// - the chain top may have moved since the grafting call began,
// but it doesn't really matter, since we explicitly want to
// clobber anything beyond the grafting point anyway.
// - if there is an existing fork, there may still be a fork after the
// grafting. A more rigorous approach would thin out the existing
// actions until a single fork is obtained.
txn.execute(
holochain_sqlite::sql::sql_cell::DELETE_ACTIONS_AFTER_SEQ,
rusqlite::named_params! {
":author": cell_id.agent_pubkey(),
":seq": seq
},
)
.map_err(StateMutationError::from)?;
}
let mut ops_to_integrate = Vec::new();
// Commit the records and ops to the authored db.
for (sah, ops, entry) in data {
// Clippy is wrong :(
#[allow(clippy::needless_collect)]
let basis = ops
.iter()
.map(|op| op.dht_basis().clone())
.collect::<Vec<_>>();
ops_to_integrate.extend(
source_chain::put_raw(txn, sah, ops, entry)?
.into_iter()
.zip(basis.into_iter()),
);
}
SourceChainResult::Ok(ops_to_integrate)
}
})
.await?;
// Check which ops need to be integrated.
// Only integrated if a cell is installed.
if handle
.list_cell_ids(Some(CellStatus::Joined))
.contains(&cell_id)
{
holochain_state::integrate::authored_ops_to_dht_db(
&network,
ops_to_integrate,
&space.authored_db,
&space.dht_db,
&space.dht_query_cache,
)
.await?;
}
Ok(())
}
async fn validate_records(
handle: ConductorHandle,
cell_id: &CellId,
chain_top: &Option<(ActionHash, u32)>,
records: &[Record],
) -> ConductorApiResult<()> {
let space = handle.get_or_create_space(cell_id.dna_hash())?;
let ribosome = handle.get_ribosome(cell_id.dna_hash())?;
let chc = None;
let network = handle
.holochain_p2p()
.to_dna(cell_id.dna_hash().clone(), chc);
// Create a raw source chain to validate against because
// genesis may not have been run yet.
let workspace = SourceChainWorkspace::raw_empty(
space.authored_db.clone(),
space.dht_db.clone(),
space.dht_query_cache.clone(),
space.cache_db.clone(),
handle.keystore().clone(),
cell_id.agent_pubkey().clone(),
Arc::new(ribosome.dna_def().as_content().clone()),
)
.await?;
let sc = workspace.source_chain();
// Validate the chain.
crate::core::validate_chain(records.iter().map(|e| e.signed_action()), chain_top)
.map_err(|e| SourceChainError::InvalidCommit(e.to_string()))?;
// Add the records to the source chain so we can validate them.
sc.scratch()
.apply(|scratch| {
for r in records {
holochain_state::prelude::insert_record_scratch(
scratch,
r.clone(),
Default::default(),
);
}
})
.map_err(SourceChainError::from)?;
// Run the individual record validations.
crate::core::workflow::inline_validation(
workspace.clone(),
network.clone(),
handle.clone(),
ribosome,
)
.await?;
Ok(())
}
sourcepub async fn register_dna(&self, dna: DnaFile) -> ConductorResult<()>
pub async fn register_dna(&self, dna: DnaFile) -> ConductorResult<()>
Install a DnaFile
in this Conductor
Examples found in repository?
More examples
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 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
pub async fn install_app(
name: &str,
cell_data: Vec<(InstalledCell, Option<MembraneProof>)>,
dnas: Vec<DnaFile>,
conductor_handle: ConductorHandle,
) {
for dna in dnas {
conductor_handle.register_dna(dna).await.unwrap();
}
conductor_handle
.clone()
.install_app(name.to_string(), cell_data)
.await
.unwrap();
conductor_handle
.clone()
.enable_app(name.to_string())
.await
.unwrap();
let errors = conductor_handle
.reconcile_cell_status_with_app_status()
.await
.unwrap();
assert!(errors.is_empty(), "{:?}", errors);
}
/// Payload for installing cells
pub type InstalledCellsWithProofs = Vec<(InstalledCell, Option<MembraneProof>)>;
/// One of various ways to setup an app, used somewhere...
pub async fn setup_app(
dnas: Vec<DnaFile>,
cell_data: Vec<(InstalledCell, Option<MembraneProof>)>,
) -> (Arc<TempDir>, RealAppInterfaceApi, ConductorHandle) {
let db_dir = test_db_dir();
let conductor_handle = ConductorBuilder::new()
.test(db_dir.path(), &[])
.await
.unwrap();
for dna in dnas {
conductor_handle.register_dna(dna).await.unwrap();
}
conductor_handle
.clone()
.install_app("test app".to_string(), cell_data)
.await
.unwrap();
conductor_handle
.clone()
.enable_app("test app".to_string())
.await
.unwrap();
let errors = conductor_handle
.clone()
.reconcile_cell_status_with_app_status()
.await
.unwrap();
assert!(errors.is_empty());
let handle = conductor_handle.clone();
(
Arc::new(db_dir),
RealAppInterfaceApi::new(conductor_handle),
handle,
)
}
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 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
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")
}
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")
}
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")
}
/// Get the post commit sender.
pub async fn post_commit_permit(
&self,
) -> Result<tokio::sync::mpsc::OwnedPermit<PostCommitArgs>, SendError<()>> {
self.post_commit.clone().reserve_owned().await
}
/// Get the conductor config
pub fn get_config(&self) -> &ConductorConfig {
&self.config
}
}
}
/// Private methods, only used within the Conductor, never called from outside.
impl Conductor {
fn add_admin_port(&self, port: u16) {
self.admin_websocket_ports.share_mut(|p| p.push(port));
}
/// Add fully constructed cells to the cell map in the Conductor
fn add_and_initialize_cells(&self, cells: Vec<(Cell, InitialQueueTriggers)>) {
let (new_cells, triggers): (Vec<_>, Vec<_>) = cells.into_iter().unzip();
self.running_cells.share_mut(|cells| {
for cell in new_cells {
let cell_id = cell.id().clone();
tracing::debug!(?cell_id, "added cell");
cells.insert(
cell_id,
CellItem {
cell: Arc::new(cell),
status: CellStatus::PendingJoin,
},
);
}
});
for trigger in triggers {
trigger.initialize_workflows();
}
}
/// Return Cells which are pending network join, and mark them as
/// currently joining.
///
/// Used to discover which cells need to be joined to the network.
/// The cells' status are upgraded to `Joining` when this function is called.
fn mark_pending_cells_as_joining(&self) -> Vec<(CellId, Arc<Cell>)> {
self.running_cells.share_mut(|cells| {
cells
.iter_mut()
.filter_map(|(id, item)| {
if item.is_pending() {
item.status = CellStatus::Joining;
Some((id.clone(), item.cell.clone()))
} else {
None
}
})
.collect()
})
}
/// Remove all Cells which are not referenced by any Enabled app.
/// (Cells belonging to Paused apps are not considered "dangling" and will not be removed)
async fn remove_dangling_cells(&self) -> ConductorResult<()> {
let state = self.get_state().await?;
let keepers: HashSet<CellId> = state
.enabled_apps()
.flat_map(|(_, app)| app.all_cells().cloned().collect::<HashSet<_>>())
.collect();
// Clean up all cells that will be dropped (leave network, etc.)
let to_cleanup: Vec<_> = self.running_cells.share_mut(|cells| {
let to_remove = cells
.keys()
.filter(|id| !keepers.contains(id))
.cloned()
.collect::<Vec<_>>();
to_remove
.iter()
.filter_map(|cell_id| cells.remove(cell_id))
.collect()
});
for cell in to_cleanup {
cell.cell.cleanup().await?;
}
// drop all but the keepers
Ok(())
}
/// Attempt to create all necessary Cells which have not already been created
/// and added to the conductor, namely the cells which are referenced by
/// Running apps. If there are no cells to create, this function does nothing.
///
/// Accepts an optional app id to only create cells of that app instead of all apps.
///
/// Returns a Result for each attempt so that successful creations can be
/// handled alongside the failures.
async fn create_cells_for_running_apps(
self: Arc<Self>,
app_id: Option<&InstalledAppId>,
) -> ConductorResult<Vec<Result<(Cell, InitialQueueTriggers), (CellId, CellError)>>> {
// Data required to create apps
let (managed_task_add_sender, managed_task_stop_broadcaster) =
self.task_manager.share_ref(|tm| {
let tm = tm.as_ref().expect("Task manager not initialized");
(
tm.task_add_sender().clone(),
tm.task_stop_broadcaster().clone(),
)
});
// Closure for creating all cells in an app
let state = self.get_state().await?;
let app_cells: HashSet<CellId> = match app_id {
Some(app_id) => {
let app = state.get_app(app_id)?;
if app.status().is_running() {
app.all_cells().into_iter().cloned().collect()
} else {
HashSet::new()
}
}
None =>
// Collect all CellIds across all apps, deduped
{
state
.installed_apps()
.iter()
.filter(|(_, app)| app.status().is_running())
.flat_map(|(_id, app)| app.all_cells().collect::<Vec<&CellId>>())
.cloned()
.collect()
}
};
// calculate the existing cells so we can filter those out, only creating
// cells for CellIds that don't have cells
let on_cells: HashSet<CellId> = self
.running_cells
.share_ref(|c| c.keys().cloned().collect());
let tasks = app_cells.difference(&on_cells).map(|cell_id| {
let handle = self.clone();
let managed_task_add_sender = managed_task_add_sender.clone();
let managed_task_stop_broadcaster = managed_task_stop_broadcaster.clone();
let chc = handle.chc(cell_id);
async move {
let holochain_p2p_cell =
handle.holochain_p2p.to_dna(cell_id.dna_hash().clone(), chc);
let space = handle
.get_or_create_space(cell_id.dna_hash())
.map_err(|e| CellError::FailedToCreateDnaSpace(e.into()))
.map_err(|err| (cell_id.clone(), err))?;
Cell::create(
cell_id.clone(),
handle,
space,
holochain_p2p_cell,
managed_task_add_sender,
managed_task_stop_broadcaster,
)
.await
.map_err(|err| (cell_id.clone(), err))
}
});
// Join on all apps and return a list of
// apps that had succelly created cells
// and any apps that encounted errors
Ok(futures::future::join_all(tasks).await)
}
/// Deal with the side effects of an app status state transition
async fn process_app_status_fx(
self: Arc<Self>,
delta: AppStatusFx,
app_ids: Option<HashSet<InstalledAppId>>,
) -> ConductorResult<CellStartupErrors> {
use AppStatusFx::*;
let mut last = (delta, vec![]);
loop {
tracing::debug!(msg = "Processing app status delta", delta = ?last.0);
last = match last.0 {
NoChange => break,
SpinDown => {
// Reconcile cell status so that dangling cells can leave the network and be removed
let errors = self.clone().reconcile_cell_status_with_app_status().await?;
// TODO: This should probably be emitted over the admin interface
if !errors.is_empty() {
error!(msg = "Errors when trying to stop app(s)", ?errors);
}
(NoChange, errors)
}
SpinUp | Both => {
// Reconcile cell status so that missing/pending cells can become fully joined
let errors = self.clone().reconcile_cell_status_with_app_status().await?;
// Reconcile app status in case some cells failed to join, so the app can be paused
let delta = self
.clone()
.reconcile_app_status_with_cell_status(app_ids.clone())
.await?;
// TODO: This should probably be emitted over the admin interface
if !errors.is_empty() {
error!(msg = "Errors when trying to start app(s)", ?errors);
}
(delta, errors)
}
};
}
Ok(last.1)
}
/// Entirely remove an app from the database, returning the removed app.
async fn remove_app_from_db(&self, app_id: &InstalledAppId) -> ConductorResult<InstalledApp> {
let (_state, app) = self
.update_state_prime({
let app_id = app_id.clone();
move |mut state| {
let app = state.remove_app(&app_id)?;
Ok((state, app))
}
})
.await?;
Ok(app)
}
/// Associate a new clone cell with an existing app.
async fn add_clone_cell_to_app(
&self,
app_id: InstalledAppId,
role_name: RoleName,
dna_modifiers: DnaModifiersOpt,
name: Option<String>,
) -> ConductorResult<InstalledCell> {
let ribosome_store = &self.ribosome_store;
// retrieve base cell DNA hash from conductor
let (_, base_cell_dna_hash) = self
.update_state_prime({
let app_id = app_id.clone();
let role_name = role_name.clone();
move |mut state| {
let app = state.get_app_mut(&app_id)?;
let app_role_assignment = app
.roles()
.get(&role_name)
.ok_or_else(|| AppError::RoleNameMissing(role_name.to_owned()))?;
if app_role_assignment.is_clone_limit_reached() {
return Err(ConductorError::AppError(AppError::CloneLimitExceeded(
app_role_assignment.clone_limit(),
app_role_assignment.clone(),
)));
}
let parent_dna_hash = app_role_assignment.dna_hash().clone();
Ok((state, parent_dna_hash))
}
})
.await?;
// clone cell from base cell DNA
let clone_dna = ribosome_store.share_ref(|ds| {
let mut dna_file = ds
.get_dna_file(&base_cell_dna_hash)
.ok_or(DnaError::DnaMissing(base_cell_dna_hash))?
.update_modifiers(dna_modifiers);
if let Some(name) = name {
dna_file = dna_file.set_name(name);
}
Ok::<_, DnaError>(dna_file)
})?;
let clone_dna_hash = clone_dna.dna_hash().to_owned();
// add clone cell to app and instantiate resulting clone cell
let (_, installed_clone_cell) = self
.update_state_prime(move |mut state| {
let app = state.get_app_mut(&app_id)?;
let agent_key = app.role(&role_name)?.agent_key().to_owned();
let cell_id = CellId::new(clone_dna_hash, agent_key);
let clone_id = app.add_clone(&role_name, &cell_id)?;
let installed_clone_cell =
InstalledCell::new(cell_id, clone_id.as_app_role_name().clone());
Ok((state, installed_clone_cell))
})
.await?;
// register clone cell dna in ribosome store
self.register_dna(clone_dna).await?;
Ok(installed_clone_cell)
}
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 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
}
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
source§impl Conductor
impl Conductor
sourcepub async fn get_agent_infos(
&self,
cell_id: Option<CellId>
) -> ConductorApiResult<Vec<AgentInfoSigned>>
pub async fn get_agent_infos(
&self,
cell_id: Option<CellId>
) -> ConductorApiResult<Vec<AgentInfoSigned>>
Get signed agent info from the conductor
Examples found in repository?
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 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
async fn create_test_data(
num_agents: usize,
approx_num_ops_held: usize,
dna_file: DnaFile,
integrity_uuid: String,
coordinator_uuid: String,
) -> GeneratedData {
let coverage = ((50.0 / num_agents as f64) * 2.0).clamp(0.0, 1.0);
let num_storage_buckets = (1.0 / coverage).round() as u32;
let bucket_size = u32::MAX / num_storage_buckets;
let buckets = (0..num_storage_buckets)
.map(|i| DhtArcRange::from_bounds(i * bucket_size, i * bucket_size + bucket_size))
.collect::<Vec<_>>();
let mut bucket_counts = vec![0; buckets.len()];
let mut entries = Vec::with_capacity(buckets.len() * approx_num_ops_held);
let rng = rand::thread_rng();
let mut rand_entry = rng.sample_iter(&Standard);
let rand_entry = rand_entry.by_ref();
let start = std::time::Instant::now();
loop {
let d: Vec<u8> = rand_entry.take(10).collect();
let d = UnsafeBytes::from(d);
let entry = Entry::app(d.try_into().unwrap()).unwrap();
let hash = EntryHash::with_data_sync(&entry);
let loc = hash.get_loc();
if let Some(index) = buckets.iter().position(|b| b.contains(&loc)) {
if bucket_counts[index] < approx_num_ops_held * 100 {
entries.push(entry);
bucket_counts[index] += 1;
}
}
if bucket_counts
.iter()
.all(|&c| c >= approx_num_ops_held * 100)
{
break;
}
}
dbg!(bucket_counts);
dbg!(start.elapsed());
let mut tuning =
kitsune_p2p_types::config::tuning_params_struct::KitsuneP2pTuningParams::default();
tuning.gossip_strategy = "none".to_string();
tuning.disable_publish = true;
let mut network = KitsuneP2pConfig::default();
network.tuning_params = Arc::new(tuning);
let config = ConductorConfig {
network: Some(network),
..Default::default()
};
let mut conductor = SweetConductor::from_config(config).await;
let mut agents = Vec::new();
dbg!("generating agents");
for i in 0..num_agents {
eprintln!("generating agent {}", i);
let agent = conductor
.keystore()
.clone()
.new_sign_keypair_random()
.await
.unwrap();
agents.push(agent);
}
dbg!("Installing apps");
let apps = conductor
.setup_app_for_agents("app", &agents, &[dna_file.clone()])
.await
.unwrap();
let cells = apps.cells_flattened();
let mut entries = entries.into_iter();
let entries = entries.by_ref();
for (i, cell) in cells.iter().enumerate() {
eprintln!("Calling {}", i);
let e = entries.take(approx_num_ops_held).collect::<Vec<_>>();
conductor
.call::<_, (), _>(&cell.zome("zome1"), "create_many", e)
.await;
}
let mut authored = HashMap::new();
let mut ops = HashMap::new();
for (i, cell) in cells.iter().enumerate() {
eprintln!("Extracting data {}", i);
let db = cell.authored_db().clone();
let data = fresh_reader_test(db, |mut txn| {
get_authored_ops(&mut txn, cell.agent_pubkey())
});
let hashes = data.keys().cloned().collect::<Vec<_>>();
authored.insert(Arc::new(cell.agent_pubkey().clone()), hashes);
ops.extend(data);
}
dbg!("Getting agent info");
let peer_data = conductor.get_agent_infos(None).await.unwrap();
dbg!("Done");
GeneratedData {
integrity_uuid,
coordinator_uuid,
peer_data,
authored,
ops,
}
}
More examples
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
sourcepub async fn call_zome(
&self,
call: ZomeCall
) -> ConductorApiResult<ZomeCallResult>
pub async fn call_zome(
&self,
call: ZomeCall
) -> ConductorApiResult<ZomeCallResult>
Invoke a zome function on a Cell
Examples found in repository?
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
async fn call_zome(
&self,
cell_id: &CellId,
call: ZomeCall,
) -> ConductorApiResult<ZomeCallResult> {
if *cell_id == call.cell_id {
self.conductor_handle
.call_zome(call)
.await
.map_err(Into::into)
} else {
Err(ConductorApiError::ZomeCallCellMismatch {
api_cell_id: cell_id.clone(),
call_cell_id: call.cell_id,
})
}
}
async fn dpki_request(&self, _method: String, _args: String) -> ConductorApiResult<String> {
warn!("Using placeholder dpki");
Ok("TODO".to_string())
}
fn keystore(&self) -> &MetaLairClient {
self.conductor_handle.keystore()
}
fn signal_broadcaster(&self) -> SignalBroadcaster {
self.conductor_handle.signal_broadcaster()
}
fn get_dna(&self, dna_hash: &DnaHash) -> Option<DnaFile> {
self.conductor_handle.get_dna_file(dna_hash)
}
fn get_this_dna(&self) -> ConductorApiResult<DnaFile> {
self.conductor_handle
.get_dna_file(self.cell_id.dna_hash())
.ok_or_else(|| ConductorApiError::DnaMissing(self.cell_id.dna_hash().clone()))
}
fn get_this_ribosome(&self) -> ConductorApiResult<RealRibosome> {
Ok(self
.conductor_handle
.get_ribosome(self.cell_id.dna_hash())?)
}
fn get_zome(&self, dna_hash: &DnaHash, zome_name: &ZomeName) -> ConductorApiResult<Zome> {
Ok(self
.get_dna(dna_hash)
.ok_or_else(|| ConductorApiError::DnaMissing(dna_hash.clone()))?
.dna_def()
.get_zome(zome_name)?)
}
fn get_entry_def(&self, key: &EntryDefBufferKey) -> Option<EntryDef> {
self.conductor_handle.get_entry_def(key)
}
fn into_call_zome_handle(self) -> CellConductorReadHandle {
Arc::new(self)
}
async fn post_commit_permit(&self) -> Result<OwnedPermit<PostCommitArgs>, SendError<()>> {
self.conductor_handle.post_commit_permit().await
}
}
/// The "internal" Conductor API interface, for a Cell to talk to its calling Conductor.
#[async_trait]
#[mockall::automock]
pub trait CellConductorApiT: Send + Sync {
/// Get this cell id
fn cell_id(&self) -> &CellId;
/// Invoke a zome function on any cell in this conductor.
/// A zome call on a different Cell than this one corresponds to a bridged call.
async fn call_zome(
&self,
cell_id: &CellId,
call: ZomeCall,
) -> ConductorApiResult<ZomeCallResult>;
/// Make a request to the DPKI service running for this Conductor.
/// TODO: decide on actual signature
async fn dpki_request(&self, method: String, args: String) -> ConductorApiResult<String>;
/// Request access to this conductor's keystore
fn keystore(&self) -> &MetaLairClient;
/// Access the broadcast Sender which will send a Signal across every
/// attached app interface
fn signal_broadcaster(&self) -> SignalBroadcaster;
/// Get a [`Dna`](holochain_types::prelude::Dna) from the [`RibosomeStore`](crate::conductor::ribosome_store::RibosomeStore)
fn get_dna(&self, dna_hash: &DnaHash) -> Option<DnaFile>;
/// Get the [`Dna`](holochain_types::prelude::Dna) of this cell from the [`RibosomeStore`](crate::conductor::ribosome_store::RibosomeStore)
fn get_this_dna(&self) -> ConductorApiResult<DnaFile>;
/// Get the [`RealRibosome`] of this cell from the [`RibosomeStore`](crate::conductor::ribosome_store::RibosomeStore)
fn get_this_ribosome(&self) -> ConductorApiResult<RealRibosome>;
/// Get a [`Zome`](holochain_types::prelude::Zome) from this cell's Dna
fn get_zome(&self, dna_hash: &DnaHash, zome_name: &ZomeName) -> ConductorApiResult<Zome>;
/// Get a [`EntryDef`](holochain_zome_types::EntryDef) from the [`EntryDefBufferKey`](holochain_types::dna::EntryDefBufferKey)
fn get_entry_def(&self, key: &EntryDefBufferKey) -> Option<EntryDef>;
/// Turn this into a call zome handle
fn into_call_zome_handle(self) -> CellConductorReadHandle;
/// Get an OwnedPermit to the post commit task.
async fn post_commit_permit(&self) -> Result<OwnedPermit<PostCommitArgs>, SendError<()>>;
}
#[async_trait]
#[mockall::automock]
/// A minimal set of functionality needed from the conductor by
/// host functions.
pub trait CellConductorReadHandleT: Send + Sync {
/// Get this cell id
fn cell_id(&self) -> &CellId;
/// Invoke a zome function on a Cell
async fn call_zome(
&self,
call: ZomeCall,
workspace_lock: SourceChainWorkspace,
) -> ConductorApiResult<ZomeCallResult>;
/// Get a zome from this cell's Dna
fn get_zome(&self, dna_hash: &DnaHash, zome_name: &ZomeName) -> ConductorApiResult<Zome>;
/// Get a [`EntryDef`](holochain_zome_types::EntryDef) from the [`EntryDefBufferKey`](holochain_types::dna::EntryDefBufferKey)
fn get_entry_def(&self, key: &EntryDefBufferKey) -> Option<EntryDef>;
/// Try to put the nonce from a calling agent in the db. Fails with a stale result if a newer nonce exists.
async fn witness_nonce_from_calling_agent(
&self,
agent: AgentPubKey,
nonce: Nonce256Bits,
expires: Timestamp,
) -> ConductorApiResult<WitnessNonceResult>;
/// Find the first cell ID across all apps the given cell id is in that
/// is assigned to the given role.
async fn find_cell_with_role_alongside_cell(
&self,
cell_id: &CellId,
role_name: &RoleName,
) -> ConductorResult<Option<CellId>>;
}
#[async_trait]
impl CellConductorReadHandleT for CellConductorApi {
fn cell_id(&self) -> &CellId {
&self.cell_id
}
async fn call_zome(
&self,
call: ZomeCall,
workspace_lock: SourceChainWorkspace,
) -> ConductorApiResult<ZomeCallResult> {
if self.cell_id == call.cell_id {
self.conductor_handle
.call_zome_with_workspace(call, workspace_lock)
.await
} else {
self.conductor_handle.call_zome(call).await
}
}
More examples
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
pub async fn call_from_fallible<I, O, F>(
&self,
provenance: &AgentPubKey,
cap_secret: Option<CapSecret>,
zome: &SweetZome,
fn_name: F,
payload: I,
) -> ConductorApiResult<O>
where
FunctionName: From<F>,
I: Serialize + std::fmt::Debug,
O: serde::de::DeserializeOwned + std::fmt::Debug,
{
let payload = ExternIO::encode(payload).expect("Couldn't serialize payload");
let now = Timestamp::now();
let (nonce, expires_at) = fresh_nonce(now)?;
let call_unsigned = ZomeCallUnsigned {
cell_id: zome.cell_id().clone(),
zome_name: zome.name().clone(),
fn_name: fn_name.into(),
cap_secret,
provenance: provenance.clone(),
payload,
nonce,
expires_at,
};
let call = ZomeCall::try_from_unsigned_zome_call(self.keystore(), call_unsigned).await?;
let response = self.0.call_zome(call).await;
match response {
Ok(Ok(response)) => Ok(unwrap_to!(response => ZomeCallResponse::Ok)
.decode()
.expect("Couldn't deserialize zome call output")),
Ok(Err(error)) => Err(ConductorApiError::Other(Box::new(error))),
Err(error) => Err(error),
}
}
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
async fn handle_app_request_inner(
&self,
request: AppRequest,
) -> ConductorApiResult<AppResponse> {
match request {
AppRequest::AppInfo { installed_app_id } => Ok(AppResponse::AppInfo(
self.conductor_handle
.get_app_info(&installed_app_id)
.await?,
)),
AppRequest::CallZome(call) => {
match self.conductor_handle.call_zome(*call.clone()).await? {
Ok(ZomeCallResponse::Ok(output)) => Ok(AppResponse::ZomeCalled(Box::new(output))),
Ok(ZomeCallResponse::Unauthorized(zome_call_authorization, _, zome_name, fn_name, _)) => Ok(AppResponse::Error(
ExternalApiWireError::ZomeCallUnauthorized(format!(
"Call was not authorized with reason {:?}, cap secret {:?} to call the function {} in zome {}",
zome_call_authorization, call.cap_secret, fn_name, zome_name
)),
)),
Ok(ZomeCallResponse::NetworkError(e)) => unreachable!(
"Interface zome calls should never be routed to the network. This is a bug. Got {}",
e
),
Ok(ZomeCallResponse::CountersigningSession(e)) => Ok(AppResponse::Error(
ExternalApiWireError::CountersigningSessionError(format!(
"A countersigning session has failed to start on this zome call because: {}",
e
)),
)),
Err(e) => Ok(AppResponse::Error(e.into())),
}
}
AppRequest::CreateCloneCell(payload) => {
let installed_clone_cell = self
.conductor_handle
.clone()
.create_clone_cell(*payload)
.await?;
Ok(AppResponse::CloneCellCreated(installed_clone_cell))
}
AppRequest::DisableCloneCell(payload) => {
self.conductor_handle
.clone()
.disable_clone_cell(&*payload)
.await?;
Ok(AppResponse::CloneCellDisabled)
}
AppRequest::EnableCloneCell(payload) => {
let enabled_cell = self
.conductor_handle
.clone()
.enable_clone_cell(&*payload)
.await?;
Ok(AppResponse::CloneCellEnabled(enabled_cell))
}
AppRequest::NetworkInfo(payload) => {
let info = self.conductor_handle.network_info(&payload.dnas).await?;
Ok(AppResponse::NetworkInfo(info))
}
AppRequest::SignalSubscription(_) => Ok(AppResponse::Unimplemented(request)),
}
}
source§impl Conductor
impl Conductor
sourcepub async fn install_app_bundle(
self: Arc<Self>,
payload: InstallAppPayload
) -> ConductorResult<StoppedApp>
pub async fn install_app_bundle(
self: Arc<Self>,
payload: InstallAppPayload
) -> ConductorResult<StoppedApp>
Install DNAs and set up Cells as specified by an AppBundle
Examples found in repository?
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
sourcepub async fn uninstall_app(
self: Arc<Self>,
installed_app_id: &InstalledAppId
) -> ConductorResult<()>
pub async fn uninstall_app(
self: Arc<Self>,
installed_app_id: &InstalledAppId
) -> ConductorResult<()>
Uninstall an app
Examples found in repository?
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
sourcepub async fn list_running_apps(&self) -> ConductorResult<Vec<InstalledAppId>>
pub async fn list_running_apps(&self) -> ConductorResult<Vec<InstalledAppId>>
List active AppIds
sourcepub async fn list_apps(
&self,
status_filter: Option<AppStatusFilter>
) -> ConductorResult<Vec<AppInfo>>
pub async fn list_apps(
&self,
status_filter: Option<AppStatusFilter>
) -> ConductorResult<Vec<AppInfo>>
List Apps with their information
Examples found in repository?
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
sourcepub async fn list_running_apps_for_dependent_cell_id(
&self,
cell_id: &CellId
) -> ConductorResult<HashSet<InstalledAppId>>
pub async fn list_running_apps_for_dependent_cell_id(
&self,
cell_id: &CellId
) -> ConductorResult<HashSet<InstalledAppId>>
Get the IDs of all active installed Apps which use this Cell
Examples found in repository?
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
async fn run(
conductor: ConductorHandle,
mut new_task_channel: mpsc::Receiver<ManagedTaskAdd>,
) -> TaskManagerResult {
let mut task_manager = TaskManager::new();
// Need to have at least one item in the stream or it will exit early
if let Some(new_task) = new_task_channel.recv().await {
task_manager.stream.push(new_task);
} else {
error!("All senders to task manager were dropped before starting");
return Err(TaskManagerError::TaskManagerFailedToStart);
}
loop {
tokio::select! {
Some(new_task) = new_task_channel.recv() => {
task_manager.stream.push(new_task);
tracing::debug!("Task added. Total tasks: {}", task_manager.stream.len());
}
result = task_manager.stream.next() => {
tracing::debug!("Task completed. Total tasks: {}", task_manager.stream.len());
match result {
Some(TaskOutcome::NewTask(new_task)) => task_manager.stream.push(new_task),
Some(TaskOutcome::LogInfo(context)) => {
debug!("Managed task completed: {}", context)
}
Some(TaskOutcome::MinorError(error, context)) => {
error!("Minor error during managed task: {:?}\nContext: {}", error, context)
}
Some(TaskOutcome::ShutdownConductor(error, context)) => {
let error = match *error {
ManagedTaskError::Join(error) => {
match error.try_into_panic() {
Ok(reason) => {
// Resume the panic on the main task
std::panic::resume_unwind(reason);
}
Err(error) => ManagedTaskError::Join(error),
}
}
error => error,
};
error!("Shutting down conductor due to unrecoverable error: {:?}\nContext: {}", error, context);
return Err(TaskManagerError::Unrecoverable(Box::new(error)));
},
Some(TaskOutcome::StopApps(cell_id, error, context)) => {
tracing::error!("About to automatically stop apps");
let app_ids = conductor.list_running_apps_for_dependent_cell_id(&cell_id).await.map_err(TaskManagerError::internal)?;
if error.is_recoverable() {
conductor.remove_cells(&[cell_id]).await;
// The following message assumes that only the app_ids calculated will be paused, but other apps
// may have been paused as well.
tracing::error!(
"PAUSING the following apps due to a recoverable error: {:?}\nError: {:?}\nContext: {}",
app_ids,
error,
context
);
// MAYBE: it could be helpful to modify this function so that when providing Some(app_ids),
// you can also pass in a PausedAppReason override, so that the reason for the apps being paused
// can be set to the specific error message encountered here, rather than having to read it from
// the logs.
let delta = conductor.reconcile_app_status_with_cell_status(None).await.map_err(TaskManagerError::internal)?;
tracing::debug!(delta = ?delta);
tracing::error!("Apps paused.");
} else {
// Since the error is unrecoverable, we don't expect to be able to use this Cell anymore.
// Therefore, we disable every app which requires that cell.
tracing::error!(
"DISABLING the following apps due to an unrecoverable error: {:?}\nError: {:?}\nContext: {}",
app_ids,
error,
context
);
for app_id in app_ids.iter() {
conductor.clone().disable_app(app_id.to_string(), DisabledAppReason::Error(error.to_string())).await.map_err(TaskManagerError::internal)?;
}
tracing::error!("Apps disabled.");
}
},
Some(TaskOutcome::StopAppsWithDna(dna_hash, error, context)) => {
tracing::error!("About to automatically stop apps with dna {}", dna_hash);
let app_ids = conductor.list_running_apps_for_dependent_dna_hash(dna_hash.as_ref()).await.map_err(TaskManagerError::internal)?;
if error.is_recoverable() {
let cells_with_same_dna: Vec<_> = conductor.list_cell_ids(None).into_iter().filter(|id| id.dna_hash() == dna_hash.as_ref()).collect();
conductor.remove_cells(&cells_with_same_dna).await;
// The following message assumes that only the app_ids calculated will be paused, but other apps
// may have been paused as well.
tracing::error!(
"PAUSING the following apps due to a recoverable error: {:?}\nError: {:?}\nContext: {}",
app_ids,
error,
context
);
// MAYBE: it could be helpful to modify this function so that when providing Some(app_ids),
// you can also pass in a PausedAppReason override, so that the reason for the apps being paused
// can be set to the specific error message encountered here, rather than having to read it from
// the logs.
let delta = conductor.reconcile_app_status_with_cell_status(None).await.map_err(TaskManagerError::internal)?;
tracing::debug!(delta = ?delta);
tracing::error!("Apps paused.");
} else {
// Since the error is unrecoverable, we don't expect to be able to use this Cell anymore.
// Therefore, we disable every app which requires that cell.
tracing::error!(
"DISABLING the following apps due to an unrecoverable error: {:?}\nError: {:?}\nContext: {}",
app_ids,
error,
context
);
for app_id in app_ids.iter() {
conductor.clone().disable_app(app_id.to_string(), DisabledAppReason::Error(error.to_string())).await.map_err(TaskManagerError::internal)?;
}
tracing::error!("Apps disabled.");
}
},
None => return Ok(()),
}}
};
}
}
sourcepub async fn find_cell_with_role_alongside_cell(
&self,
cell_id: &CellId,
role_name: &RoleName
) -> ConductorResult<Option<CellId>>
pub async fn find_cell_with_role_alongside_cell(
&self,
cell_id: &CellId,
role_name: &RoleName
) -> ConductorResult<Option<CellId>>
Find the ID of the first active installed App which uses this Cell
sourcepub async fn list_running_apps_for_dependent_dna_hash(
&self,
dna_hash: &DnaHash
) -> ConductorResult<HashSet<InstalledAppId>>
pub async fn list_running_apps_for_dependent_dna_hash(
&self,
dna_hash: &DnaHash
) -> ConductorResult<HashSet<InstalledAppId>>
Get the IDs of all active installed Apps which use this Dna
Examples found in repository?
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
async fn run(
conductor: ConductorHandle,
mut new_task_channel: mpsc::Receiver<ManagedTaskAdd>,
) -> TaskManagerResult {
let mut task_manager = TaskManager::new();
// Need to have at least one item in the stream or it will exit early
if let Some(new_task) = new_task_channel.recv().await {
task_manager.stream.push(new_task);
} else {
error!("All senders to task manager were dropped before starting");
return Err(TaskManagerError::TaskManagerFailedToStart);
}
loop {
tokio::select! {
Some(new_task) = new_task_channel.recv() => {
task_manager.stream.push(new_task);
tracing::debug!("Task added. Total tasks: {}", task_manager.stream.len());
}
result = task_manager.stream.next() => {
tracing::debug!("Task completed. Total tasks: {}", task_manager.stream.len());
match result {
Some(TaskOutcome::NewTask(new_task)) => task_manager.stream.push(new_task),
Some(TaskOutcome::LogInfo(context)) => {
debug!("Managed task completed: {}", context)
}
Some(TaskOutcome::MinorError(error, context)) => {
error!("Minor error during managed task: {:?}\nContext: {}", error, context)
}
Some(TaskOutcome::ShutdownConductor(error, context)) => {
let error = match *error {
ManagedTaskError::Join(error) => {
match error.try_into_panic() {
Ok(reason) => {
// Resume the panic on the main task
std::panic::resume_unwind(reason);
}
Err(error) => ManagedTaskError::Join(error),
}
}
error => error,
};
error!("Shutting down conductor due to unrecoverable error: {:?}\nContext: {}", error, context);
return Err(TaskManagerError::Unrecoverable(Box::new(error)));
},
Some(TaskOutcome::StopApps(cell_id, error, context)) => {
tracing::error!("About to automatically stop apps");
let app_ids = conductor.list_running_apps_for_dependent_cell_id(&cell_id).await.map_err(TaskManagerError::internal)?;
if error.is_recoverable() {
conductor.remove_cells(&[cell_id]).await;
// The following message assumes that only the app_ids calculated will be paused, but other apps
// may have been paused as well.
tracing::error!(
"PAUSING the following apps due to a recoverable error: {:?}\nError: {:?}\nContext: {}",
app_ids,
error,
context
);
// MAYBE: it could be helpful to modify this function so that when providing Some(app_ids),
// you can also pass in a PausedAppReason override, so that the reason for the apps being paused
// can be set to the specific error message encountered here, rather than having to read it from
// the logs.
let delta = conductor.reconcile_app_status_with_cell_status(None).await.map_err(TaskManagerError::internal)?;
tracing::debug!(delta = ?delta);
tracing::error!("Apps paused.");
} else {
// Since the error is unrecoverable, we don't expect to be able to use this Cell anymore.
// Therefore, we disable every app which requires that cell.
tracing::error!(
"DISABLING the following apps due to an unrecoverable error: {:?}\nError: {:?}\nContext: {}",
app_ids,
error,
context
);
for app_id in app_ids.iter() {
conductor.clone().disable_app(app_id.to_string(), DisabledAppReason::Error(error.to_string())).await.map_err(TaskManagerError::internal)?;
}
tracing::error!("Apps disabled.");
}
},
Some(TaskOutcome::StopAppsWithDna(dna_hash, error, context)) => {
tracing::error!("About to automatically stop apps with dna {}", dna_hash);
let app_ids = conductor.list_running_apps_for_dependent_dna_hash(dna_hash.as_ref()).await.map_err(TaskManagerError::internal)?;
if error.is_recoverable() {
let cells_with_same_dna: Vec<_> = conductor.list_cell_ids(None).into_iter().filter(|id| id.dna_hash() == dna_hash.as_ref()).collect();
conductor.remove_cells(&cells_with_same_dna).await;
// The following message assumes that only the app_ids calculated will be paused, but other apps
// may have been paused as well.
tracing::error!(
"PAUSING the following apps due to a recoverable error: {:?}\nError: {:?}\nContext: {}",
app_ids,
error,
context
);
// MAYBE: it could be helpful to modify this function so that when providing Some(app_ids),
// you can also pass in a PausedAppReason override, so that the reason for the apps being paused
// can be set to the specific error message encountered here, rather than having to read it from
// the logs.
let delta = conductor.reconcile_app_status_with_cell_status(None).await.map_err(TaskManagerError::internal)?;
tracing::debug!(delta = ?delta);
tracing::error!("Apps paused.");
} else {
// Since the error is unrecoverable, we don't expect to be able to use this Cell anymore.
// Therefore, we disable every app which requires that cell.
tracing::error!(
"DISABLING the following apps due to an unrecoverable error: {:?}\nError: {:?}\nContext: {}",
app_ids,
error,
context
);
for app_id in app_ids.iter() {
conductor.clone().disable_app(app_id.to_string(), DisabledAppReason::Error(error.to_string())).await.map_err(TaskManagerError::internal)?;
}
tracing::error!("Apps disabled.");
}
},
None => return Ok(()),
}}
};
}
}
sourcepub async fn get_app_info(
&self,
installed_app_id: &InstalledAppId
) -> ConductorResult<Option<AppInfo>>
pub async fn get_app_info(
&self,
installed_app_id: &InstalledAppId
) -> ConductorResult<Option<AppInfo>>
Get info about an installed App, regardless of status
Examples found in repository?
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
async fn handle_app_request_inner(
&self,
request: AppRequest,
) -> ConductorApiResult<AppResponse> {
match request {
AppRequest::AppInfo { installed_app_id } => Ok(AppResponse::AppInfo(
self.conductor_handle
.get_app_info(&installed_app_id)
.await?,
)),
AppRequest::CallZome(call) => {
match self.conductor_handle.call_zome(*call.clone()).await? {
Ok(ZomeCallResponse::Ok(output)) => Ok(AppResponse::ZomeCalled(Box::new(output))),
Ok(ZomeCallResponse::Unauthorized(zome_call_authorization, _, zome_name, fn_name, _)) => Ok(AppResponse::Error(
ExternalApiWireError::ZomeCallUnauthorized(format!(
"Call was not authorized with reason {:?}, cap secret {:?} to call the function {} in zome {}",
zome_call_authorization, call.cap_secret, fn_name, zome_name
)),
)),
Ok(ZomeCallResponse::NetworkError(e)) => unreachable!(
"Interface zome calls should never be routed to the network. This is a bug. Got {}",
e
),
Ok(ZomeCallResponse::CountersigningSession(e)) => Ok(AppResponse::Error(
ExternalApiWireError::CountersigningSessionError(format!(
"A countersigning session has failed to start on this zome call because: {}",
e
)),
)),
Err(e) => Ok(AppResponse::Error(e.into())),
}
}
AppRequest::CreateCloneCell(payload) => {
let installed_clone_cell = self
.conductor_handle
.clone()
.create_clone_cell(*payload)
.await?;
Ok(AppResponse::CloneCellCreated(installed_clone_cell))
}
AppRequest::DisableCloneCell(payload) => {
self.conductor_handle
.clone()
.disable_clone_cell(&*payload)
.await?;
Ok(AppResponse::CloneCellDisabled)
}
AppRequest::EnableCloneCell(payload) => {
let enabled_cell = self
.conductor_handle
.clone()
.enable_clone_cell(&*payload)
.await?;
Ok(AppResponse::CloneCellEnabled(enabled_cell))
}
AppRequest::NetworkInfo(payload) => {
let info = self.conductor_handle.network_info(&payload.dnas).await?;
Ok(AppResponse::NetworkInfo(info))
}
AppRequest::SignalSubscription(_) => Ok(AppResponse::Unimplemented(request)),
}
}
More examples
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
source§impl Conductor
impl Conductor
sourcepub fn running_cell_ids(&self) -> HashSet<CellId>
pub fn running_cell_ids(&self) -> HashSet<CellId>
Iterator over only the cells which are fully running. Generally used to handle conductor interface requests
Examples found in repository?
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
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;
}
sourcepub fn list_cell_ids(&self, filter: Option<CellStatusFilter>) -> Vec<CellId> ⓘ
pub fn list_cell_ids(&self, filter: Option<CellStatusFilter>) -> Vec<CellId> ⓘ
List CellIds for Cells which match a status filter
Examples found in repository?
More examples
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
pub async fn force_all_publish_dht_ops(&self) {
use futures::stream::StreamExt;
if let Some(handle) = self.handle.as_ref() {
let iter = handle.list_cell_ids(None).into_iter().map(|id| async {
let id = id;
let db = self.get_authored_db(id.dna_hash()).unwrap();
let trigger = self.get_cell_triggers(&id).unwrap();
(db, trigger)
});
futures::stream::iter(iter)
.then(|f| f)
.for_each(|(db, mut triggers)| async move {
// The line below was added when migrating to rust edition 2021, per
// https://doc.rust-lang.org/edition-guide/rust-2021/disjoint-capture-in-closures.html#migration
let _ = &triggers;
crate::test_utils::force_publish_dht_ops(&db, &mut triggers.publish_dht_ops)
.await
.unwrap();
})
.await;
}
}
40 41 42 43 44 45 46 47 48 49 50 51 52 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
pub async fn local_machine_session(conductors: &[ConductorHandle], timeout: Duration) {
// For each space get all the cells, their db and the p2p envs.
let mut spaces = HashMap::new();
for (i, c) in conductors.iter().enumerate() {
for cell_id in c.list_cell_ids(None) {
let space = spaces
.entry(cell_id.dna_hash().clone())
.or_insert_with(|| vec![None; conductors.len()]);
if space[i].is_none() {
let p2p_agents_db: DbRead<DbKindP2pAgents> =
c.get_p2p_db(cell_id.dna_hash()).into();
space[i] = Some((p2p_agents_db, Vec::new()));
}
space[i].as_mut().unwrap().1.push((
c.get_authored_db(cell_id.dna_hash()).unwrap().into(),
c.get_dht_db(cell_id.dna_hash()).unwrap().into(),
cell_id.agent_pubkey().to_kitsune(),
));
}
}
// Run a consistency session for each space.
for (_, conductors) in spaces {
// The agents we need to wait for.
let mut wait_for_agents = HashSet::new();
// Maps to environments.
let mut agent_dht_map = HashMap::new();
let mut agent_p2p_map = HashMap::new();
// All the agents that should be held.
let mut all_agents = Vec::new();
// All the op hashes that should be held.
let mut all_hashes = Vec::new();
let (tx, rx) = tokio::sync::mpsc::channel(1000);
// Gather the expected agents and op hashes from each conductor.
for (p2p_agents_db, agents) in conductors.into_iter().flatten() {
wait_for_agents.extend(agents.iter().map(|(_, _, agent)| agent.clone()));
agent_dht_map.extend(agents.iter().cloned().map(|(_, dht, agent)| (agent, dht)));
agent_p2p_map.extend(
agents
.iter()
.cloned()
.map(|(_, _, a)| (a, p2p_agents_db.clone())),
);
let (a, h) = gather_conductor_data(p2p_agents_db, agents).await;
all_agents.extend(a);
all_hashes.extend(h);
}
// Spawn a background task that will run each
// cells self consistency check against the data that
// they are expected to hold.
tokio::spawn(expect_all(
tx,
timeout,
all_agents,
all_hashes,
agent_dht_map,
agent_p2p_map,
));
// Wait up to the timeout for all the agents to report success.
wait_for_consistency(rx, wait_for_agents, timeout).await;
}
}
/// Get consistency for a particular hash.
pub async fn local_machine_session_with_hashes(
handles: Vec<&ConductorHandle>,
hashes: impl Iterator<Item = (DhtLocation, DhtOpHash)>,
space: &DnaHash,
timeout: Duration,
) {
// Grab the environments and cells for each conductor in this space.
let mut conductors = vec![None; handles.len()];
for (i, c) in handles.iter().enumerate() {
for cell_id in c.list_cell_ids(None) {
if cell_id.dna_hash() != space {
continue;
}
if conductors[i].is_none() {
let p2p_agents_db: DbRead<DbKindP2pAgents> =
c.get_p2p_db(cell_id.dna_hash()).into();
conductors[i] = Some((p2p_agents_db, Vec::new()));
}
conductors[i].as_mut().unwrap().1.push((
c.get_dht_db(cell_id.dna_hash()).unwrap().into(),
cell_id.agent_pubkey().to_kitsune(),
));
}
}
// Convert the hashes to kitsune.
let all_hashes = hashes
.into_iter()
.map(|(l, h)| (l, h.into_kitsune_raw()))
.collect::<Vec<_>>();
// The agents we need to wait for.
let mut wait_for_agents = HashSet::new();
// Maps to environments.
let mut agent_dht_map = HashMap::new();
let mut agent_p2p_map = HashMap::new();
// All the agents that should be held.
let mut all_agents = Vec::new();
let (tx, rx) = tokio::sync::mpsc::channel(1000);
// Gather the expected agents from each conductor.
for (p2p_agents_db, agents) in conductors.into_iter().flatten() {
wait_for_agents.extend(agents.iter().map(|(_, agent)| agent.clone()));
agent_dht_map.extend(agents.iter().cloned().map(|(e, a)| (a, e)));
agent_p2p_map.extend(
agents
.iter()
.cloned()
.map(|(_, a)| (a, p2p_agents_db.clone())),
);
for (_, agent) in &agents {
if let Some(storage_arc) = request_arc(&p2p_agents_db, (**agent).clone())
.await
.unwrap()
{
all_agents.push((agent.clone(), storage_arc));
}
}
}
// Spawn a background task that will run each
// cells self consistency check against the data that
// they are expected to hold.
tokio::spawn(expect_all(
tx,
timeout,
all_agents,
all_hashes,
agent_dht_map,
agent_p2p_map,
));
// Wait up to the timeout for all the agents to report success.
wait_for_consistency(rx, wait_for_agents, timeout).await;
}
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 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
pub(crate) async fn graft_records_onto_source_chain(
handle: ConductorHandle,
cell_id: CellId,
validate: bool,
records: Vec<Record>,
) -> ConductorApiResult<()> {
// Get or create the space for this cell.
// Note: This doesn't require the cell be installed.
let space = handle.get_or_create_space(cell_id.dna_hash())?;
let chc = None;
let network = handle
.holochain_p2p()
.to_dna(cell_id.dna_hash().clone(), chc);
let source_chain: SourceChain = space
.source_chain(handle.keystore().clone(), cell_id.agent_pubkey().clone())
.await?;
let existing = source_chain
.query(ChainQueryFilter::new().descending())
.await?
.into_iter()
.map(|r| r.signed_action)
.collect::<Vec<SignedActionHashed>>();
let graft = ChainGraft::new(existing, records).rebalance();
let chain_top = graft.existing_chain_top();
if validate {
validate_records(handle.clone(), &cell_id, &chain_top, graft.incoming()).await?;
}
// Produce the op lights for each record.
let data = graft
.incoming
.into_iter()
.map(|el| {
let ops = produce_op_lights_from_records(vec![&el])?;
// Check have the same author as cell.
let (sah, entry) = el.into_inner();
if sah.action().author() != cell_id.agent_pubkey() {
return Err(StateMutationError::AuthorsMustMatch);
}
Ok((sah, ops, entry.into_option()))
})
.collect::<StateMutationResult<Vec<_>>>()?;
// Commit the records to the source chain.
let ops_to_integrate = space
.authored_db
.async_commit({
let cell_id = cell_id.clone();
move |txn| {
if let Some((_, seq)) = chain_top {
// Remove records above the grafting position.
//
// NOTES:
// - the chain top may have moved since the grafting call began,
// but it doesn't really matter, since we explicitly want to
// clobber anything beyond the grafting point anyway.
// - if there is an existing fork, there may still be a fork after the
// grafting. A more rigorous approach would thin out the existing
// actions until a single fork is obtained.
txn.execute(
holochain_sqlite::sql::sql_cell::DELETE_ACTIONS_AFTER_SEQ,
rusqlite::named_params! {
":author": cell_id.agent_pubkey(),
":seq": seq
},
)
.map_err(StateMutationError::from)?;
}
let mut ops_to_integrate = Vec::new();
// Commit the records and ops to the authored db.
for (sah, ops, entry) in data {
// Clippy is wrong :(
#[allow(clippy::needless_collect)]
let basis = ops
.iter()
.map(|op| op.dht_basis().clone())
.collect::<Vec<_>>();
ops_to_integrate.extend(
source_chain::put_raw(txn, sah, ops, entry)?
.into_iter()
.zip(basis.into_iter()),
);
}
SourceChainResult::Ok(ops_to_integrate)
}
})
.await?;
// Check which ops need to be integrated.
// Only integrated if a cell is installed.
if handle
.list_cell_ids(Some(CellStatus::Joined))
.contains(&cell_id)
{
holochain_state::integrate::authored_ops_to_dht_db(
&network,
ops_to_integrate,
&space.authored_db,
&space.dht_db,
&space.dht_query_cache,
)
.await?;
}
Ok(())
}
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
async fn run(
conductor: ConductorHandle,
mut new_task_channel: mpsc::Receiver<ManagedTaskAdd>,
) -> TaskManagerResult {
let mut task_manager = TaskManager::new();
// Need to have at least one item in the stream or it will exit early
if let Some(new_task) = new_task_channel.recv().await {
task_manager.stream.push(new_task);
} else {
error!("All senders to task manager were dropped before starting");
return Err(TaskManagerError::TaskManagerFailedToStart);
}
loop {
tokio::select! {
Some(new_task) = new_task_channel.recv() => {
task_manager.stream.push(new_task);
tracing::debug!("Task added. Total tasks: {}", task_manager.stream.len());
}
result = task_manager.stream.next() => {
tracing::debug!("Task completed. Total tasks: {}", task_manager.stream.len());
match result {
Some(TaskOutcome::NewTask(new_task)) => task_manager.stream.push(new_task),
Some(TaskOutcome::LogInfo(context)) => {
debug!("Managed task completed: {}", context)
}
Some(TaskOutcome::MinorError(error, context)) => {
error!("Minor error during managed task: {:?}\nContext: {}", error, context)
}
Some(TaskOutcome::ShutdownConductor(error, context)) => {
let error = match *error {
ManagedTaskError::Join(error) => {
match error.try_into_panic() {
Ok(reason) => {
// Resume the panic on the main task
std::panic::resume_unwind(reason);
}
Err(error) => ManagedTaskError::Join(error),
}
}
error => error,
};
error!("Shutting down conductor due to unrecoverable error: {:?}\nContext: {}", error, context);
return Err(TaskManagerError::Unrecoverable(Box::new(error)));
},
Some(TaskOutcome::StopApps(cell_id, error, context)) => {
tracing::error!("About to automatically stop apps");
let app_ids = conductor.list_running_apps_for_dependent_cell_id(&cell_id).await.map_err(TaskManagerError::internal)?;
if error.is_recoverable() {
conductor.remove_cells(&[cell_id]).await;
// The following message assumes that only the app_ids calculated will be paused, but other apps
// may have been paused as well.
tracing::error!(
"PAUSING the following apps due to a recoverable error: {:?}\nError: {:?}\nContext: {}",
app_ids,
error,
context
);
// MAYBE: it could be helpful to modify this function so that when providing Some(app_ids),
// you can also pass in a PausedAppReason override, so that the reason for the apps being paused
// can be set to the specific error message encountered here, rather than having to read it from
// the logs.
let delta = conductor.reconcile_app_status_with_cell_status(None).await.map_err(TaskManagerError::internal)?;
tracing::debug!(delta = ?delta);
tracing::error!("Apps paused.");
} else {
// Since the error is unrecoverable, we don't expect to be able to use this Cell anymore.
// Therefore, we disable every app which requires that cell.
tracing::error!(
"DISABLING the following apps due to an unrecoverable error: {:?}\nError: {:?}\nContext: {}",
app_ids,
error,
context
);
for app_id in app_ids.iter() {
conductor.clone().disable_app(app_id.to_string(), DisabledAppReason::Error(error.to_string())).await.map_err(TaskManagerError::internal)?;
}
tracing::error!("Apps disabled.");
}
},
Some(TaskOutcome::StopAppsWithDna(dna_hash, error, context)) => {
tracing::error!("About to automatically stop apps with dna {}", dna_hash);
let app_ids = conductor.list_running_apps_for_dependent_dna_hash(dna_hash.as_ref()).await.map_err(TaskManagerError::internal)?;
if error.is_recoverable() {
let cells_with_same_dna: Vec<_> = conductor.list_cell_ids(None).into_iter().filter(|id| id.dna_hash() == dna_hash.as_ref()).collect();
conductor.remove_cells(&cells_with_same_dna).await;
// The following message assumes that only the app_ids calculated will be paused, but other apps
// may have been paused as well.
tracing::error!(
"PAUSING the following apps due to a recoverable error: {:?}\nError: {:?}\nContext: {}",
app_ids,
error,
context
);
// MAYBE: it could be helpful to modify this function so that when providing Some(app_ids),
// you can also pass in a PausedAppReason override, so that the reason for the apps being paused
// can be set to the specific error message encountered here, rather than having to read it from
// the logs.
let delta = conductor.reconcile_app_status_with_cell_status(None).await.map_err(TaskManagerError::internal)?;
tracing::debug!(delta = ?delta);
tracing::error!("Apps paused.");
} else {
// Since the error is unrecoverable, we don't expect to be able to use this Cell anymore.
// Therefore, we disable every app which requires that cell.
tracing::error!(
"DISABLING the following apps due to an unrecoverable error: {:?}\nError: {:?}\nContext: {}",
app_ids,
error,
context
);
for app_id in app_ids.iter() {
conductor.clone().disable_app(app_id.to_string(), DisabledAppReason::Error(error.to_string())).await.map_err(TaskManagerError::internal)?;
}
tracing::error!("Apps disabled.");
}
},
None => return Ok(()),
}}
};
}
}
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
source§impl Conductor
impl Conductor
sourcepub async fn create_clone_cell(
self: Arc<Self>,
payload: CreateCloneCellPayload
) -> ConductorResult<InstalledCell>
pub async fn create_clone_cell(
self: Arc<Self>,
payload: CreateCloneCellPayload
) -> ConductorResult<InstalledCell>
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.
Examples found in repository?
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
async fn handle_app_request_inner(
&self,
request: AppRequest,
) -> ConductorApiResult<AppResponse> {
match request {
AppRequest::AppInfo { installed_app_id } => Ok(AppResponse::AppInfo(
self.conductor_handle
.get_app_info(&installed_app_id)
.await?,
)),
AppRequest::CallZome(call) => {
match self.conductor_handle.call_zome(*call.clone()).await? {
Ok(ZomeCallResponse::Ok(output)) => Ok(AppResponse::ZomeCalled(Box::new(output))),
Ok(ZomeCallResponse::Unauthorized(zome_call_authorization, _, zome_name, fn_name, _)) => Ok(AppResponse::Error(
ExternalApiWireError::ZomeCallUnauthorized(format!(
"Call was not authorized with reason {:?}, cap secret {:?} to call the function {} in zome {}",
zome_call_authorization, call.cap_secret, fn_name, zome_name
)),
)),
Ok(ZomeCallResponse::NetworkError(e)) => unreachable!(
"Interface zome calls should never be routed to the network. This is a bug. Got {}",
e
),
Ok(ZomeCallResponse::CountersigningSession(e)) => Ok(AppResponse::Error(
ExternalApiWireError::CountersigningSessionError(format!(
"A countersigning session has failed to start on this zome call because: {}",
e
)),
)),
Err(e) => Ok(AppResponse::Error(e.into())),
}
}
AppRequest::CreateCloneCell(payload) => {
let installed_clone_cell = self
.conductor_handle
.clone()
.create_clone_cell(*payload)
.await?;
Ok(AppResponse::CloneCellCreated(installed_clone_cell))
}
AppRequest::DisableCloneCell(payload) => {
self.conductor_handle
.clone()
.disable_clone_cell(&*payload)
.await?;
Ok(AppResponse::CloneCellDisabled)
}
AppRequest::EnableCloneCell(payload) => {
let enabled_cell = self
.conductor_handle
.clone()
.enable_clone_cell(&*payload)
.await?;
Ok(AppResponse::CloneCellEnabled(enabled_cell))
}
AppRequest::NetworkInfo(payload) => {
let info = self.conductor_handle.network_info(&payload.dnas).await?;
Ok(AppResponse::NetworkInfo(info))
}
AppRequest::SignalSubscription(_) => Ok(AppResponse::Unimplemented(request)),
}
}
sourcepub async fn enable_clone_cell(
self: Arc<Self>,
payload: &EnableCloneCellPayload
) -> ConductorResult<InstalledCell>
pub async fn enable_clone_cell(
self: Arc<Self>,
payload: &EnableCloneCellPayload
) -> ConductorResult<InstalledCell>
Enable a disabled clone cell.
Examples found in repository?
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
async fn handle_app_request_inner(
&self,
request: AppRequest,
) -> ConductorApiResult<AppResponse> {
match request {
AppRequest::AppInfo { installed_app_id } => Ok(AppResponse::AppInfo(
self.conductor_handle
.get_app_info(&installed_app_id)
.await?,
)),
AppRequest::CallZome(call) => {
match self.conductor_handle.call_zome(*call.clone()).await? {
Ok(ZomeCallResponse::Ok(output)) => Ok(AppResponse::ZomeCalled(Box::new(output))),
Ok(ZomeCallResponse::Unauthorized(zome_call_authorization, _, zome_name, fn_name, _)) => Ok(AppResponse::Error(
ExternalApiWireError::ZomeCallUnauthorized(format!(
"Call was not authorized with reason {:?}, cap secret {:?} to call the function {} in zome {}",
zome_call_authorization, call.cap_secret, fn_name, zome_name
)),
)),
Ok(ZomeCallResponse::NetworkError(e)) => unreachable!(
"Interface zome calls should never be routed to the network. This is a bug. Got {}",
e
),
Ok(ZomeCallResponse::CountersigningSession(e)) => Ok(AppResponse::Error(
ExternalApiWireError::CountersigningSessionError(format!(
"A countersigning session has failed to start on this zome call because: {}",
e
)),
)),
Err(e) => Ok(AppResponse::Error(e.into())),
}
}
AppRequest::CreateCloneCell(payload) => {
let installed_clone_cell = self
.conductor_handle
.clone()
.create_clone_cell(*payload)
.await?;
Ok(AppResponse::CloneCellCreated(installed_clone_cell))
}
AppRequest::DisableCloneCell(payload) => {
self.conductor_handle
.clone()
.disable_clone_cell(&*payload)
.await?;
Ok(AppResponse::CloneCellDisabled)
}
AppRequest::EnableCloneCell(payload) => {
let enabled_cell = self
.conductor_handle
.clone()
.enable_clone_cell(&*payload)
.await?;
Ok(AppResponse::CloneCellEnabled(enabled_cell))
}
AppRequest::NetworkInfo(payload) => {
let info = self.conductor_handle.network_info(&payload.dnas).await?;
Ok(AppResponse::NetworkInfo(info))
}
AppRequest::SignalSubscription(_) => Ok(AppResponse::Unimplemented(request)),
}
}
source§impl Conductor
impl Conductor
sourcepub async fn reconcile_cell_status_with_app_status(
self: Arc<Self>
) -> ConductorResult<CellStartupErrors>
pub async fn reconcile_cell_status_with_app_status(
self: Arc<Self>
) -> ConductorResult<CellStartupErrors>
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.
Examples found in repository?
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 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
pub async fn install_app(
name: &str,
cell_data: Vec<(InstalledCell, Option<MembraneProof>)>,
dnas: Vec<DnaFile>,
conductor_handle: ConductorHandle,
) {
for dna in dnas {
conductor_handle.register_dna(dna).await.unwrap();
}
conductor_handle
.clone()
.install_app(name.to_string(), cell_data)
.await
.unwrap();
conductor_handle
.clone()
.enable_app(name.to_string())
.await
.unwrap();
let errors = conductor_handle
.reconcile_cell_status_with_app_status()
.await
.unwrap();
assert!(errors.is_empty(), "{:?}", errors);
}
/// Payload for installing cells
pub type InstalledCellsWithProofs = Vec<(InstalledCell, Option<MembraneProof>)>;
/// One of various ways to setup an app, used somewhere...
pub async fn setup_app(
dnas: Vec<DnaFile>,
cell_data: Vec<(InstalledCell, Option<MembraneProof>)>,
) -> (Arc<TempDir>, RealAppInterfaceApi, ConductorHandle) {
let db_dir = test_db_dir();
let conductor_handle = ConductorBuilder::new()
.test(db_dir.path(), &[])
.await
.unwrap();
for dna in dnas {
conductor_handle.register_dna(dna).await.unwrap();
}
conductor_handle
.clone()
.install_app("test app".to_string(), cell_data)
.await
.unwrap();
conductor_handle
.clone()
.enable_app("test app".to_string())
.await
.unwrap();
let errors = conductor_handle
.clone()
.reconcile_cell_status_with_app_status()
.await
.unwrap();
assert!(errors.is_empty());
let handle = conductor_handle.clone();
(
Arc::new(db_dir),
RealAppInterfaceApi::new(conductor_handle),
handle,
)
}
More examples
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 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
pub async fn setup_app_for_agent<'a, R, D>(
&mut self,
installed_app_id: &str,
agent: AgentPubKey,
roles: D,
) -> ConductorApiResult<SweetApp>
where
R: Into<DnaWithRole> + Clone + 'a,
D: IntoIterator<Item = &'a R>,
{
let roles: Vec<DnaWithRole> = roles.into_iter().cloned().map(Into::into).collect();
let dnas = roles.iter().map(|r| &r.dna).collect::<Vec<_>>();
self.setup_app_1_register_dna(&dnas).await?;
self.setup_app_2_install_and_enable(installed_app_id, agent.clone(), roles.as_slice())
.await?;
self.raw_handle()
.reconcile_cell_status_with_app_status()
.await?;
let dna_hashes = roles.iter().map(|r| r.dna.dna_hash().clone());
self.setup_app_3_create_sweet_app(installed_app_id, agent, dna_hashes)
.await
}
/// Opinionated app setup.
/// Creates an app using the given DnaFiles, with no extra configuration.
/// An AgentPubKey will be generated, and is accessible via the returned SweetApp.
pub async fn setup_app<'a, R, D>(
&mut self,
installed_app_id: &str,
dnas: D,
) -> ConductorApiResult<SweetApp>
where
R: Into<DnaWithRole> + Clone + 'a,
D: IntoIterator<Item = &'a R> + Clone,
{
let agent = SweetAgents::one(self.keystore()).await;
self.setup_app_for_agent(installed_app_id, agent, dnas.clone())
.await
}
/// Opinionated app setup. Creates one app per agent, using the given DnaFiles.
///
/// All InstalledAppIds and RoleNames are auto-generated. In tests driven directly
/// by Rust, you typically won't care what these values are set to, but in case you
/// do, they are set as so:
/// - InstalledAppId: {app_id_prefix}-{agent_pub_key}
/// - RoleName: {dna_hash}
///
/// Returns a batch of SweetApps, sorted in the same order as Agents passed in.
pub async fn setup_app_for_agents<'a, A, R, D>(
&mut self,
app_id_prefix: &str,
agents: A,
roles: D,
) -> ConductorApiResult<SweetAppBatch>
where
A: IntoIterator<Item = &'a AgentPubKey>,
R: Into<DnaWithRole> + Clone + 'a,
D: IntoIterator<Item = &'a R>,
{
let agents: Vec<_> = agents.into_iter().collect();
let roles: Vec<DnaWithRole> = roles.into_iter().cloned().map(Into::into).collect();
let dnas: Vec<&DnaFile> = roles.iter().map(|r| &r.dna).collect();
self.setup_app_1_register_dna(dnas.as_slice()).await?;
for &agent in agents.iter() {
let installed_app_id = format!("{}{}", app_id_prefix, agent);
self.setup_app_2_install_and_enable(
&installed_app_id,
agent.to_owned(),
roles.as_slice(),
)
.await?;
}
self.raw_handle()
.reconcile_cell_status_with_app_status()
.await?;
let mut apps = Vec::new();
for agent in agents {
let installed_app_id = format!("{}{}", app_id_prefix, agent);
apps.push(
self.setup_app_3_create_sweet_app(
&installed_app_id,
agent.clone(),
roles.iter().map(|r| r.dna.dna_hash().clone()),
)
.await?,
);
}
Ok(SweetAppBatch(apps))
}
2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
async fn process_app_status_fx(
self: Arc<Self>,
delta: AppStatusFx,
app_ids: Option<HashSet<InstalledAppId>>,
) -> ConductorResult<CellStartupErrors> {
use AppStatusFx::*;
let mut last = (delta, vec![]);
loop {
tracing::debug!(msg = "Processing app status delta", delta = ?last.0);
last = match last.0 {
NoChange => break,
SpinDown => {
// Reconcile cell status so that dangling cells can leave the network and be removed
let errors = self.clone().reconcile_cell_status_with_app_status().await?;
// TODO: This should probably be emitted over the admin interface
if !errors.is_empty() {
error!(msg = "Errors when trying to stop app(s)", ?errors);
}
(NoChange, errors)
}
SpinUp | Both => {
// Reconcile cell status so that missing/pending cells can become fully joined
let errors = self.clone().reconcile_cell_status_with_app_status().await?;
// Reconcile app status in case some cells failed to join, so the app can be paused
let delta = self
.clone()
.reconcile_app_status_with_cell_status(app_ids.clone())
.await?;
// TODO: This should probably be emitted over the admin interface
if !errors.is_empty() {
error!(msg = "Errors when trying to start app(s)", ?errors);
}
(delta, errors)
}
};
}
Ok(last.1)
}
sourcepub async fn enable_app(
self: Arc<Self>,
app_id: InstalledAppId
) -> ConductorResult<(InstalledApp, CellStartupErrors)>
pub async fn enable_app(
self: Arc<Self>,
app_id: InstalledAppId
) -> ConductorResult<(InstalledApp, CellStartupErrors)>
Enable an app
Examples found in repository?
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
pub async fn enable_app(
&self,
id: InstalledAppId,
) -> ConductorResult<(InstalledApp, Vec<(CellId, CellError)>)> {
self.raw_handle().enable_app(id).await
}
/// Convenience function that uses the internal handle to disable an app
pub async fn disable_app(
&self,
id: InstalledAppId,
reason: DisabledAppReason,
) -> ConductorResult<InstalledApp> {
self.raw_handle().disable_app(id, reason).await
}
/// Convenience function that uses the internal handle to start an app
pub async fn start_app(&self, id: InstalledAppId) -> ConductorResult<InstalledApp> {
self.raw_handle().start_app(id).await
}
/// Convenience function that uses the internal handle to pause an app
pub async fn pause_app(
&self,
id: InstalledAppId,
reason: PausedAppReason,
) -> ConductorResult<InstalledApp> {
self.raw_handle().pause_app(id, reason).await
}
/// Install the dna first.
/// This allows a big speed up when
/// installing many apps with the same dna
async fn setup_app_1_register_dna(&mut self, dna_files: &[&DnaFile]) -> ConductorApiResult<()> {
for &dna_file in dna_files {
self.register_dna(dna_file.clone()).await?;
self.dnas.push(dna_file.clone());
}
Ok(())
}
/// Install the app and enable it
// TODO: make this take a more flexible config for specifying things like
// membrane proofs
async fn setup_app_2_install_and_enable(
&mut self,
installed_app_id: &str,
agent: AgentPubKey,
roles: &[DnaWithRole],
) -> ConductorApiResult<()> {
let installed_app_id = installed_app_id.to_string();
let installed_cells = roles
.iter()
.map(|r| {
let cell_id = CellId::new(r.dna.dna_hash().clone(), agent.clone());
(InstalledCell::new(cell_id, r.role.clone()), None)
})
.collect();
self.raw_handle()
.install_app(installed_app_id.clone(), installed_cells)
.await?;
self.raw_handle().enable_app(installed_app_id).await?;
Ok(())
}
More examples
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 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
pub async fn install_app(
name: &str,
cell_data: Vec<(InstalledCell, Option<MembraneProof>)>,
dnas: Vec<DnaFile>,
conductor_handle: ConductorHandle,
) {
for dna in dnas {
conductor_handle.register_dna(dna).await.unwrap();
}
conductor_handle
.clone()
.install_app(name.to_string(), cell_data)
.await
.unwrap();
conductor_handle
.clone()
.enable_app(name.to_string())
.await
.unwrap();
let errors = conductor_handle
.reconcile_cell_status_with_app_status()
.await
.unwrap();
assert!(errors.is_empty(), "{:?}", errors);
}
/// Payload for installing cells
pub type InstalledCellsWithProofs = Vec<(InstalledCell, Option<MembraneProof>)>;
/// One of various ways to setup an app, used somewhere...
pub async fn setup_app(
dnas: Vec<DnaFile>,
cell_data: Vec<(InstalledCell, Option<MembraneProof>)>,
) -> (Arc<TempDir>, RealAppInterfaceApi, ConductorHandle) {
let db_dir = test_db_dir();
let conductor_handle = ConductorBuilder::new()
.test(db_dir.path(), &[])
.await
.unwrap();
for dna in dnas {
conductor_handle.register_dna(dna).await.unwrap();
}
conductor_handle
.clone()
.install_app("test app".to_string(), cell_data)
.await
.unwrap();
conductor_handle
.clone()
.enable_app("test app".to_string())
.await
.unwrap();
let errors = conductor_handle
.clone()
.reconcile_cell_status_with_app_status()
.await
.unwrap();
assert!(errors.is_empty());
let handle = conductor_handle.clone();
(
Arc::new(db_dir),
RealAppInterfaceApi::new(conductor_handle),
handle,
)
}
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
sourcepub async fn disable_app(
self: Arc<Self>,
app_id: InstalledAppId,
reason: DisabledAppReason
) -> ConductorResult<InstalledApp>
pub async fn disable_app(
self: Arc<Self>,
app_id: InstalledAppId,
reason: DisabledAppReason
) -> ConductorResult<InstalledApp>
Disable an app
Examples found in repository?
More examples
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
async fn run(
conductor: ConductorHandle,
mut new_task_channel: mpsc::Receiver<ManagedTaskAdd>,
) -> TaskManagerResult {
let mut task_manager = TaskManager::new();
// Need to have at least one item in the stream or it will exit early
if let Some(new_task) = new_task_channel.recv().await {
task_manager.stream.push(new_task);
} else {
error!("All senders to task manager were dropped before starting");
return Err(TaskManagerError::TaskManagerFailedToStart);
}
loop {
tokio::select! {
Some(new_task) = new_task_channel.recv() => {
task_manager.stream.push(new_task);
tracing::debug!("Task added. Total tasks: {}", task_manager.stream.len());
}
result = task_manager.stream.next() => {
tracing::debug!("Task completed. Total tasks: {}", task_manager.stream.len());
match result {
Some(TaskOutcome::NewTask(new_task)) => task_manager.stream.push(new_task),
Some(TaskOutcome::LogInfo(context)) => {
debug!("Managed task completed: {}", context)
}
Some(TaskOutcome::MinorError(error, context)) => {
error!("Minor error during managed task: {:?}\nContext: {}", error, context)
}
Some(TaskOutcome::ShutdownConductor(error, context)) => {
let error = match *error {
ManagedTaskError::Join(error) => {
match error.try_into_panic() {
Ok(reason) => {
// Resume the panic on the main task
std::panic::resume_unwind(reason);
}
Err(error) => ManagedTaskError::Join(error),
}
}
error => error,
};
error!("Shutting down conductor due to unrecoverable error: {:?}\nContext: {}", error, context);
return Err(TaskManagerError::Unrecoverable(Box::new(error)));
},
Some(TaskOutcome::StopApps(cell_id, error, context)) => {
tracing::error!("About to automatically stop apps");
let app_ids = conductor.list_running_apps_for_dependent_cell_id(&cell_id).await.map_err(TaskManagerError::internal)?;
if error.is_recoverable() {
conductor.remove_cells(&[cell_id]).await;
// The following message assumes that only the app_ids calculated will be paused, but other apps
// may have been paused as well.
tracing::error!(
"PAUSING the following apps due to a recoverable error: {:?}\nError: {:?}\nContext: {}",
app_ids,
error,
context
);
// MAYBE: it could be helpful to modify this function so that when providing Some(app_ids),
// you can also pass in a PausedAppReason override, so that the reason for the apps being paused
// can be set to the specific error message encountered here, rather than having to read it from
// the logs.
let delta = conductor.reconcile_app_status_with_cell_status(None).await.map_err(TaskManagerError::internal)?;
tracing::debug!(delta = ?delta);
tracing::error!("Apps paused.");
} else {
// Since the error is unrecoverable, we don't expect to be able to use this Cell anymore.
// Therefore, we disable every app which requires that cell.
tracing::error!(
"DISABLING the following apps due to an unrecoverable error: {:?}\nError: {:?}\nContext: {}",
app_ids,
error,
context
);
for app_id in app_ids.iter() {
conductor.clone().disable_app(app_id.to_string(), DisabledAppReason::Error(error.to_string())).await.map_err(TaskManagerError::internal)?;
}
tracing::error!("Apps disabled.");
}
},
Some(TaskOutcome::StopAppsWithDna(dna_hash, error, context)) => {
tracing::error!("About to automatically stop apps with dna {}", dna_hash);
let app_ids = conductor.list_running_apps_for_dependent_dna_hash(dna_hash.as_ref()).await.map_err(TaskManagerError::internal)?;
if error.is_recoverable() {
let cells_with_same_dna: Vec<_> = conductor.list_cell_ids(None).into_iter().filter(|id| id.dna_hash() == dna_hash.as_ref()).collect();
conductor.remove_cells(&cells_with_same_dna).await;
// The following message assumes that only the app_ids calculated will be paused, but other apps
// may have been paused as well.
tracing::error!(
"PAUSING the following apps due to a recoverable error: {:?}\nError: {:?}\nContext: {}",
app_ids,
error,
context
);
// MAYBE: it could be helpful to modify this function so that when providing Some(app_ids),
// you can also pass in a PausedAppReason override, so that the reason for the apps being paused
// can be set to the specific error message encountered here, rather than having to read it from
// the logs.
let delta = conductor.reconcile_app_status_with_cell_status(None).await.map_err(TaskManagerError::internal)?;
tracing::debug!(delta = ?delta);
tracing::error!("Apps paused.");
} else {
// Since the error is unrecoverable, we don't expect to be able to use this Cell anymore.
// Therefore, we disable every app which requires that cell.
tracing::error!(
"DISABLING the following apps due to an unrecoverable error: {:?}\nError: {:?}\nContext: {}",
app_ids,
error,
context
);
for app_id in app_ids.iter() {
conductor.clone().disable_app(app_id.to_string(), DisabledAppReason::Error(error.to_string())).await.map_err(TaskManagerError::internal)?;
}
tracing::error!("Apps disabled.");
}
},
None => return Ok(()),
}}
};
}
}
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
sourcepub async fn start_app(
self: Arc<Self>,
app_id: InstalledAppId
) -> ConductorResult<InstalledApp>
pub async fn start_app(
self: Arc<Self>,
app_id: InstalledAppId
) -> ConductorResult<InstalledApp>
Start an app
Examples found in repository?
More examples
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
sourcepub async fn pause_app(
self: Arc<Self>,
app_id: InstalledAppId,
reason: PausedAppReason
) -> ConductorResult<InstalledApp>
pub async fn pause_app(
self: Arc<Self>,
app_id: InstalledAppId,
reason: PausedAppReason
) -> ConductorResult<InstalledApp>
Pause an app
source§impl Conductor
impl Conductor
sourcepub async fn grant_zome_call_capability(
&self,
payload: GrantZomeCallCapabilityPayload
) -> ConductorApiResult<()>
pub async fn grant_zome_call_capability(
&self,
payload: GrantZomeCallCapabilityPayload
) -> ConductorApiResult<()>
Grant a zome call capability for a cell
Examples found in repository?
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
sourcepub async fn dump_cell_state(
&self,
cell_id: &CellId
) -> ConductorApiResult<String>
pub async fn dump_cell_state(
&self,
cell_id: &CellId
) -> ConductorApiResult<String>
Create a JSON dump of the cell’s state
Examples found in repository?
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
sourcepub async fn dump_full_cell_state(
&self,
cell_id: &CellId,
dht_ops_cursor: Option<u64>
) -> ConductorApiResult<FullStateDump>
pub async fn dump_full_cell_state(
&self,
cell_id: &CellId,
dht_ops_cursor: Option<u64>
) -> ConductorApiResult<FullStateDump>
Create a comprehensive structured dump of a cell’s state
Examples found in repository?
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
sourcepub async fn dump_network_metrics(
&self,
dna_hash: Option<DnaHash>
) -> ConductorApiResult<String>
pub async fn dump_network_metrics(
&self,
dna_hash: Option<DnaHash>
) -> ConductorApiResult<String>
JSON dump of network metrics
Examples found in repository?
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
sourcepub async fn add_agent_infos(
&self,
agent_infos: Vec<AgentInfoSigned>
) -> ConductorApiResult<()>
pub async fn add_agent_infos(
&self,
agent_infos: Vec<AgentInfoSigned>
) -> ConductorApiResult<()>
Add signed agent info to the conductor
Examples found in repository?
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
sourcepub async fn graft_records_onto_source_chain(
self: Arc<Self>,
cell_id: CellId,
validate: bool,
records: Vec<Record>
) -> ConductorApiResult<()>
pub async fn graft_records_onto_source_chain(
self: Arc<Self>,
cell_id: CellId,
validate: bool,
records: Vec<Record>
) -> ConductorApiResult<()>
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.
Examples found in repository?
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
sourcepub async fn update_coordinators(
&self,
hash: &DnaHash,
coordinator_zomes: CoordinatorZomes,
wasms: Vec<DnaWasm>
) -> ConductorResult<()>
pub async fn update_coordinators(
&self,
hash: &DnaHash,
coordinator_zomes: CoordinatorZomes,
wasms: Vec<DnaWasm>
) -> ConductorResult<()>
Update coordinator zomes on an existing dna.
Examples found in repository?
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
async fn handle_admin_request_inner(
&self,
request: AdminRequest,
) -> ConductorApiResult<AdminResponse> {
use AdminRequest::*;
match request {
AddAdminInterfaces(configs) => {
self.conductor_handle
.clone()
.add_admin_interfaces(configs)
.await?;
Ok(AdminResponse::AdminInterfacesAdded)
}
RegisterDna(payload) => {
trace!(register_dna_payload = ?payload);
let RegisterDnaPayload { modifiers, source } = *payload;
let modifiers = modifiers.serialized().map_err(SerializationError::Bytes)?;
// network seed and properties from the register call will override any in the bundle
let dna = match source {
DnaSource::Hash(ref hash) => {
if !modifiers.has_some_option_set() {
return Err(ConductorApiError::DnaReadError(
"DnaSource::Hash requires `properties` or `network_seed` or `origin_time` to create a derived Dna"
.to_string(),
));
}
self.conductor_handle
.get_dna_file(hash)
.ok_or_else(|| {
ConductorApiError::DnaReadError(format!(
"Unable to create derived Dna: {} not registered",
hash
))
})?
.update_modifiers(modifiers)
}
DnaSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: DnaBundle = bundle.into();
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
DnaSource::Bundle(bundle) => {
let (dna_file, _original_hash) = bundle.into_dna_file(modifiers).await?;
dna_file
}
};
let hash = dna.dna_hash().clone();
let dna_list = self.conductor_handle.list_dnas();
if !dna_list.contains(&hash) {
self.conductor_handle.register_dna(dna).await?;
}
Ok(AdminResponse::DnaRegistered(hash))
}
GetDnaDefinition(dna_hash) => {
let dna_def = self
.conductor_handle
.get_dna_def(&dna_hash)
.ok_or(ConductorApiError::DnaMissing(*dna_hash))?;
Ok(AdminResponse::DnaDefinitionReturned(dna_def))
}
UpdateCoordinators(payload) => {
let UpdateCoordinatorsPayload { dna_hash, source } = *payload;
let (coordinator_zomes, wasms) = match source {
CoordinatorSource::Path(ref path) => {
let bundle = Bundle::read_from_file(path).await?;
let bundle: CoordinatorBundle = bundle.into();
bundle.into_zomes().await?
}
CoordinatorSource::Bundle(bundle) => bundle.into_zomes().await?,
};
self.conductor_handle
.update_coordinators(&dna_hash, coordinator_zomes, wasms)
.await?;
Ok(AdminResponse::CoordinatorsUpdated)
}
InstallApp(payload) => {
let app: InstalledApp = self
.conductor_handle
.clone()
.install_app_bundle(*payload)
.await?
.into();
let dna_definitions = self.conductor_handle.get_dna_definitions(&app)?;
Ok(AdminResponse::AppInstalled(AppInfo::from_installed_app(
&app,
&dna_definitions,
)))
}
UninstallApp { installed_app_id } => {
self.conductor_handle
.clone()
.uninstall_app(&installed_app_id)
.await?;
Ok(AdminResponse::AppUninstalled)
}
ListDnas => {
let dna_list = self.conductor_handle.list_dnas();
Ok(AdminResponse::DnasListed(dna_list))
}
GenerateAgentPubKey => {
let agent_pub_key = self
.conductor_handle
.keystore()
.clone()
.new_sign_keypair_random()
.await?;
Ok(AdminResponse::AgentPubKeyGenerated(agent_pub_key))
}
ListCellIds => {
let cell_ids = self
.conductor_handle
.list_cell_ids(Some(CellStatus::Joined));
Ok(AdminResponse::CellIdsListed(cell_ids))
}
ListApps { status_filter } => {
let apps = self.conductor_handle.list_apps(status_filter).await?;
Ok(AdminResponse::AppsListed(apps))
}
EnableApp { installed_app_id } => {
// Enable app
let (app, errors) = self
.conductor_handle
.clone()
.enable_app(installed_app_id.clone())
.await?;
let app_cells: HashSet<_> = app.required_cells().collect();
let app_info = self
.conductor_handle
.get_app_info(&installed_app_id)
.await?
.ok_or(ConductorError::AppNotInstalled(installed_app_id))?;
let errors: Vec<_> = errors
.into_iter()
.filter(|(cell_id, _)| app_cells.contains(cell_id))
.map(|(cell_id, error)| (cell_id, error.to_string()))
.collect();
Ok(AdminResponse::AppEnabled {
app: app_info,
errors,
})
}
DisableApp { installed_app_id } => {
// Disable app
self.conductor_handle
.clone()
.disable_app(installed_app_id, DisabledAppReason::User)
.await?;
Ok(AdminResponse::AppDisabled)
}
StartApp { installed_app_id } => {
// TODO: check to see if app was actually started
let app = self
.conductor_handle
.clone()
.start_app(installed_app_id)
.await?;
Ok(AdminResponse::AppStarted(app.status().is_running()))
}
AttachAppInterface { port } => {
let port = port.unwrap_or(0);
let port = self
.conductor_handle
.clone()
.add_app_interface(either::Either::Left(port))
.await?;
Ok(AdminResponse::AppInterfaceAttached { port })
}
ListAppInterfaces => {
let interfaces = self.conductor_handle.list_app_interfaces().await?;
Ok(AdminResponse::AppInterfacesListed(interfaces))
}
DumpState { cell_id } => {
let state = self.conductor_handle.dump_cell_state(&cell_id).await?;
Ok(AdminResponse::StateDumped(state))
}
DumpFullState {
cell_id,
dht_ops_cursor,
} => {
let state = self
.conductor_handle
.dump_full_cell_state(&cell_id, dht_ops_cursor)
.await?;
Ok(AdminResponse::FullStateDumped(state))
}
DumpNetworkMetrics { dna_hash } => {
let dump = self.conductor_handle.dump_network_metrics(dna_hash).await?;
Ok(AdminResponse::NetworkMetricsDumped(dump))
}
AddAgentInfo { agent_infos } => {
self.conductor_handle.add_agent_infos(agent_infos).await?;
Ok(AdminResponse::AgentInfoAdded)
}
AgentInfo { cell_id } => {
let r = self.conductor_handle.get_agent_infos(cell_id).await?;
Ok(AdminResponse::AgentInfo(r))
}
GraftRecords {
cell_id,
validate,
records,
} => {
self.conductor_handle
.clone()
.graft_records_onto_source_chain(cell_id, validate, records)
.await?;
Ok(AdminResponse::RecordsGrafted)
}
GrantZomeCallCapability(payload) => {
self.conductor_handle
.clone()
.grant_zome_call_capability(*payload)
.await?;
Ok(AdminResponse::ZomeCallCapabilityGranted)
}
DeleteCloneCell(payload) => {
self.conductor_handle
.clone()
.delete_clone_cell(&*payload)
.await?;
Ok(AdminResponse::CloneCellDeleted)
}
}
}
source§impl Conductor
impl Conductor
sourcepub fn signal_broadcaster(&self) -> SignalBroadcaster
pub fn signal_broadcaster(&self) -> SignalBroadcaster
Access to the signal broadcast channel, to create new subscriptions
Examples found in repository?
More examples
47 48 49 50 51 52 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
pub async fn new(
cell_id: &CellId,
handle: &ConductorHandle,
dna_file: &DnaFile,
chc: Option<ChcImpl>,
) -> Self {
let authored_db = handle.get_authored_db(cell_id.dna_hash()).unwrap();
let dht_db = handle.get_dht_db(cell_id.dna_hash()).unwrap();
let dht_db_cache = handle.get_dht_db_cache(cell_id.dna_hash()).unwrap();
let cache = handle.get_cache_db(cell_id).unwrap();
let keystore = handle.keystore().clone();
let network = handle
.holochain_p2p()
.to_dna(cell_id.dna_hash().clone(), chc);
let triggers = handle.get_cell_triggers(cell_id).unwrap();
let cell_conductor_api = CellConductorApi::new(handle.clone(), cell_id.clone());
let ribosome = handle.get_ribosome(dna_file.dna_hash()).unwrap();
let signal_tx = handle.signal_broadcaster();
CellHostFnCaller {
cell_id: cell_id.clone(),
authored_db,
dht_db,
dht_db_cache,
cache,
ribosome,
network,
keystore,
signal_tx,
triggers,
cell_conductor_api,
}
}
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)),
}
}
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
pub async fn create_for_zome(
cell_id: &CellId,
handle: &ConductorHandle,
dna_file: &DnaFile,
zome_index: usize,
) -> HostFnCaller {
let authored_db = handle.get_authored_db(cell_id.dna_hash()).unwrap();
let dht_db = handle.get_dht_db(cell_id.dna_hash()).unwrap();
let dht_db_cache = handle.get_dht_db_cache(cell_id.dna_hash()).unwrap();
let cache = handle.get_cache_db(cell_id).unwrap();
let keystore = handle.keystore().clone();
let network = handle
.holochain_p2p()
.to_dna(cell_id.dna_hash().clone(), None);
let zome_path = (
cell_id.clone(),
dna_file
.dna()
.integrity_zomes
.get(zome_index)
.unwrap()
.0
.clone(),
)
.into();
let ribosome = handle.get_ribosome(dna_file.dna_hash()).unwrap();
let signal_tx = handle.signal_broadcaster();
let call_zome_handle =
CellConductorApi::new(handle.clone(), cell_id.clone()).into_call_zome_handle();
HostFnCaller {
authored_db,
dht_db,
dht_db_cache,
cache,
ribosome,
zome_path,
network,
keystore,
signal_tx,
call_zome_handle,
}
}
sourcepub async fn post_commit_permit(
&self
) -> Result<OwnedPermit<PostCommitArgs>, SendError<()>>
pub async fn post_commit_permit(
&self
) -> Result<OwnedPermit<PostCommitArgs>, SendError<()>>
Get the post commit sender.
Examples found in repository?
More examples
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
pub async fn send_post_commit(
conductor_handle: ConductorHandle,
workspace: SourceChainWorkspace,
network: HolochainP2pDna,
keystore: MetaLairClient,
actions: Vec<SignedActionHashed>,
zomes: Vec<CoordinatorZome>,
) -> Result<(), tokio::sync::mpsc::error::SendError<()>> {
let cell_id = workspace.source_chain().cell_id();
for zome in zomes {
conductor_handle
.post_commit_permit()
.await?
.send(PostCommitArgs {
host_access: PostCommitHostAccess {
workspace: workspace.clone().into(),
keystore: keystore.clone(),
network: network.clone(),
},
invocation: PostCommitInvocation::new(zome, actions.clone()),
cell_id: cell_id.clone(),
});
}
Ok(())
}
sourcepub fn get_config(&self) -> &ConductorConfig
pub fn get_config(&self) -> &ConductorConfig
Get the conductor config
source§impl Conductor
impl Conductor
pub async fn get_state_from_handle(&self) -> ConductorResult<ConductorState>
sourcepub async fn add_test_app_interface<I: Into<AppInterfaceId>>(
&self,
id: I
) -> ConductorResult<()>
pub async fn add_test_app_interface<I: Into<AppInterfaceId>>(
&self,
id: I
) -> ConductorResult<()>
Examples found in repository?
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)),
}
}
Examples found in repository?
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 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 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 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
pub fn get_sweet_cell(&self, cell_id: CellId) -> ConductorApiResult<SweetCell> {
let (dna_hash, agent) = cell_id.into_dna_and_agent();
let cell_authored_db = self.raw_handle().get_authored_db(&dna_hash)?;
let cell_dht_db = self.raw_handle().get_dht_db(&dna_hash)?;
let cell_id = CellId::new(dna_hash, agent);
Ok(SweetCell {
cell_id,
cell_authored_db,
cell_dht_db,
})
}
/// Opinionated app setup.
/// Creates an app for the given agent, using the given DnaFiles, with no extra configuration.
pub async fn setup_app_for_agent<'a, R, D>(
&mut self,
installed_app_id: &str,
agent: AgentPubKey,
roles: D,
) -> ConductorApiResult<SweetApp>
where
R: Into<DnaWithRole> + Clone + 'a,
D: IntoIterator<Item = &'a R>,
{
let roles: Vec<DnaWithRole> = roles.into_iter().cloned().map(Into::into).collect();
let dnas = roles.iter().map(|r| &r.dna).collect::<Vec<_>>();
self.setup_app_1_register_dna(&dnas).await?;
self.setup_app_2_install_and_enable(installed_app_id, agent.clone(), roles.as_slice())
.await?;
self.raw_handle()
.reconcile_cell_status_with_app_status()
.await?;
let dna_hashes = roles.iter().map(|r| r.dna.dna_hash().clone());
self.setup_app_3_create_sweet_app(installed_app_id, agent, dna_hashes)
.await
}
/// Opinionated app setup.
/// Creates an app using the given DnaFiles, with no extra configuration.
/// An AgentPubKey will be generated, and is accessible via the returned SweetApp.
pub async fn setup_app<'a, R, D>(
&mut self,
installed_app_id: &str,
dnas: D,
) -> ConductorApiResult<SweetApp>
where
R: Into<DnaWithRole> + Clone + 'a,
D: IntoIterator<Item = &'a R> + Clone,
{
let agent = SweetAgents::one(self.keystore()).await;
self.setup_app_for_agent(installed_app_id, agent, dnas.clone())
.await
}
/// Opinionated app setup. Creates one app per agent, using the given DnaFiles.
///
/// All InstalledAppIds and RoleNames are auto-generated. In tests driven directly
/// by Rust, you typically won't care what these values are set to, but in case you
/// do, they are set as so:
/// - InstalledAppId: {app_id_prefix}-{agent_pub_key}
/// - RoleName: {dna_hash}
///
/// Returns a batch of SweetApps, sorted in the same order as Agents passed in.
pub async fn setup_app_for_agents<'a, A, R, D>(
&mut self,
app_id_prefix: &str,
agents: A,
roles: D,
) -> ConductorApiResult<SweetAppBatch>
where
A: IntoIterator<Item = &'a AgentPubKey>,
R: Into<DnaWithRole> + Clone + 'a,
D: IntoIterator<Item = &'a R>,
{
let agents: Vec<_> = agents.into_iter().collect();
let roles: Vec<DnaWithRole> = roles.into_iter().cloned().map(Into::into).collect();
let dnas: Vec<&DnaFile> = roles.iter().map(|r| &r.dna).collect();
self.setup_app_1_register_dna(dnas.as_slice()).await?;
for &agent in agents.iter() {
let installed_app_id = format!("{}{}", app_id_prefix, agent);
self.setup_app_2_install_and_enable(
&installed_app_id,
agent.to_owned(),
roles.as_slice(),
)
.await?;
}
self.raw_handle()
.reconcile_cell_status_with_app_status()
.await?;
let mut apps = Vec::new();
for agent in agents {
let installed_app_id = format!("{}{}", app_id_prefix, agent);
apps.push(
self.setup_app_3_create_sweet_app(
&installed_app_id,
agent.clone(),
roles.iter().map(|r| r.dna.dna_hash().clone()),
)
.await?,
);
}
Ok(SweetAppBatch(apps))
}
/// Get a stream of all Signals emitted on the "sweet-interface" AppInterface.
///
/// This is designed to crash if called more than once, because as currently
/// implemented, creating multiple signal streams would simply cause multiple
/// consumers of the same underlying streams, not a fresh subscription
pub fn signals(&mut self) -> SignalStream {
self.signal_stream
.take()
.expect("Can't take the SweetConductor signal stream twice")
}
/// Get a new websocket client which can send requests over the admin
/// interface. It presupposes that an admin interface has been configured.
/// (The standard_config includes an admin interface at port 0.)
pub async fn admin_ws_client(&self) -> (WebsocketSender, WebsocketReceiver) {
let port = self
.get_arbitrary_admin_websocket_port()
.expect("No admin port open on conductor");
websocket_client_by_port(port).await.unwrap()
}
/// Shutdown this conductor.
/// This will wait for the conductor to shutdown but
/// keep the inner state to restart it.
///
/// Attempting to use this conductor without starting it up again will cause a panic.
pub async fn shutdown(&mut self) {
if let Some(handle) = self.handle.take() {
handle.shutdown_and_wait().await;
} else {
panic!("Attempted to shutdown conductor which was already shutdown");
}
}
/// Start up this conductor if it's not already running.
pub async fn startup(&mut self) {
if self.handle.is_none() {
self.handle = Some(SweetConductorHandle(
Self::handle_from_existing(
&self.db_dir,
self.keystore.clone(),
&self.config,
self.dnas.as_slice(),
)
.await,
));
} else {
panic!("Attempted to start conductor which was already started");
}
}
/// Check if this conductor is running
pub fn is_running(&self) -> bool {
self.handle.is_some()
}
// NB: keep this private to prevent leaking out owned references
#[allow(dead_code)]
fn sweet_handle(&self) -> SweetConductorHandle {
self.handle
.as_ref()
.map(|h| h.clone_privately())
.expect("Tried to use a conductor that is offline")
}
/// Get the ConductorHandle within this Conductor.
/// Be careful when using this, because this leaks out handles, which may
/// make it harder to shut down the conductor during tests.
pub fn raw_handle(&self) -> ConductorHandle {
self.handle
.as_ref()
.map(|h| h.0.clone())
.expect("Tried to use a conductor that is offline")
}
/// Force trigger all dht ops that haven't received
/// enough validation receipts yet.
pub async fn force_all_publish_dht_ops(&self) {
use futures::stream::StreamExt;
if let Some(handle) = self.handle.as_ref() {
let iter = handle.list_cell_ids(None).into_iter().map(|id| async {
let id = id;
let db = self.get_authored_db(id.dna_hash()).unwrap();
let trigger = self.get_cell_triggers(&id).unwrap();
(db, trigger)
});
futures::stream::iter(iter)
.then(|f| f)
.for_each(|(db, mut triggers)| async move {
// The line below was added when migrating to rust edition 2021, per
// https://doc.rust-lang.org/edition-guide/rust-2021/disjoint-capture-in-closures.html#migration
let _ = &triggers;
crate::test_utils::force_publish_dht_ops(&db, &mut triggers.publish_dht_ops)
.await
.unwrap();
})
.await;
}
}
More examples
47 48 49 50 51 52 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
pub async fn new(
cell_id: &CellId,
handle: &ConductorHandle,
dna_file: &DnaFile,
chc: Option<ChcImpl>,
) -> Self {
let authored_db = handle.get_authored_db(cell_id.dna_hash()).unwrap();
let dht_db = handle.get_dht_db(cell_id.dna_hash()).unwrap();
let dht_db_cache = handle.get_dht_db_cache(cell_id.dna_hash()).unwrap();
let cache = handle.get_cache_db(cell_id).unwrap();
let keystore = handle.keystore().clone();
let network = handle
.holochain_p2p()
.to_dna(cell_id.dna_hash().clone(), chc);
let triggers = handle.get_cell_triggers(cell_id).unwrap();
let cell_conductor_api = CellConductorApi::new(handle.clone(), cell_id.clone());
let ribosome = handle.get_ribosome(dna_file.dna_hash()).unwrap();
let signal_tx = handle.signal_broadcaster();
CellHostFnCaller {
cell_id: cell_id.clone(),
authored_db,
dht_db,
dht_db_cache,
cache,
ribosome,
network,
keystore,
signal_tx,
triggers,
cell_conductor_api,
}
}
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
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(())
}
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
pub async fn create_for_zome(
cell_id: &CellId,
handle: &ConductorHandle,
dna_file: &DnaFile,
zome_index: usize,
) -> HostFnCaller {
let authored_db = handle.get_authored_db(cell_id.dna_hash()).unwrap();
let dht_db = handle.get_dht_db(cell_id.dna_hash()).unwrap();
let dht_db_cache = handle.get_dht_db_cache(cell_id.dna_hash()).unwrap();
let cache = handle.get_cache_db(cell_id).unwrap();
let keystore = handle.keystore().clone();
let network = handle
.holochain_p2p()
.to_dna(cell_id.dna_hash().clone(), None);
let zome_path = (
cell_id.clone(),
dna_file
.dna()
.integrity_zomes
.get(zome_index)
.unwrap()
.0
.clone(),
)
.into();
let ribosome = handle.get_ribosome(dna_file.dna_hash()).unwrap();
let signal_tx = handle.signal_broadcaster();
let call_zome_handle =
CellConductorApi::new(handle.clone(), cell_id.clone()).into_call_zome_handle();
HostFnCaller {
authored_db,
dht_db,
dht_db_cache,
cache,
ribosome,
zome_path,
network,
keystore,
signal_tx,
call_zome_handle,
}
}
40 41 42 43 44 45 46 47 48 49 50 51 52 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
pub async fn local_machine_session(conductors: &[ConductorHandle], timeout: Duration) {
// For each space get all the cells, their db and the p2p envs.
let mut spaces = HashMap::new();
for (i, c) in conductors.iter().enumerate() {
for cell_id in c.list_cell_ids(None) {
let space = spaces
.entry(cell_id.dna_hash().clone())
.or_insert_with(|| vec![None; conductors.len()]);
if space[i].is_none() {
let p2p_agents_db: DbRead<DbKindP2pAgents> =
c.get_p2p_db(cell_id.dna_hash()).into();
space[i] = Some((p2p_agents_db, Vec::new()));
}
space[i].as_mut().unwrap().1.push((
c.get_authored_db(cell_id.dna_hash()).unwrap().into(),
c.get_dht_db(cell_id.dna_hash()).unwrap().into(),
cell_id.agent_pubkey().to_kitsune(),
));
}
}
// Run a consistency session for each space.
for (_, conductors) in spaces {
// The agents we need to wait for.
let mut wait_for_agents = HashSet::new();
// Maps to environments.
let mut agent_dht_map = HashMap::new();
let mut agent_p2p_map = HashMap::new();
// All the agents that should be held.
let mut all_agents = Vec::new();
// All the op hashes that should be held.
let mut all_hashes = Vec::new();
let (tx, rx) = tokio::sync::mpsc::channel(1000);
// Gather the expected agents and op hashes from each conductor.
for (p2p_agents_db, agents) in conductors.into_iter().flatten() {
wait_for_agents.extend(agents.iter().map(|(_, _, agent)| agent.clone()));
agent_dht_map.extend(agents.iter().cloned().map(|(_, dht, agent)| (agent, dht)));
agent_p2p_map.extend(
agents
.iter()
.cloned()
.map(|(_, _, a)| (a, p2p_agents_db.clone())),
);
let (a, h) = gather_conductor_data(p2p_agents_db, agents).await;
all_agents.extend(a);
all_hashes.extend(h);
}
// Spawn a background task that will run each
// cells self consistency check against the data that
// they are expected to hold.
tokio::spawn(expect_all(
tx,
timeout,
all_agents,
all_hashes,
agent_dht_map,
agent_p2p_map,
));
// Wait up to the timeout for all the agents to report success.
wait_for_consistency(rx, wait_for_agents, timeout).await;
}
}
sourcepub fn get_dht_db(
&self,
dna_hash: &DnaHash
) -> ConductorApiResult<DbWrite<DbKindDht>>
pub fn get_dht_db(
&self,
dna_hash: &DnaHash
) -> ConductorApiResult<DbWrite<DbKindDht>>
Examples found in repository?
More examples
47 48 49 50 51 52 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
pub async fn new(
cell_id: &CellId,
handle: &ConductorHandle,
dna_file: &DnaFile,
chc: Option<ChcImpl>,
) -> Self {
let authored_db = handle.get_authored_db(cell_id.dna_hash()).unwrap();
let dht_db = handle.get_dht_db(cell_id.dna_hash()).unwrap();
let dht_db_cache = handle.get_dht_db_cache(cell_id.dna_hash()).unwrap();
let cache = handle.get_cache_db(cell_id).unwrap();
let keystore = handle.keystore().clone();
let network = handle
.holochain_p2p()
.to_dna(cell_id.dna_hash().clone(), chc);
let triggers = handle.get_cell_triggers(cell_id).unwrap();
let cell_conductor_api = CellConductorApi::new(handle.clone(), cell_id.clone());
let ribosome = handle.get_ribosome(dna_file.dna_hash()).unwrap();
let signal_tx = handle.signal_broadcaster();
CellHostFnCaller {
cell_id: cell_id.clone(),
authored_db,
dht_db,
dht_db_cache,
cache,
ribosome,
network,
keystore,
signal_tx,
triggers,
cell_conductor_api,
}
}
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
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(())
}
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
pub async fn create_for_zome(
cell_id: &CellId,
handle: &ConductorHandle,
dna_file: &DnaFile,
zome_index: usize,
) -> HostFnCaller {
let authored_db = handle.get_authored_db(cell_id.dna_hash()).unwrap();
let dht_db = handle.get_dht_db(cell_id.dna_hash()).unwrap();
let dht_db_cache = handle.get_dht_db_cache(cell_id.dna_hash()).unwrap();
let cache = handle.get_cache_db(cell_id).unwrap();
let keystore = handle.keystore().clone();
let network = handle
.holochain_p2p()
.to_dna(cell_id.dna_hash().clone(), None);
let zome_path = (
cell_id.clone(),
dna_file
.dna()
.integrity_zomes
.get(zome_index)
.unwrap()
.0
.clone(),
)
.into();
let ribosome = handle.get_ribosome(dna_file.dna_hash()).unwrap();
let signal_tx = handle.signal_broadcaster();
let call_zome_handle =
CellConductorApi::new(handle.clone(), cell_id.clone()).into_call_zome_handle();
HostFnCaller {
authored_db,
dht_db,
dht_db_cache,
cache,
ribosome,
zome_path,
network,
keystore,
signal_tx,
call_zome_handle,
}
}
40 41 42 43 44 45 46 47 48 49 50 51 52 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
pub async fn local_machine_session(conductors: &[ConductorHandle], timeout: Duration) {
// For each space get all the cells, their db and the p2p envs.
let mut spaces = HashMap::new();
for (i, c) in conductors.iter().enumerate() {
for cell_id in c.list_cell_ids(None) {
let space = spaces
.entry(cell_id.dna_hash().clone())
.or_insert_with(|| vec![None; conductors.len()]);
if space[i].is_none() {
let p2p_agents_db: DbRead<DbKindP2pAgents> =
c.get_p2p_db(cell_id.dna_hash()).into();
space[i] = Some((p2p_agents_db, Vec::new()));
}
space[i].as_mut().unwrap().1.push((
c.get_authored_db(cell_id.dna_hash()).unwrap().into(),
c.get_dht_db(cell_id.dna_hash()).unwrap().into(),
cell_id.agent_pubkey().to_kitsune(),
));
}
}
// Run a consistency session for each space.
for (_, conductors) in spaces {
// The agents we need to wait for.
let mut wait_for_agents = HashSet::new();
// Maps to environments.
let mut agent_dht_map = HashMap::new();
let mut agent_p2p_map = HashMap::new();
// All the agents that should be held.
let mut all_agents = Vec::new();
// All the op hashes that should be held.
let mut all_hashes = Vec::new();
let (tx, rx) = tokio::sync::mpsc::channel(1000);
// Gather the expected agents and op hashes from each conductor.
for (p2p_agents_db, agents) in conductors.into_iter().flatten() {
wait_for_agents.extend(agents.iter().map(|(_, _, agent)| agent.clone()));
agent_dht_map.extend(agents.iter().cloned().map(|(_, dht, agent)| (agent, dht)));
agent_p2p_map.extend(
agents
.iter()
.cloned()
.map(|(_, _, a)| (a, p2p_agents_db.clone())),
);
let (a, h) = gather_conductor_data(p2p_agents_db, agents).await;
all_agents.extend(a);
all_hashes.extend(h);
}
// Spawn a background task that will run each
// cells self consistency check against the data that
// they are expected to hold.
tokio::spawn(expect_all(
tx,
timeout,
all_agents,
all_hashes,
agent_dht_map,
agent_p2p_map,
));
// Wait up to the timeout for all the agents to report success.
wait_for_consistency(rx, wait_for_agents, timeout).await;
}
}
/// Get consistency for a particular hash.
pub async fn local_machine_session_with_hashes(
handles: Vec<&ConductorHandle>,
hashes: impl Iterator<Item = (DhtLocation, DhtOpHash)>,
space: &DnaHash,
timeout: Duration,
) {
// Grab the environments and cells for each conductor in this space.
let mut conductors = vec![None; handles.len()];
for (i, c) in handles.iter().enumerate() {
for cell_id in c.list_cell_ids(None) {
if cell_id.dna_hash() != space {
continue;
}
if conductors[i].is_none() {
let p2p_agents_db: DbRead<DbKindP2pAgents> =
c.get_p2p_db(cell_id.dna_hash()).into();
conductors[i] = Some((p2p_agents_db, Vec::new()));
}
conductors[i].as_mut().unwrap().1.push((
c.get_dht_db(cell_id.dna_hash()).unwrap().into(),
cell_id.agent_pubkey().to_kitsune(),
));
}
}
// Convert the hashes to kitsune.
let all_hashes = hashes
.into_iter()
.map(|(l, h)| (l, h.into_kitsune_raw()))
.collect::<Vec<_>>();
// The agents we need to wait for.
let mut wait_for_agents = HashSet::new();
// Maps to environments.
let mut agent_dht_map = HashMap::new();
let mut agent_p2p_map = HashMap::new();
// All the agents that should be held.
let mut all_agents = Vec::new();
let (tx, rx) = tokio::sync::mpsc::channel(1000);
// Gather the expected agents from each conductor.
for (p2p_agents_db, agents) in conductors.into_iter().flatten() {
wait_for_agents.extend(agents.iter().map(|(_, agent)| agent.clone()));
agent_dht_map.extend(agents.iter().cloned().map(|(e, a)| (a, e)));
agent_p2p_map.extend(
agents
.iter()
.cloned()
.map(|(_, a)| (a, p2p_agents_db.clone())),
);
for (_, agent) in &agents {
if let Some(storage_arc) = request_arc(&p2p_agents_db, (**agent).clone())
.await
.unwrap()
{
all_agents.push((agent.clone(), storage_arc));
}
}
}
// Spawn a background task that will run each
// cells self consistency check against the data that
// they are expected to hold.
tokio::spawn(expect_all(
tx,
timeout,
all_agents,
all_hashes,
agent_dht_map,
agent_p2p_map,
));
// Wait up to the timeout for all the agents to report success.
wait_for_consistency(rx, wait_for_agents, timeout).await;
}
sourcepub fn get_dht_db_cache(
&self,
dna_hash: &DnaHash
) -> ConductorApiResult<DhtDbQueryCache>
pub fn get_dht_db_cache(
&self,
dna_hash: &DnaHash
) -> ConductorApiResult<DhtDbQueryCache>
Examples found in repository?
47 48 49 50 51 52 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
pub async fn new(
cell_id: &CellId,
handle: &ConductorHandle,
dna_file: &DnaFile,
chc: Option<ChcImpl>,
) -> Self {
let authored_db = handle.get_authored_db(cell_id.dna_hash()).unwrap();
let dht_db = handle.get_dht_db(cell_id.dna_hash()).unwrap();
let dht_db_cache = handle.get_dht_db_cache(cell_id.dna_hash()).unwrap();
let cache = handle.get_cache_db(cell_id).unwrap();
let keystore = handle.keystore().clone();
let network = handle
.holochain_p2p()
.to_dna(cell_id.dna_hash().clone(), chc);
let triggers = handle.get_cell_triggers(cell_id).unwrap();
let cell_conductor_api = CellConductorApi::new(handle.clone(), cell_id.clone());
let ribosome = handle.get_ribosome(dna_file.dna_hash()).unwrap();
let signal_tx = handle.signal_broadcaster();
CellHostFnCaller {
cell_id: cell_id.clone(),
authored_db,
dht_db,
dht_db_cache,
cache,
ribosome,
network,
keystore,
signal_tx,
triggers,
cell_conductor_api,
}
}
More examples
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
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(())
}
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
pub async fn create_for_zome(
cell_id: &CellId,
handle: &ConductorHandle,
dna_file: &DnaFile,
zome_index: usize,
) -> HostFnCaller {
let authored_db = handle.get_authored_db(cell_id.dna_hash()).unwrap();
let dht_db = handle.get_dht_db(cell_id.dna_hash()).unwrap();
let dht_db_cache = handle.get_dht_db_cache(cell_id.dna_hash()).unwrap();
let cache = handle.get_cache_db(cell_id).unwrap();
let keystore = handle.keystore().clone();
let network = handle
.holochain_p2p()
.to_dna(cell_id.dna_hash().clone(), None);
let zome_path = (
cell_id.clone(),
dna_file
.dna()
.integrity_zomes
.get(zome_index)
.unwrap()
.0
.clone(),
)
.into();
let ribosome = handle.get_ribosome(dna_file.dna_hash()).unwrap();
let signal_tx = handle.signal_broadcaster();
let call_zome_handle =
CellConductorApi::new(handle.clone(), cell_id.clone()).into_call_zome_handle();
HostFnCaller {
authored_db,
dht_db,
dht_db_cache,
cache,
ribosome,
zome_path,
network,
keystore,
signal_tx,
call_zome_handle,
}
}
sourcepub fn get_cache_db(
&self,
cell_id: &CellId
) -> ConductorApiResult<DbWrite<DbKindCache>>
pub fn get_cache_db(
&self,
cell_id: &CellId
) -> ConductorApiResult<DbWrite<DbKindCache>>
Examples found in repository?
47 48 49 50 51 52 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
pub async fn new(
cell_id: &CellId,
handle: &ConductorHandle,
dna_file: &DnaFile,
chc: Option<ChcImpl>,
) -> Self {
let authored_db = handle.get_authored_db(cell_id.dna_hash()).unwrap();
let dht_db = handle.get_dht_db(cell_id.dna_hash()).unwrap();
let dht_db_cache = handle.get_dht_db_cache(cell_id.dna_hash()).unwrap();
let cache = handle.get_cache_db(cell_id).unwrap();
let keystore = handle.keystore().clone();
let network = handle
.holochain_p2p()
.to_dna(cell_id.dna_hash().clone(), chc);
let triggers = handle.get_cell_triggers(cell_id).unwrap();
let cell_conductor_api = CellConductorApi::new(handle.clone(), cell_id.clone());
let ribosome = handle.get_ribosome(dna_file.dna_hash()).unwrap();
let signal_tx = handle.signal_broadcaster();
CellHostFnCaller {
cell_id: cell_id.clone(),
authored_db,
dht_db,
dht_db_cache,
cache,
ribosome,
network,
keystore,
signal_tx,
triggers,
cell_conductor_api,
}
}
More examples
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
pub async fn create_for_zome(
cell_id: &CellId,
handle: &ConductorHandle,
dna_file: &DnaFile,
zome_index: usize,
) -> HostFnCaller {
let authored_db = handle.get_authored_db(cell_id.dna_hash()).unwrap();
let dht_db = handle.get_dht_db(cell_id.dna_hash()).unwrap();
let dht_db_cache = handle.get_dht_db_cache(cell_id.dna_hash()).unwrap();
let cache = handle.get_cache_db(cell_id).unwrap();
let keystore = handle.keystore().clone();
let network = handle
.holochain_p2p()
.to_dna(cell_id.dna_hash().clone(), None);
let zome_path = (
cell_id.clone(),
dna_file
.dna()
.integrity_zomes
.get(zome_index)
.unwrap()
.0
.clone(),
)
.into();
let ribosome = handle.get_ribosome(dna_file.dna_hash()).unwrap();
let signal_tx = handle.signal_broadcaster();
let call_zome_handle =
CellConductorApi::new(handle.clone(), cell_id.clone()).into_call_zome_handle();
HostFnCaller {
authored_db,
dht_db,
dht_db_cache,
cache,
ribosome,
zome_path,
network,
keystore,
signal_tx,
call_zome_handle,
}
}
sourcepub fn get_p2p_db(&self, space: &DnaHash) -> DbWrite<DbKindP2pAgents>
pub fn get_p2p_db(&self, space: &DnaHash) -> DbWrite<DbKindP2pAgents>
Examples found in repository?
More examples
40 41 42 43 44 45 46 47 48 49 50 51 52 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
pub async fn local_machine_session(conductors: &[ConductorHandle], timeout: Duration) {
// For each space get all the cells, their db and the p2p envs.
let mut spaces = HashMap::new();
for (i, c) in conductors.iter().enumerate() {
for cell_id in c.list_cell_ids(None) {
let space = spaces
.entry(cell_id.dna_hash().clone())
.or_insert_with(|| vec![None; conductors.len()]);
if space[i].is_none() {
let p2p_agents_db: DbRead<DbKindP2pAgents> =
c.get_p2p_db(cell_id.dna_hash()).into();
space[i] = Some((p2p_agents_db, Vec::new()));
}
space[i].as_mut().unwrap().1.push((
c.get_authored_db(cell_id.dna_hash()).unwrap().into(),
c.get_dht_db(cell_id.dna_hash()).unwrap().into(),
cell_id.agent_pubkey().to_kitsune(),
));
}
}
// Run a consistency session for each space.
for (_, conductors) in spaces {
// The agents we need to wait for.
let mut wait_for_agents = HashSet::new();
// Maps to environments.
let mut agent_dht_map = HashMap::new();
let mut agent_p2p_map = HashMap::new();
// All the agents that should be held.
let mut all_agents = Vec::new();
// All the op hashes that should be held.
let mut all_hashes = Vec::new();
let (tx, rx) = tokio::sync::mpsc::channel(1000);
// Gather the expected agents and op hashes from each conductor.
for (p2p_agents_db, agents) in conductors.into_iter().flatten() {
wait_for_agents.extend(agents.iter().map(|(_, _, agent)| agent.clone()));
agent_dht_map.extend(agents.iter().cloned().map(|(_, dht, agent)| (agent, dht)));
agent_p2p_map.extend(
agents
.iter()
.cloned()
.map(|(_, _, a)| (a, p2p_agents_db.clone())),
);
let (a, h) = gather_conductor_data(p2p_agents_db, agents).await;
all_agents.extend(a);
all_hashes.extend(h);
}
// Spawn a background task that will run each
// cells self consistency check against the data that
// they are expected to hold.
tokio::spawn(expect_all(
tx,
timeout,
all_agents,
all_hashes,
agent_dht_map,
agent_p2p_map,
));
// Wait up to the timeout for all the agents to report success.
wait_for_consistency(rx, wait_for_agents, timeout).await;
}
}
/// Get consistency for a particular hash.
pub async fn local_machine_session_with_hashes(
handles: Vec<&ConductorHandle>,
hashes: impl Iterator<Item = (DhtLocation, DhtOpHash)>,
space: &DnaHash,
timeout: Duration,
) {
// Grab the environments and cells for each conductor in this space.
let mut conductors = vec![None; handles.len()];
for (i, c) in handles.iter().enumerate() {
for cell_id in c.list_cell_ids(None) {
if cell_id.dna_hash() != space {
continue;
}
if conductors[i].is_none() {
let p2p_agents_db: DbRead<DbKindP2pAgents> =
c.get_p2p_db(cell_id.dna_hash()).into();
conductors[i] = Some((p2p_agents_db, Vec::new()));
}
conductors[i].as_mut().unwrap().1.push((
c.get_dht_db(cell_id.dna_hash()).unwrap().into(),
cell_id.agent_pubkey().to_kitsune(),
));
}
}
// Convert the hashes to kitsune.
let all_hashes = hashes
.into_iter()
.map(|(l, h)| (l, h.into_kitsune_raw()))
.collect::<Vec<_>>();
// The agents we need to wait for.
let mut wait_for_agents = HashSet::new();
// Maps to environments.
let mut agent_dht_map = HashMap::new();
let mut agent_p2p_map = HashMap::new();
// All the agents that should be held.
let mut all_agents = Vec::new();
let (tx, rx) = tokio::sync::mpsc::channel(1000);
// Gather the expected agents from each conductor.
for (p2p_agents_db, agents) in conductors.into_iter().flatten() {
wait_for_agents.extend(agents.iter().map(|(_, agent)| agent.clone()));
agent_dht_map.extend(agents.iter().cloned().map(|(e, a)| (a, e)));
agent_p2p_map.extend(
agents
.iter()
.cloned()
.map(|(_, a)| (a, p2p_agents_db.clone())),
);
for (_, agent) in &agents {
if let Some(storage_arc) = request_arc(&p2p_agents_db, (**agent).clone())
.await
.unwrap()
{
all_agents.push((agent.clone(), storage_arc));
}
}
}
// Spawn a background task that will run each
// cells self consistency check against the data that
// they are expected to hold.
tokio::spawn(expect_all(
tx,
timeout,
all_agents,
all_hashes,
agent_dht_map,
agent_p2p_map,
));
// Wait up to the timeout for all the agents to report success.
wait_for_consistency(rx, wait_for_agents, timeout).await;
}
pub fn get_p2p_metrics_db(&self, space: &DnaHash) -> DbWrite<DbKindP2pMetrics>
pub fn get_spaces(&self) -> Spaces
sourcepub fn get_cell_triggers(
&self,
cell_id: &CellId
) -> ConductorApiResult<QueueTriggers>
pub fn get_cell_triggers(
&self,
cell_id: &CellId
) -> ConductorApiResult<QueueTriggers>
Examples found in repository?
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
pub async fn force_all_publish_dht_ops(&self) {
use futures::stream::StreamExt;
if let Some(handle) = self.handle.as_ref() {
let iter = handle.list_cell_ids(None).into_iter().map(|id| async {
let id = id;
let db = self.get_authored_db(id.dna_hash()).unwrap();
let trigger = self.get_cell_triggers(&id).unwrap();
(db, trigger)
});
futures::stream::iter(iter)
.then(|f| f)
.for_each(|(db, mut triggers)| async move {
// The line below was added when migrating to rust edition 2021, per
// https://doc.rust-lang.org/edition-guide/rust-2021/disjoint-capture-in-closures.html#migration
let _ = &triggers;
crate::test_utils::force_publish_dht_ops(&db, &mut triggers.publish_dht_ops)
.await
.unwrap();
})
.await;
}
}
More examples
47 48 49 50 51 52 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
pub async fn new(
cell_id: &CellId,
handle: &ConductorHandle,
dna_file: &DnaFile,
chc: Option<ChcImpl>,
) -> Self {
let authored_db = handle.get_authored_db(cell_id.dna_hash()).unwrap();
let dht_db = handle.get_dht_db(cell_id.dna_hash()).unwrap();
let dht_db_cache = handle.get_dht_db_cache(cell_id.dna_hash()).unwrap();
let cache = handle.get_cache_db(cell_id).unwrap();
let keystore = handle.keystore().clone();
let network = handle
.holochain_p2p()
.to_dna(cell_id.dna_hash().clone(), chc);
let triggers = handle.get_cell_triggers(cell_id).unwrap();
let cell_conductor_api = CellConductorApi::new(handle.clone(), cell_id.clone());
let ribosome = handle.get_ribosome(dna_file.dna_hash()).unwrap();
let signal_tx = handle.signal_broadcaster();
CellHostFnCaller {
cell_id: cell_id.clone(),
authored_db,
dht_db,
dht_db_cache,
cache,
ribosome,
network,
keystore,
signal_tx,
triggers,
cell_conductor_api,
}
}
source§impl Conductor
impl Conductor
sourcepub fn builder() -> ConductorBuilder
pub fn builder() -> ConductorBuilder
Create a conductor builder
Examples found in repository?
133 134 135 136 137 138 139 140 141 142 143 144 145 146
pub async fn handle_from_existing(
db_dir: &Path,
keystore: MetaLairClient,
config: &ConductorConfig,
extra_dnas: &[DnaFile],
) -> ConductorHandle {
Conductor::builder()
.config(config.clone())
.with_keystore(keystore)
.no_print_setup()
.test(db_dir, extra_dnas)
.await
.unwrap()
}
Auto Trait Implementations§
impl !RefUnwindSafe for Conductor
impl Send for Conductor
impl Sync for Conductor
impl Unpin for Conductor
impl !UnwindSafe for Conductor
Blanket Implementations§
§impl<T> Any for Twhere
T: Any + ?Sized,
impl<T> Any for Twhere
T: Any + ?Sized,
§fn type_id_compat(&self) -> TypeId
fn type_id_compat(&self) -> TypeId
§impl<T> ArchivePointee for T
impl<T> ArchivePointee for T
§type ArchivedMetadata = ()
type ArchivedMetadata = ()
§fn pointer_metadata(
_: &<T as ArchivePointee>::ArchivedMetadata
) -> <T as Pointee>::Metadata
fn pointer_metadata(
_: &<T as ArchivePointee>::ArchivedMetadata
) -> <T as Pointee>::Metadata
§impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere
W: DeserializeWith<F, T, D>,
D: Fallible + ?Sized,
F: ?Sized,
impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere
W: DeserializeWith<F, T, D>,
D: Fallible + ?Sized,
F: ?Sized,
§fn deserialize(
&self,
deserializer: &mut D
) -> Result<With<T, W>, <D as Fallible>::Error>
fn deserialize(
&self,
deserializer: &mut D
) -> Result<With<T, W>, <D as Fallible>::Error>
§impl<T> FutureExt for T
impl<T> FutureExt for T
§fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
§fn with_current_context(self) -> WithContext<Self> ⓘ
fn with_current_context(self) -> WithContext<Self> ⓘ
source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
§impl<T> Pointable for T
impl<T> Pointable for T
§impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
§fn to_subset(&self) -> Option<SS>
fn to_subset(&self) -> Option<SS>
self
from the equivalent element of its
superset. Read more§fn is_in_subset(&self) -> bool
fn is_in_subset(&self) -> bool
self
is actually part of its subset T
(and can be converted to it).§fn to_subset_unchecked(&self) -> SS
fn to_subset_unchecked(&self) -> SS
self.to_subset
but without any property checks. Always succeeds.§fn from_subset(element: &SS) -> SP
fn from_subset(element: &SS) -> SP
self
to the equivalent element of its superset.