Merge pull request #271 from kinode-dao/dr/terminal-color-fix

terminal: color changes and print provenance
This commit is contained in:
doria 2024-03-04 17:47:26 -03:00 committed by GitHub
commit e500e67c22
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
16 changed files with 139 additions and 152 deletions

View File

@ -73,7 +73,7 @@ fn fetch_logs(eth_provider: &eth::Provider, filter: &eth::Filter) -> Vec<eth::Lo
match eth_provider.get_logs(filter) { match eth_provider.get_logs(filter) {
Ok(res) => return res, Ok(res) => return res,
Err(_) => { Err(_) => {
println!("app store: failed to fetch logs! trying again in 5s..."); println!("failed to fetch logs! trying again in 5s...");
std::thread::sleep(std::time::Duration::from_secs(5)); std::thread::sleep(std::time::Duration::from_secs(5));
continue; continue;
} }
@ -86,13 +86,13 @@ fn subscribe_to_logs(eth_provider: &eth::Provider, filter: eth::Filter) {
match eth_provider.subscribe(1, filter.clone()) { match eth_provider.subscribe(1, filter.clone()) {
Ok(()) => break, Ok(()) => break,
Err(_) => { Err(_) => {
println!("app store: failed to subscribe to chain! trying again in 5s..."); println!("failed to subscribe to chain! trying again in 5s...");
std::thread::sleep(std::time::Duration::from_secs(5)); std::thread::sleep(std::time::Duration::from_secs(5));
continue; continue;
} }
} }
} }
println!("app store: subscribed to logs successfully"); println!("subscribed to logs successfully");
} }
call_init!(init); call_init!(init);
@ -124,14 +124,11 @@ fn init(our: Address) {
.unwrap_or(State::new(CONTRACT_ADDRESS.to_string()).unwrap()); .unwrap_or(State::new(CONTRACT_ADDRESS.to_string()).unwrap());
if state.contract_address != CONTRACT_ADDRESS { if state.contract_address != CONTRACT_ADDRESS {
println!("app store: warning: contract address mismatch--overwriting saved state"); println!("warning: contract address mismatch--overwriting saved state");
state = State::new(CONTRACT_ADDRESS.to_string()).unwrap(); state = State::new(CONTRACT_ADDRESS.to_string()).unwrap();
} }
println!( println!("indexing on contract address {}", state.contract_address);
"app store: indexing on contract address {}",
state.contract_address
);
// create new provider for sepolia with request-timeout of 60s // create new provider for sepolia with request-timeout of 60s
// can change, log requests can take quite a long time. // can change, log requests can take quite a long time.
@ -148,7 +145,7 @@ fn init(our: Address) {
for log in fetch_logs(&eth_provider, &filter) { for log in fetch_logs(&eth_provider, &filter) {
if let Err(e) = state.ingest_listings_contract_event(&our, log) { if let Err(e) = state.ingest_listings_contract_event(&our, log) {
println!("app store: error ingesting log: {e:?}"); println!("error ingesting log: {e:?}");
}; };
} }
subscribe_to_logs(&eth_provider, filter); subscribe_to_logs(&eth_provider, filter);
@ -157,7 +154,7 @@ fn init(our: Address) {
match await_message() { match await_message() {
Err(send_error) => { Err(send_error) => {
// TODO handle these based on what they are triggered by // TODO handle these based on what they are triggered by
println!("app store: got network error: {send_error}"); println!("got network error: {send_error}");
} }
Ok(message) => { Ok(message) => {
if let Err(e) = handle_message( if let Err(e) = handle_message(
@ -167,7 +164,7 @@ fn init(our: Address) {
&mut requested_packages, &mut requested_packages,
&message, &message,
) { ) {
println!("app store: error handling message: {:?}", e) println!("error handling message: {:?}", e)
} }
} }
} }
@ -220,7 +217,7 @@ fn handle_message(
spawn_receive_transfer(&our, &body)?; spawn_receive_transfer(&our, &body)?;
} }
Req::FTWorkerResult(r) => { Req::FTWorkerResult(r) => {
println!("app store: got weird ft_worker result: {r:?}"); println!("got weird ft_worker result: {r:?}");
} }
Req::Eth(eth_result) => { Req::Eth(eth_result) => {
if source.node() != our.node() || source.process != "eth:distro:sys" { if source.node() != our.node() || source.process != "eth:distro:sys" {
@ -229,7 +226,7 @@ fn handle_message(
if let Ok(eth::EthSub { result, .. }) = eth_result { if let Ok(eth::EthSub { result, .. }) = eth_result {
handle_eth_sub_event(our, &mut state, result)?; handle_eth_sub_event(our, &mut state, result)?;
} else { } else {
println!("app store: got eth subscription error"); println!("got eth subscription error");
// attempt to resubscribe // attempt to resubscribe
subscribe_to_logs( subscribe_to_logs(
&eth_provider, &eth_provider,
@ -255,7 +252,7 @@ fn handle_message(
Message::Response { body, context, .. } => { Message::Response { body, context, .. } => {
// the only kind of response we care to handle here! // the only kind of response we care to handle here!
let Some(context) = context else { let Some(context) = context else {
return Err(anyhow::anyhow!("app store: missing context")); return Err(anyhow::anyhow!("missing context"));
}; };
handle_ft_worker_result(body, context)?; handle_ft_worker_result(body, context)?;
} }
@ -396,7 +393,7 @@ fn handle_local_request(
for log in fetch_logs(&eth_provider, &filter) { for log in fetch_logs(&eth_provider, &filter) {
if let Err(e) = state.ingest_listings_contract_event(our, log) { if let Err(e) = state.ingest_listings_contract_event(our, log) {
println!("app store: error ingesting log: {e:?}"); println!("error ingesting log: {e:?}");
}; };
} }
subscribe_to_logs(&eth_provider, filter); subscribe_to_logs(&eth_provider, filter);
@ -454,20 +451,16 @@ fn handle_receive_download(
let package_name = package_name[1..].trim_end_matches(".zip"); let package_name = package_name[1..].trim_end_matches(".zip");
let Ok(package_id) = package_name.parse::<PackageId>() else { let Ok(package_id) = package_name.parse::<PackageId>() else {
return Err(anyhow::anyhow!( return Err(anyhow::anyhow!(
"app store: bad package filename fron download: {package_name}" "bad package filename fron download: {package_name}"
)); ));
}; };
println!("app store: successfully received {}", package_id); println!("successfully received {}", package_id);
// only save the package if we actually requested it // only save the package if we actually requested it
let Some(requested_package) = requested_packages.remove(&package_id) else { let Some(requested_package) = requested_packages.remove(&package_id) else {
return Err(anyhow::anyhow!( return Err(anyhow::anyhow!("received unrequested package--rejecting!"));
"app store: received unrequested package--rejecting!"
));
}; };
let Some(blob) = get_blob() else { let Some(blob) = get_blob() else {
return Err(anyhow::anyhow!( return Err(anyhow::anyhow!("received download but found no blob"));
"app store: received download but found no blob"
));
}; };
// check the version hash for this download against requested!! // check the version hash for this download against requested!!
// for now we can reject if it's not latest. // for now we can reject if it's not latest.
@ -482,7 +475,7 @@ fn handle_receive_download(
); );
} else { } else {
return Err(anyhow::anyhow!( return Err(anyhow::anyhow!(
"app store: downloaded package is not desired version--rejecting download! download hash: {download_hash}, desired hash: {hash}" "downloaded package is not desired version--rejecting download! download hash: {download_hash}, desired hash: {hash}"
)); ));
} }
} else { } else {
@ -493,12 +486,12 @@ fn handle_receive_download(
// check against `metadata.properties.current_version` // check against `metadata.properties.current_version`
let Some(package_listing) = state.get_listing(&package_id) else { let Some(package_listing) = state.get_listing(&package_id) else {
return Err(anyhow::anyhow!( return Err(anyhow::anyhow!(
"app store: downloaded package cannot be found in manager--rejecting download!" "downloaded package cannot be found in manager--rejecting download!"
)); ));
}; };
let Some(metadata) = &package_listing.metadata else { let Some(metadata) = &package_listing.metadata else {
return Err(anyhow::anyhow!( return Err(anyhow::anyhow!(
"app store: downloaded package has no metadata to check validity against!" "downloaded package has no metadata to check validity against!"
)); ));
}; };
let Some(latest_hash) = metadata let Some(latest_hash) = metadata
@ -507,7 +500,7 @@ fn handle_receive_download(
.get(&metadata.properties.current_version) .get(&metadata.properties.current_version)
else { else {
return Err(anyhow::anyhow!( return Err(anyhow::anyhow!(
"app store: downloaded package has no versions in manager--rejecting download!" "downloaded package has no versions in manager--rejecting download!"
)); ));
}; };
if &download_hash != latest_hash { if &download_hash != latest_hash {
@ -517,7 +510,7 @@ fn handle_receive_download(
); );
} else { } else {
return Err(anyhow::anyhow!( return Err(anyhow::anyhow!(
"app store: downloaded package is not latest version--rejecting download! download hash: {download_hash}, latest hash: {latest_hash}" "downloaded package is not latest version--rejecting download! download hash: {download_hash}, latest hash: {latest_hash}"
)); ));
} }
} else { } else {
@ -571,7 +564,7 @@ fn handle_ft_worker_result(body: &[u8], context: &[u8]) -> anyhow::Result<()> {
let context = serde_json::from_slice::<FileTransferContext>(context)?; let context = serde_json::from_slice::<FileTransferContext>(context)?;
if let FTWorkerResult::SendSuccess = ft_worker_result { if let FTWorkerResult::SendSuccess = ft_worker_result {
println!( println!(
"app store: successfully shared {} in {:.4}s", "successfully shared {} in {:.4}s",
context.file_name, context.file_name,
std::time::SystemTime::now() std::time::SystemTime::now()
.duration_since(context.start_time) .duration_since(context.start_time)
@ -579,7 +572,7 @@ fn handle_ft_worker_result(body: &[u8], context: &[u8]) -> anyhow::Result<()> {
.as_secs_f64(), .as_secs_f64(),
); );
} else { } else {
return Err(anyhow::anyhow!("app store: failed to share app")); return Err(anyhow::anyhow!("failed to share app"));
} }
} }
Ok(()) Ok(())
@ -591,7 +584,7 @@ fn handle_eth_sub_event(
event: eth::SubscriptionResult, event: eth::SubscriptionResult,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
let eth::SubscriptionResult::Log(log) = event else { let eth::SubscriptionResult::Log(log) = event else {
return Err(anyhow::anyhow!("app store: got non-log event")); return Err(anyhow::anyhow!("got non-log event"));
}; };
state.ingest_listings_contract_event(our, *log) state.ingest_listings_contract_event(our, *log)
} }
@ -630,7 +623,7 @@ pub fn handle_install(
"drive": drive_path, "drive": drive_path,
}))?, }))?,
) else { ) else {
return Err(anyhow::anyhow!("app store: no read cap")); return Err(anyhow::anyhow!("no read cap"));
}; };
let Some(write_cap) = get_capability( let Some(write_cap) = get_capability(
&Address::new(&our.node, ("vfs", "distro", "sys")), &Address::new(&our.node, ("vfs", "distro", "sys")),
@ -639,13 +632,13 @@ pub fn handle_install(
"drive": drive_path, "drive": drive_path,
}))?, }))?,
) else { ) else {
return Err(anyhow::anyhow!("app store: no write cap")); return Err(anyhow::anyhow!("no write cap"));
}; };
let Some(networking_cap) = get_capability( let Some(networking_cap) = get_capability(
&Address::new(&our.node, ("kernel", "distro", "sys")), &Address::new(&our.node, ("kernel", "distro", "sys")),
&"\"network\"".to_string(), &"\"network\"".to_string(),
) else { ) else {
return Err(anyhow::anyhow!("app store: no net cap")); return Err(anyhow::anyhow!("no net cap"));
}; };
// first, for each process in manifest, initialize it // first, for each process in manifest, initialize it
// then, once all have been initialized, grant them requested caps // then, once all have been initialized, grant them requested caps
@ -659,7 +652,7 @@ pub fn handle_install(
let wasm_path = format!("{}{}", drive_path, wasm_path); let wasm_path = format!("{}{}", drive_path, wasm_path);
let process_id = format!("{}:{}", entry.process_name, package_id); let process_id = format!("{}:{}", entry.process_name, package_id);
let Ok(parsed_new_process_id) = process_id.parse::<ProcessId>() else { let Ok(parsed_new_process_id) = process_id.parse::<ProcessId>() else {
return Err(anyhow::anyhow!("app store: invalid process id!")); return Err(anyhow::anyhow!("invalid process id!"));
}; };
// kill process if it already exists // kill process if it already exists
Request::to(("our", "kernel", "distro", "sys")) Request::to(("our", "kernel", "distro", "sys"))
@ -757,7 +750,7 @@ pub fn handle_install(
for entry in &manifest { for entry in &manifest {
let process_id = format!("{}:{}", entry.process_name, package_id); let process_id = format!("{}:{}", entry.process_name, package_id);
let Ok(parsed_new_process_id) = process_id.parse::<ProcessId>() else { let Ok(parsed_new_process_id) = process_id.parse::<ProcessId>() else {
return Err(anyhow::anyhow!("app store: invalid process id!")); return Err(anyhow::anyhow!("invalid process id!"));
}; };
for value in &entry.grant_capabilities { for value in &entry.grant_capabilities {
match value { match value {

View File

@ -108,7 +108,7 @@ impl State {
/// To create a new state, we populate the downloaded_packages map /// To create a new state, we populate the downloaded_packages map
/// with all packages parseable from our filesystem. /// with all packages parseable from our filesystem.
pub fn new(contract_address: String) -> anyhow::Result<Self> { pub fn new(contract_address: String) -> anyhow::Result<Self> {
crate::print_to_terminal(1, "app store: producing new state"); crate::print_to_terminal(1, "producing new state");
let mut state = State { let mut state = State {
contract_address, contract_address,
last_saved_block: 1, last_saved_block: 1,
@ -361,7 +361,7 @@ impl State {
self.downloaded_packages.remove(package_id); self.downloaded_packages.remove(package_id);
crate::set_state(&bincode::serialize(self)?); crate::set_state(&bincode::serialize(self)?);
println!("app store: uninstalled {package_id}"); println!("uninstalled {package_id}");
Ok(()) Ok(())
} }
@ -373,7 +373,7 @@ impl State {
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
let block_number: u64 = log let block_number: u64 = log
.block_number .block_number
.ok_or(anyhow::anyhow!("app store: got log with no block number"))? .ok_or(anyhow::anyhow!("got log with no block number"))?
.try_into()?; .try_into()?;
// let package_hash: alloy_primitives::U256 = log.topics[1].into(); // let package_hash: alloy_primitives::U256 = log.topics[1].into();
@ -398,15 +398,11 @@ impl State {
if generate_package_hash(&package_name, publisher_dnswire.as_slice()) if generate_package_hash(&package_name, publisher_dnswire.as_slice())
!= package_hash != package_hash
{ {
return Err(anyhow::anyhow!( return Err(anyhow::anyhow!("got log with mismatched package hash"));
"app store: got log with mismatched package hash"
));
} }
let Ok(publisher_name) = dnswire_decode(publisher_dnswire.as_slice()) else { let Ok(publisher_name) = dnswire_decode(publisher_dnswire.as_slice()) else {
return Err(anyhow::anyhow!( return Err(anyhow::anyhow!("got log with invalid publisher name"));
"app store: got log with invalid publisher name"
));
}; };
let metadata = fetch_metadata(&metadata_url, &metadata_hash).ok(); let metadata = fetch_metadata(&metadata_url, &metadata_hash).ok();
@ -414,7 +410,7 @@ impl State {
if let Some(metadata) = &metadata { if let Some(metadata) = &metadata {
if metadata.properties.publisher != publisher_name { if metadata.properties.publisher != publisher_name {
return Err(anyhow::anyhow!(format!( return Err(anyhow::anyhow!(format!(
"app store: metadata publisher name mismatch: got {}, expected {}", "metadata publisher name mismatch: got {}, expected {}",
metadata.properties.publisher, publisher_name metadata.properties.publisher, publisher_name
))); )));
} }
@ -454,25 +450,20 @@ impl State {
let current_listing = self let current_listing = self
.get_listing_with_hash_mut(&package_hash.to_string()) .get_listing_with_hash_mut(&package_hash.to_string())
.ok_or(anyhow::anyhow!( .ok_or(anyhow::anyhow!("got log with no matching listing"))?;
"app store: got log with no matching listing"
))?;
let metadata = match fetch_metadata(&metadata_url, &metadata_hash) { let metadata = match fetch_metadata(&metadata_url, &metadata_hash) {
Ok(metadata) => { Ok(metadata) => {
if metadata.properties.publisher != current_listing.publisher { if metadata.properties.publisher != current_listing.publisher {
return Err(anyhow::anyhow!(format!( return Err(anyhow::anyhow!(format!(
"app store: metadata publisher name mismatch: got {}, expected {}", "metadata publisher name mismatch: got {}, expected {}",
metadata.properties.publisher, current_listing.publisher metadata.properties.publisher, current_listing.publisher
))); )));
} }
Some(metadata) Some(metadata)
} }
Err(e) => { Err(e) => {
crate::print_to_terminal( crate::print_to_terminal(1, &format!("failed to fetch metadata: {e:?}"));
1,
&format!("app store: failed to fetch metadata: {e:?}"),
);
None None
} }
}; };
@ -490,9 +481,7 @@ impl State {
if let Some(mirrored_from) = &package_state.mirrored_from { if let Some(mirrored_from) = &package_state.mirrored_from {
crate::print_to_terminal( crate::print_to_terminal(
1, 1,
&format!( &format!("auto-updating package {package_id} from {mirrored_from}"),
"app store: auto-updating package {package_id} from {mirrored_from}"
),
); );
Request::to(our) Request::to(our)
.body(serde_json::to_vec(&LocalRequest::Download { .body(serde_json::to_vec(&LocalRequest::Download {
@ -542,11 +531,9 @@ impl State {
self.delete_listing(&package_hash); self.delete_listing(&package_hash);
} else { } else {
crate::print_to_terminal(1, "transferring listing"); crate::print_to_terminal(1, "transferring listing");
let current_listing = let current_listing = self
self.get_listing_with_hash_mut(&package_hash) .get_listing_with_hash_mut(&package_hash)
.ok_or(anyhow::anyhow!( .ok_or(anyhow::anyhow!("got log with no matching listing"))?;
"app store: got log with no matching listing"
))?;
current_listing.owner = to.to_string(); current_listing.owner = to.to_string();
} }
} }

View File

@ -189,7 +189,7 @@ fn handle_request(our: &Address, message: &Message, state: &mut ChessState) -> a
None, None,
"Service Unavailable".to_string().as_bytes().to_vec(), "Service Unavailable".to_string().as_bytes().to_vec(),
); );
Err(anyhow::anyhow!("chess: error handling http request: {e:?}")) Err(anyhow::anyhow!("error handling http request: {e:?}"))
} }
} }
} }
@ -228,7 +228,7 @@ fn handle_chess_request(
state: &mut ChessState, state: &mut ChessState,
action: &ChessRequest, action: &ChessRequest,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
println!("chess: handling action from {source_node}: {action:?}"); println!("handling action from {source_node}: {action:?}");
// For simplicity's sake, we'll just use the node we're playing with as the game id. // For simplicity's sake, we'll just use the node we're playing with as the game id.
// This limits us to one active game per partner. // This limits us to one active game per partner.

View File

@ -21,7 +21,7 @@ impl Guest for Component {
match main(our) { match main(our) {
Ok(_) => {} Ok(_) => {}
Err(e) => { Err(e) => {
println!("homepage: ended with error: {:?}", e); println!("ended with error: {:?}", e);
} }
} }
} }
@ -61,7 +61,7 @@ fn main(our: Address) -> anyhow::Result<()> {
loop { loop {
let Ok(ref message) = await_message() else { let Ok(ref message) = await_message() else {
println!("homepage: got network error??"); println!("got network error??");
continue; continue;
}; };
if let Message::Response { source, body, .. } = message if let Message::Response { source, body, .. } = message
@ -69,12 +69,12 @@ fn main(our: Address) -> anyhow::Result<()> {
{ {
match serde_json::from_slice::<Result<(), HttpServerError>>(&body) { match serde_json::from_slice::<Result<(), HttpServerError>>(&body) {
Ok(Ok(())) => continue, Ok(Ok(())) => continue,
Ok(Err(e)) => println!("homepage: got error from http_server: {e}"), Ok(Err(e)) => println!("got error from http_server: {e}"),
Err(_e) => println!("homepage: got malformed message from http_server!"), Err(_e) => println!("got malformed message from http_server!"),
} }
} else { } else {
println!("homepage: got message: {message:?}"); println!("got message: {message:?}");
//println!("homepage: got message from {source:?}: {message:?}"); //println!("got message from {source:?}: {message:?}");
} }
} }
} }

View File

@ -99,13 +99,13 @@ fn subscribe_to_logs(eth_provider: &eth::Provider, from_block: u64, filter: eth:
match eth_provider.subscribe(1, filter.clone().from_block(from_block)) { match eth_provider.subscribe(1, filter.clone().from_block(from_block)) {
Ok(()) => break, Ok(()) => break,
Err(_) => { Err(_) => {
println!("kns_indexer: failed to subscribe to chain! trying again in 5s..."); println!("failed to subscribe to chain! trying again in 5s...");
std::thread::sleep(std::time::Duration::from_secs(5)); std::thread::sleep(std::time::Duration::from_secs(5));
continue; continue;
} }
} }
} }
println!("kns_indexer: subscribed to logs successfully"); println!("subscribed to logs successfully");
} }
struct Component; struct Component;
@ -127,10 +127,7 @@ impl Guest for Component {
(chain_id, contract_address) = serde_json::from_slice(&body).unwrap(); (chain_id, contract_address) = serde_json::from_slice(&body).unwrap();
break; break;
} }
println!( println!("indexing on contract address {}", contract_address);
"kns_indexer: indexing on contract address {}",
contract_address
);
// if we have state, load it in // if we have state, load it in
let state: State = match get_typed_state(|bytes| Ok(bincode::deserialize::<State>(bytes)?)) let state: State = match get_typed_state(|bytes| Ok(bincode::deserialize::<State>(bytes)?))
@ -138,7 +135,9 @@ impl Guest for Component {
Some(s) => { Some(s) => {
// if chain id or contract address changed from a previous run, reset state // if chain id or contract address changed from a previous run, reset state
if s.chain_id != chain_id || s.contract_address != contract_address { if s.chain_id != chain_id || s.contract_address != contract_address {
println!("kns_indexer: resetting state because runtime contract address or chain ID changed"); println!(
"resetting state because runtime contract address or chain ID changed"
);
State { State {
chain_id, chain_id,
contract_address, contract_address,
@ -147,10 +146,7 @@ impl Guest for Component {
block: 1, block: 1,
} }
} else { } else {
println!( println!("loading in {} persisted PKI entries", s.nodes.len());
"kns_indexer: loading in {} persisted PKI entries",
s.nodes.len()
);
s s
} }
} }
@ -166,7 +162,7 @@ impl Guest for Component {
match main(our, state) { match main(our, state) {
Ok(_) => {} Ok(_) => {}
Err(e) => { Err(e) => {
println!("kns_indexer: error: {:?}", e); println!("error: {:?}", e);
} }
} }
} }
@ -208,7 +204,7 @@ fn main(our: Address, mut state: State) -> anyhow::Result<()> {
break; break;
} }
Err(_) => { Err(_) => {
println!("kns_indexer: failed to fetch logs! trying again in 5s..."); println!("failed to fetch logs! trying again in 5s...");
std::thread::sleep(std::time::Duration::from_secs(5)); std::thread::sleep(std::time::Duration::from_secs(5));
continue; continue;
} }
@ -231,7 +227,7 @@ fn main(our: Address, mut state: State) -> anyhow::Result<()> {
loop { loop {
let Ok(message) = await_message() else { let Ok(message) = await_message() else {
println!("kns_indexer: got network error"); println!("got network error");
continue; continue;
}; };
let Message::Request { source, body, .. } = message else { let Message::Request { source, body, .. } = message else {
@ -251,7 +247,7 @@ fn main(our: Address, mut state: State) -> anyhow::Result<()> {
)?; )?;
} else { } else {
let Ok(request) = serde_json::from_slice::<IndexerRequests>(&body) else { let Ok(request) = serde_json::from_slice::<IndexerRequests>(&body) else {
println!("kns_indexer: got invalid message"); println!("got invalid message");
continue; continue;
}; };
@ -294,7 +290,7 @@ fn handle_eth_message(
filter: &eth::Filter, filter: &eth::Filter,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
let Ok(eth_result) = serde_json::from_slice::<eth::EthSubResult>(body) else { let Ok(eth_result) = serde_json::from_slice::<eth::EthSubResult>(body) else {
return Err(anyhow::anyhow!("kns_indexer: got invalid message")); return Err(anyhow::anyhow!("got invalid message"));
}; };
match eth_result { match eth_result {
@ -304,7 +300,7 @@ fn handle_eth_message(
} }
} }
Err(_e) => { Err(_e) => {
println!("kns_indexer: got eth subscription error"); println!("got eth subscription error");
subscribe_to_logs(&eth_provider, state.block - 1, filter.clone()); subscribe_to_logs(&eth_provider, state.block - 1, filter.clone());
} }
} }
@ -415,7 +411,7 @@ fn handle_log(our: &Address, state: &mut State, log: &eth::Log) -> anyhow::Resul
let block = log.block_number.expect("expect").to::<u64>(); let block = log.block_number.expect("expect").to::<u64>();
if block > state.block + 100 { if block > state.block + 100 {
println!( println!(
"kns_indexer: persisting {} PKI entries at block {}", "persisting {} PKI entries at block {}",
state.nodes.len(), state.nodes.len(),
block block
); );
@ -430,7 +426,7 @@ fn get_name(log: &eth::Log) -> String {
let name = match dnswire_decode(decoded.0.clone()) { let name = match dnswire_decode(decoded.0.clone()) {
Ok(n) => n, Ok(n) => n,
Err(_) => { Err(_) => {
println!("kns_indexer: failed to decode name: {:?}", decoded.0); println!("failed to decode name: {:?}", decoded.0);
panic!("") panic!("")
} }
}; };

View File

@ -23,11 +23,11 @@ call_init!(init);
fn init(_our: Address) { fn init(_our: Address) {
let Ok(args) = await_next_request_body() else { let Ok(args) = await_next_request_body() else {
println!("alias: failed to get args, aborting"); println!("failed to get args, aborting");
return; return;
}; };
let line = String::from_utf8(args).unwrap_or("alias: error".into()); let line = String::from_utf8(args).unwrap_or("error".into());
if line.is_empty() { if line.is_empty() {
println!("Change alias for a process"); println!("Change alias for a process");
println!("\x1b[1mUsage:\x1b[0m alias <alias_name> <process_id>"); println!("\x1b[1mUsage:\x1b[0m alias <alias_name> <process_id>");
@ -37,7 +37,7 @@ fn init(_our: Address) {
let (alias, process) = line.split_once(" ").unwrap_or((&line, "")); let (alias, process) = line.split_once(" ").unwrap_or((&line, ""));
if alias.is_empty() { if alias.is_empty() {
println!("alias: no alias given"); println!("no alias given");
return; return;
} }
@ -67,7 +67,7 @@ fn init(_our: Address) {
.send(); .send();
} }
Err(_) => { Err(_) => {
println!("alias: invalid process id"); println!("invalid process id");
} }
} }
} }

View File

@ -14,12 +14,12 @@ call_init!(init);
fn init(_our: Address) { fn init(_our: Address) {
let Ok(args) = await_next_request_body() else { let Ok(args) = await_next_request_body() else {
println!("cat: failed to get args, aborting"); println!("failed to get args, aborting");
return; return;
}; };
let Ok(file_path) = String::from_utf8(args) else { let Ok(file_path) = String::from_utf8(args) else {
println!("cat: bad args, aborting"); println!("bad args, aborting");
return; return;
}; };

View File

@ -12,7 +12,7 @@ call_init!(init);
fn init(_our: Address) { fn init(_our: Address) {
let Ok(args) = await_next_request_body() else { let Ok(args) = await_next_request_body() else {
println!("echo: failed to get args, aborting"); println!("failed to get args, aborting");
return; return;
}; };

View File

@ -14,7 +14,7 @@ call_init!(init);
fn init(our: Address) { fn init(our: Address) {
let Ok(args) = await_next_request_body() else { let Ok(args) = await_next_request_body() else {
println!("hi: failed to get args, aborting"); println!("failed to get args, aborting");
return; return;
}; };
@ -28,7 +28,7 @@ fn init(our: Address) {
let (node_id, message) = match tail.split_once(" ") { let (node_id, message) = match tail.split_once(" ") {
Some((s, t)) => (s, t), Some((s, t)) => (s, t),
None => { None => {
println!("hi: invalid command, please provide a message"); println!("invalid command, please provide a message");
return; return;
} }
}; };
@ -48,12 +48,10 @@ fn init(our: Address) {
} }
Err(SendError { kind, .. }) => match kind { Err(SendError { kind, .. }) => match kind {
SendErrorKind::Timeout => { SendErrorKind::Timeout => {
println!("hi: message to {node_id} timed out"); println!("message to {node_id} timed out");
return;
} }
SendErrorKind::Offline => { SendErrorKind::Offline => {
println!("hi: {node_id} is offline or does not exist"); println!("{node_id} is offline or does not exist");
return;
} }
}, },
} }

View File

@ -16,7 +16,7 @@ call_init!(init);
fn init(_our: Address) { fn init(_our: Address) {
let Ok(body) = await_next_request_body() else { let Ok(body) = await_next_request_body() else {
println!("m: failed to get args, aborting"); println!("failed to get args, aborting");
return; return;
}; };
let body_string = String::from_utf8(body).unwrap(); let body_string = String::from_utf8(body).unwrap();
@ -54,12 +54,12 @@ fn init(_our: Address) {
) )
.try_get_matches_from(args) .try_get_matches_from(args)
else { else {
println!("m: failed to parse args"); println!("failed to parse args");
return; return;
}; };
let Some(target) = parsed.get_one::<String>("target") else { let Some(target) = parsed.get_one::<String>("target") else {
println!("m: no target"); println!("no target");
return; return;
}; };
@ -69,7 +69,7 @@ fn init(_our: Address) {
}; };
let Some(body) = parsed.get_one::<String>("body") else { let Some(body) = parsed.get_one::<String>("body") else {
println!("m: no body"); println!("no body");
return; return;
}; };
@ -77,14 +77,14 @@ fn init(_our: Address) {
match parsed.get_one::<u64>("await") { match parsed.get_one::<u64>("await") {
Some(s) => { Some(s) => {
println!("m: awaiting response for {}s", s); println!("awaiting response for {}s", s);
match req.send_and_await_response(*s).unwrap() { match req.send_and_await_response(*s).unwrap() {
Ok(res) => { Ok(res) => {
println!("{}", String::from_utf8(res.body().to_vec()).unwrap()); println!("{}", String::from_utf8(res.body().to_vec()).unwrap());
} }
Err(e) => { Err(e) => {
println!( println!(
"m: {}", "{}",
match e.kind { match e.kind {
SendErrorKind::Timeout => SendErrorKind::Timeout =>
"target did not send Response in time, try increasing the await time", "target did not send Response in time, try increasing the await time",

View File

@ -92,7 +92,7 @@ impl Guest for Component {
let (source, message) = match wit::receive() { let (source, message) = match wit::receive() {
Ok((source, message)) => (source, message), Ok((source, message)) => (source, message),
Err((error, _context)) => { Err((error, _context)) => {
println!("terminal: net error: {:?}!", error.kind); println!("net error: {:?}!", error.kind);
continue; continue;
} }
}; };
@ -104,25 +104,25 @@ impl Guest for Component {
std::str::from_utf8(&body).unwrap_or_default(), std::str::from_utf8(&body).unwrap_or_default(),
) { ) {
Ok(()) => continue, Ok(()) => continue,
Err(e) => println!("terminal: {e}"), Err(e) => println!("{e}"),
} }
} else if state.our.node == source.node } else if state.our.node == source.node
&& state.our.package() == source.package() && state.our.package() == source.package()
{ {
let Ok(action) = serde_json::from_slice::<TerminalAction>(&body) else { let Ok(action) = serde_json::from_slice::<TerminalAction>(&body) else {
println!("terminal: failed to parse action from: {}", source); println!("failed to parse action from: {}", source);
continue; continue;
}; };
match action { match action {
TerminalAction::EditAlias { alias, process } => { TerminalAction::EditAlias { alias, process } => {
match handle_alias_change(&mut state, alias, process) { match handle_alias_change(&mut state, alias, process) {
Ok(()) => continue, Ok(()) => continue,
Err(e) => println!("terminal: {e}"), Err(e) => println!("{e}"),
}; };
} }
} }
} else { } else {
println!("terminal: ignoring message from: {}", source); println!("ignoring message from: {}", source);
continue; continue;
} }
} }
@ -154,7 +154,7 @@ fn handle_run(our: &Address, process: &ProcessId, args: String) -> anyhow::Resul
// build initial caps // build initial caps
let process_id = format!("{}:{}", rand::random::<u64>(), package); // all scripts are given random process IDs let process_id = format!("{}:{}", rand::random::<u64>(), package); // all scripts are given random process IDs
let Ok(parsed_new_process_id) = process_id.parse::<ProcessId>() else { let Ok(parsed_new_process_id) = process_id.parse::<ProcessId>() else {
return Err(anyhow::anyhow!("terminal: invalid process id!")); return Err(anyhow::anyhow!("invalid process id!"));
}; };
let _bytes_response = Request::new() let _bytes_response = Request::new()
@ -337,18 +337,18 @@ fn handle_alias_change(
Some(process) => { Some(process) => {
// first check to make sure the script is actually a script // first check to make sure the script is actually a script
let Ok(_) = get_entry(&process) else { let Ok(_) = get_entry(&process) else {
return Err(anyhow!("terminal: process {} not found", process)); return Err(anyhow!("process {} not found", process));
}; };
state.aliases.insert(alias.clone(), process.clone()); state.aliases.insert(alias.clone(), process.clone());
println!("terminal: alias {} set to {}", alias, process); println!("alias {} set to {}", alias, process);
} }
None => { None => {
if state.aliases.contains_key(&alias) { if state.aliases.contains_key(&alias) {
state.aliases.remove(&alias); state.aliases.remove(&alias);
println!("terminal: alias {} removed", alias); println!("alias {} removed", alias);
} else { } else {
println!("terminal: alias {} not found", alias); println!("alias {} not found", alias);
} }
} }
} }

View File

@ -15,12 +15,12 @@ call_init!(init);
fn init(_our: Address) { fn init(_our: Address) {
let Ok(args) = await_next_request_body() else { let Ok(args) = await_next_request_body() else {
println!("top: failed to get args, aborting"); println!("failed to get args, aborting");
return; return;
}; };
let Ok(proc_id) = String::from_utf8(args) else { let Ok(proc_id) = String::from_utf8(args) else {
println!("top: failed to stringify arguments"); println!("failed to stringify arguments");
return; return;
}; };
@ -41,8 +41,7 @@ fn init(_our: Address) {
.send(); .send();
} }
Err(_) => { Err(_) => {
println!("top: invalid process id"); println!("invalid process id");
return;
} }
} }
} }

View File

@ -59,7 +59,7 @@ fn handle_message(
test_timeout, test_timeout,
.. ..
} => { } => {
println!("tester: got Run"); println!("got Run");
assert!(input_node_names.len() >= 1); assert!(input_node_names.len() >= 1);
*node_names = input_node_names.clone(); *node_names = input_node_names.clone();

View File

@ -26,10 +26,20 @@ impl StandardHost for process::ProcessWasi {
// system utils: // system utils:
// //
/// Print a message to the runtime terminal. Add the name of the process to the
/// beginning of the string, so user can verify source.
async fn print_to_terminal(&mut self, verbosity: u8, content: String) -> Result<()> { async fn print_to_terminal(&mut self, verbosity: u8, content: String) -> Result<()> {
self.process self.process
.send_to_terminal .send_to_terminal
.send(t::Printout { verbosity, content }) .send(t::Printout {
verbosity,
content: format!(
"{}:{}: {}",
self.process.metadata.our.process.package(),
self.process.metadata.our.process.publisher(),
content
),
})
.await .await
.map_err(|e| anyhow::anyhow!("fatal: couldn't send to terminal: {e:?}")) .map_err(|e| anyhow::anyhow!("fatal: couldn't send to terminal: {e:?}"))
} }

View File

@ -249,9 +249,7 @@ async fn main() {
{ {
ip ip
} else { } else {
println!( println!("failed to find public IPv4 address: booting as a routed node");
"\x1b[38;5;196mfailed to find public IPv4 address: booting as a routed node\x1b[0m"
);
std::net::Ipv4Addr::LOCALHOST std::net::Ipv4Addr::LOCALHOST
} }
}; };
@ -586,7 +584,7 @@ async fn main() {
let quit_msg: String = tokio::select! { let quit_msg: String = tokio::select! {
Some(Ok(res)) = tasks.join_next() => { Some(Ok(res)) = tasks.join_next() => {
format!( format!(
"\x1b[38;5;196muh oh, a kernel process crashed -- this should never happen: {:?}\x1b[0m", "uh oh, a kernel process crashed -- this should never happen: {:?}",
res res
) )
} }
@ -641,6 +639,8 @@ async fn main() {
stdout, stdout,
crossterm::event::DisableBracketedPaste, crossterm::event::DisableBracketedPaste,
crossterm::terminal::SetTitle(""), crossterm::terminal::SetTitle(""),
crossterm::style::SetForegroundColor(crossterm::style::Color::Red),
crossterm::style::Print(format!("\r\n{quit_msg}")),
crossterm::style::ResetColor,
); );
println!("\r\n\x1b[38;5;196m{}\x1b[0m", quit_msg);
} }

View File

@ -6,7 +6,7 @@ use crossterm::{
DisableBracketedPaste, EnableBracketedPaste, Event, EventStream, KeyCode, KeyEvent, DisableBracketedPaste, EnableBracketedPaste, Event, EventStream, KeyCode, KeyEvent,
KeyModifiers, KeyModifiers,
}, },
execute, execute, style,
style::Print, style::Print,
terminal::{self, disable_raw_mode, enable_raw_mode, ClearType}, terminal::{self, disable_raw_mode, enable_raw_mode, ClearType},
}; };
@ -64,9 +64,10 @@ pub async fn terminal(
let (mut win_cols, mut win_rows) = terminal::size().unwrap(); let (mut win_cols, mut win_rows) = terminal::size().unwrap();
// print initial splash screen, large if there's room, small otherwise // print initial splash screen, large if there's room, small otherwise
if win_cols >= 90 { if win_cols >= 90 {
println!( execute!(
"\x1b[38;5;128m{}\x1b[0m", stdout,
format_args!( style::SetForegroundColor(style::Color::Magenta),
Print(format!(
r#" r#"
888 d8P d8b 888 888 d8P d8b 888
@ -95,12 +96,14 @@ pub async fn terminal(
}, },
version, version,
our.networking_key, our.networking_key,
) )),
); style::ResetColor
)?;
} else { } else {
println!( execute!(
"\x1b[38;5;128m{}\x1b[0m", stdout,
format_args!( style::SetForegroundColor(style::Color::Magenta),
Print(format!(
r#" r#"
888 d8P d8b 888 888 d8P d8b 888
888 d8P Y8P 888 888 d8P Y8P 888
@ -124,8 +127,9 @@ pub async fn terminal(
}, },
version, version,
our.networking_key, our.networking_key,
) )),
); style::ResetColor
)?;
} }
let _raw_mode = if is_detached { let _raw_mode = if is_detached {
@ -202,24 +206,24 @@ pub async fn terminal(
stdout, stdout,
cursor::MoveTo(0, win_rows - 1), cursor::MoveTo(0, win_rows - 1),
terminal::Clear(ClearType::CurrentLine), terminal::Clear(ClearType::CurrentLine),
Print(format!("{}{} {}/{} {:02}:{:02} ", Print(format!("{} {:02}:{:02} ",
match printout.verbosity {
0 => "",
1 => "1",
2 => "2",
_ => "3",
},
now.weekday(), now.weekday(),
now.month(),
now.day(),
now.hour(), now.hour(),
now.minute(), now.minute(),
)), )),
)?; )?;
let color = match printout.verbosity {
0 => style::Color::Black,
1 => style::Color::Green,
2 => style::Color::Magenta,
_ => style::Color::Red,
};
for line in printout.content.lines() { for line in printout.content.lines() {
execute!( execute!(
stdout, stdout,
Print(format!("\x1b[38;5;238m{}\x1b[0m\r\n", line)), style::SetForegroundColor(color),
Print(format!("{}\r\n", line)),
style::ResetColor,
)?; )?;
} }
execute!( execute!(