use std::io::Write;
use std::path::Path;
use std::process::ExitCode;
#[derive(Debug, lgwks_macros::Error)]
#[non_exhaustive]
pub enum Failure {
#[error("{0}")]
Input(String),
#[error("I/O failure: {0}")]
Io(#[from] std::io::Error),
#[error("invalid UTF-8: {0}")]
Utf8(#[from] std::string::FromUtf8Error),
#[error("input size overflow")]
SizeOverflow(#[from] std::num::TryFromIntError),
#[error("invalid JSON: {0}")]
Json(#[from] lgwks_std::json::Error),
#[error("trace rejected: {0}")]
Check(#[from] crate::preview::TraceCheckError),
#[error("scene failure: {0}")]
Scene(#[from] crate::canvas_scene::model::Error),
#[error("invalid session: {0}")]
Session(#[from] crate::canvas_protocol::SessionInvariantError),
#[cfg(feature = "desktop")]
#[error("event loop failure: {0}")]
EventLoop(#[from] lgwks_deps::winit::error::EventLoopError),
#[cfg(feature = "desktop")]
#[error("window creation failure: {0}")]
Window(#[from] lgwks_deps::winit::error::OsError),
#[cfg(feature = "desktop")]
#[error("surface failure: {0}")]
Surface(#[from] lgwks_deps::softbuffer::SoftBufferError),
}
impl From<&str> for Failure {
fn from(message: &str) -> Self {
Self::Input(String::from(message))
}
}
impl From<String> for Failure {
fn from(message: String) -> Self {
Self::Input(message)
}
}
pub struct Streams<'sink> {
out: &'sink mut dyn Write,
err: &'sink mut dyn Write,
}
impl Streams<'_> {
fn new<'sink>(out: &'sink mut dyn Write, err: &'sink mut dyn Write) -> Streams<'sink> {
Streams { out, err }
}
pub fn tell(&mut self, text: &str) -> Result<(), Failure> {
writeln!(self.out, "{text}")
.map_err(|error| Failure::from(format!("the report was not written: {error}")))
}
pub fn warn(&mut self, text: &str) -> Result<(), Failure> {
writeln!(self.err, "{text}")
.map_err(|error| Failure::from(format!("the report was not written: {error}")))
}
pub fn out(&mut self) -> &mut dyn Write {
&mut *self.out
}
}
pub fn read_bounded(path: &Path, cap: u64, over_message: &'static str) -> Result<Vec<u8>, Failure> {
let size = std::fs::metadata(path)?.len();
(size <= cap)
.then_some(())
.ok_or_else(|| Failure::from(over_message))?;
let file = std::fs::File::open(path)?;
let mut bytes = Vec::new();
use std::io::Read as _;
file.take(cap.saturating_add(1)).read_to_end(&mut bytes)?;
(u64::try_from(bytes.len())? <= cap)
.then_some(())
.ok_or_else(|| Failure::from(over_message))?;
Ok(bytes)
}
pub fn run<F>(program: &'static str, execute: F) -> ExitCode
where
F: FnOnce(&mut Streams<'_>) -> Result<u8, Failure>,
{
let stdout = std::io::stdout();
let stderr = std::io::stderr();
let (mut out, mut err) = (stdout.lock(), stderr.lock());
let mut streams = Streams::new(&mut out, &mut err);
exit(execute(&mut streams), &mut streams, program)
}
fn exit(result: Result<u8, Failure>, streams: &mut Streams<'_>, program: &str) -> ExitCode {
match result {
Ok(code) => ExitCode::from(code),
Err(failure) => match streams.warn(&format!("{program}: {failure}")) {
Ok(()) => ExitCode::from(1),
Err(_) => ExitCode::from(2),
},
}
}
pub mod drive {
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use super::Failure;
use crate::canvas_protocol::Capability;
use crate::canvas_protocol::SessionInvariant;
use crate::native_host::broker::{
AuditEvent, AuditFn, Broker, ClockFn, GrantFn, GrantVerificationResult, IdFn,
RegisteredHandle, VerifyGrantFn,
};
use crate::native_host::protocol::{WidgetDescriptor, WidgetSurface};
pub type Events = Arc<Mutex<Vec<AuditEvent>>>;
#[must_use]
pub fn frozen_broker() -> (Broker, Events, Arc<AtomicBool>) {
let ids = Arc::new(Mutex::new(0_u128));
let clock: ClockFn = Arc::new(|| 1_000);
let new_id: IdFn = Arc::new(move || {
let mut guard = match ids.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
*guard = guard.wrapping_add(1);
lgwks_std::id::Uuid::from(guard.to_le_bytes())
});
let verify: VerifyGrantFn = Arc::new(|_| GrantVerificationResult::Valid);
let open = Arc::new(AtomicBool::new(false));
let gate = Arc::clone(&open);
let grants: GrantFn = Arc::new(move |_, _| gate.load(Ordering::SeqCst));
let events: Events = Arc::new(Mutex::new(Vec::new()));
let sink = Arc::clone(&events);
let audit: AuditFn = Arc::new(move |event: &AuditEvent| match sink.lock() {
Ok(mut guard) => guard.push(event.clone()),
Err(poisoned) => poisoned.into_inner().push(event.clone()),
});
(
Broker::new(clock, new_id, verify, grants, audit),
events,
open,
)
}
pub const WORK_OBJECT: &str = "11111111-1111-1111-1111-111111111111";
pub const SESSION_ID: &str = "22222222-2222-2222-2222-222222222222";
pub const POLICY_BUNDLE: &str = "33333333-3333-3333-3333-333333333333";
pub const USER_SUB: &str = "44444444-4444-4444-4444-444444444444";
pub fn widget_owner(
digest: &mut String,
broker: &Broker,
session: &SessionInvariant,
) -> Result<RegisteredHandle, Failure> {
let descriptor = WidgetDescriptor::new(
String::from("demo.kind"),
String::from("widget.owner"),
String::from("1.0.0"),
WidgetSurface::Native,
Vec::new(),
Vec::new(),
vec![Capability::SignalEmit, Capability::SignalSubscribe],
);
must(
digest,
"widget-owner",
broker.register(descriptor, session.clone()),
)
}
#[must_use]
pub fn captured(events: &Events) -> Vec<AuditEvent> {
match events.lock() {
Ok(guard) => guard.clone(),
Err(poisoned) => poisoned.into_inner().clone(),
}
}
pub fn note<T: std::fmt::Debug + ?Sized>(
digest: &mut String,
what: &str,
value: &T,
) -> Result<(), Failure> {
std::fmt::Write::write_fmt(digest, format_args!("{what}={value:?}\n"))
.map_err(|error| Failure::from(format!("digest unwritable: {error}")))?;
Ok(())
}
pub fn must<T: std::fmt::Debug, E: std::fmt::Display>(
digest: &mut String,
what: &str,
result: Result<T, E>,
) -> Result<T, Failure> {
match result {
Ok(value) => {
note(digest, what, &value)?;
Ok(value)
}
Err(error) => Err(Failure::from(format!("{what} refused: {error}"))),
}
}
pub fn ensure(condition: bool, message: &'static str) -> Result<(), Failure> {
crate::native_host::ensure(condition, || Failure::from(message))
}
pub fn refused<T, E>(outcome: Result<T, E>, message: &'static str) -> Result<E, Failure> {
outcome.err().ok_or_else(|| Failure::from(message))
}
pub fn uuid(
digest: &mut String,
what: &str,
text: &str,
) -> Result<lgwks_std::id::Uuid, Failure> {
must(digest, what, lgwks_std::id::Uuid::parse(text))
}
#[must_use]
pub fn forged_nonce(live: &lgwks_std::id::Uuid) -> lgwks_std::id::Uuid {
lgwks_std::id::Uuid::from((*live.as_bytes()).map(|byte| !byte))
}
pub fn session(digest: &mut String, tenant: &str) -> Result<SessionInvariant, Failure> {
must(
digest,
"session",
SessionInvariant::new(
String::from(WORK_OBJECT),
String::from(SESSION_ID),
String::from(POLICY_BUNDLE),
String::from(tenant),
String::from(USER_SUB),
),
)
}
}