Struct holochain::conductor::ribosome_store::RibosomeStore
source · pub struct RibosomeStore { /* private fields */ }
Implementations§
source§impl RibosomeStore
impl RibosomeStore
pub fn new() -> RwShare<Self>
pub fn add_dna(&mut self, dna: DnaFile) -> RibosomeResult<()>
sourcepub fn add_ribosome(&mut self, ribosome: RealRibosome)
pub fn add_ribosome(&mut self, ribosome: RealRibosome)
Examples found in repository?
src/conductor/conductor.rs (line 595)
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026
pub(crate) fn add_ribosome_to_store(&self, ribosome: RealRibosome) {
self.ribosome_store.share_mut(|d| d.add_ribosome(ribosome));
}
pub(crate) async fn load_wasms_into_dna_files(
&self,
) -> ConductorResult<(
impl IntoIterator<Item = (DnaHash, RealRibosome)>,
impl IntoIterator<Item = (EntryDefBufferKey, EntryDef)>,
)> {
let db = &self.spaces.wasm_db;
// Load out all dna defs
let (wasm_tasks, defs) = db
.async_reader(move |txn| {
// Get all the dna defs.
let dna_defs: Vec<_> = holochain_state::dna_def::get_all(&txn)?
.into_iter()
.collect();
// Gather all the unique wasms.
let unique_wasms = dna_defs
.iter()
.flat_map(|dna_def| {
dna_def
.all_zomes()
.map(|(zome_name, zome)| Ok(zome.wasm_hash(zome_name)?))
})
.collect::<ConductorResult<HashSet<_>>>()?;
// Get the code for each unique wasm.
let wasms = unique_wasms
.into_iter()
.map(|wasm_hash| {
holochain_state::wasm::get(&txn, &wasm_hash)?
.map(|hashed| hashed.into_content())
.ok_or(ConductorError::WasmMissing)
.map(|wasm| (wasm_hash, wasm))
})
.collect::<ConductorResult<HashMap<_, _>>>()?;
let wasm_tasks = holochain_state::dna_def::get_all(&txn)?
.into_iter()
.map(|dna_def| {
// Load all wasms for each dna_def from the wasm db into memory
let wasms = dna_def.all_zomes().filter_map(|(zome_name, zome)| {
let wasm_hash = zome.wasm_hash(zome_name).ok()?;
// Note this is a cheap arc clone.
wasms.get(&wasm_hash).cloned()
});
let wasms = wasms.collect::<Vec<_>>();
async move {
let dna_file = DnaFile::new(dna_def.into_content(), wasms).await;
let ribosome = RealRibosome::new(dna_file)?;
ConductorResult::Ok((ribosome.dna_hash().clone(), ribosome))
}
})
// This needs to happen due to the environment not being Send
.collect::<Vec<_>>();
let defs = holochain_state::entry_def::get_all(&txn)?;
ConductorResult::Ok((wasm_tasks, defs))
})
.await?;
// try to join all the tasks and return the list of dna files
let dnas = futures::future::try_join_all(wasm_tasks).await?;
Ok((dnas, defs))
}
/// Get the root environment directory.
pub fn root_db_dir(&self) -> &DatabaseRootPath {
&self.spaces.db_dir
}
/// Get the keystore.
pub fn keystore(&self) -> &MetaLairClient {
&self.keystore
}
/// Get a reference to the conductor's HolochainP2p.
pub fn holochain_p2p(&self) -> &holochain_p2p::HolochainP2pRef {
&self.holochain_p2p
}
/// Remove cells from the cell map in the Conductor
pub(crate) async fn remove_cells(&self, cell_ids: &[CellId]) {
let to_cleanup: Vec<_> = self.running_cells.share_mut(|cells| {
cell_ids
.iter()
.filter_map(|cell_id| cells.remove(cell_id).map(|c| (cell_id, c)))
.collect()
});
for (cell_id, item) in to_cleanup {
if let Err(err) = item.cell.cleanup().await {
tracing::error!("Error cleaning up Cell: {:?}\nCellId: {}", err, cell_id);
}
}
}
/// Restart every paused app
pub(crate) async fn start_paused_apps(&self) -> ConductorResult<AppStatusFx> {
let (_, delta) = self
.update_state_prime(|mut state| {
let ids = state.paused_apps().map(first).cloned().collect::<Vec<_>>();
if !ids.is_empty() {
tracing::info!("Restarting {} paused apps: {:#?}", ids.len(), ids);
}
let deltas: Vec<AppStatusFx> = ids
.into_iter()
.map(|id| {
state
.transition_app_status(&id, AppStatusTransition::Start)
.map(second)
})
.collect::<Result<Vec<_>, _>>()?;
let delta = deltas
.into_iter()
.fold(AppStatusFx::default(), AppStatusFx::combine);
Ok((state, delta))
})
.await?;
Ok(delta)
}
pub(crate) async fn put_wasm(
&self,
ribosome: RealRibosome,
) -> ConductorResult<Vec<(EntryDefBufferKey, EntryDef)>> {
let dna_def = ribosome.dna_def().clone();
let code = ribosome
.dna_file()
.code()
.clone()
.into_iter()
.map(|(_, c)| c);
let zome_defs = get_entry_defs(ribosome).await?;
self.put_wasm_code(dna_def, code, zome_defs).await
}
pub(crate) async fn put_wasm_code(
&self,
dna: DnaDefHashed,
code: impl Iterator<Item = wasm::DnaWasm>,
zome_defs: Vec<(EntryDefBufferKey, EntryDef)>,
) -> ConductorResult<Vec<(EntryDefBufferKey, EntryDef)>> {
// TODO: PERF: This loop might be slow
let wasms = futures::future::join_all(code.map(DnaWasmHashed::from_content)).await;
self.spaces
.wasm_db
.async_commit({
let zome_defs = zome_defs.clone();
move |txn| {
for dna_wasm in wasms {
if !holochain_state::wasm::contains(txn, dna_wasm.as_hash())? {
holochain_state::wasm::put(txn, dna_wasm)?;
}
}
for (key, entry_def) in zome_defs.clone() {
holochain_state::entry_def::put(txn, key, &entry_def)?;
}
if !holochain_state::dna_def::contains(txn, dna.as_hash())? {
holochain_state::dna_def::put(txn, dna.into_content())?;
}
StateMutationResult::Ok(())
}
})
.await?;
Ok(zome_defs)
}
pub(crate) async fn load_dnas(&self) -> ConductorResult<()> {
let (ribosomes, entry_defs) = self.load_wasms_into_dna_files().await?;
self.ribosome_store().share_mut(|ds| {
ds.add_ribosomes(ribosomes);
ds.add_entry_defs(entry_defs);
});
Ok(())
}
/// Install a [`DnaFile`](holochain_types::dna::DnaFile) in this Conductor
pub async fn register_dna(&self, dna: DnaFile) -> ConductorResult<()> {
let ribosome = RealRibosome::new(dna)?;
let entry_defs = self.register_dna_wasm(ribosome.clone()).await?;
self.register_dna_entry_defs(entry_defs);
self.add_ribosome_to_store(ribosome);
Ok(())
}
}
}
/// Network-related methods
mod network_impls {
use holochain_conductor_api::NetworkInfo;
use holochain_p2p::HolochainP2pSender;
use super::*;
impl Conductor {
/// Get signed agent info from the conductor
pub async fn get_agent_infos(
&self,
cell_id: Option<CellId>,
) -> ConductorApiResult<Vec<AgentInfoSigned>> {
match cell_id {
Some(c) => {
let (d, a) = c.into_dna_and_agent();
let db = self.p2p_agents_db(&d);
Ok(get_single_agent_info(db.into(), d, a)
.await?
.map(|a| vec![a])
.unwrap_or_default())
}
None => {
let mut out = Vec::new();
// collecting so the mutex lock can close
let envs = self.spaces.get_from_spaces(|s| s.p2p_agents_db.clone());
for db in envs {
out.append(&mut all_agent_infos(db.into()).await?);
}
Ok(out)
}
}
}
pub(crate) async fn prune_p2p_agents_db(&self) -> ConductorResult<()> {
use holochain_p2p::AgentPubKeyExt;
let mut space_to_agents = HashMap::new();
for cell in self.running_cells.share_ref(|c| {
<Result<_, one_err::OneErr>>::Ok(c.keys().cloned().collect::<Vec<_>>())
})? {
space_to_agents
.entry(cell.dna_hash().clone())
.or_insert_with(Vec::new)
.push(cell.agent_pubkey().to_kitsune());
}
for (space, agents) in space_to_agents {
let db = self.spaces.p2p_agents_db(&space)?;
p2p_prune(&db, agents).await?;
}
Ok(())
}
pub(crate) async fn network_info(
&self,
dnas: &[DnaHash],
) -> ConductorResult<Vec<NetworkInfo>> {
futures::future::join_all(dnas.iter().map(|dna| async move {
let d = self.holochain_p2p.get_diagnostics(dna.clone()).await?;
let fetch_queue_info = d.fetch_queue.info([dna.to_kitsune()].into_iter().collect());
ConductorResult::Ok(NetworkInfo { fetch_queue_info })
}))
.await
.into_iter()
.collect::<Result<Vec<_>, _>>()
}
#[instrument(skip(self))]
pub(crate) async fn dispatch_holochain_p2p_event(
&self,
event: holochain_p2p::event::HolochainP2pEvent,
) -> ConductorApiResult<()> {
use HolochainP2pEvent::*;
let dna_hash = event.dna_hash().clone();
trace!(dispatch_event = ?event);
match event {
PutAgentInfoSigned {
peer_data, respond, ..
} => {
let sender = self.p2p_batch_sender(&dna_hash);
let (result_sender, response) = tokio::sync::oneshot::channel();
let _ = sender
.send(P2pBatch {
peer_data,
result_sender,
})
.await;
let res = match response.await {
Ok(r) => r.map_err(holochain_p2p::HolochainP2pError::other),
Err(e) => Err(holochain_p2p::HolochainP2pError::other(e)),
};
respond.respond(Ok(async move { res }.boxed().into()));
}
QueryAgentInfoSigned {
kitsune_space,
agents,
respond,
..
} => {
let db = { self.p2p_agents_db(&dna_hash) };
let res = list_all_agent_info(db.into(), kitsune_space)
.await
.map(|infos| match agents {
Some(agents) => infos
.into_iter()
.filter(|info| agents.contains(&info.agent))
.collect(),
None => infos,
})
.map_err(holochain_p2p::HolochainP2pError::other);
respond.respond(Ok(async move { res }.boxed().into()));
}
QueryGossipAgents {
since_ms,
until_ms,
arc_set,
respond,
..
} => {
use holochain_sqlite::db::AsP2pAgentStoreConExt;
let db = { self.p2p_agents_db(&dna_hash) };
let permit = db.conn_permit().await;
let res = tokio::task::spawn_blocking(move || {
let mut conn = db.with_permit(permit)?;
conn.p2p_gossip_query_agents(since_ms, until_ms, (*arc_set).clone())
})
.await;
let res = res
.map_err(holochain_p2p::HolochainP2pError::other)
.and_then(|r| r.map_err(holochain_p2p::HolochainP2pError::other));
respond.respond(Ok(async move { res }.boxed().into()));
}
QueryAgentInfoSignedNearBasis {
kitsune_space,
basis_loc,
limit,
respond,
..
} => {
let db = { self.p2p_agents_db(&dna_hash) };
let res = list_all_agent_info_signed_near_basis(
db.into(),
kitsune_space,
basis_loc,
limit,
)
.await
.map_err(holochain_p2p::HolochainP2pError::other);
respond.respond(Ok(async move { res }.boxed().into()));
}
QueryPeerDensity {
kitsune_space,
dht_arc,
respond,
..
} => {
let cutoff = self
.get_config()
.network
.clone()
.unwrap_or_default()
.tuning_params
.danger_gossip_recent_threshold();
let topo = self
.get_dna_def(&dna_hash)
.ok_or_else(|| DnaError::DnaMissing(dna_hash.clone()))?
.topology(cutoff);
let db = { self.p2p_agents_db(&dna_hash) };
let res = query_peer_density(db.into(), topo, kitsune_space, dht_arc)
.await
.map_err(holochain_p2p::HolochainP2pError::other);
respond.respond(Ok(async move { res }.boxed().into()));
}
SignNetworkData {
respond,
to_agent,
data,
..
} => {
let signature = to_agent.sign_raw(self.keystore(), data.into()).await?;
respond.respond(Ok(async move { Ok(signature) }.boxed().into()));
}
HolochainP2pEvent::CallRemote { .. }
| CountersigningSessionNegotiation { .. }
| Get { .. }
| GetMeta { .. }
| GetLinks { .. }
| GetAgentActivity { .. }
| MustGetAgentActivity { .. }
| ValidationReceiptReceived { .. } => {
let cell_id =
CellId::new(event.dna_hash().clone(), event.target_agents().clone());
let cell = self.cell_by_id(&cell_id)?;
cell.handle_holochain_p2p_event(event).await?;
}
Publish {
dna_hash,
respond,
request_validation_receipt,
countersigning_session,
ops,
..
} => {
async {
let res = self
.spaces
.handle_publish(
&dna_hash,
request_validation_receipt,
countersigning_session,
ops,
)
.await
.map_err(holochain_p2p::HolochainP2pError::other);
respond.respond(Ok(async move { res }.boxed().into()));
}
.instrument(debug_span!("handle_publish"))
.await;
}
FetchOpData {
respond,
query,
dna_hash,
..
} => {
async {
let res = self
.spaces
.handle_fetch_op_data(&dna_hash, query)
.await
.map_err(holochain_p2p::HolochainP2pError::other);
respond.respond(Ok(async move { res }.boxed().into()));
}
.instrument(debug_span!("handle_fetch_op_data"))
.await;
}
HolochainP2pEvent::QueryOpHashes {
dna_hash,
window,
max_ops,
include_limbo,
arc_set,
respond,
..
} => {
let res = self
.spaces
.handle_query_op_hashes(&dna_hash, arc_set, window, max_ops, include_limbo)
.await
.map_err(holochain_p2p::HolochainP2pError::other);
respond.respond(Ok(async move { res }.boxed().into()));
}
}
Ok(())
}
/// Invoke a zome function on a Cell
pub async fn call_zome(&self, call: ZomeCall) -> ConductorApiResult<ZomeCallResult> {
let cell = self.cell_by_id(&call.cell_id)?;
Ok(cell.call_zome(call, None).await?)
}
pub(crate) async fn call_zome_with_workspace(
&self,
call: ZomeCall,
workspace_lock: SourceChainWorkspace,
) -> ConductorApiResult<ZomeCallResult> {
debug!(cell_id = ?call.cell_id);
let cell = self.cell_by_id(&call.cell_id)?;
Ok(cell.call_zome(call, Some(workspace_lock)).await?)
}
}
}
/// Methods related to app installation and management
mod app_impls {
use super::*;
impl Conductor {
pub(crate) async fn install_app(
self: Arc<Self>,
installed_app_id: InstalledAppId,
cell_data: Vec<(InstalledCell, Option<MembraneProof>)>,
) -> ConductorResult<()> {
crate::conductor::conductor::genesis_cells(
self.clone(),
cell_data
.iter()
.map(|(c, p)| (c.as_id().clone(), p.clone()))
.collect(),
)
.await?;
let cell_data = cell_data.into_iter().map(|(c, _)| c);
let app = InstalledAppCommon::new_legacy(installed_app_id, cell_data)?;
// Update the db
let _ = self.add_disabled_app_to_db(app).await?;
Ok(())
}
/// Install DNAs and set up Cells as specified by an AppBundle
pub async fn install_app_bundle(
self: Arc<Self>,
payload: InstallAppPayload,
) -> ConductorResult<StoppedApp> {
let InstallAppPayload {
source,
agent_key,
installed_app_id,
membrane_proofs,
network_seed,
} = payload;
let bundle: AppBundle = {
let original_bundle = source.resolve().await?;
if let Some(network_seed) = network_seed {
let mut manifest = original_bundle.manifest().to_owned();
manifest.set_network_seed(network_seed);
AppBundle::from(original_bundle.into_inner().update_manifest(manifest)?)
} else {
original_bundle
}
};
let installed_app_id =
installed_app_id.unwrap_or_else(|| bundle.manifest().app_name().to_owned());
let ops = bundle
.resolve_cells(agent_key.clone(), DnaGamut::placeholder(), membrane_proofs)
.await?;
let cells_to_create = ops.cells_to_create();
for (dna, _) in ops.dnas_to_register {
self.clone().register_dna(dna).await?;
}
crate::conductor::conductor::genesis_cells(self.clone(), cells_to_create).await?;
let roles = ops.role_assignments;
let app = InstalledAppCommon::new(installed_app_id, agent_key, roles)?;
// Update the db
let stopped_app = self.add_disabled_app_to_db(app).await?;
Ok(stopped_app)
}
/// Uninstall an app
#[tracing::instrument(skip(self))]
pub async fn uninstall_app(
self: Arc<Self>,
installed_app_id: &InstalledAppId,
) -> ConductorResult<()> {
let self_clone = self.clone();
let app = self.remove_app_from_db(installed_app_id).await?;
tracing::debug!(msg = "Removed app from db.", app = ?app);
// Remove cells which may now be dangling due to the removed app
self_clone
.process_app_status_fx(AppStatusFx::SpinDown, None)
.await?;
Ok(())
}
/// List active AppIds
pub async fn list_running_apps(&self) -> ConductorResult<Vec<InstalledAppId>> {
let state = self.get_state().await?;
Ok(state.running_apps().map(|(id, _)| id).cloned().collect())
}
/// List Apps with their information
pub async fn list_apps(
&self,
status_filter: Option<AppStatusFilter>,
) -> ConductorResult<Vec<AppInfo>> {
use AppStatusFilter::*;
let conductor_state = self.get_state().await?;
let apps_ids: Vec<&String> = match status_filter {
Some(Enabled) => conductor_state.enabled_apps().map(|(id, _)| id).collect(),
Some(Disabled) => conductor_state.disabled_apps().map(|(id, _)| id).collect(),
Some(Running) => conductor_state.running_apps().map(|(id, _)| id).collect(),
Some(Stopped) => conductor_state.stopped_apps().map(|(id, _)| id).collect(),
Some(Paused) => conductor_state.paused_apps().map(|(id, _)| id).collect(),
None => conductor_state.installed_apps().keys().collect(),
};
let app_infos: Vec<AppInfo> = apps_ids
.into_iter()
.map(|app_id| self.get_app_info_inner(app_id, &conductor_state))
.collect::<Result<Vec<_>, _>>()?
.into_iter()
.flatten()
.collect();
Ok(app_infos)
}
/// Get the IDs of all active installed Apps which use this Cell
pub async fn list_running_apps_for_dependent_cell_id(
&self,
cell_id: &CellId,
) -> ConductorResult<HashSet<InstalledAppId>> {
Ok(self
.get_state()
.await?
.running_apps()
.filter(|(_, v)| v.all_cells().any(|i| i == cell_id))
.map(|(k, _)| k)
.cloned()
.collect())
}
/// Find the ID of the first active installed App which uses this Cell
pub async fn find_cell_with_role_alongside_cell(
&self,
cell_id: &CellId,
role_name: &RoleName,
) -> ConductorResult<Option<CellId>> {
Ok(self
.get_state()
.await?
.running_apps()
.find(|(_, running_app)| running_app.all_cells().any(|i| i == cell_id))
.and_then(|(_, running_app)| {
running_app
.into_common()
.role(role_name)
.ok()
.map(|role| role.cell_id())
.cloned()
}))
}
/// Get the IDs of all active installed Apps which use this Dna
pub async fn list_running_apps_for_dependent_dna_hash(
&self,
dna_hash: &DnaHash,
) -> ConductorResult<HashSet<InstalledAppId>> {
Ok(self
.get_state()
.await?
.running_apps()
.filter(|(_, v)| v.all_cells().any(|i| i.dna_hash() == dna_hash))
.map(|(k, _)| k)
.cloned()
.collect())
}
/// Get info about an installed App, regardless of status
pub async fn get_app_info(
&self,
installed_app_id: &InstalledAppId,
) -> ConductorResult<Option<AppInfo>> {
let state = self.get_state().await?;
let maybe_app_info = self.get_app_info_inner(installed_app_id, &state)?;
Ok(maybe_app_info)
}
fn get_app_info_inner(
&self,
app_id: &InstalledAppId,
state: &ConductorState,
) -> ConductorResult<Option<AppInfo>> {
match state.installed_apps().get(app_id) {
None => Ok(None),
Some(app) => {
let dna_definitions = self.get_dna_definitions(app)?;
Ok(Some(AppInfo::from_installed_app(app, &dna_definitions)))
}
}
}
}
}
/// Methods related to cell access
mod cell_impls {
use super::*;
impl Conductor {
pub(crate) fn cell_by_id(&self, cell_id: &CellId) -> ConductorResult<Arc<Cell>> {
let cell = self
.running_cells
.share_ref(|c| c.get(cell_id).map(|i| i.cell.clone()))
.ok_or_else(|| ConductorError::CellMissing(cell_id.clone()))?;
Ok(cell)
}
/// Iterator over only the cells which are fully running. Generally used
/// to handle conductor interface requests
pub fn running_cell_ids(&self) -> HashSet<CellId> {
self.running_cells.share_ref(|c| {
c.iter()
.filter_map(|(id, item)| {
if item.is_running() {
Some(id.clone())
} else {
None
}
})
.collect()
})
}
/// List CellIds for Cells which match a status filter
pub fn list_cell_ids(&self, filter: Option<CellStatusFilter>) -> Vec<CellId> {
self.running_cells.share_ref(|cells| {
cells
.iter()
.filter_map(|(id, cell)| {
let matches = filter
.as_ref()
.map(|status| cell.status == *status)
.unwrap_or(true);
if matches {
Some(id)
} else {
None
}
})
.cloned()
.collect()
})
}
}
}
/// Methods related to clone cell management
mod clone_cell_impls {
use super::*;
impl Conductor {
/// Create a new cell in an existing app based on an existing DNA.
///
/// # Returns
///
/// A struct with the created cell's clone id and cell id.
pub async fn create_clone_cell(
self: Arc<Self>,
payload: CreateCloneCellPayload,
) -> ConductorResult<InstalledCell> {
let CreateCloneCellPayload {
app_id,
role_name,
modifiers,
membrane_proof,
name,
} = payload;
if !modifiers.has_some_option_set() {
return Err(ConductorError::CloneCellError(
"neither network_seed nor properties nor origin_time provided for clone cell"
.to_string(),
));
}
let state = self.get_state().await?;
let app = state.get_app(&app_id)?;
app.provisioned_cells()
.find(|(app_role_name, _)| **app_role_name == role_name)
.ok_or_else(|| {
ConductorError::CloneCellError(
"no base cell found for provided role id".to_string(),
)
})?;
// add cell to app
let installed_clone_cell = self
.add_clone_cell_to_app(
app_id.clone(),
role_name.clone(),
modifiers.serialized()?,
name,
)
.await?;
// run genesis on cloned cell
let cells = vec![(installed_clone_cell.as_id().clone(), membrane_proof)];
crate::conductor::conductor::genesis_cells(self.clone(), cells).await?;
self.create_and_add_initialized_cells_for_running_apps(Some(&app_id))
.await?;
Ok(installed_clone_cell)
}
/// Disable a clone cell.
pub(crate) async fn disable_clone_cell(
&self,
DisableCloneCellPayload {
app_id,
clone_cell_id,
}: &DisableCloneCellPayload,
) -> ConductorResult<()> {
let (_, removed_cell_id) = self
.update_state_prime({
let app_id = app_id.to_owned();
let clone_cell_id = clone_cell_id.to_owned();
move |mut state| {
let app = state.get_app_mut(&app_id)?;
let clone_id = app.get_clone_id(&clone_cell_id)?;
let cell_id = app.get_clone_cell_id(&clone_cell_id)?;
app.disable_clone_cell(&clone_id)?;
Ok((state, cell_id))
}
})
.await?;
self.remove_cells(&[removed_cell_id]).await;
Ok(())
}
/// Enable a disabled clone cell.
pub async fn enable_clone_cell(
self: Arc<Self>,
payload: &EnableCloneCellPayload,
) -> ConductorResult<InstalledCell> {
let (_, enabled_cell) = self
.update_state_prime({
let app_id = payload.app_id.to_owned();
let clone_cell_id = payload.clone_cell_id.to_owned();
move |mut state| {
let app = state.get_app_mut(&app_id)?;
let clone_id = app.get_disabled_clone_id(&clone_cell_id)?;
let enabled_cell = app.enable_clone_cell(&clone_id)?;
Ok((state, enabled_cell))
}
})
.await?;
self.create_and_add_initialized_cells_for_running_apps(Some(&payload.app_id))
.await?;
Ok(enabled_cell)
}
/// Delete a clone cell.
pub(crate) async fn delete_clone_cell(
&self,
DeleteCloneCellPayload {
app_id,
clone_cell_id,
}: &DeleteCloneCellPayload,
) -> ConductorResult<()> {
self.update_state_prime({
let app_id = app_id.clone();
let clone_cell_id = clone_cell_id.clone();
move |mut state| {
let app = state.get_app_mut(&app_id)?;
let clone_id = app.get_disabled_clone_id(&clone_cell_id)?;
app.delete_clone_cell(&clone_id)?;
Ok((state, ()))
}
})
.await?;
self.remove_dangling_cells().await?;
Ok(())
}
}
}
/// Methods related to management of app and cell status
mod app_status_impls {
use super::*;
impl Conductor {
/// Adjust which cells are present in the Conductor (adding and removing as
/// needed) to match the current reality of all app statuses.
/// - If a Cell is used by at least one Running app, then ensure it is added
/// - If a Cell is used by no running apps, then ensure it is removed.
#[tracing::instrument(skip(self))]
pub async fn reconcile_cell_status_with_app_status(
self: Arc<Self>,
) -> ConductorResult<CellStartupErrors> {
self.remove_dangling_cells().await?;
let results = self
.create_and_add_initialized_cells_for_running_apps(None)
.await?;
Ok(results)
}
/// Enable an app
#[tracing::instrument(skip(self))]
pub async fn enable_app(
self: Arc<Self>,
app_id: InstalledAppId,
) -> ConductorResult<(InstalledApp, CellStartupErrors)> {
let (app, delta) = self
.transition_app_status(app_id.clone(), AppStatusTransition::Enable)
.await?;
let errors = self
.process_app_status_fx(delta, Some(vec![app_id.to_owned()].into_iter().collect()))
.await?;
Ok((app, errors))
}
/// Disable an app
#[tracing::instrument(skip(self))]
pub async fn disable_app(
self: Arc<Self>,
app_id: InstalledAppId,
reason: DisabledAppReason,
) -> ConductorResult<InstalledApp> {
let (app, delta) = self
.transition_app_status(app_id.clone(), AppStatusTransition::Disable(reason))
.await?;
self.process_app_status_fx(delta, Some(vec![app_id.to_owned()].into_iter().collect()))
.await?;
Ok(app)
}
/// Start an app
#[tracing::instrument(skip(self))]
pub async fn start_app(
self: Arc<Self>,
app_id: InstalledAppId,
) -> ConductorResult<InstalledApp> {
let (app, delta) = self
.transition_app_status(app_id.clone(), AppStatusTransition::Start)
.await?;
self.process_app_status_fx(delta, Some(vec![app_id.to_owned()].into_iter().collect()))
.await?;
Ok(app)
}
/// Register an app as disabled in the database
pub(crate) async fn add_disabled_app_to_db(
&self,
app: InstalledAppCommon,
) -> ConductorResult<StoppedApp> {
let (_, stopped_app) = self
.update_state_prime(move |mut state| {
let stopped_app = state.add_app(app)?;
Ok((state, stopped_app))
})
.await?;
Ok(stopped_app)
}
/// Transition an app's status to a new state.
#[tracing::instrument(skip(self))]
pub(crate) async fn transition_app_status(
&self,
app_id: InstalledAppId,
transition: AppStatusTransition,
) -> ConductorResult<(InstalledApp, AppStatusFx)> {
Ok(self
.update_state_prime(move |mut state| {
let (app, delta) = state.transition_app_status(&app_id, transition)?.clone();
let app = app.clone();
Ok((state, (app, delta)))
})
.await?
.1)
}
/// Pause an app
#[tracing::instrument(skip(self))]
#[cfg(any(test, feature = "test_utils"))]
pub async fn pause_app(
self: Arc<Self>,
app_id: InstalledAppId,
reason: PausedAppReason,
) -> ConductorResult<InstalledApp> {
let (app, delta) = self
.transition_app_status(app_id.clone(), AppStatusTransition::Pause(reason))
.await?;
self.process_app_status_fx(delta, Some(vec![app_id.clone()].into_iter().collect()))
.await?;
Ok(app)
}
/// Create any Cells which are missing for any running apps, then initialize
/// and join them. (Joining could take a while.)
pub(crate) async fn create_and_add_initialized_cells_for_running_apps(
self: Arc<Self>,
app_id: Option<&InstalledAppId>,
) -> ConductorResult<CellStartupErrors> {
let results = self.clone().create_cells_for_running_apps(app_id).await?;
let (new_cells, errors): (Vec<_>, Vec<_>) =
results.into_iter().partition(Result::is_ok);
let new_cells = new_cells
.into_iter()
// We can unwrap the successes because of the partition
.map(Result::unwrap)
.collect();
let errors = errors
.into_iter()
// throw away the non-Debug types which will be unwrapped away anyway
.map(|r| r.map(|_| ()))
// We can unwrap the errors because of the partition
.map(Result::unwrap_err)
.collect();
// Add the newly created cells to the Conductor with the PendingJoin
// status, and start their workflow loops
self.add_and_initialize_cells(new_cells);
// Join these newly created cells to the network
// (as well as any others which need joining)
self.join_all_pending_cells().await;
Ok(errors)
}
/// Attempt to join all PendingJoin cells to the kitsune network.
/// Returns the cells which were joined during this call.
///
/// NB: this could take as long as JOIN_NETWORK_TIMEOUT, which is significant.
/// Be careful to only await this future if it's important that cells be
/// joined before proceeding.
pub(crate) async fn join_all_pending_cells(&self) -> Vec<CellId> {
// Join the network but ignore errors because the
// space retries joining all cells every 5 minutes.
use holochain_p2p::AgentPubKeyExt;
let tasks = self
.mark_pending_cells_as_joining()
.into_iter()
.map(|(cell_id, cell)| async move {
let p2p_agents_db = cell.p2p_agents_db().clone();
let kagent = cell_id.agent_pubkey().to_kitsune();
let agent_info = match p2p_agents_db.async_reader(move |tx| {
tx.p2p_get_agent(&kagent)
}).await {
Ok(maybe_info) => maybe_info,
_ => None,
};
let maybe_initial_arc = agent_info.map(|i| i.storage_arc);
let network = cell.holochain_p2p_dna().clone();
match tokio::time::timeout(JOIN_NETWORK_TIMEOUT, network.join(cell_id.agent_pubkey().clone(), maybe_initial_arc)).await {
Ok(Err(e)) => {
tracing::info!(error = ?e, cell_id = ?cell_id, "Error while trying to join the network");
Err(cell_id)
}
Err(_) => {
tracing::info!(cell_id = ?cell_id, "Timed out trying to join the network");
Err(cell_id)
}
Ok(Ok(_)) => Ok(cell_id),
}
});
let maybes: Vec<_> = futures::stream::iter(tasks)
.buffer_unordered(100)
.collect()
.await;
let (cell_ids, failed_joins): (Vec<_>, Vec<_>) =
maybes.into_iter().partition(Result::is_ok);
// These unwraps are both safe because of the partition.
let cell_ids: Vec<_> = cell_ids.into_iter().map(Result::unwrap).collect();
let failed_joins: Vec<_> = failed_joins.into_iter().map(Result::unwrap_err).collect();
// Update the status of the cells which were able to join the network
// (may or may not be all cells which were added)
self.update_cell_status(cell_ids.as_slice(), CellStatus::Joined);
self.update_cell_status(failed_joins.as_slice(), CellStatus::PendingJoin);
cell_ids
}
/// Adjust app statuses (via state transitions) to match the current
/// reality of which Cells are present in the conductor.
/// - Do not change state for Disabled apps. For all others:
/// - If an app is Paused but all of its (required) Cells are on,
/// then set it to Running
/// - If an app is Running but at least one of its (required) Cells are off,
/// then set it to Paused
pub(crate) async fn reconcile_app_status_with_cell_status(
&self,
app_ids: Option<HashSet<InstalledAppId>>,
) -> ConductorResult<AppStatusFx> {
use AppStatus::*;
use AppStatusTransition::*;
let running_cells: HashSet<CellId> = self.running_cell_ids();
let (_, delta) = self
.update_state_prime(move |mut state| {
#[allow(deprecated)]
let apps = state.installed_apps_mut().iter_mut().filter(|(id, _)| {
app_ids
.as_ref()
.map(|ids| ids.contains(&**id))
.unwrap_or(true)
});
let delta = apps
.into_iter()
.map(|(_app_id, app)| {
match app.status().clone() {
Running => {
// If not all required cells are running, pause the app
let missing: Vec<_> = app
.required_cells()
.filter(|id| !running_cells.contains(id))
.collect();
if !missing.is_empty() {
let reason = PausedAppReason::Error(format!(
"Some cells are missing / not able to run: {:#?}",
missing
));
app.status.transition(Pause(reason))
} else {
AppStatusFx::NoChange
}
}
Paused(_) => {
// If all required cells are now running, restart the app
if app.required_cells().all(|id| running_cells.contains(id)) {
app.status.transition(Start)
} else {
AppStatusFx::NoChange
}
}
Disabled(_) => {
// Disabled status should never automatically change.
AppStatusFx::NoChange
}
}
})
.fold(AppStatusFx::default(), AppStatusFx::combine);
Ok((state, delta))
})
.await?;
Ok(delta)
}
/// Change the CellStatus of the given Cells in the Conductor.
/// Silently ignores Cells that don't exist.
pub(crate) fn update_cell_status(&self, cell_ids: &[CellId], status: CellStatus) {
for cell_id in cell_ids {
self.running_cells.share_mut(|cells| {
if let Some(mut cell) = cells.get_mut(cell_id) {
cell.status = status.clone();
}
});
}
}
}
}
/// Methods related to management of Conductor state
mod state_impls {
use super::*;
impl Conductor {
pub(crate) async fn get_state(&self) -> ConductorResult<ConductorState> {
self.spaces.get_state().await
}
/// Update the internal state with a pure function mapping old state to new
pub(crate) async fn update_state<F: Send>(&self, f: F) -> ConductorResult<ConductorState>
where
F: FnOnce(ConductorState) -> ConductorResult<ConductorState> + 'static,
{
self.spaces.update_state(f).await
}
/// Update the internal state with a pure function mapping old state to new,
/// which may also produce an output value which will be the output of
/// this function
pub(crate) async fn update_state_prime<F, O>(
&self,
f: F,
) -> ConductorResult<(ConductorState, O)>
where
F: FnOnce(ConductorState) -> ConductorResult<(ConductorState, O)> + Send + 'static,
O: Send + 'static,
{
self.check_running()?;
self.spaces.update_state_prime(f).await
}
/// Sends a JoinHandle to the TaskManager task to be managed
pub(crate) async fn manage_task(&self, handle: ManagedTaskAdd) -> ConductorResult<()> {
self.task_manager
.share_ref(|tm| {
tm.as_ref()
.expect("Task manager not initialized")
.task_add_sender()
.clone()
})
.send(handle)
.await
.map_err(|e| ConductorError::SubmitTaskError(format!("{}", e)))
}
}
}
/// Methods related to zome function scheduling
mod scheduler_impls {
use super::*;
impl Conductor {
pub(super) fn set_scheduler(&self, join_handle: tokio::task::JoinHandle<()>) {
let mut scheduler = self.scheduler.lock();
if let Some(existing_join_handle) = &*scheduler {
existing_join_handle.abort();
}
*scheduler = Some(join_handle);
}
/// Start the scheduler. None is not an option.
/// Calling this will:
/// - Delete/unschedule all ephemeral scheduled functions GLOBALLY
/// - Add an interval that runs IN ADDITION to previous invocations
/// So ideally this would be called ONCE per conductor lifecyle ONLY.
pub(crate) async fn start_scheduler(self: Arc<Self>, interval_period: std::time::Duration) {
// Clear all ephemeral cruft in all cells before starting a scheduler.
let cell_arcs = {
let mut cell_arcs = vec![];
for cell_id in self.running_cell_ids() {
if let Ok(cell_arc) = self.cell_by_id(&cell_id) {
cell_arcs.push(cell_arc);
}
}
cell_arcs
};
let tasks = cell_arcs
.into_iter()
.map(|cell_arc| cell_arc.delete_all_ephemeral_scheduled_fns());
futures::future::join_all(tasks).await;
let scheduler_handle = self.clone();
self.set_scheduler(tokio::task::spawn(async move {
let mut interval = tokio::time::interval(interval_period);
loop {
interval.tick().await;
scheduler_handle
.clone()
.dispatch_scheduled_fns(Timestamp::now())
.await;
}
}));
}
/// The scheduler wants to dispatch any functions that are due.
pub(crate) async fn dispatch_scheduled_fns(self: Arc<Self>, now: Timestamp) {
let cell_arcs = {
let mut cell_arcs = vec![];
for cell_id in self.running_cell_ids() {
if let Ok(cell_arc) = self.cell_by_id(&cell_id) {
cell_arcs.push(cell_arc);
}
}
cell_arcs
};
let tasks = cell_arcs
.into_iter()
.map(|cell_arc| cell_arc.dispatch_scheduled_fns(now));
futures::future::join_all(tasks).await;
}
}
}
/// Miscellaneous methods
mod misc_impls {
use holochain_zome_types::builder;
use super::*;
impl Conductor {
/// Grant a zome call capability for a cell
pub async fn grant_zome_call_capability(
&self,
payload: GrantZomeCallCapabilityPayload,
) -> ConductorApiResult<()> {
let GrantZomeCallCapabilityPayload { cell_id, cap_grant } = payload;
let source_chain = SourceChain::new(
self.get_authored_db(cell_id.dna_hash())?,
self.get_dht_db(cell_id.dna_hash())?,
self.get_dht_db_cache(cell_id.dna_hash())?,
self.keystore.clone(),
cell_id.agent_pubkey().clone(),
)
.await?;
let cap_grant_entry = Entry::CapGrant(cap_grant);
let entry_hash = EntryHash::with_data_sync(&cap_grant_entry);
let action_builder = builder::Create {
entry_type: EntryType::CapGrant,
entry_hash,
};
source_chain
.put_weightless(
action_builder,
Some(cap_grant_entry),
ChainTopOrdering::default(),
)
.await?;
let cell = self.cell_by_id(&cell_id)?;
source_chain.flush(cell.holochain_p2p_dna()).await?;
Ok(())
}
/// Create a JSON dump of the cell's state
pub async fn dump_cell_state(&self, cell_id: &CellId) -> ConductorApiResult<String> {
let cell = self.cell_by_id(cell_id)?;
let authored_db = cell.authored_db();
let dht_db = cell.dht_db();
let space = cell_id.dna_hash();
let p2p_agents_db = self.p2p_agents_db(space);
let peer_dump =
p2p_agent_store::dump_state(p2p_agents_db.into(), Some(cell_id.clone())).await?;
let source_chain_dump = source_chain::dump_state(
authored_db.clone().into(),
cell_id.agent_pubkey().clone(),
)
.await?;
let out = JsonDump {
peer_dump,
source_chain_dump,
integration_dump: integration_dump(&dht_db.clone().into()).await?,
};
// Add summary
let summary = out.to_string();
let out = (out, summary);
Ok(serde_json::to_string_pretty(&out)?)
}
/// Create a comprehensive structured dump of a cell's state
pub async fn dump_full_cell_state(
&self,
cell_id: &CellId,
dht_ops_cursor: Option<u64>,
) -> ConductorApiResult<FullStateDump> {
let authored_db = self.get_or_create_authored_db(cell_id.dna_hash())?;
let dht_db = self.get_or_create_dht_db(cell_id.dna_hash())?;
let dna_hash = cell_id.dna_hash();
let p2p_agents_db = self.spaces.p2p_agents_db(dna_hash)?;
let peer_dump =
p2p_agent_store::dump_state(p2p_agents_db.into(), Some(cell_id.clone())).await?;
let source_chain_dump =
source_chain::dump_state(authored_db.into(), cell_id.agent_pubkey().clone())
.await?;
let out = FullStateDump {
peer_dump,
source_chain_dump,
integration_dump: full_integration_dump(&dht_db, dht_ops_cursor).await?,
};
Ok(out)
}
/// JSON dump of network metrics
pub async fn dump_network_metrics(
&self,
dna_hash: Option<DnaHash>,
) -> ConductorApiResult<String> {
use holochain_p2p::HolochainP2pSender;
self.holochain_p2p()
.dump_network_metrics(dna_hash)
.await
.map_err(crate::conductor::api::error::ConductorApiError::other)
}
/// Add signed agent info to the conductor
pub async fn add_agent_infos(
&self,
agent_infos: Vec<AgentInfoSigned>,
) -> ConductorApiResult<()> {
let mut space_map = HashMap::new();
for agent_info_signed in agent_infos {
let space = agent_info_signed.space.clone();
space_map
.entry(space)
.or_insert_with(Vec::new)
.push(agent_info_signed);
}
for (space, agent_infos) in space_map {
let db = self.p2p_agents_db(&DnaHash::from_kitsune(&space));
inject_agent_infos(db, agent_infos.iter()).await?;
}
Ok(())
}
/// Inject records into a source chain for a cell.
/// If the records form a chain segment that can be "grafted" onto the existing chain, it will be.
/// Otherwise, a new chain will be formed using the specified records.
pub async fn graft_records_onto_source_chain(
self: Arc<Self>,
cell_id: CellId,
validate: bool,
records: Vec<Record>,
) -> ConductorApiResult<()> {
graft_records_onto_source_chain::graft_records_onto_source_chain(
self, cell_id, validate, records,
)
.await
}
/// Update coordinator zomes on an existing dna.
pub async fn update_coordinators(
&self,
hash: &DnaHash,
coordinator_zomes: CoordinatorZomes,
wasms: Vec<wasm::DnaWasm>,
) -> ConductorResult<()> {
// Note this isn't really concurrent safe. It would be a race condition to update the
// same dna concurrently.
let mut ribosome = self
.ribosome_store()
.share_ref(|d| match d.get_ribosome(hash) {
Some(dna) => Ok(dna),
None => Err(DnaError::DnaMissing(hash.to_owned())),
})?;
let _old_wasms = ribosome
.dna_file
.update_coordinators(coordinator_zomes.clone(), wasms.clone())
.await?;
// Add new wasm code to db.
self.put_wasm_code(
ribosome.dna_def().clone(),
wasms.into_iter(),
Vec::with_capacity(0),
)
.await?;
// Update RibosomeStore.
self.ribosome_store()
.share_mut(|d| d.add_ribosome(ribosome));
// TODO: Remove old wasm code? (Maybe this needs to be done on restart as it could be in use).
Ok(())
}
sourcepub fn add_ribosomes<T: IntoIterator<Item = (DnaHash, RealRibosome)> + 'static>(
&mut self,
ribosomes: T
)
pub fn add_ribosomes<T: IntoIterator<Item = (DnaHash, RealRibosome)> + 'static>(
&mut self,
ribosomes: T
)
sourcepub fn get_dna_def(&self, hash: &DnaHash) -> Option<DnaDef>
pub fn get_dna_def(&self, hash: &DnaHash) -> Option<DnaDef>
Examples found in repository?
More examples
sourcepub fn get_dna_file(&self, hash: &DnaHash) -> Option<DnaFile>
pub fn get_dna_file(&self, hash: &DnaHash) -> Option<DnaFile>
Examples found in repository?
src/conductor/conductor.rs (line 546)
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 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 fn get_dna_file(&self, hash: &DnaHash) -> Option<DnaFile> {
self.ribosome_store().share_ref(|ds| ds.get_dna_file(hash))
}
/// Get an [`EntryDef`](holochain_zome_types::EntryDef) from the [`EntryDefBufferKey`](holochain_types::dna::EntryDefBufferKey)
pub fn get_entry_def(&self, key: &EntryDefBufferKey) -> Option<EntryDef> {
self.ribosome_store().share_ref(|ds| ds.get_entry_def(key))
}
/// Create a hash map of all existing DNA definitions, mapped to cell
/// ids.
pub fn get_dna_definitions(
&self,
app: &InstalledApp,
) -> ConductorResult<HashMap<CellId, DnaDefHashed>> {
let mut dna_defs = HashMap::new();
for cell_id in app.all_cells() {
let ribosome = self.get_ribosome(cell_id.dna_hash())?;
let dna_def = ribosome.dna_def();
dna_defs.insert(cell_id.to_owned(), dna_def.to_owned());
}
Ok(dna_defs)
}
pub(crate) async fn register_dna_wasm(
&self,
ribosome: RealRibosome,
) -> ConductorResult<Vec<(EntryDefBufferKey, EntryDef)>> {
let is_full_wasm_dna = ribosome
.dna_def()
.all_zomes()
.all(|(_, zome_def)| matches!(zome_def, ZomeDef::Wasm(_)));
// Only install wasm if the DNA is composed purely of WasmZomes (no InlineZomes)
if is_full_wasm_dna {
Ok(self.put_wasm(ribosome).await?)
} else {
Ok(Vec::with_capacity(0))
}
}
pub(crate) fn register_dna_entry_defs(
&self,
entry_defs: Vec<(EntryDefBufferKey, EntryDef)>,
) {
self.ribosome_store
.share_mut(|d| d.add_entry_defs(entry_defs));
}
pub(crate) fn add_ribosome_to_store(&self, ribosome: RealRibosome) {
self.ribosome_store.share_mut(|d| d.add_ribosome(ribosome));
}
pub(crate) async fn load_wasms_into_dna_files(
&self,
) -> ConductorResult<(
impl IntoIterator<Item = (DnaHash, RealRibosome)>,
impl IntoIterator<Item = (EntryDefBufferKey, EntryDef)>,
)> {
let db = &self.spaces.wasm_db;
// Load out all dna defs
let (wasm_tasks, defs) = db
.async_reader(move |txn| {
// Get all the dna defs.
let dna_defs: Vec<_> = holochain_state::dna_def::get_all(&txn)?
.into_iter()
.collect();
// Gather all the unique wasms.
let unique_wasms = dna_defs
.iter()
.flat_map(|dna_def| {
dna_def
.all_zomes()
.map(|(zome_name, zome)| Ok(zome.wasm_hash(zome_name)?))
})
.collect::<ConductorResult<HashSet<_>>>()?;
// Get the code for each unique wasm.
let wasms = unique_wasms
.into_iter()
.map(|wasm_hash| {
holochain_state::wasm::get(&txn, &wasm_hash)?
.map(|hashed| hashed.into_content())
.ok_or(ConductorError::WasmMissing)
.map(|wasm| (wasm_hash, wasm))
})
.collect::<ConductorResult<HashMap<_, _>>>()?;
let wasm_tasks = holochain_state::dna_def::get_all(&txn)?
.into_iter()
.map(|dna_def| {
// Load all wasms for each dna_def from the wasm db into memory
let wasms = dna_def.all_zomes().filter_map(|(zome_name, zome)| {
let wasm_hash = zome.wasm_hash(zome_name).ok()?;
// Note this is a cheap arc clone.
wasms.get(&wasm_hash).cloned()
});
let wasms = wasms.collect::<Vec<_>>();
async move {
let dna_file = DnaFile::new(dna_def.into_content(), wasms).await;
let ribosome = RealRibosome::new(dna_file)?;
ConductorResult::Ok((ribosome.dna_hash().clone(), ribosome))
}
})
// This needs to happen due to the environment not being Send
.collect::<Vec<_>>();
let defs = holochain_state::entry_def::get_all(&txn)?;
ConductorResult::Ok((wasm_tasks, defs))
})
.await?;
// try to join all the tasks and return the list of dna files
let dnas = futures::future::try_join_all(wasm_tasks).await?;
Ok((dnas, defs))
}
/// Get the root environment directory.
pub fn root_db_dir(&self) -> &DatabaseRootPath {
&self.spaces.db_dir
}
/// Get the keystore.
pub fn keystore(&self) -> &MetaLairClient {
&self.keystore
}
/// Get a reference to the conductor's HolochainP2p.
pub fn holochain_p2p(&self) -> &holochain_p2p::HolochainP2pRef {
&self.holochain_p2p
}
/// Remove cells from the cell map in the Conductor
pub(crate) async fn remove_cells(&self, cell_ids: &[CellId]) {
let to_cleanup: Vec<_> = self.running_cells.share_mut(|cells| {
cell_ids
.iter()
.filter_map(|cell_id| cells.remove(cell_id).map(|c| (cell_id, c)))
.collect()
});
for (cell_id, item) in to_cleanup {
if let Err(err) = item.cell.cleanup().await {
tracing::error!("Error cleaning up Cell: {:?}\nCellId: {}", err, cell_id);
}
}
}
/// Restart every paused app
pub(crate) async fn start_paused_apps(&self) -> ConductorResult<AppStatusFx> {
let (_, delta) = self
.update_state_prime(|mut state| {
let ids = state.paused_apps().map(first).cloned().collect::<Vec<_>>();
if !ids.is_empty() {
tracing::info!("Restarting {} paused apps: {:#?}", ids.len(), ids);
}
let deltas: Vec<AppStatusFx> = ids
.into_iter()
.map(|id| {
state
.transition_app_status(&id, AppStatusTransition::Start)
.map(second)
})
.collect::<Result<Vec<_>, _>>()?;
let delta = deltas
.into_iter()
.fold(AppStatusFx::default(), AppStatusFx::combine);
Ok((state, delta))
})
.await?;
Ok(delta)
}
pub(crate) async fn put_wasm(
&self,
ribosome: RealRibosome,
) -> ConductorResult<Vec<(EntryDefBufferKey, EntryDef)>> {
let dna_def = ribosome.dna_def().clone();
let code = ribosome
.dna_file()
.code()
.clone()
.into_iter()
.map(|(_, c)| c);
let zome_defs = get_entry_defs(ribosome).await?;
self.put_wasm_code(dna_def, code, zome_defs).await
}
pub(crate) async fn put_wasm_code(
&self,
dna: DnaDefHashed,
code: impl Iterator<Item = wasm::DnaWasm>,
zome_defs: Vec<(EntryDefBufferKey, EntryDef)>,
) -> ConductorResult<Vec<(EntryDefBufferKey, EntryDef)>> {
// TODO: PERF: This loop might be slow
let wasms = futures::future::join_all(code.map(DnaWasmHashed::from_content)).await;
self.spaces
.wasm_db
.async_commit({
let zome_defs = zome_defs.clone();
move |txn| {
for dna_wasm in wasms {
if !holochain_state::wasm::contains(txn, dna_wasm.as_hash())? {
holochain_state::wasm::put(txn, dna_wasm)?;
}
}
for (key, entry_def) in zome_defs.clone() {
holochain_state::entry_def::put(txn, key, &entry_def)?;
}
if !holochain_state::dna_def::contains(txn, dna.as_hash())? {
holochain_state::dna_def::put(txn, dna.into_content())?;
}
StateMutationResult::Ok(())
}
})
.await?;
Ok(zome_defs)
}
pub(crate) async fn load_dnas(&self) -> ConductorResult<()> {
let (ribosomes, entry_defs) = self.load_wasms_into_dna_files().await?;
self.ribosome_store().share_mut(|ds| {
ds.add_ribosomes(ribosomes);
ds.add_entry_defs(entry_defs);
});
Ok(())
}
/// Install a [`DnaFile`](holochain_types::dna::DnaFile) in this Conductor
pub async fn register_dna(&self, dna: DnaFile) -> ConductorResult<()> {
let ribosome = RealRibosome::new(dna)?;
let entry_defs = self.register_dna_wasm(ribosome.clone()).await?;
self.register_dna_entry_defs(entry_defs);
self.add_ribosome_to_store(ribosome);
Ok(())
}
}
}
/// Network-related methods
mod network_impls {
use holochain_conductor_api::NetworkInfo;
use holochain_p2p::HolochainP2pSender;
use super::*;
impl Conductor {
/// Get signed agent info from the conductor
pub async fn get_agent_infos(
&self,
cell_id: Option<CellId>,
) -> ConductorApiResult<Vec<AgentInfoSigned>> {
match cell_id {
Some(c) => {
let (d, a) = c.into_dna_and_agent();
let db = self.p2p_agents_db(&d);
Ok(get_single_agent_info(db.into(), d, a)
.await?
.map(|a| vec![a])
.unwrap_or_default())
}
None => {
let mut out = Vec::new();
// collecting so the mutex lock can close
let envs = self.spaces.get_from_spaces(|s| s.p2p_agents_db.clone());
for db in envs {
out.append(&mut all_agent_infos(db.into()).await?);
}
Ok(out)
}
}
}
pub(crate) async fn prune_p2p_agents_db(&self) -> ConductorResult<()> {
use holochain_p2p::AgentPubKeyExt;
let mut space_to_agents = HashMap::new();
for cell in self.running_cells.share_ref(|c| {
<Result<_, one_err::OneErr>>::Ok(c.keys().cloned().collect::<Vec<_>>())
})? {
space_to_agents
.entry(cell.dna_hash().clone())
.or_insert_with(Vec::new)
.push(cell.agent_pubkey().to_kitsune());
}
for (space, agents) in space_to_agents {
let db = self.spaces.p2p_agents_db(&space)?;
p2p_prune(&db, agents).await?;
}
Ok(())
}
pub(crate) async fn network_info(
&self,
dnas: &[DnaHash],
) -> ConductorResult<Vec<NetworkInfo>> {
futures::future::join_all(dnas.iter().map(|dna| async move {
let d = self.holochain_p2p.get_diagnostics(dna.clone()).await?;
let fetch_queue_info = d.fetch_queue.info([dna.to_kitsune()].into_iter().collect());
ConductorResult::Ok(NetworkInfo { fetch_queue_info })
}))
.await
.into_iter()
.collect::<Result<Vec<_>, _>>()
}
#[instrument(skip(self))]
pub(crate) async fn dispatch_holochain_p2p_event(
&self,
event: holochain_p2p::event::HolochainP2pEvent,
) -> ConductorApiResult<()> {
use HolochainP2pEvent::*;
let dna_hash = event.dna_hash().clone();
trace!(dispatch_event = ?event);
match event {
PutAgentInfoSigned {
peer_data, respond, ..
} => {
let sender = self.p2p_batch_sender(&dna_hash);
let (result_sender, response) = tokio::sync::oneshot::channel();
let _ = sender
.send(P2pBatch {
peer_data,
result_sender,
})
.await;
let res = match response.await {
Ok(r) => r.map_err(holochain_p2p::HolochainP2pError::other),
Err(e) => Err(holochain_p2p::HolochainP2pError::other(e)),
};
respond.respond(Ok(async move { res }.boxed().into()));
}
QueryAgentInfoSigned {
kitsune_space,
agents,
respond,
..
} => {
let db = { self.p2p_agents_db(&dna_hash) };
let res = list_all_agent_info(db.into(), kitsune_space)
.await
.map(|infos| match agents {
Some(agents) => infos
.into_iter()
.filter(|info| agents.contains(&info.agent))
.collect(),
None => infos,
})
.map_err(holochain_p2p::HolochainP2pError::other);
respond.respond(Ok(async move { res }.boxed().into()));
}
QueryGossipAgents {
since_ms,
until_ms,
arc_set,
respond,
..
} => {
use holochain_sqlite::db::AsP2pAgentStoreConExt;
let db = { self.p2p_agents_db(&dna_hash) };
let permit = db.conn_permit().await;
let res = tokio::task::spawn_blocking(move || {
let mut conn = db.with_permit(permit)?;
conn.p2p_gossip_query_agents(since_ms, until_ms, (*arc_set).clone())
})
.await;
let res = res
.map_err(holochain_p2p::HolochainP2pError::other)
.and_then(|r| r.map_err(holochain_p2p::HolochainP2pError::other));
respond.respond(Ok(async move { res }.boxed().into()));
}
QueryAgentInfoSignedNearBasis {
kitsune_space,
basis_loc,
limit,
respond,
..
} => {
let db = { self.p2p_agents_db(&dna_hash) };
let res = list_all_agent_info_signed_near_basis(
db.into(),
kitsune_space,
basis_loc,
limit,
)
.await
.map_err(holochain_p2p::HolochainP2pError::other);
respond.respond(Ok(async move { res }.boxed().into()));
}
QueryPeerDensity {
kitsune_space,
dht_arc,
respond,
..
} => {
let cutoff = self
.get_config()
.network
.clone()
.unwrap_or_default()
.tuning_params
.danger_gossip_recent_threshold();
let topo = self
.get_dna_def(&dna_hash)
.ok_or_else(|| DnaError::DnaMissing(dna_hash.clone()))?
.topology(cutoff);
let db = { self.p2p_agents_db(&dna_hash) };
let res = query_peer_density(db.into(), topo, kitsune_space, dht_arc)
.await
.map_err(holochain_p2p::HolochainP2pError::other);
respond.respond(Ok(async move { res }.boxed().into()));
}
SignNetworkData {
respond,
to_agent,
data,
..
} => {
let signature = to_agent.sign_raw(self.keystore(), data.into()).await?;
respond.respond(Ok(async move { Ok(signature) }.boxed().into()));
}
HolochainP2pEvent::CallRemote { .. }
| CountersigningSessionNegotiation { .. }
| Get { .. }
| GetMeta { .. }
| GetLinks { .. }
| GetAgentActivity { .. }
| MustGetAgentActivity { .. }
| ValidationReceiptReceived { .. } => {
let cell_id =
CellId::new(event.dna_hash().clone(), event.target_agents().clone());
let cell = self.cell_by_id(&cell_id)?;
cell.handle_holochain_p2p_event(event).await?;
}
Publish {
dna_hash,
respond,
request_validation_receipt,
countersigning_session,
ops,
..
} => {
async {
let res = self
.spaces
.handle_publish(
&dna_hash,
request_validation_receipt,
countersigning_session,
ops,
)
.await
.map_err(holochain_p2p::HolochainP2pError::other);
respond.respond(Ok(async move { res }.boxed().into()));
}
.instrument(debug_span!("handle_publish"))
.await;
}
FetchOpData {
respond,
query,
dna_hash,
..
} => {
async {
let res = self
.spaces
.handle_fetch_op_data(&dna_hash, query)
.await
.map_err(holochain_p2p::HolochainP2pError::other);
respond.respond(Ok(async move { res }.boxed().into()));
}
.instrument(debug_span!("handle_fetch_op_data"))
.await;
}
HolochainP2pEvent::QueryOpHashes {
dna_hash,
window,
max_ops,
include_limbo,
arc_set,
respond,
..
} => {
let res = self
.spaces
.handle_query_op_hashes(&dna_hash, arc_set, window, max_ops, include_limbo)
.await
.map_err(holochain_p2p::HolochainP2pError::other);
respond.respond(Ok(async move { res }.boxed().into()));
}
}
Ok(())
}
/// Invoke a zome function on a Cell
pub async fn call_zome(&self, call: ZomeCall) -> ConductorApiResult<ZomeCallResult> {
let cell = self.cell_by_id(&call.cell_id)?;
Ok(cell.call_zome(call, None).await?)
}
pub(crate) async fn call_zome_with_workspace(
&self,
call: ZomeCall,
workspace_lock: SourceChainWorkspace,
) -> ConductorApiResult<ZomeCallResult> {
debug!(cell_id = ?call.cell_id);
let cell = self.cell_by_id(&call.cell_id)?;
Ok(cell.call_zome(call, Some(workspace_lock)).await?)
}
}
}
/// Methods related to app installation and management
mod app_impls {
use super::*;
impl Conductor {
pub(crate) async fn install_app(
self: Arc<Self>,
installed_app_id: InstalledAppId,
cell_data: Vec<(InstalledCell, Option<MembraneProof>)>,
) -> ConductorResult<()> {
crate::conductor::conductor::genesis_cells(
self.clone(),
cell_data
.iter()
.map(|(c, p)| (c.as_id().clone(), p.clone()))
.collect(),
)
.await?;
let cell_data = cell_data.into_iter().map(|(c, _)| c);
let app = InstalledAppCommon::new_legacy(installed_app_id, cell_data)?;
// Update the db
let _ = self.add_disabled_app_to_db(app).await?;
Ok(())
}
/// Install DNAs and set up Cells as specified by an AppBundle
pub async fn install_app_bundle(
self: Arc<Self>,
payload: InstallAppPayload,
) -> ConductorResult<StoppedApp> {
let InstallAppPayload {
source,
agent_key,
installed_app_id,
membrane_proofs,
network_seed,
} = payload;
let bundle: AppBundle = {
let original_bundle = source.resolve().await?;
if let Some(network_seed) = network_seed {
let mut manifest = original_bundle.manifest().to_owned();
manifest.set_network_seed(network_seed);
AppBundle::from(original_bundle.into_inner().update_manifest(manifest)?)
} else {
original_bundle
}
};
let installed_app_id =
installed_app_id.unwrap_or_else(|| bundle.manifest().app_name().to_owned());
let ops = bundle
.resolve_cells(agent_key.clone(), DnaGamut::placeholder(), membrane_proofs)
.await?;
let cells_to_create = ops.cells_to_create();
for (dna, _) in ops.dnas_to_register {
self.clone().register_dna(dna).await?;
}
crate::conductor::conductor::genesis_cells(self.clone(), cells_to_create).await?;
let roles = ops.role_assignments;
let app = InstalledAppCommon::new(installed_app_id, agent_key, roles)?;
// Update the db
let stopped_app = self.add_disabled_app_to_db(app).await?;
Ok(stopped_app)
}
/// Uninstall an app
#[tracing::instrument(skip(self))]
pub async fn uninstall_app(
self: Arc<Self>,
installed_app_id: &InstalledAppId,
) -> ConductorResult<()> {
let self_clone = self.clone();
let app = self.remove_app_from_db(installed_app_id).await?;
tracing::debug!(msg = "Removed app from db.", app = ?app);
// Remove cells which may now be dangling due to the removed app
self_clone
.process_app_status_fx(AppStatusFx::SpinDown, None)
.await?;
Ok(())
}
/// List active AppIds
pub async fn list_running_apps(&self) -> ConductorResult<Vec<InstalledAppId>> {
let state = self.get_state().await?;
Ok(state.running_apps().map(|(id, _)| id).cloned().collect())
}
/// List Apps with their information
pub async fn list_apps(
&self,
status_filter: Option<AppStatusFilter>,
) -> ConductorResult<Vec<AppInfo>> {
use AppStatusFilter::*;
let conductor_state = self.get_state().await?;
let apps_ids: Vec<&String> = match status_filter {
Some(Enabled) => conductor_state.enabled_apps().map(|(id, _)| id).collect(),
Some(Disabled) => conductor_state.disabled_apps().map(|(id, _)| id).collect(),
Some(Running) => conductor_state.running_apps().map(|(id, _)| id).collect(),
Some(Stopped) => conductor_state.stopped_apps().map(|(id, _)| id).collect(),
Some(Paused) => conductor_state.paused_apps().map(|(id, _)| id).collect(),
None => conductor_state.installed_apps().keys().collect(),
};
let app_infos: Vec<AppInfo> = apps_ids
.into_iter()
.map(|app_id| self.get_app_info_inner(app_id, &conductor_state))
.collect::<Result<Vec<_>, _>>()?
.into_iter()
.flatten()
.collect();
Ok(app_infos)
}
/// Get the IDs of all active installed Apps which use this Cell
pub async fn list_running_apps_for_dependent_cell_id(
&self,
cell_id: &CellId,
) -> ConductorResult<HashSet<InstalledAppId>> {
Ok(self
.get_state()
.await?
.running_apps()
.filter(|(_, v)| v.all_cells().any(|i| i == cell_id))
.map(|(k, _)| k)
.cloned()
.collect())
}
/// Find the ID of the first active installed App which uses this Cell
pub async fn find_cell_with_role_alongside_cell(
&self,
cell_id: &CellId,
role_name: &RoleName,
) -> ConductorResult<Option<CellId>> {
Ok(self
.get_state()
.await?
.running_apps()
.find(|(_, running_app)| running_app.all_cells().any(|i| i == cell_id))
.and_then(|(_, running_app)| {
running_app
.into_common()
.role(role_name)
.ok()
.map(|role| role.cell_id())
.cloned()
}))
}
/// Get the IDs of all active installed Apps which use this Dna
pub async fn list_running_apps_for_dependent_dna_hash(
&self,
dna_hash: &DnaHash,
) -> ConductorResult<HashSet<InstalledAppId>> {
Ok(self
.get_state()
.await?
.running_apps()
.filter(|(_, v)| v.all_cells().any(|i| i.dna_hash() == dna_hash))
.map(|(k, _)| k)
.cloned()
.collect())
}
/// Get info about an installed App, regardless of status
pub async fn get_app_info(
&self,
installed_app_id: &InstalledAppId,
) -> ConductorResult<Option<AppInfo>> {
let state = self.get_state().await?;
let maybe_app_info = self.get_app_info_inner(installed_app_id, &state)?;
Ok(maybe_app_info)
}
fn get_app_info_inner(
&self,
app_id: &InstalledAppId,
state: &ConductorState,
) -> ConductorResult<Option<AppInfo>> {
match state.installed_apps().get(app_id) {
None => Ok(None),
Some(app) => {
let dna_definitions = self.get_dna_definitions(app)?;
Ok(Some(AppInfo::from_installed_app(app, &dna_definitions)))
}
}
}
}
}
/// Methods related to cell access
mod cell_impls {
use super::*;
impl Conductor {
pub(crate) fn cell_by_id(&self, cell_id: &CellId) -> ConductorResult<Arc<Cell>> {
let cell = self
.running_cells
.share_ref(|c| c.get(cell_id).map(|i| i.cell.clone()))
.ok_or_else(|| ConductorError::CellMissing(cell_id.clone()))?;
Ok(cell)
}
/// Iterator over only the cells which are fully running. Generally used
/// to handle conductor interface requests
pub fn running_cell_ids(&self) -> HashSet<CellId> {
self.running_cells.share_ref(|c| {
c.iter()
.filter_map(|(id, item)| {
if item.is_running() {
Some(id.clone())
} else {
None
}
})
.collect()
})
}
/// List CellIds for Cells which match a status filter
pub fn list_cell_ids(&self, filter: Option<CellStatusFilter>) -> Vec<CellId> {
self.running_cells.share_ref(|cells| {
cells
.iter()
.filter_map(|(id, cell)| {
let matches = filter
.as_ref()
.map(|status| cell.status == *status)
.unwrap_or(true);
if matches {
Some(id)
} else {
None
}
})
.cloned()
.collect()
})
}
}
}
/// Methods related to clone cell management
mod clone_cell_impls {
use super::*;
impl Conductor {
/// Create a new cell in an existing app based on an existing DNA.
///
/// # Returns
///
/// A struct with the created cell's clone id and cell id.
pub async fn create_clone_cell(
self: Arc<Self>,
payload: CreateCloneCellPayload,
) -> ConductorResult<InstalledCell> {
let CreateCloneCellPayload {
app_id,
role_name,
modifiers,
membrane_proof,
name,
} = payload;
if !modifiers.has_some_option_set() {
return Err(ConductorError::CloneCellError(
"neither network_seed nor properties nor origin_time provided for clone cell"
.to_string(),
));
}
let state = self.get_state().await?;
let app = state.get_app(&app_id)?;
app.provisioned_cells()
.find(|(app_role_name, _)| **app_role_name == role_name)
.ok_or_else(|| {
ConductorError::CloneCellError(
"no base cell found for provided role id".to_string(),
)
})?;
// add cell to app
let installed_clone_cell = self
.add_clone_cell_to_app(
app_id.clone(),
role_name.clone(),
modifiers.serialized()?,
name,
)
.await?;
// run genesis on cloned cell
let cells = vec![(installed_clone_cell.as_id().clone(), membrane_proof)];
crate::conductor::conductor::genesis_cells(self.clone(), cells).await?;
self.create_and_add_initialized_cells_for_running_apps(Some(&app_id))
.await?;
Ok(installed_clone_cell)
}
/// Disable a clone cell.
pub(crate) async fn disable_clone_cell(
&self,
DisableCloneCellPayload {
app_id,
clone_cell_id,
}: &DisableCloneCellPayload,
) -> ConductorResult<()> {
let (_, removed_cell_id) = self
.update_state_prime({
let app_id = app_id.to_owned();
let clone_cell_id = clone_cell_id.to_owned();
move |mut state| {
let app = state.get_app_mut(&app_id)?;
let clone_id = app.get_clone_id(&clone_cell_id)?;
let cell_id = app.get_clone_cell_id(&clone_cell_id)?;
app.disable_clone_cell(&clone_id)?;
Ok((state, cell_id))
}
})
.await?;
self.remove_cells(&[removed_cell_id]).await;
Ok(())
}
/// Enable a disabled clone cell.
pub async fn enable_clone_cell(
self: Arc<Self>,
payload: &EnableCloneCellPayload,
) -> ConductorResult<InstalledCell> {
let (_, enabled_cell) = self
.update_state_prime({
let app_id = payload.app_id.to_owned();
let clone_cell_id = payload.clone_cell_id.to_owned();
move |mut state| {
let app = state.get_app_mut(&app_id)?;
let clone_id = app.get_disabled_clone_id(&clone_cell_id)?;
let enabled_cell = app.enable_clone_cell(&clone_id)?;
Ok((state, enabled_cell))
}
})
.await?;
self.create_and_add_initialized_cells_for_running_apps(Some(&payload.app_id))
.await?;
Ok(enabled_cell)
}
/// Delete a clone cell.
pub(crate) async fn delete_clone_cell(
&self,
DeleteCloneCellPayload {
app_id,
clone_cell_id,
}: &DeleteCloneCellPayload,
) -> ConductorResult<()> {
self.update_state_prime({
let app_id = app_id.clone();
let clone_cell_id = clone_cell_id.clone();
move |mut state| {
let app = state.get_app_mut(&app_id)?;
let clone_id = app.get_disabled_clone_id(&clone_cell_id)?;
app.delete_clone_cell(&clone_id)?;
Ok((state, ()))
}
})
.await?;
self.remove_dangling_cells().await?;
Ok(())
}
}
}
/// Methods related to management of app and cell status
mod app_status_impls {
use super::*;
impl Conductor {
/// Adjust which cells are present in the Conductor (adding and removing as
/// needed) to match the current reality of all app statuses.
/// - If a Cell is used by at least one Running app, then ensure it is added
/// - If a Cell is used by no running apps, then ensure it is removed.
#[tracing::instrument(skip(self))]
pub async fn reconcile_cell_status_with_app_status(
self: Arc<Self>,
) -> ConductorResult<CellStartupErrors> {
self.remove_dangling_cells().await?;
let results = self
.create_and_add_initialized_cells_for_running_apps(None)
.await?;
Ok(results)
}
/// Enable an app
#[tracing::instrument(skip(self))]
pub async fn enable_app(
self: Arc<Self>,
app_id: InstalledAppId,
) -> ConductorResult<(InstalledApp, CellStartupErrors)> {
let (app, delta) = self
.transition_app_status(app_id.clone(), AppStatusTransition::Enable)
.await?;
let errors = self
.process_app_status_fx(delta, Some(vec![app_id.to_owned()].into_iter().collect()))
.await?;
Ok((app, errors))
}
/// Disable an app
#[tracing::instrument(skip(self))]
pub async fn disable_app(
self: Arc<Self>,
app_id: InstalledAppId,
reason: DisabledAppReason,
) -> ConductorResult<InstalledApp> {
let (app, delta) = self
.transition_app_status(app_id.clone(), AppStatusTransition::Disable(reason))
.await?;
self.process_app_status_fx(delta, Some(vec![app_id.to_owned()].into_iter().collect()))
.await?;
Ok(app)
}
/// Start an app
#[tracing::instrument(skip(self))]
pub async fn start_app(
self: Arc<Self>,
app_id: InstalledAppId,
) -> ConductorResult<InstalledApp> {
let (app, delta) = self
.transition_app_status(app_id.clone(), AppStatusTransition::Start)
.await?;
self.process_app_status_fx(delta, Some(vec![app_id.to_owned()].into_iter().collect()))
.await?;
Ok(app)
}
/// Register an app as disabled in the database
pub(crate) async fn add_disabled_app_to_db(
&self,
app: InstalledAppCommon,
) -> ConductorResult<StoppedApp> {
let (_, stopped_app) = self
.update_state_prime(move |mut state| {
let stopped_app = state.add_app(app)?;
Ok((state, stopped_app))
})
.await?;
Ok(stopped_app)
}
/// Transition an app's status to a new state.
#[tracing::instrument(skip(self))]
pub(crate) async fn transition_app_status(
&self,
app_id: InstalledAppId,
transition: AppStatusTransition,
) -> ConductorResult<(InstalledApp, AppStatusFx)> {
Ok(self
.update_state_prime(move |mut state| {
let (app, delta) = state.transition_app_status(&app_id, transition)?.clone();
let app = app.clone();
Ok((state, (app, delta)))
})
.await?
.1)
}
/// Pause an app
#[tracing::instrument(skip(self))]
#[cfg(any(test, feature = "test_utils"))]
pub async fn pause_app(
self: Arc<Self>,
app_id: InstalledAppId,
reason: PausedAppReason,
) -> ConductorResult<InstalledApp> {
let (app, delta) = self
.transition_app_status(app_id.clone(), AppStatusTransition::Pause(reason))
.await?;
self.process_app_status_fx(delta, Some(vec![app_id.clone()].into_iter().collect()))
.await?;
Ok(app)
}
/// Create any Cells which are missing for any running apps, then initialize
/// and join them. (Joining could take a while.)
pub(crate) async fn create_and_add_initialized_cells_for_running_apps(
self: Arc<Self>,
app_id: Option<&InstalledAppId>,
) -> ConductorResult<CellStartupErrors> {
let results = self.clone().create_cells_for_running_apps(app_id).await?;
let (new_cells, errors): (Vec<_>, Vec<_>) =
results.into_iter().partition(Result::is_ok);
let new_cells = new_cells
.into_iter()
// We can unwrap the successes because of the partition
.map(Result::unwrap)
.collect();
let errors = errors
.into_iter()
// throw away the non-Debug types which will be unwrapped away anyway
.map(|r| r.map(|_| ()))
// We can unwrap the errors because of the partition
.map(Result::unwrap_err)
.collect();
// Add the newly created cells to the Conductor with the PendingJoin
// status, and start their workflow loops
self.add_and_initialize_cells(new_cells);
// Join these newly created cells to the network
// (as well as any others which need joining)
self.join_all_pending_cells().await;
Ok(errors)
}
/// Attempt to join all PendingJoin cells to the kitsune network.
/// Returns the cells which were joined during this call.
///
/// NB: this could take as long as JOIN_NETWORK_TIMEOUT, which is significant.
/// Be careful to only await this future if it's important that cells be
/// joined before proceeding.
pub(crate) async fn join_all_pending_cells(&self) -> Vec<CellId> {
// Join the network but ignore errors because the
// space retries joining all cells every 5 minutes.
use holochain_p2p::AgentPubKeyExt;
let tasks = self
.mark_pending_cells_as_joining()
.into_iter()
.map(|(cell_id, cell)| async move {
let p2p_agents_db = cell.p2p_agents_db().clone();
let kagent = cell_id.agent_pubkey().to_kitsune();
let agent_info = match p2p_agents_db.async_reader(move |tx| {
tx.p2p_get_agent(&kagent)
}).await {
Ok(maybe_info) => maybe_info,
_ => None,
};
let maybe_initial_arc = agent_info.map(|i| i.storage_arc);
let network = cell.holochain_p2p_dna().clone();
match tokio::time::timeout(JOIN_NETWORK_TIMEOUT, network.join(cell_id.agent_pubkey().clone(), maybe_initial_arc)).await {
Ok(Err(e)) => {
tracing::info!(error = ?e, cell_id = ?cell_id, "Error while trying to join the network");
Err(cell_id)
}
Err(_) => {
tracing::info!(cell_id = ?cell_id, "Timed out trying to join the network");
Err(cell_id)
}
Ok(Ok(_)) => Ok(cell_id),
}
});
let maybes: Vec<_> = futures::stream::iter(tasks)
.buffer_unordered(100)
.collect()
.await;
let (cell_ids, failed_joins): (Vec<_>, Vec<_>) =
maybes.into_iter().partition(Result::is_ok);
// These unwraps are both safe because of the partition.
let cell_ids: Vec<_> = cell_ids.into_iter().map(Result::unwrap).collect();
let failed_joins: Vec<_> = failed_joins.into_iter().map(Result::unwrap_err).collect();
// Update the status of the cells which were able to join the network
// (may or may not be all cells which were added)
self.update_cell_status(cell_ids.as_slice(), CellStatus::Joined);
self.update_cell_status(failed_joins.as_slice(), CellStatus::PendingJoin);
cell_ids
}
/// Adjust app statuses (via state transitions) to match the current
/// reality of which Cells are present in the conductor.
/// - Do not change state for Disabled apps. For all others:
/// - If an app is Paused but all of its (required) Cells are on,
/// then set it to Running
/// - If an app is Running but at least one of its (required) Cells are off,
/// then set it to Paused
pub(crate) async fn reconcile_app_status_with_cell_status(
&self,
app_ids: Option<HashSet<InstalledAppId>>,
) -> ConductorResult<AppStatusFx> {
use AppStatus::*;
use AppStatusTransition::*;
let running_cells: HashSet<CellId> = self.running_cell_ids();
let (_, delta) = self
.update_state_prime(move |mut state| {
#[allow(deprecated)]
let apps = state.installed_apps_mut().iter_mut().filter(|(id, _)| {
app_ids
.as_ref()
.map(|ids| ids.contains(&**id))
.unwrap_or(true)
});
let delta = apps
.into_iter()
.map(|(_app_id, app)| {
match app.status().clone() {
Running => {
// If not all required cells are running, pause the app
let missing: Vec<_> = app
.required_cells()
.filter(|id| !running_cells.contains(id))
.collect();
if !missing.is_empty() {
let reason = PausedAppReason::Error(format!(
"Some cells are missing / not able to run: {:#?}",
missing
));
app.status.transition(Pause(reason))
} else {
AppStatusFx::NoChange
}
}
Paused(_) => {
// If all required cells are now running, restart the app
if app.required_cells().all(|id| running_cells.contains(id)) {
app.status.transition(Start)
} else {
AppStatusFx::NoChange
}
}
Disabled(_) => {
// Disabled status should never automatically change.
AppStatusFx::NoChange
}
}
})
.fold(AppStatusFx::default(), AppStatusFx::combine);
Ok((state, delta))
})
.await?;
Ok(delta)
}
/// Change the CellStatus of the given Cells in the Conductor.
/// Silently ignores Cells that don't exist.
pub(crate) fn update_cell_status(&self, cell_ids: &[CellId], status: CellStatus) {
for cell_id in cell_ids {
self.running_cells.share_mut(|cells| {
if let Some(mut cell) = cells.get_mut(cell_id) {
cell.status = status.clone();
}
});
}
}
}
}
/// Methods related to management of Conductor state
mod state_impls {
use super::*;
impl Conductor {
pub(crate) async fn get_state(&self) -> ConductorResult<ConductorState> {
self.spaces.get_state().await
}
/// Update the internal state with a pure function mapping old state to new
pub(crate) async fn update_state<F: Send>(&self, f: F) -> ConductorResult<ConductorState>
where
F: FnOnce(ConductorState) -> ConductorResult<ConductorState> + 'static,
{
self.spaces.update_state(f).await
}
/// Update the internal state with a pure function mapping old state to new,
/// which may also produce an output value which will be the output of
/// this function
pub(crate) async fn update_state_prime<F, O>(
&self,
f: F,
) -> ConductorResult<(ConductorState, O)>
where
F: FnOnce(ConductorState) -> ConductorResult<(ConductorState, O)> + Send + 'static,
O: Send + 'static,
{
self.check_running()?;
self.spaces.update_state_prime(f).await
}
/// Sends a JoinHandle to the TaskManager task to be managed
pub(crate) async fn manage_task(&self, handle: ManagedTaskAdd) -> ConductorResult<()> {
self.task_manager
.share_ref(|tm| {
tm.as_ref()
.expect("Task manager not initialized")
.task_add_sender()
.clone()
})
.send(handle)
.await
.map_err(|e| ConductorError::SubmitTaskError(format!("{}", e)))
}
}
}
/// Methods related to zome function scheduling
mod scheduler_impls {
use super::*;
impl Conductor {
pub(super) fn set_scheduler(&self, join_handle: tokio::task::JoinHandle<()>) {
let mut scheduler = self.scheduler.lock();
if let Some(existing_join_handle) = &*scheduler {
existing_join_handle.abort();
}
*scheduler = Some(join_handle);
}
/// Start the scheduler. None is not an option.
/// Calling this will:
/// - Delete/unschedule all ephemeral scheduled functions GLOBALLY
/// - Add an interval that runs IN ADDITION to previous invocations
/// So ideally this would be called ONCE per conductor lifecyle ONLY.
pub(crate) async fn start_scheduler(self: Arc<Self>, interval_period: std::time::Duration) {
// Clear all ephemeral cruft in all cells before starting a scheduler.
let cell_arcs = {
let mut cell_arcs = vec![];
for cell_id in self.running_cell_ids() {
if let Ok(cell_arc) = self.cell_by_id(&cell_id) {
cell_arcs.push(cell_arc);
}
}
cell_arcs
};
let tasks = cell_arcs
.into_iter()
.map(|cell_arc| cell_arc.delete_all_ephemeral_scheduled_fns());
futures::future::join_all(tasks).await;
let scheduler_handle = self.clone();
self.set_scheduler(tokio::task::spawn(async move {
let mut interval = tokio::time::interval(interval_period);
loop {
interval.tick().await;
scheduler_handle
.clone()
.dispatch_scheduled_fns(Timestamp::now())
.await;
}
}));
}
/// The scheduler wants to dispatch any functions that are due.
pub(crate) async fn dispatch_scheduled_fns(self: Arc<Self>, now: Timestamp) {
let cell_arcs = {
let mut cell_arcs = vec![];
for cell_id in self.running_cell_ids() {
if let Ok(cell_arc) = self.cell_by_id(&cell_id) {
cell_arcs.push(cell_arc);
}
}
cell_arcs
};
let tasks = cell_arcs
.into_iter()
.map(|cell_arc| cell_arc.dispatch_scheduled_fns(now));
futures::future::join_all(tasks).await;
}
}
}
/// Miscellaneous methods
mod misc_impls {
use holochain_zome_types::builder;
use super::*;
impl Conductor {
/// Grant a zome call capability for a cell
pub async fn grant_zome_call_capability(
&self,
payload: GrantZomeCallCapabilityPayload,
) -> ConductorApiResult<()> {
let GrantZomeCallCapabilityPayload { cell_id, cap_grant } = payload;
let source_chain = SourceChain::new(
self.get_authored_db(cell_id.dna_hash())?,
self.get_dht_db(cell_id.dna_hash())?,
self.get_dht_db_cache(cell_id.dna_hash())?,
self.keystore.clone(),
cell_id.agent_pubkey().clone(),
)
.await?;
let cap_grant_entry = Entry::CapGrant(cap_grant);
let entry_hash = EntryHash::with_data_sync(&cap_grant_entry);
let action_builder = builder::Create {
entry_type: EntryType::CapGrant,
entry_hash,
};
source_chain
.put_weightless(
action_builder,
Some(cap_grant_entry),
ChainTopOrdering::default(),
)
.await?;
let cell = self.cell_by_id(&cell_id)?;
source_chain.flush(cell.holochain_p2p_dna()).await?;
Ok(())
}
/// Create a JSON dump of the cell's state
pub async fn dump_cell_state(&self, cell_id: &CellId) -> ConductorApiResult<String> {
let cell = self.cell_by_id(cell_id)?;
let authored_db = cell.authored_db();
let dht_db = cell.dht_db();
let space = cell_id.dna_hash();
let p2p_agents_db = self.p2p_agents_db(space);
let peer_dump =
p2p_agent_store::dump_state(p2p_agents_db.into(), Some(cell_id.clone())).await?;
let source_chain_dump = source_chain::dump_state(
authored_db.clone().into(),
cell_id.agent_pubkey().clone(),
)
.await?;
let out = JsonDump {
peer_dump,
source_chain_dump,
integration_dump: integration_dump(&dht_db.clone().into()).await?,
};
// Add summary
let summary = out.to_string();
let out = (out, summary);
Ok(serde_json::to_string_pretty(&out)?)
}
/// Create a comprehensive structured dump of a cell's state
pub async fn dump_full_cell_state(
&self,
cell_id: &CellId,
dht_ops_cursor: Option<u64>,
) -> ConductorApiResult<FullStateDump> {
let authored_db = self.get_or_create_authored_db(cell_id.dna_hash())?;
let dht_db = self.get_or_create_dht_db(cell_id.dna_hash())?;
let dna_hash = cell_id.dna_hash();
let p2p_agents_db = self.spaces.p2p_agents_db(dna_hash)?;
let peer_dump =
p2p_agent_store::dump_state(p2p_agents_db.into(), Some(cell_id.clone())).await?;
let source_chain_dump =
source_chain::dump_state(authored_db.into(), cell_id.agent_pubkey().clone())
.await?;
let out = FullStateDump {
peer_dump,
source_chain_dump,
integration_dump: full_integration_dump(&dht_db, dht_ops_cursor).await?,
};
Ok(out)
}
/// JSON dump of network metrics
pub async fn dump_network_metrics(
&self,
dna_hash: Option<DnaHash>,
) -> ConductorApiResult<String> {
use holochain_p2p::HolochainP2pSender;
self.holochain_p2p()
.dump_network_metrics(dna_hash)
.await
.map_err(crate::conductor::api::error::ConductorApiError::other)
}
/// Add signed agent info to the conductor
pub async fn add_agent_infos(
&self,
agent_infos: Vec<AgentInfoSigned>,
) -> ConductorApiResult<()> {
let mut space_map = HashMap::new();
for agent_info_signed in agent_infos {
let space = agent_info_signed.space.clone();
space_map
.entry(space)
.or_insert_with(Vec::new)
.push(agent_info_signed);
}
for (space, agent_infos) in space_map {
let db = self.p2p_agents_db(&DnaHash::from_kitsune(&space));
inject_agent_infos(db, agent_infos.iter()).await?;
}
Ok(())
}
/// Inject records into a source chain for a cell.
/// If the records form a chain segment that can be "grafted" onto the existing chain, it will be.
/// Otherwise, a new chain will be formed using the specified records.
pub async fn graft_records_onto_source_chain(
self: Arc<Self>,
cell_id: CellId,
validate: bool,
records: Vec<Record>,
) -> ConductorApiResult<()> {
graft_records_onto_source_chain::graft_records_onto_source_chain(
self, cell_id, validate, records,
)
.await
}
/// Update coordinator zomes on an existing dna.
pub async fn update_coordinators(
&self,
hash: &DnaHash,
coordinator_zomes: CoordinatorZomes,
wasms: Vec<wasm::DnaWasm>,
) -> ConductorResult<()> {
// Note this isn't really concurrent safe. It would be a race condition to update the
// same dna concurrently.
let mut ribosome = self
.ribosome_store()
.share_ref(|d| match d.get_ribosome(hash) {
Some(dna) => Ok(dna),
None => Err(DnaError::DnaMissing(hash.to_owned())),
})?;
let _old_wasms = ribosome
.dna_file
.update_coordinators(coordinator_zomes.clone(), wasms.clone())
.await?;
// Add new wasm code to db.
self.put_wasm_code(
ribosome.dna_def().clone(),
wasms.into_iter(),
Vec::with_capacity(0),
)
.await?;
// Update RibosomeStore.
self.ribosome_store()
.share_mut(|d| d.add_ribosome(ribosome));
// TODO: Remove old wasm code? (Maybe this needs to be done on restart as it could be in use).
Ok(())
}
}
}
/// Pure accessor methods
mod accessor_impls {
use super::*;
impl Conductor {
pub(crate) fn ribosome_store(&self) -> &RwShare<RibosomeStore> {
&self.ribosome_store
}
pub(crate) fn get_queue_consumer_workflows(&self) -> QueueConsumerMap {
self.spaces.queue_consumer_map.clone()
}
/// Access to the signal broadcast channel, to create
/// new subscriptions
pub fn signal_broadcaster(&self) -> SignalBroadcaster {
let senders = self
.app_interfaces
.share_ref(|ai| ai.values().map(|i| i.signal_tx()).cloned().collect());
SignalBroadcaster::new(senders)
}
/// Instantiate a Ribosome for use with a DNA
pub(crate) fn get_ribosome(&self, dna_hash: &DnaHash) -> ConductorResult<RealRibosome> {
self.ribosome_store
.share_ref(|d| match d.get_ribosome(dna_hash) {
Some(r) => Ok(r),
None => Err(DnaError::DnaMissing(dna_hash.to_owned()).into()),
})
}
/// Get a dna space or create it if one doesn't exist.
pub(crate) fn get_or_create_space(&self, dna_hash: &DnaHash) -> ConductorResult<Space> {
self.spaces.get_or_create_space(dna_hash)
}
pub(crate) fn get_or_create_authored_db(
&self,
dna_hash: &DnaHash,
) -> ConductorResult<DbWrite<DbKindAuthored>> {
self.spaces.authored_db(dna_hash)
}
pub(crate) fn get_or_create_dht_db(
&self,
dna_hash: &DnaHash,
) -> ConductorResult<DbWrite<DbKindDht>> {
self.spaces.dht_db(dna_hash)
}
pub(crate) fn p2p_agents_db(&self, hash: &DnaHash) -> DbWrite<DbKindP2pAgents> {
self.spaces
.p2p_agents_db(hash)
.expect("failed to open p2p_agent_store database")
}
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)
}
sourcepub fn get_ribosome(&self, hash: &DnaHash) -> Option<RealRibosome>
pub fn get_ribosome(&self, hash: &DnaHash) -> Option<RealRibosome>
Examples found in repository?
src/conductor/conductor.rs (line 2002)
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
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()),
})
}
pub fn add_entry_def(&mut self, k: EntryDefBufferKey, entry_def: EntryDef)
sourcepub fn add_entry_defs<T: IntoIterator<Item = (EntryDefBufferKey, EntryDef)> + 'static>(
&mut self,
entry_defs: T
)
pub fn add_entry_defs<T: IntoIterator<Item = (EntryDefBufferKey, EntryDef)> + 'static>(
&mut self,
entry_defs: T
)
Examples found in repository?
src/conductor/conductor.rs (line 591)
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
pub(crate) fn register_dna_entry_defs(
&self,
entry_defs: Vec<(EntryDefBufferKey, EntryDef)>,
) {
self.ribosome_store
.share_mut(|d| d.add_entry_defs(entry_defs));
}
pub(crate) fn add_ribosome_to_store(&self, ribosome: RealRibosome) {
self.ribosome_store.share_mut(|d| d.add_ribosome(ribosome));
}
pub(crate) async fn load_wasms_into_dna_files(
&self,
) -> ConductorResult<(
impl IntoIterator<Item = (DnaHash, RealRibosome)>,
impl IntoIterator<Item = (EntryDefBufferKey, EntryDef)>,
)> {
let db = &self.spaces.wasm_db;
// Load out all dna defs
let (wasm_tasks, defs) = db
.async_reader(move |txn| {
// Get all the dna defs.
let dna_defs: Vec<_> = holochain_state::dna_def::get_all(&txn)?
.into_iter()
.collect();
// Gather all the unique wasms.
let unique_wasms = dna_defs
.iter()
.flat_map(|dna_def| {
dna_def
.all_zomes()
.map(|(zome_name, zome)| Ok(zome.wasm_hash(zome_name)?))
})
.collect::<ConductorResult<HashSet<_>>>()?;
// Get the code for each unique wasm.
let wasms = unique_wasms
.into_iter()
.map(|wasm_hash| {
holochain_state::wasm::get(&txn, &wasm_hash)?
.map(|hashed| hashed.into_content())
.ok_or(ConductorError::WasmMissing)
.map(|wasm| (wasm_hash, wasm))
})
.collect::<ConductorResult<HashMap<_, _>>>()?;
let wasm_tasks = holochain_state::dna_def::get_all(&txn)?
.into_iter()
.map(|dna_def| {
// Load all wasms for each dna_def from the wasm db into memory
let wasms = dna_def.all_zomes().filter_map(|(zome_name, zome)| {
let wasm_hash = zome.wasm_hash(zome_name).ok()?;
// Note this is a cheap arc clone.
wasms.get(&wasm_hash).cloned()
});
let wasms = wasms.collect::<Vec<_>>();
async move {
let dna_file = DnaFile::new(dna_def.into_content(), wasms).await;
let ribosome = RealRibosome::new(dna_file)?;
ConductorResult::Ok((ribosome.dna_hash().clone(), ribosome))
}
})
// This needs to happen due to the environment not being Send
.collect::<Vec<_>>();
let defs = holochain_state::entry_def::get_all(&txn)?;
ConductorResult::Ok((wasm_tasks, defs))
})
.await?;
// try to join all the tasks and return the list of dna files
let dnas = futures::future::try_join_all(wasm_tasks).await?;
Ok((dnas, defs))
}
/// Get the root environment directory.
pub fn root_db_dir(&self) -> &DatabaseRootPath {
&self.spaces.db_dir
}
/// Get the keystore.
pub fn keystore(&self) -> &MetaLairClient {
&self.keystore
}
/// Get a reference to the conductor's HolochainP2p.
pub fn holochain_p2p(&self) -> &holochain_p2p::HolochainP2pRef {
&self.holochain_p2p
}
/// Remove cells from the cell map in the Conductor
pub(crate) async fn remove_cells(&self, cell_ids: &[CellId]) {
let to_cleanup: Vec<_> = self.running_cells.share_mut(|cells| {
cell_ids
.iter()
.filter_map(|cell_id| cells.remove(cell_id).map(|c| (cell_id, c)))
.collect()
});
for (cell_id, item) in to_cleanup {
if let Err(err) = item.cell.cleanup().await {
tracing::error!("Error cleaning up Cell: {:?}\nCellId: {}", err, cell_id);
}
}
}
/// Restart every paused app
pub(crate) async fn start_paused_apps(&self) -> ConductorResult<AppStatusFx> {
let (_, delta) = self
.update_state_prime(|mut state| {
let ids = state.paused_apps().map(first).cloned().collect::<Vec<_>>();
if !ids.is_empty() {
tracing::info!("Restarting {} paused apps: {:#?}", ids.len(), ids);
}
let deltas: Vec<AppStatusFx> = ids
.into_iter()
.map(|id| {
state
.transition_app_status(&id, AppStatusTransition::Start)
.map(second)
})
.collect::<Result<Vec<_>, _>>()?;
let delta = deltas
.into_iter()
.fold(AppStatusFx::default(), AppStatusFx::combine);
Ok((state, delta))
})
.await?;
Ok(delta)
}
pub(crate) async fn put_wasm(
&self,
ribosome: RealRibosome,
) -> ConductorResult<Vec<(EntryDefBufferKey, EntryDef)>> {
let dna_def = ribosome.dna_def().clone();
let code = ribosome
.dna_file()
.code()
.clone()
.into_iter()
.map(|(_, c)| c);
let zome_defs = get_entry_defs(ribosome).await?;
self.put_wasm_code(dna_def, code, zome_defs).await
}
pub(crate) async fn put_wasm_code(
&self,
dna: DnaDefHashed,
code: impl Iterator<Item = wasm::DnaWasm>,
zome_defs: Vec<(EntryDefBufferKey, EntryDef)>,
) -> ConductorResult<Vec<(EntryDefBufferKey, EntryDef)>> {
// TODO: PERF: This loop might be slow
let wasms = futures::future::join_all(code.map(DnaWasmHashed::from_content)).await;
self.spaces
.wasm_db
.async_commit({
let zome_defs = zome_defs.clone();
move |txn| {
for dna_wasm in wasms {
if !holochain_state::wasm::contains(txn, dna_wasm.as_hash())? {
holochain_state::wasm::put(txn, dna_wasm)?;
}
}
for (key, entry_def) in zome_defs.clone() {
holochain_state::entry_def::put(txn, key, &entry_def)?;
}
if !holochain_state::dna_def::contains(txn, dna.as_hash())? {
holochain_state::dna_def::put(txn, dna.into_content())?;
}
StateMutationResult::Ok(())
}
})
.await?;
Ok(zome_defs)
}
pub(crate) async fn load_dnas(&self) -> ConductorResult<()> {
let (ribosomes, entry_defs) = self.load_wasms_into_dna_files().await?;
self.ribosome_store().share_mut(|ds| {
ds.add_ribosomes(ribosomes);
ds.add_entry_defs(entry_defs);
});
Ok(())
}
sourcepub fn get_entry_def(&self, k: &EntryDefBufferKey) -> Option<EntryDef>
pub fn get_entry_def(&self, k: &EntryDefBufferKey) -> Option<EntryDef>
Trait Implementations§
source§impl Debug for RibosomeStore
impl Debug for RibosomeStore
source§impl Default for RibosomeStore
impl Default for RibosomeStore
source§fn default() -> RibosomeStore
fn default() -> RibosomeStore
Returns the “default value” for a type. Read more
Auto Trait Implementations§
impl !RefUnwindSafe for RibosomeStore
impl Send for RibosomeStore
impl Sync for RibosomeStore
impl Unpin for RibosomeStore
impl !UnwindSafe for RibosomeStore
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
TODO: once 1.33.0 is the minimum supported compiler version, remove
Any::type_id_compat and use StdAny::type_id instead.
https://github.com/rust-lang/rust/issues/27745
§impl<T> ArchivePointee for T
impl<T> ArchivePointee for T
§type ArchivedMetadata = ()
type ArchivedMetadata = ()
The archived version of the pointer metadata for this type.
§fn pointer_metadata(
_: &<T as ArchivePointee>::ArchivedMetadata
) -> <T as Pointee>::Metadata
fn pointer_metadata(
_: &<T as ArchivePointee>::ArchivedMetadata
) -> <T as Pointee>::Metadata
Converts some archived metadata to the pointer metadata for itself.
§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>
Deserializes using the given deserializer
§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>
The inverse inclusion map: attempts to construct
self
from the equivalent element of its
superset. Read more§fn is_in_subset(&self) -> bool
fn is_in_subset(&self) -> bool
Checks if
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
Use with care! Same as
self.to_subset
but without any property checks. Always succeeds.§fn from_subset(element: &SS) -> SP
fn from_subset(element: &SS) -> SP
The inclusion map: converts
self
to the equivalent element of its superset.§impl<T> Upcastable for Twhere
T: 'static + Any + Send + Sync,
impl<T> Upcastable for Twhere
T: 'static + Any + Send + Sync,
§fn upcast_any_ref(&self) -> &(dyn Any + 'static)
fn upcast_any_ref(&self) -> &(dyn Any + 'static)
upcast ref
§fn upcast_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn upcast_any_mut(&mut self) -> &mut (dyn Any + 'static)
upcast mut ref