Skip to content

Commit

Permalink
more outputs
Browse files Browse the repository at this point in the history
  • Loading branch information
Shane Osbourne committed Jun 4, 2024
1 parent 440fa40 commit 039395b
Show file tree
Hide file tree
Showing 18 changed files with 208 additions and 111 deletions.
3 changes: 2 additions & 1 deletion crates/bsnext_client/generated/dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,8 @@ export type InputErrorDTO =
| { kind: "MarkdownError", payload: string }
| { kind: "Io", payload: string }
| { kind: "UnsupportedExtension", payload: string }
| { kind: "MissingExtension", payload: string };
| { kind: "MissingExtension", payload: string }
| { kind: "EmptyInput", payload: string };

export type ClientEvent =
| { kind: "Change", payload: ChangeDTO };
Expand Down
4 changes: 4 additions & 0 deletions crates/bsnext_client/generated/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,10 @@ export const inputErrorDTOSchema = z.union([
kind: z.literal("MissingExtension"),
payload: z.string(),
}),
z.object({
kind: z.literal("EmptyInput"),
payload: z.string(),
}),
]);

export const debounceDTOSchema = z.object({
Expand Down
4 changes: 4 additions & 0 deletions crates/bsnext_client/inject/dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6422,6 +6422,10 @@ var inputErrorDTOSchema = z.union([
z.object({
kind: z.literal("MissingExtension"),
payload: z.string()
}),
z.object({
kind: z.literal("EmptyInput"),
payload: z.string()
})
]);
var debounceDTOSchema = z.object({
Expand Down
2 changes: 2 additions & 0 deletions crates/bsnext_dto/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,7 @@ pub enum InputErrorDTO {
Io(String),
UnsupportedExtension(String),
MissingExtension(String),
EmptyInput(String),
}

impl From<&InputError> for InputErrorDTO {
Expand All @@ -311,6 +312,7 @@ impl From<&InputError> for InputErrorDTO {
InputErrorDTO::UnsupportedExtension(e.to_string())
}
e @ InputError::MissingExtension(_) => InputErrorDTO::MissingExtension(e.to_string()),
e @ InputError::EmptyInput => InputErrorDTO::EmptyInput(e.to_string()),
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions crates/bsnext_fs/src/inner_fs_event_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ impl Handler<InnerChangeEvent> for FsWatcher {
path: relative.clone(),
}),
ctx: self.ctx.clone(),
span: None,
})
}
}
Expand Down Expand Up @@ -88,6 +89,7 @@ impl Handler<MultipleInnerChangeEvent> for FsWatcher {
recipient.do_send(FsEvent {
kind: evt,
ctx: self.ctx.clone(),
span: None,
})
}
}
Expand Down
8 changes: 6 additions & 2 deletions crates/bsnext_fs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ pub mod watch_path_handler;
mod watcher;

use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tracing::Span;

// use tokio_stream::StreamExt;

Expand Down Expand Up @@ -77,14 +79,16 @@ impl Default for FsEventContext {
pub struct FsEvent {
pub kind: FsEventKind,
pub ctx: FsEventContext,
pub span: Option<Arc<Span>>,
}

#[derive(Debug, Clone)]
pub enum FsEventKind {
Change(ChangeEvent),
ChangeBuffered(BufferedChangeEvent),
PathAdded(PathAddedEvent),
PathRemoved(PathRemovedEvent),
PathRemoved(PathEvent),
PathNotFoundError(PathEvent),
}

#[derive(actix::Message, Debug, Clone)]
Expand Down Expand Up @@ -130,7 +134,7 @@ pub struct PathAddedEvent {

#[derive(actix::Message, Debug, Clone)]
#[rtype(result = "()")]
pub struct PathRemovedEvent {
pub struct PathEvent {
pub path: PathBuf,
}

Expand Down
5 changes: 3 additions & 2 deletions crates/bsnext_fs/src/remove_path_handler.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::actor::FsWatcher;
use crate::{FsEvent, FsEventKind, FsWatchError, PathRemovedEvent};
use crate::{FsEvent, FsEventKind, FsWatchError, PathEvent};
use actix::Handler;
use notify::Watcher;
use std::path::PathBuf;
Expand Down Expand Up @@ -27,12 +27,13 @@ impl Handler<RemoveWatchPath> for FsWatcher {
}
};
for recip in &self.receivers {
let evt = FsEventKind::PathRemoved(PathRemovedEvent {
let evt = FsEventKind::PathRemoved(PathEvent {
path: relative.clone(),
});
recip.do_send(FsEvent {
kind: evt,
ctx: self.ctx.clone(),
span: None,
})
}
}
Expand Down
7 changes: 5 additions & 2 deletions crates/bsnext_fs/src/stop_handler.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
use crate::actor::FsWatcher;
use actix::{ActorContext, Handler};
use std::sync::Arc;
use tracing::{instrument, Span};

#[derive(actix::Message, Debug, Clone)]
#[rtype(result = "()")]
pub struct StopWatcher;
pub struct StopWatcher(pub Arc<Span>);

impl Handler<StopWatcher> for FsWatcher {
type Result = ();

fn handle(&mut self, _msg: StopWatcher, ctx: &mut Self::Context) -> Self::Result {
#[instrument(skip_all, name = "StopWatcher for FsWatcher", parent=msg.0.id())]
fn handle(&mut self, msg: StopWatcher, ctx: &mut Self::Context) -> Self::Result {
self.watcher = None;
ctx.stop();
}
Expand Down
4 changes: 4 additions & 0 deletions crates/bsnext_fs/src/test/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ use actix::{Actor, Addr};
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tempfile::TempDir;

use crate::filter::Filter;
use tokio::time::sleep;
use tracing::Span;

struct A {
events: Vec<FsEvent>,
Expand Down Expand Up @@ -76,6 +78,7 @@ impl TestCase {
let r = RequestWatchPath {
recipients: vec![self.recip_addr.clone().recipient()],
path: self.dir.to_path_buf(),
span: Arc::new(Span::none()),
};

let _ = self.addr.send(r).await;
Expand Down Expand Up @@ -121,6 +124,7 @@ impl TestCase {
.collect(),
FsEventKind::PathAdded(_) => vec![],
FsEventKind::PathRemoved(_) => vec![],
FsEventKind::PathNotFoundError(_) => vec![],
})
.map(|pb| pb.file_name().unwrap().to_string_lossy().to_string())
.collect()
Expand Down
29 changes: 22 additions & 7 deletions crates/bsnext_fs/src/watch_path_handler.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,29 @@
use crate::actor::FsWatcher;
use crate::{FsEvent, FsEventKind, FsWatchError, PathAddedEvent};
use crate::{FsEvent, FsEventKind, PathAddedEvent, PathEvent};
use actix::{ActorContext, Handler, Recipient};
use notify::{RecursiveMode, Watcher};
use std::path::PathBuf;
use std::sync::Arc;
use tracing::{trace_span, Span};

#[derive(actix::Message)]
#[rtype(result = "Result<(), FsWatchError>")]
#[rtype(result = "()")]
pub struct RequestWatchPath {
pub recipients: Vec<Recipient<FsEvent>>,
pub path: PathBuf,
pub span: Arc<Span>,
}

impl Handler<RequestWatchPath> for FsWatcher {
type Result = Result<(), FsWatchError>;
type Result = ();

// todo: ensure this isn't sent for every input change
#[tracing::instrument(skip_all, name = "RequestWatchPath for FsWatcher")]
fn handle(&mut self, msg: RequestWatchPath, _ctx: &mut Self::Context) -> Self::Result {
tracing::trace!(path = ?msg.path, "-> WatchPath");
let span = trace_span!(parent: msg.span.id(), "RequestWatchPath for FsWatcher", ?msg.path);
let s = Arc::new(span);
let span_c = s.clone();
let _guard = s.enter();
// tracing::trace!(path = ?msg.path, "-> WatchPath");
if let Some(watcher) = self.watcher.as_mut() {
match watcher.watch(&msg.path, RecursiveMode::Recursive) {
Ok(_) => {
Expand Down Expand Up @@ -53,16 +59,25 @@ impl Handler<RequestWatchPath> for FsWatcher {
recip.do_send(FsEvent {
kind: evt,
ctx: self.ctx.clone(),
span: Some(span_c.clone()),
})
}
}
Err(err) => {
tracing::error!("cannot watch: {}", err);
for recip in &msg.recipients {
let evt = FsEventKind::PathNotFoundError(PathEvent {
path: msg.path.clone(),
});
recip.do_send(FsEvent {
kind: evt,
ctx: self.ctx.clone(),
span: Some(span_c.clone()),
})
}
_ctx.stop();
return Err(FsWatchError::Watcher(err));
}
}
}
Ok(())
}
}
11 changes: 9 additions & 2 deletions crates/bsnext_input/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ impl Input {
}
fn from_yaml_path<P: AsRef<Path>>(path: P) -> Result<Self, InputError> {
let str = read_to_string(&path)?;
if str.trim().is_empty() {
return Err(InputError::YamlError(YamlError::EmptyError {
path: path.as_ref().to_string_lossy().to_string(),
}));
}
let output = serde_yaml::from_str::<Self>(str.as_str()).map_err(move |e| {
if let Some(location) = e.location() {
YamlError::ParseErrorWithLocation {
Expand Down Expand Up @@ -71,6 +76,8 @@ impl Input {
pub enum InputError {
#[error("no suitable inputs could be found")]
MissingInputs,
#[error("input file is empty")]
EmptyInput,
#[error("could not read input, error: {0}")]
InvalidInput(String),
#[error("io error")]
Expand Down Expand Up @@ -132,10 +139,10 @@ pub enum DirError {
}

#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)]
pub struct PathDefs(Vec<PathDefinition>);
pub struct PathDefs(pub Vec<PathDefinition>);

#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)]
struct PathDefinition {
pub struct PathDefinition {
pub input: String,
pub cwd: PathBuf,
pub absolute: PathBuf,
Expand Down
2 changes: 2 additions & 0 deletions crates/bsnext_input/src/yml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,6 @@ original error:
input: String,
serde_error: serde_yaml::Error,
},
#[error("Input file was empty: {path}")]
EmptyError { path: String },
}
3 changes: 2 additions & 1 deletion crates/bsnext_output/src/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ impl OutputWriter for PrettyPrint {
) -> anyhow::Result<()> {
match evt {
StartupEvent::Started => {
write!(sink, "{}", Line::prefixed().info("started..."))?;
writeln!(sink, "{}", Line::prefixed().info("started..."))?;
}
StartupEvent::FailedStartup(err) => {
writeln!(
Expand Down Expand Up @@ -196,6 +196,7 @@ fn print_input_error<W: Write>(
InputErrorDTO::Io(evt) => evt,
InputErrorDTO::UnsupportedExtension(evt) => evt,
InputErrorDTO::MissingExtension(evt) => evt,
InputErrorDTO::EmptyInput(evt) => evt,
};
writeln!(w, "{}", Line::unprefixed().indent(indent).error(v))?;
Ok(())
Expand Down
6 changes: 3 additions & 3 deletions crates/bsnext_output/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use crate::pretty::PrettyPrint;
use crate::OutputWriter;
use bsnext_dto::{
ExternalEvents, GetServersMessageResponse, IdentityDTO, ServerChange,
ServerChangeSet, ServerChangeSetItem, ServerDTO, ServersStarted, StartupEvent,
ExternalEvents, GetServersMessageResponse, IdentityDTO, ServerChange, ServerChangeSet,
ServerChangeSetItem, ServerDTO, ServersStarted, StartupEvent,
};
use std::io::{BufWriter};
use std::io::BufWriter;

fn iden_1() -> IdentityDTO {
IdentityDTO::Address {
Expand Down
12 changes: 11 additions & 1 deletion crates/bsnext_system/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,17 @@ where
let stdout = &mut std::io::stdout();

match startup_oneshot_receiver.await? {
Ok(DidStart::Started) => tracing::info!("started..."),
Ok(DidStart::Started) => {
let evt = StartupEvent::Started;
match printer.handle_startup_event(stdout, &evt) {
Ok(_) => {}
Err(e) => tracing::error!(?e),
};
match stdout.flush() {
Ok(_) => {}
Err(e) => tracing::error!("could not flush {e}"),
};
}
Err(e) => {
let evt = StartupEvent::FailedStartup((&e).into());
match printer.handle_startup_event(stdout, &evt) {
Expand Down
6 changes: 4 additions & 2 deletions crates/bsnext_system/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ impl BsSystem {
let s = Arc::new(span);
let c = s.clone();
let _c2 = s.clone();

let _g = s.enter();
let route_watchables = to_route_watchables(input);
let server_watchables = to_server_watchables(input);
Expand Down Expand Up @@ -169,7 +168,10 @@ impl BsSystem {

#[tracing::instrument(skip(self))]
fn publish_external_event(&mut self, evt: ExternalEvents) {
tracing::debug!(?evt);
match evt {
ExternalEvents::InputError(_) => tracing::error!(?evt),
_ => tracing::debug!(?evt),
}
let outgoing = EventWithSpan { evt };
if let Some(external_event_sender) = &self.external_event_sender {
Arbiter::current().spawn({
Expand Down
Loading

0 comments on commit 039395b

Please sign in to comment.