1use std::{
9 any::{Any, TypeId},
10 cell::RefCell,
11 fmt,
12 future::Future,
13 path::PathBuf,
14 pin::Pin,
15 rc::Rc,
16 sync::Arc,
17};
18
19use rustc_hash::FxHashMap;
20
21use super::{JsHost, Ret, Thrown, call::JsResult, module::ModuleFuture};
22use crate::{
23 JsonValue,
24 access::{Access, TrustedPaths},
25};
26
27#[derive(Clone, Default)]
33#[non_exhaustive]
34pub struct System {
35 pub access: Arc<Access>,
37 pub data_dir: Option<PathBuf>,
39 pub paths: TrustedPaths,
41 pub quotas: Quotas,
43 pub locals: Locals,
45 pub exit: Option<Rc<dyn Fn(i32)>>,
48 pub websocket: Option<Arc<dyn crate::websocket::WebSocketTransport>>,
50 pub filesystem: Option<Arc<dyn crate::filesystem::FileSystem>>,
52 pub os: crate::platform::Os,
54 pub refuse_connections: Option<RefuseConnections>,
59 pub updater: Option<Arc<dyn crate::runtime::UpdaterHost>>,
61 #[doc(hidden)]
64 pub app_url: crate::url_scheme::AppUrlCell,
65 pub base_url: Option<Arc<str>>,
68}
69
70pub type RefuseConnections = Arc<dyn Fn(&str) -> JsError + Send + Sync>;
75
76impl System {
77 pub fn new(
79 access: Arc<Access>,
80 data_dir: Option<PathBuf>,
81 paths: TrustedPaths,
82 quotas: Quotas,
83 ) -> Self {
84 Self {
85 access,
86 data_dir,
87 paths,
88 quotas,
89 locals: Locals::default(),
90 exit: None,
91 websocket: None,
92 filesystem: None,
93 os: crate::platform::Os::default(),
94 refuse_connections: None,
95 updater: None,
96 app_url: Default::default(),
97 base_url: None,
98 }
99 }
100
101 pub fn check_connection(&self, target: &str) -> Result<(), JsError> {
106 match &self.refuse_connections {
107 Some(refuse) => Err(refuse(target)),
108 None => Ok(()),
109 }
110 }
111
112 pub fn with_refuse_connections(mut self, refuse: Option<RefuseConnections>) -> Self {
115 self.refuse_connections = refuse;
116 self
117 }
118
119 pub fn with_websocket(
121 mut self,
122 websocket: Option<Arc<dyn crate::websocket::WebSocketTransport>>,
123 ) -> Self {
124 self.websocket = websocket;
125 self
126 }
127
128 pub fn with_updater(mut self, updater: Option<Arc<dyn crate::runtime::UpdaterHost>>) -> Self {
131 self.updater = updater;
132 self
133 }
134
135 #[doc(hidden)]
137 pub fn with_app_url(mut self, app_url: crate::url_scheme::AppUrlCell) -> Self {
138 self.app_url = app_url;
139 self
140 }
141
142 pub fn with_base_url(mut self, base_url: Option<Arc<str>>) -> Self {
144 self.base_url = base_url;
145 self
146 }
147
148 pub fn with_filesystem(
150 mut self,
151 filesystem: Option<Arc<dyn crate::filesystem::FileSystem>>,
152 ) -> Self {
153 self.filesystem = filesystem;
154 self
155 }
156
157 pub fn with_os(mut self, os: crate::platform::Os) -> Self {
159 self.os = os;
160 self
161 }
162
163 pub fn with_locals(mut self, locals: Locals) -> Self {
165 self.locals = locals;
166 self
167 }
168
169 pub fn with_exit(mut self, exit: Option<Rc<dyn Fn(i32)>>) -> Self {
171 self.exit = exit;
172 self
173 }
174}
175
176pub trait Local: Default + 'static {
179 fn close(&self) {}
182}
183
184type Entry = (TypeId, Rc<dyn Any>, fn(&dyn Any));
185
186#[derive(Clone, Default)]
190pub struct Locals(Rc<RefCell<Vec<Entry>>>);
191
192impl Locals {
193 pub fn get<T: Local>(&self) -> Rc<T> {
195 let id = TypeId::of::<T>();
196 if let Some((_, local, _)) = self.0.borrow().iter().find(|(t, ..)| *t == id) {
197 return local
198 .clone()
199 .downcast()
200 .expect("the type it is filed under");
201 }
202 let local = Rc::new(T::default());
203 let close: fn(&dyn Any) = |local| {
204 if let Some(local) = local.downcast_ref::<T>() {
205 local.close();
206 }
207 };
208 self.0.borrow_mut().push((id, local.clone(), close));
209 local
210 }
211
212 pub fn close_all(&self) {
215 let locals = std::mem::take(&mut *self.0.borrow_mut());
216 for (_, local, close) in &locals {
217 close(&**local);
218 }
219 }
220}
221
222#[derive(Clone, Copy)]
226pub struct CallCx<'a> {
227 host: &'a dyn JsHost,
228}
229
230impl<'a> CallCx<'a> {
231 #[doc(hidden)]
232 pub fn new(host: &'a dyn JsHost) -> Self {
233 Self { host }
234 }
235
236 pub fn start(&self, work: impl Future<Output = ()> + 'static) {
239 self.host.start_task(Box::new(move || {
240 Box::pin(async move {
241 work.await;
242 Ok(Box::new(()) as Box<dyn super::ToJs>)
243 })
244 }));
245 }
246
247 pub fn on_cleanup(&self, f: impl FnOnce() + 'static) -> Cleanup {
253 Cleanup(Some(self.host.on_cleanup(Box::new(f))))
254 }
255}
256
257pub struct Cleanup(Option<Box<dyn FnOnce()>>);
260
261impl Cleanup {
262 pub fn release(mut self) {
264 if let Some(release) = self.0.take() {
265 release();
266 }
267 }
268}
269
270impl fmt::Debug for Cleanup {
271 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272 f.write_str("Cleanup")
273 }
274}
275
276#[derive(Default)]
286#[non_exhaustive]
287pub struct Stop {
288 run: Rc<StopOnce>,
289}
290
291type StopOnce = RefCell<Option<Box<dyn FnOnce()>>>;
293
294impl Stop {
295 pub fn new(f: impl FnOnce() + 'static) -> Self {
297 Self {
298 run: Rc::new(RefCell::new(Some(Box::new(f)))),
299 }
300 }
301
302 fn run(run: &StopOnce) {
303 let f = run.borrow_mut().take();
305 if let Some(f) = f {
306 f();
307 }
308 }
309}
310
311impl fmt::Debug for Stop {
312 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313 f.write_str("Stop")
314 }
315}
316
317impl Ret for Stop {
318 fn ts_type(_types: &mut super::TsTypes) -> String {
319 "() => void".into()
320 }
321
322 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<super::JsOwned<'a>, super::PropError> {
323 let run = self.run;
324 let release = host.on_cleanup(Box::new({
325 let run = run.clone();
326 move || Self::run(&run)
327 }));
328 let release = RefCell::new(Some(release));
329 let stop = host.new_function(Box::new(move || {
330 let release = release.borrow_mut().take();
333 if let Some(release) = release {
334 release();
335 }
336 Self::run(&run);
337 }))?;
338 Ok(super::JsOwned::new(host, stop))
339 }
340}
341
342impl fmt::Debug for System {
343 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
344 f.debug_struct("System")
345 .field("data_dir", &self.data_dir)
346 .field("os", &self.os)
347 .finish_non_exhaustive()
348 }
349}
350
351#[derive(Clone, Default)]
355pub struct Quotas(Rc<RefCell<FxHashMap<&'static str, usize>>>);
356
357impl Quotas {
358 pub fn take(&self, kind: &'static str, max: usize) -> Option<Held> {
361 self.reserve(kind, 1, max)
362 }
363
364 pub fn reserve(&self, kind: &'static str, amount: usize, max: usize) -> Option<Held> {
367 let mut counts = self.0.borrow_mut();
368 let count = counts.entry(kind).or_default();
369 let total = count.checked_add(amount).filter(|&total| total <= max)?;
370 *count = total;
371 Some(Held {
372 quotas: self.clone(),
373 kind,
374 amount,
375 })
376 }
377
378 pub fn held(&self, kind: &'static str) -> usize {
380 self.0.borrow().get(kind).copied().unwrap_or(0)
381 }
382}
383
384pub struct Held {
387 quotas: Quotas,
388 kind: &'static str,
389 amount: usize,
390}
391
392impl Held {
393 pub fn amount(&self) -> usize {
395 self.amount
396 }
397}
398
399impl Drop for Held {
400 fn drop(&mut self) {
401 if let Some(count) = self.quotas.0.borrow_mut().get_mut(self.kind) {
402 *count -= self.amount;
403 }
404 }
405}
406
407impl fmt::Debug for Held {
408 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
409 write!(f, "Held({} {})", self.amount, self.kind)
410 }
411}
412
413#[must_use = "the work runs only when the call returns it"]
420pub struct Later<T>(Pin<Box<dyn Future<Output = Result<T, Thrown>>>>);
421
422impl<T: Ret + 'static> Later<T> {
423 pub fn new<E: IntoThrown>(work: impl Future<Output = Result<T, E>> + 'static) -> Self {
425 Self(Box::pin(async move {
426 work.await.map_err(IntoThrown::into_thrown)
427 }))
428 }
429
430 pub(crate) fn into_future(self) -> ModuleFuture {
431 Box::pin(async move {
432 let result: JsResult = match self.0.await {
433 Ok(v) => Ok(Box::new(v)),
434 Err(e) => Err(e),
435 };
436 result
437 })
438 }
439}
440
441impl<T> fmt::Debug for Later<T> {
442 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
443 f.write_str("Later")
444 }
445}
446
447#[derive(Debug, Clone, PartialEq, Eq)]
453pub enum JsError {
454 Type(String),
456 Range(String),
458 Error(String),
460 Fields(Box<ErrorFields>),
462}
463
464#[derive(Debug, Clone, Copy, PartialEq, Eq)]
466pub enum ErrorClass {
467 Type,
469 Range,
471 Error,
473}
474
475#[derive(Debug, Clone, PartialEq, Eq)]
478pub struct ErrorFields {
479 pub class: ErrorClass,
481 pub message: String,
483 pub fields: Vec<(&'static str, JsonValue)>,
485}
486
487impl ErrorFields {
488 fn of(class: ErrorClass, message: String) -> Self {
489 Self {
490 class,
491 message,
492 fields: Vec::new(),
493 }
494 }
495
496 pub fn field(&self, key: &str) -> Option<&JsonValue> {
498 self.fields.iter().find(|(k, _)| *k == key).map(|(_, v)| v)
499 }
500}
501
502impl JsError {
503 pub fn with(self, key: &'static str, value: impl Into<JsonValue>) -> Self {
506 let mut fields = match self {
507 JsError::Type(m) => ErrorFields::of(ErrorClass::Type, m),
508 JsError::Range(m) => ErrorFields::of(ErrorClass::Range, m),
509 JsError::Error(m) => ErrorFields::of(ErrorClass::Error, m),
510 JsError::Fields(f) => *f,
511 };
512 fields.fields.retain(|(k, _)| *k != key);
513 fields.fields.push((key, value.into()));
514 JsError::Fields(Box::new(fields))
515 }
516
517 pub fn with_code(self, code: &str) -> Self {
519 self.with("code", code)
520 }
521
522 pub fn access_denied(
528 message: impl Into<String>,
529 permission: &str,
530 resource: impl Into<String>,
531 ) -> Self {
532 JsError::Error(message.into())
533 .with_code(codes::ACCESS_DENIED)
534 .with("permission", permission)
535 .with("resource", resource.into())
536 }
537
538 pub fn message(&self) -> &str {
540 match self {
541 JsError::Type(m) | JsError::Range(m) | JsError::Error(m) => m,
542 JsError::Fields(f) => &f.message,
543 }
544 }
545
546 pub fn code(&self) -> Option<&str> {
548 match self {
549 JsError::Fields(f) => f.field("code").and_then(JsonValue::as_str),
550 _ => None,
551 }
552 }
553}
554
555pub mod codes {
559 pub const ACCESS_DENIED: &str = "ERR_ACCESS_DENIED";
562 pub const UNAVAILABLE: &str = "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM";
564 pub const QUOTA_EXCEEDED: &str = "ERR_NSH_QUOTA_EXCEEDED";
567 pub const TIMED_OUT: &str = "ETIMEDOUT";
569 pub const HOST_ERROR: &str = "ERR_NSH_HOST_ERROR";
572 pub const WEBVIEW_SCRIPT: &str = "ERR_NSH_WEBVIEW_SCRIPT";
575 pub const WEBVIEW_ABORTED: &str = "ERR_NSH_WEBVIEW_ABORTED";
579}
580
581impl From<std::io::Error> for JsError {
585 fn from(error: std::io::Error) -> Self {
586 let message = error.to_string();
587 match io_code(&error) {
588 Some(code) => JsError::Error(message).with_code(code),
589 None => JsError::Error(message),
590 }
591 }
592}
593
594pub fn io_code(error: &std::io::Error) -> Option<&'static str> {
597 use std::io::ErrorKind as K;
598 #[cfg(unix)]
599 if let Some(code) = error.raw_os_error().and_then(errno_name) {
600 return Some(code);
601 }
602 Some(match error.kind() {
603 K::NotFound => "ENOENT",
604 K::PermissionDenied => "EACCES",
605 K::AlreadyExists => "EEXIST",
606 K::NotADirectory => "ENOTDIR",
607 K::IsADirectory => "EISDIR",
608 K::DirectoryNotEmpty => "ENOTEMPTY",
609 K::InvalidFilename => "ENAMETOOLONG",
610 K::ReadOnlyFilesystem => "EROFS",
611 K::CrossesDevices => "EXDEV",
612 K::StorageFull => "ENOSPC",
613 K::QuotaExceeded => "EDQUOT",
614 K::FileTooLarge => "EFBIG",
615 K::ResourceBusy => "EBUSY",
616 K::ExecutableFileBusy => "ETXTBSY",
617 K::Deadlock => "EDEADLK",
618 K::TooManyLinks => "EMLINK",
619 K::ArgumentListTooLong => "E2BIG",
620 K::Interrupted => "EINTR",
621 K::WouldBlock => "EAGAIN",
622 K::TimedOut => "ETIMEDOUT",
623 K::BrokenPipe => "EPIPE",
624 K::ConnectionRefused => "ECONNREFUSED",
625 K::ConnectionReset => "ECONNRESET",
626 K::ConnectionAborted => "ECONNABORTED",
627 K::NotConnected => "ENOTCONN",
628 K::AddrInUse => "EADDRINUSE",
629 K::AddrNotAvailable => "EADDRNOTAVAIL",
630 K::HostUnreachable => "EHOSTUNREACH",
631 K::NetworkUnreachable => "ENETUNREACH",
632 K::NetworkDown => "ENETDOWN",
633 K::InvalidInput => "EINVAL",
634 K::Unsupported => "ENOTSUP",
635 K::OutOfMemory => "ENOMEM",
636 _ => return None,
637 })
638}
639
640#[cfg(unix)]
643fn errno_name(errno: i32) -> Option<&'static str> {
644 let names: &[(i32, &str)] = &[
645 (libc::ENOENT, "ENOENT"),
646 (libc::EACCES, "EACCES"),
647 (libc::EPERM, "EPERM"),
648 (libc::EEXIST, "EEXIST"),
649 (libc::ENOTDIR, "ENOTDIR"),
650 (libc::EISDIR, "EISDIR"),
651 (libc::ENOTEMPTY, "ENOTEMPTY"),
652 (libc::ELOOP, "ELOOP"),
653 (libc::ENAMETOOLONG, "ENAMETOOLONG"),
654 (libc::EBADF, "EBADF"),
655 (libc::EBUSY, "EBUSY"),
656 (libc::EINVAL, "EINVAL"),
657 (libc::EMFILE, "EMFILE"),
658 (libc::ENFILE, "ENFILE"),
659 (libc::ENOSPC, "ENOSPC"),
660 (libc::EROFS, "EROFS"),
661 (libc::EXDEV, "EXDEV"),
662 (libc::EAGAIN, "EAGAIN"),
663 (libc::ENXIO, "ENXIO"),
664 (libc::ETXTBSY, "ETXTBSY"),
665 (libc::EFBIG, "EFBIG"),
666 (libc::EMLINK, "EMLINK"),
667 (libc::EPIPE, "EPIPE"),
668 (libc::ENOEXEC, "ENOEXEC"),
669 ];
670 names
671 .iter()
672 .find(|(n, _)| *n == errno)
673 .map(|(_, name)| *name)
674}
675
676pub trait IntoThrown {
679 fn into_thrown(self) -> Thrown;
681}
682
683impl<E: fmt::Display> IntoThrown for E {
684 fn into_thrown(self) -> Thrown {
685 Thrown::Error(self.to_string())
686 }
687}
688
689impl IntoThrown for JsError {
690 fn into_thrown(self) -> Thrown {
691 match self {
692 JsError::Type(m) => Thrown::Type(m),
693 JsError::Range(m) => Thrown::Range(m),
694 JsError::Error(m) => Thrown::Error(m),
695 JsError::Fields(f) => Thrown::Fields(f),
696 }
697 }
698}
699
700#[cfg(test)]
701mod tests {
702 use crate::{
703 JsonValue,
704 element::{JsValue, Registry, declarations, json_host},
705 prelude::*,
706 };
707
708 #[module]
709 struct Files;
710
711 #[module(flat)]
712 impl Files {
713 pub(crate) fn read(path: String, sys: System) -> Result<Later<Vec<u8>>, JsError> {
715 let _ = (path, sys);
716 Ok(Later::new(async { Ok::<_, String>(vec![1]) }))
717 }
718
719 pub(crate) fn write(sys: System, bytes: Vec<u8>) -> u32 {
721 let _ = sys;
722 bytes.len() as u32
723 }
724
725 pub(crate) fn watch(path: String, cx: CallCx<'_>) {
727 cx.on_cleanup(move || drop(path));
728 cx.start(async {});
729 }
730
731 pub(crate) fn listen() -> Stop {
733 Stop::new(|| {})
734 }
735
736 #[getter]
738 pub(crate) fn root(sys: System) -> Option<String> {
739 sys.data_dir.map(|d| d.display().to_string())
740 }
741 }
742
743 #[class]
744 struct Handle;
745
746 #[class]
747 impl Handle {
748 pub(crate) fn next(&self, sys: System, size: Option<u32>) -> Later<Option<Vec<u8>>> {
750 let _ = (sys, size);
751 Later::new(async { Ok::<_, String>(None) })
752 }
753
754 #[overload(fn(event: String, #[args(index, label)] f: Callback<(u32, String)>) -> Instance<Handle>)]
756 pub(crate) fn on(this: Instance<Self>, event: String, cx: CallCx<'_>) -> Instance<Self> {
757 let _ = (event, cx);
758 this
759 }
760 }
761
762 #[test]
763 fn bytes_are_uint8_arrays_tasks_promises_and_the_system_no_parameter() {
764 let mut registry = Registry::ui_set("test/system");
765 registry.module::<Files>().class::<Handle>();
766 let d = declarations(®istry, &[]);
767 assert!(
768 d.contains("function read(path: string): Promise<Uint8Array>;"),
769 "{d}"
770 );
771 assert!(
772 d.contains("function write(bytes: Uint8Array): number;"),
773 "{d}"
774 );
775 assert!(
776 d.contains("next(size?: number | null): Promise<Uint8Array | null>;"),
777 "{d}"
778 );
779 assert!(d.contains("function watch(path: string): void;"), "{d}");
780 assert!(d.contains("function listen(): () => void;"), "{d}");
781 assert!(
782 d.contains(" on(event: string, f: (index: number, label: string) => void): Handle;"),
783 "{d}"
784 );
785 assert!(!d.contains("function root"), "{d}");
787 }
788
789 #[test]
790 fn bytes_convert_from_and_to_js() {
791 let host = json_host::JsonHost::default();
792 let raw = host.value(serde_json::json!([0, 7, 255]));
793 let bytes = <Vec<u8>>::from_js(crate::element::JsIn::new(&host, raw)).unwrap();
794 assert_eq!(bytes, [0, 7, 255]);
795 let out = bytes.to_js(&host).unwrap();
796 assert_eq!(host.read(out), Some(serde_json::json!([0, 7, 255])));
797 let bad = host.value(JsonValue::from("x"));
798 assert!(<Vec<u8>>::from_js(crate::element::JsIn::new(&host, bad)).is_err());
799 }
800
801 #[test]
802 fn a_stop_is_a_function_that_runs_once() {
803 use crate::element::Ret;
804 let host = json_host::JsonHost::default();
805 let runs = std::rc::Rc::new(std::cell::Cell::new(0));
806 let stop = Stop::new({
807 let runs = runs.clone();
808 move || runs.set(runs.get() + 1)
809 });
810 let f = stop.into_js(&host).unwrap().into_raw();
811 assert_eq!(
812 crate::element::JsHost::kind(&host, f),
813 crate::element::JsKind::Function
814 );
815 assert_eq!(runs.get(), 0);
816 host.call(f);
817 host.call(f);
818 assert_eq!(runs.get(), 1);
819 }
820
821 #[derive(Debug, JsObject)]
822 #[prop(exact)]
823 struct Options {
824 recursive: Option<bool>,
825 #[prop(skip_none)]
826 note: Option<String>,
827 }
828
829 #[test]
830 fn times_are_dates_and_exact_objects_refuse_other_keys() {
831 let host = json_host::JsonHost::default();
832 let time = std::time::UNIX_EPOCH + std::time::Duration::from_millis(1500);
833 let out = time.to_js(&host).unwrap();
834 assert_eq!(host.read(out), Some(serde_json::json!({ "$date": 1500.0 })));
835 let date = host.value(serde_json::json!({ "$date": -250.0 }));
836 let back = std::time::SystemTime::from_js(crate::element::JsIn::new(&host, date)).unwrap();
837 assert_eq!(
838 std::time::UNIX_EPOCH
839 .duration_since(back)
840 .unwrap()
841 .as_millis(),
842 250
843 );
844 let options = host.value(serde_json::json!({ "recursive": true }));
845 let options = Options::from_js(crate::element::JsIn::new(&host, options)).unwrap();
846 assert_eq!(options.recursive, Some(true));
847 let shown = Options {
848 recursive: None,
849 note: None,
850 }
851 .to_js(&host)
852 .unwrap();
853 assert_eq!(
854 host.read(shown),
855 Some(serde_json::json!({ "recursive": null }))
856 );
857 let typo = host.value(serde_json::json!({ "recursive": true, "typo": 1 }));
858 let error = Options::from_js(crate::element::JsIn::new(&host, typo)).unwrap_err();
859 assert_eq!(error.0, "unknown field `typo`");
860 }
861
862 #[test]
863 fn errors_carry_node_s_codes_thrown_and_rejected() {
864 use super::{ErrorClass, JsError, io_code};
865 use crate::element::{IntoThrown, Thrown};
866 let missing = std::io::Error::from(std::io::ErrorKind::NotFound);
867 assert_eq!(io_code(&missing), Some("ENOENT"));
868 #[cfg(unix)]
869 assert_eq!(
870 io_code(&std::io::Error::from_raw_os_error(libc::ELOOP)),
871 Some("ELOOP")
872 );
873 assert_eq!(io_code(&std::io::Error::other("x")), None);
874 let error = JsError::Type("denied".into())
875 .with_code("EPERM")
876 .with_code("EACCES")
877 .with("path", "a.txt");
878 assert_eq!((error.message(), error.code()), ("denied", Some("EACCES")));
879 let Thrown::Fields(fields) = error.clone().into_thrown() else {
880 panic!("fields go with the error");
881 };
882 assert_eq!(fields.class, ErrorClass::Type);
883 assert_eq!(fields.fields.len(), 2);
884 assert_eq!(JsError::from(missing).code(), Some("ENOENT"));
885 let later = super::Later::<u32>::new(async { Err::<u32, _>(error) });
887 let runtime = tokio::runtime::Builder::new_current_thread()
888 .build()
889 .unwrap();
890 let Err(Thrown::Fields(rejected)) = runtime.block_on(later.into_future()) else {
891 panic!("a rejection with fields");
892 };
893 assert_eq!(rejected.field("path"), Some(&serde_json::json!("a.txt")));
894 let later = super::Later::<u32>::new(async { Err::<u32, _>("plain") });
896 assert!(matches!(
897 runtime.block_on(later.into_future()),
898 Err(Thrown::Error(m)) if m == "plain"
899 ));
900 }
901
902 #[test]
903 fn quotas_count_what_is_held() {
904 let quotas = super::Quotas::default();
905 let a = quotas.take("k", 2).unwrap();
906 let _b = quotas.take("k", 2).unwrap();
907 assert!(quotas.take("k", 2).is_none());
908 drop(a);
909 assert_eq!(quotas.held("k"), 1);
910 assert!(quotas.take("other", 1).is_some());
911 }
912
913 #[test]
914 fn quotas_reserve_amounts_up_to_their_limit() {
915 let quotas = super::Quotas::default();
916 let a = quotas.reserve("bytes", 40, 64).unwrap();
917 assert!(quotas.reserve("bytes", 25, 64).is_none());
918 let b = quotas.reserve("bytes", 24, 64).unwrap();
919 assert_eq!((quotas.held("bytes"), a.amount()), (64, 40));
920 assert!(quotas.reserve("bytes", usize::MAX, usize::MAX).is_none());
921 drop(a);
922 assert_eq!(quotas.held("bytes"), 24);
923 drop(b);
924 assert!(quotas.reserve("bytes", 64, 64).is_some());
925 }
926}