initial import of main veilid core
This commit is contained in:
99
veilid-core/src/xx/bump_port.rs
Normal file
99
veilid-core/src/xx/bump_port.rs
Normal file
@@ -0,0 +1,99 @@
|
||||
use super::*;
|
||||
cfg_if! {
|
||||
if #[cfg(target_arch = "wasm32")] {
|
||||
|
||||
} else {
|
||||
use std::net::{TcpListener, UdpSocket};
|
||||
}
|
||||
}
|
||||
|
||||
pub enum BumpPortType {
|
||||
UDP,
|
||||
TCP,
|
||||
}
|
||||
|
||||
pub fn tcp_port_available(addr: &SocketAddr) -> bool {
|
||||
cfg_if! {
|
||||
if #[cfg(target_arch = "wasm32")] {
|
||||
false
|
||||
} else {
|
||||
match TcpListener::bind(addr) {
|
||||
Ok(_) => true,
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn udp_port_available(addr: &SocketAddr) -> bool {
|
||||
cfg_if! {
|
||||
if #[cfg(target_arch = "wasm32")] {
|
||||
false
|
||||
} else {
|
||||
match UdpSocket::bind(addr) {
|
||||
Ok(_) => true,
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bump_port(addr: &mut SocketAddr, bpt: BumpPortType) -> Result<bool, String> {
|
||||
cfg_if! {
|
||||
if #[cfg(target_arch = "wasm32")] {
|
||||
Err("unsupported architecture".to_owned())
|
||||
}
|
||||
else
|
||||
{
|
||||
let mut bumped = false;
|
||||
let mut port = addr.port();
|
||||
let mut addr_bump = addr.clone();
|
||||
loop {
|
||||
|
||||
if match bpt {
|
||||
BumpPortType::TCP => tcp_port_available(&addr_bump),
|
||||
BumpPortType::UDP => udp_port_available(&addr_bump),
|
||||
} {
|
||||
*addr = addr_bump;
|
||||
return Ok(bumped);
|
||||
}
|
||||
if port == u16::MAX {
|
||||
break;
|
||||
}
|
||||
port += 1;
|
||||
addr_bump.set_port(port);
|
||||
bumped = true;
|
||||
}
|
||||
|
||||
Err("no ports remaining".to_owned())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bump_port_string(addr: &mut String, bpt: BumpPortType) -> Result<bool, String> {
|
||||
cfg_if! {
|
||||
if #[cfg(target_arch = "wasm32")] {
|
||||
return Err("unsupported architecture".to_owned());
|
||||
}
|
||||
else
|
||||
{
|
||||
let savec: Vec<SocketAddr> = addr
|
||||
.to_socket_addrs()
|
||||
.map_err(|x| format!("failed to resolve socket address: {}", x))?
|
||||
.collect();
|
||||
|
||||
if savec.len() == 0 {
|
||||
return Err("No socket addresses resolved".to_owned());
|
||||
}
|
||||
let mut sa = savec.first().unwrap().clone();
|
||||
|
||||
if !bump_port(&mut sa, bpt)? {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
*addr = sa.to_string();
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
}
|
212
veilid-core/src/xx/eventual.rs
Normal file
212
veilid-core/src/xx/eventual.rs
Normal file
@@ -0,0 +1,212 @@
|
||||
use super::*;
|
||||
use eventual_base::*;
|
||||
|
||||
pub struct Eventual {
|
||||
inner: Arc<Mutex<EventualBaseInner<()>>>,
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for Eventual {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
f.debug_struct("Eventual").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for Eventual {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
inner: self.inner.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EventualBase for Eventual {
|
||||
type ResolvedType = ();
|
||||
fn base_inner(&self) -> MutexGuard<EventualBaseInner<Self::ResolvedType>> {
|
||||
self.inner.lock()
|
||||
}
|
||||
}
|
||||
|
||||
impl Eventual {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
inner: Arc::new(Mutex::new(EventualBaseInner::new())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn instance_clone<T>(&self, value: T) -> EventualFutureClone<T>
|
||||
where
|
||||
T: Clone + Unpin,
|
||||
{
|
||||
EventualFutureClone {
|
||||
id: None,
|
||||
value: value,
|
||||
eventual: self.clone(),
|
||||
}
|
||||
}
|
||||
pub fn instance_none<T>(&self) -> EventualFutureNone<T>
|
||||
where
|
||||
T: Unpin,
|
||||
{
|
||||
EventualFutureNone {
|
||||
id: None,
|
||||
eventual: self.clone(),
|
||||
_marker: core::marker::PhantomData {},
|
||||
}
|
||||
}
|
||||
pub fn instance_empty(&self) -> EventualFutureEmpty {
|
||||
EventualFutureEmpty {
|
||||
id: None,
|
||||
eventual: self.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resolve(&self) -> EventualResolvedFuture<Self> {
|
||||
self.resolve_to_value(())
|
||||
}
|
||||
}
|
||||
|
||||
///////
|
||||
|
||||
pub struct EventualFutureClone<T>
|
||||
where
|
||||
T: Clone + Unpin,
|
||||
{
|
||||
id: Option<usize>,
|
||||
value: T,
|
||||
eventual: Eventual,
|
||||
}
|
||||
|
||||
impl<T> Future for EventualFutureClone<T>
|
||||
where
|
||||
T: Clone + Unpin,
|
||||
{
|
||||
type Output = T;
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<Self::Output> {
|
||||
let this = &mut *self;
|
||||
let out = {
|
||||
let mut inner = this.eventual.base_inner();
|
||||
inner.instance_poll(&mut this.id, cx)
|
||||
};
|
||||
match out {
|
||||
None => task::Poll::<Self::Output>::Pending,
|
||||
Some(wakers) => {
|
||||
// Wake all EventualResolvedFutures
|
||||
for w in wakers {
|
||||
w.wake();
|
||||
}
|
||||
task::Poll::<Self::Output>::Ready(this.value.clone())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for EventualFutureClone<T>
|
||||
where
|
||||
T: Clone + Unpin,
|
||||
{
|
||||
fn drop(&mut self) {
|
||||
if let Some(id) = self.id.take() {
|
||||
let wakers = {
|
||||
let mut inner = self.eventual.base_inner();
|
||||
inner.remove_waker(id)
|
||||
};
|
||||
for w in wakers {
|
||||
w.wake();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///////
|
||||
|
||||
pub struct EventualFutureNone<T>
|
||||
where
|
||||
T: Unpin,
|
||||
{
|
||||
id: Option<usize>,
|
||||
eventual: Eventual,
|
||||
_marker: core::marker::PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T> Future for EventualFutureNone<T>
|
||||
where
|
||||
T: Unpin,
|
||||
{
|
||||
type Output = Option<T>;
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<Self::Output> {
|
||||
let this = &mut *self;
|
||||
let out = {
|
||||
let mut inner = this.eventual.base_inner();
|
||||
inner.instance_poll(&mut this.id, cx)
|
||||
};
|
||||
match out {
|
||||
None => task::Poll::<Self::Output>::Pending,
|
||||
Some(wakers) => {
|
||||
// Wake all EventualResolvedFutures
|
||||
for w in wakers {
|
||||
w.wake();
|
||||
}
|
||||
task::Poll::<Self::Output>::Ready(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for EventualFutureNone<T>
|
||||
where
|
||||
T: Unpin,
|
||||
{
|
||||
fn drop(&mut self) {
|
||||
if let Some(id) = self.id.take() {
|
||||
let wakers = {
|
||||
let mut inner = self.eventual.base_inner();
|
||||
inner.remove_waker(id)
|
||||
};
|
||||
for w in wakers {
|
||||
w.wake();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///////
|
||||
|
||||
pub struct EventualFutureEmpty {
|
||||
id: Option<usize>,
|
||||
eventual: Eventual,
|
||||
}
|
||||
|
||||
impl Future for EventualFutureEmpty {
|
||||
type Output = ();
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<Self::Output> {
|
||||
let this = &mut *self;
|
||||
let out = {
|
||||
let mut inner = this.eventual.base_inner();
|
||||
inner.instance_poll(&mut this.id, cx)
|
||||
};
|
||||
match out {
|
||||
None => task::Poll::<Self::Output>::Pending,
|
||||
Some(wakers) => {
|
||||
// Wake all EventualResolvedFutures
|
||||
for w in wakers {
|
||||
w.wake();
|
||||
}
|
||||
task::Poll::<Self::Output>::Ready(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for EventualFutureEmpty {
|
||||
fn drop(&mut self) {
|
||||
if let Some(id) = self.id.take() {
|
||||
let wakers = {
|
||||
let mut inner = self.eventual.base_inner();
|
||||
inner.remove_waker(id)
|
||||
};
|
||||
for w in wakers {
|
||||
w.wake();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
210
veilid-core/src/xx/eventual_base.rs
Normal file
210
veilid-core/src/xx/eventual_base.rs
Normal file
@@ -0,0 +1,210 @@
|
||||
use super::*;
|
||||
|
||||
pub struct EventualBaseInner<T> {
|
||||
resolved: Option<T>,
|
||||
wakers: BTreeMap<usize, task::Waker>,
|
||||
resolved_wakers: BTreeMap<usize, task::Waker>,
|
||||
freelist: Vec<usize>,
|
||||
resolved_freelist: Vec<usize>,
|
||||
}
|
||||
|
||||
impl<T> EventualBaseInner<T> {
|
||||
pub(super) fn new() -> Self {
|
||||
EventualBaseInner {
|
||||
resolved: None,
|
||||
wakers: BTreeMap::new(),
|
||||
resolved_wakers: BTreeMap::new(),
|
||||
freelist: Vec::new(),
|
||||
resolved_freelist: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn insert_waker(&mut self, waker: task::Waker) -> usize {
|
||||
let id = match self.freelist.pop() {
|
||||
Some(id) => id,
|
||||
None => self.wakers.len(),
|
||||
};
|
||||
self.wakers.insert(id, waker);
|
||||
id
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub(super) fn remove_waker(&mut self, id: usize) -> Vec<task::Waker> {
|
||||
self.freelist.push(id);
|
||||
self.wakers.remove(&id);
|
||||
// See if we should complete the EventualResolvedFutures
|
||||
let mut resolved_waker_list = Vec::new();
|
||||
if self.wakers.len() == 0 && self.resolved.is_some() {
|
||||
for w in &self.resolved_wakers {
|
||||
resolved_waker_list.push(w.1.clone());
|
||||
}
|
||||
}
|
||||
resolved_waker_list
|
||||
}
|
||||
|
||||
pub(super) fn insert_resolved_waker(&mut self, waker: task::Waker) -> usize {
|
||||
let id = match self.resolved_freelist.pop() {
|
||||
Some(id) => id,
|
||||
None => self.resolved_wakers.len(),
|
||||
};
|
||||
self.resolved_wakers.insert(id, waker);
|
||||
id
|
||||
}
|
||||
|
||||
pub(super) fn remove_resolved_waker(&mut self, id: usize) {
|
||||
self.resolved_freelist.push(id);
|
||||
self.resolved_wakers.remove(&id);
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub(super) fn resolve_and_get_wakers(&mut self, value: T) -> Option<Vec<task::Waker>> {
|
||||
if self.resolved.is_some() {
|
||||
// Already resolved
|
||||
return None;
|
||||
}
|
||||
|
||||
// Store resolved value
|
||||
self.resolved = Some(value);
|
||||
|
||||
// Return a copy of the waker list so the caller can wake all the EventualFutures
|
||||
let mut waker_list = Vec::new();
|
||||
for w in &self.wakers {
|
||||
waker_list.push(w.1.clone());
|
||||
}
|
||||
Some(waker_list)
|
||||
}
|
||||
|
||||
pub(super) fn is_resolved(&self) -> bool {
|
||||
self.resolved.is_some()
|
||||
}
|
||||
pub(super) fn resolved_value_ref(&self) -> &Option<T> {
|
||||
&self.resolved
|
||||
}
|
||||
pub(super) fn resolved_value_mut(&mut self) -> &mut Option<T> {
|
||||
&mut self.resolved
|
||||
}
|
||||
|
||||
pub(super) fn reset(&mut self) {
|
||||
assert_eq!(self.wakers.len(), 0);
|
||||
assert_eq!(self.resolved_wakers.len(), 0);
|
||||
self.resolved = None;
|
||||
self.freelist.clear();
|
||||
self.resolved_freelist.clear();
|
||||
}
|
||||
|
||||
pub(super) fn try_reset(&mut self) -> Result<(), ()> {
|
||||
if self.wakers.len() != 0 {
|
||||
return Err(());
|
||||
}
|
||||
if self.resolved_wakers.len() != 0 {
|
||||
return Err(());
|
||||
}
|
||||
self.reset();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Resolved future helpers
|
||||
#[must_use]
|
||||
pub(super) fn resolved_poll(
|
||||
&mut self,
|
||||
id: &mut Option<usize>,
|
||||
cx: &mut task::Context<'_>,
|
||||
) -> task::Poll<()> {
|
||||
// If there are any instance futures still waiting, we resolution isn't finished
|
||||
if self.wakers.len() != 0 {
|
||||
if id.is_none() {
|
||||
*id = Some(self.insert_resolved_waker(cx.waker().clone()));
|
||||
}
|
||||
task::Poll::<()>::Pending
|
||||
} else {
|
||||
if let Some(id) = id.take() {
|
||||
self.remove_resolved_waker(id);
|
||||
}
|
||||
task::Poll::<()>::Ready(())
|
||||
}
|
||||
}
|
||||
|
||||
// Instance future helpers
|
||||
#[must_use]
|
||||
pub(super) fn instance_poll(
|
||||
&mut self,
|
||||
id: &mut Option<usize>,
|
||||
cx: &mut task::Context<'_>,
|
||||
) -> Option<Vec<task::Waker>> {
|
||||
// If the resolved value hasn't showed up then we can't wake the instance futures
|
||||
if self.resolved.is_none() {
|
||||
if id.is_none() {
|
||||
*id = Some(self.insert_waker(cx.waker().clone()));
|
||||
}
|
||||
None
|
||||
} else {
|
||||
if let Some(id) = id.take() {
|
||||
Some(self.remove_waker(id))
|
||||
} else {
|
||||
Some(Vec::new())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// xxx: this would love to be 'pub(super)' instead of pub, to ensure nobody else touches resolve_to_value directly
|
||||
pub trait EventualBase: Clone + Unpin {
|
||||
type ResolvedType;
|
||||
|
||||
fn base_inner(&self) -> MutexGuard<EventualBaseInner<Self::ResolvedType>>;
|
||||
|
||||
fn resolve_to_value(&self, value: Self::ResolvedType) -> EventualResolvedFuture<Self> {
|
||||
let wakers = {
|
||||
let mut inner = self.base_inner();
|
||||
inner.resolve_and_get_wakers(value)
|
||||
};
|
||||
if let Some(wakers) = wakers {
|
||||
for w in wakers {
|
||||
w.wake();
|
||||
}
|
||||
}
|
||||
EventualResolvedFuture {
|
||||
id: None,
|
||||
eventual: self.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EventualResolvedFuture<B: EventualBase> {
|
||||
id: Option<usize>,
|
||||
eventual: B,
|
||||
}
|
||||
|
||||
impl<B: EventualBase> Future for EventualResolvedFuture<B> {
|
||||
type Output = ();
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<Self::Output> {
|
||||
let this = &mut *self;
|
||||
let mut inner = this.eventual.base_inner();
|
||||
inner.resolved_poll(&mut this.id, cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl<B: EventualBase> Drop for EventualResolvedFuture<B> {
|
||||
fn drop(&mut self) {
|
||||
if let Some(id) = self.id.take() {
|
||||
let mut inner = self.eventual.base_inner();
|
||||
inner.remove_resolved_waker(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait EventualCommon: EventualBase {
|
||||
fn is_resolved(&self) -> bool {
|
||||
self.base_inner().is_resolved()
|
||||
}
|
||||
|
||||
fn reset(&self) {
|
||||
self.base_inner().reset()
|
||||
}
|
||||
|
||||
fn try_reset(&self) -> Result<(), ()> {
|
||||
self.base_inner().try_reset()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> EventualCommon for T where T: EventualBase {}
|
94
veilid-core/src/xx/eventual_value.rs
Normal file
94
veilid-core/src/xx/eventual_value.rs
Normal file
@@ -0,0 +1,94 @@
|
||||
use super::*;
|
||||
use eventual_base::*;
|
||||
|
||||
pub struct EventualValue<T: Unpin> {
|
||||
inner: Arc<Mutex<EventualBaseInner<T>>>,
|
||||
}
|
||||
|
||||
impl<T: Unpin> core::fmt::Debug for EventualValue<T> {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
f.debug_struct("EventualValue").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Unpin> Clone for EventualValue<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
inner: self.inner.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Unpin> EventualBase for EventualValue<T> {
|
||||
type ResolvedType = T;
|
||||
fn base_inner(&self) -> MutexGuard<EventualBaseInner<Self::ResolvedType>> {
|
||||
self.inner.lock()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Unpin> EventualValue<T> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
inner: Arc::new(Mutex::new(EventualBaseInner::new())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn instance(&self) -> EventualValueFuture<T> {
|
||||
EventualValueFuture {
|
||||
id: None,
|
||||
eventual: self.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resolve(&self, value: T) -> EventualResolvedFuture<Self> {
|
||||
self.resolve_to_value(value)
|
||||
}
|
||||
|
||||
pub fn take_value(&self) -> Option<T> {
|
||||
let mut inner = self.inner.lock();
|
||||
inner.resolved_value_mut().take()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EventualValueFuture<T: Unpin> {
|
||||
id: Option<usize>,
|
||||
eventual: EventualValue<T>,
|
||||
}
|
||||
|
||||
impl<T: Unpin> Future for EventualValueFuture<T> {
|
||||
type Output = ();
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<Self::Output> {
|
||||
let this = &mut *self;
|
||||
let out = {
|
||||
let mut inner = this.eventual.base_inner();
|
||||
inner.instance_poll(&mut this.id, cx)
|
||||
};
|
||||
match out {
|
||||
None => task::Poll::<Self::Output>::Pending,
|
||||
Some(wakers) => {
|
||||
// Wake all EventualResolvedFutures
|
||||
for w in wakers {
|
||||
w.wake();
|
||||
}
|
||||
task::Poll::<Self::Output>::Ready(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for EventualValueFuture<T>
|
||||
where
|
||||
T: Unpin,
|
||||
{
|
||||
fn drop(&mut self) {
|
||||
if let Some(id) = self.id.take() {
|
||||
let wakers = {
|
||||
let mut inner = self.eventual.base_inner();
|
||||
inner.remove_waker(id)
|
||||
};
|
||||
for w in wakers {
|
||||
w.wake();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
98
veilid-core/src/xx/eventual_value_clone.rs
Normal file
98
veilid-core/src/xx/eventual_value_clone.rs
Normal file
@@ -0,0 +1,98 @@
|
||||
use super::*;
|
||||
use eventual_base::*;
|
||||
|
||||
pub struct EventualValueClone<T: Unpin + Clone> {
|
||||
inner: Arc<Mutex<EventualBaseInner<T>>>,
|
||||
}
|
||||
|
||||
impl<T: Unpin + Clone> core::fmt::Debug for EventualValueClone<T> {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
f.debug_struct("EventualValueClone").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Unpin + Clone> Clone for EventualValueClone<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
inner: self.inner.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Unpin + Clone> EventualBase for EventualValueClone<T> {
|
||||
type ResolvedType = T;
|
||||
fn base_inner(&self) -> MutexGuard<EventualBaseInner<Self::ResolvedType>> {
|
||||
self.inner.lock()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Unpin + Clone> EventualValueClone<T> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
inner: Arc::new(Mutex::new(EventualBaseInner::new())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn instance(&self) -> EventualValueCloneFuture<T>
|
||||
where
|
||||
T: Clone + Unpin,
|
||||
{
|
||||
EventualValueCloneFuture {
|
||||
id: None,
|
||||
eventual: self.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resolve(&self, value: T) -> EventualResolvedFuture<Self> {
|
||||
self.resolve_to_value(value)
|
||||
}
|
||||
|
||||
pub fn value(&self) -> Option<T> {
|
||||
let inner = self.inner.lock();
|
||||
inner.resolved_value_ref().clone()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EventualValueCloneFuture<T: Unpin + Clone> {
|
||||
id: Option<usize>,
|
||||
eventual: EventualValueClone<T>,
|
||||
}
|
||||
|
||||
impl<T: Unpin + Clone> Future for EventualValueCloneFuture<T> {
|
||||
type Output = T;
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<Self::Output> {
|
||||
let this = &mut *self;
|
||||
let (out, some_value) = {
|
||||
let mut inner = this.eventual.base_inner();
|
||||
let out = inner.instance_poll(&mut this.id, cx);
|
||||
(out, inner.resolved_value_ref().clone())
|
||||
};
|
||||
match out {
|
||||
None => task::Poll::<Self::Output>::Pending,
|
||||
Some(wakers) => {
|
||||
// Wake all EventualResolvedFutures
|
||||
for w in wakers {
|
||||
w.wake();
|
||||
}
|
||||
task::Poll::<Self::Output>::Ready(some_value.unwrap())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for EventualValueCloneFuture<T>
|
||||
where
|
||||
T: Clone + Unpin,
|
||||
{
|
||||
fn drop(&mut self) {
|
||||
if let Some(id) = self.id.take() {
|
||||
let wakers = {
|
||||
let mut inner = self.eventual.base_inner();
|
||||
inner.remove_waker(id)
|
||||
};
|
||||
for w in wakers {
|
||||
w.wake();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
68
veilid-core/src/xx/ip_addr_port.rs
Normal file
68
veilid-core/src/xx/ip_addr_port.rs
Normal file
@@ -0,0 +1,68 @@
|
||||
use super::*;
|
||||
use core::fmt;
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
|
||||
pub struct IpAddrPort {
|
||||
addr: IpAddr,
|
||||
port: u16,
|
||||
}
|
||||
|
||||
impl IpAddrPort {
|
||||
pub fn new(addr: IpAddr, port: u16) -> Self {
|
||||
Self {
|
||||
addr: addr,
|
||||
port: port,
|
||||
}
|
||||
}
|
||||
pub fn addr(&self) -> &IpAddr {
|
||||
&self.addr
|
||||
}
|
||||
pub fn port(&self) -> u16 {
|
||||
self.port
|
||||
}
|
||||
pub fn set_addr(&mut self, new_addr: IpAddr) {
|
||||
self.addr = new_addr;
|
||||
}
|
||||
pub fn set_port(&mut self, new_port: u16) {
|
||||
self.port = new_port;
|
||||
}
|
||||
|
||||
pub fn from_socket_addr(sa: &SocketAddr) -> Self {
|
||||
match sa {
|
||||
SocketAddr::V4(v) => Self {
|
||||
addr: IpAddr::V4(*v.ip()),
|
||||
port: v.port(),
|
||||
},
|
||||
SocketAddr::V6(v) => Self {
|
||||
addr: IpAddr::V6(*v.ip()),
|
||||
port: v.port(),
|
||||
},
|
||||
}
|
||||
}
|
||||
pub fn to_socket_addr(&self) -> SocketAddr {
|
||||
match self.addr {
|
||||
IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, self.port)),
|
||||
IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, self.port, 0, 0)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for IpAddrPort {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self.addr {
|
||||
IpAddr::V4(a) => write!(f, "{}:{}", a, self.port()),
|
||||
IpAddr::V6(a) => write!(f, "[{}]:{}", a, self.port()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SocketAddrV4> for IpAddrPort {
|
||||
fn from(sock4: SocketAddrV4) -> IpAddrPort {
|
||||
Self::from_socket_addr(&SocketAddr::V4(sock4))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SocketAddrV6> for IpAddrPort {
|
||||
fn from(sock6: SocketAddrV6) -> IpAddrPort {
|
||||
Self::from_socket_addr(&SocketAddr::V6(sock6))
|
||||
}
|
||||
}
|
198
veilid-core/src/xx/ip_extra.rs
Normal file
198
veilid-core/src/xx/ip_extra.rs
Normal file
@@ -0,0 +1,198 @@
|
||||
//
|
||||
// This file really shouldn't be necessary, but 'ip' isn't a stable feature
|
||||
// and things may not agree between the no_std_net crate and the stuff in std.
|
||||
//
|
||||
|
||||
use crate::xx::*;
|
||||
use core::hash::*;
|
||||
|
||||
#[derive(Copy, PartialEq, Eq, Clone, Hash, Debug)]
|
||||
pub enum Ipv6MulticastScope {
|
||||
InterfaceLocal,
|
||||
LinkLocal,
|
||||
RealmLocal,
|
||||
AdminLocal,
|
||||
SiteLocal,
|
||||
OrganizationLocal,
|
||||
Global,
|
||||
}
|
||||
|
||||
pub fn ipaddr_is_unspecified(addr: &IpAddr) -> bool {
|
||||
match addr {
|
||||
IpAddr::V4(ip) => ipv4addr_is_unspecified(ip),
|
||||
IpAddr::V6(ip) => ipv6addr_is_unspecified(ip),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ipaddr_is_loopback(addr: &IpAddr) -> bool {
|
||||
match addr {
|
||||
IpAddr::V4(ip) => ipv4addr_is_loopback(ip),
|
||||
IpAddr::V6(ip) => ipv6addr_is_loopback(ip),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ipaddr_is_global(addr: &IpAddr) -> bool {
|
||||
match addr {
|
||||
IpAddr::V4(ip) => ipv4addr_is_global(ip),
|
||||
IpAddr::V6(ip) => ipv6addr_is_global(ip),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ipaddr_is_multicast(addr: &IpAddr) -> bool {
|
||||
match addr {
|
||||
IpAddr::V4(ip) => ipv4addr_is_multicast(ip),
|
||||
IpAddr::V6(ip) => ipv6addr_is_multicast(ip),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ipaddr_is_documentation(addr: &IpAddr) -> bool {
|
||||
match addr {
|
||||
IpAddr::V4(ip) => ipv4addr_is_documentation(ip),
|
||||
IpAddr::V6(ip) => ipv6addr_is_documentation(ip),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ipv4addr_is_unspecified(addr: &Ipv4Addr) -> bool {
|
||||
addr.octets() == [0u8, 0u8, 0u8, 0u8]
|
||||
}
|
||||
|
||||
pub fn ipv4addr_is_loopback(addr: &Ipv4Addr) -> bool {
|
||||
addr.octets()[0] == 127
|
||||
}
|
||||
|
||||
pub fn ipv4addr_is_private(addr: &Ipv4Addr) -> bool {
|
||||
match addr.octets() {
|
||||
[10, ..] => true,
|
||||
[172, b, ..] if b >= 16 && b <= 31 => true,
|
||||
[192, 168, ..] => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ipv4addr_is_link_local(addr: &Ipv4Addr) -> bool {
|
||||
match addr.octets() {
|
||||
[169, 254, ..] => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ipv4addr_is_global(addr: &Ipv4Addr) -> bool {
|
||||
// check if this address is 192.0.0.9 or 192.0.0.10. These addresses are the only two
|
||||
// globally routable addresses in the 192.0.0.0/24 range.
|
||||
if u32::from(*addr) == 0xc0000009 || u32::from(*addr) == 0xc000000a {
|
||||
return true;
|
||||
}
|
||||
!ipv4addr_is_private(addr)
|
||||
&& !ipv4addr_is_loopback(addr)
|
||||
&& !ipv4addr_is_link_local(addr)
|
||||
&& !ipv4addr_is_broadcast(addr)
|
||||
&& !ipv4addr_is_documentation(addr)
|
||||
&& !ipv4addr_is_shared(addr)
|
||||
&& !ipv4addr_is_ietf_protocol_assignment(addr)
|
||||
&& !ipv4addr_is_reserved(addr)
|
||||
&& !ipv4addr_is_benchmarking(addr)
|
||||
// Make sure the address is not in 0.0.0.0/8
|
||||
&& addr.octets()[0] != 0
|
||||
}
|
||||
|
||||
pub fn ipv4addr_is_shared(addr: &Ipv4Addr) -> bool {
|
||||
addr.octets()[0] == 100 && (addr.octets()[1] & 0b1100_0000 == 0b0100_0000)
|
||||
}
|
||||
|
||||
pub fn ipv4addr_is_ietf_protocol_assignment(addr: &Ipv4Addr) -> bool {
|
||||
addr.octets()[0] == 192 && addr.octets()[1] == 0 && addr.octets()[2] == 0
|
||||
}
|
||||
|
||||
pub fn ipv4addr_is_benchmarking(addr: &Ipv4Addr) -> bool {
|
||||
addr.octets()[0] == 198 && (addr.octets()[1] & 0xfe) == 18
|
||||
}
|
||||
|
||||
pub fn ipv4addr_is_reserved(addr: &Ipv4Addr) -> bool {
|
||||
addr.octets()[0] & 240 == 240 && !addr.is_broadcast()
|
||||
}
|
||||
|
||||
pub fn ipv4addr_is_multicast(addr: &Ipv4Addr) -> bool {
|
||||
addr.octets()[0] >= 224 && addr.octets()[0] <= 239
|
||||
}
|
||||
|
||||
pub fn ipv4addr_is_broadcast(addr: &Ipv4Addr) -> bool {
|
||||
addr.octets() == [255u8, 255u8, 255u8, 255u8]
|
||||
}
|
||||
|
||||
pub fn ipv4addr_is_documentation(addr: &Ipv4Addr) -> bool {
|
||||
match addr.octets() {
|
||||
[192, 0, 2, _] => true,
|
||||
[198, 51, 100, _] => true,
|
||||
[203, 0, 113, _] => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ipv6addr_is_unspecified(addr: &Ipv6Addr) -> bool {
|
||||
addr.segments() == [0, 0, 0, 0, 0, 0, 0, 0]
|
||||
}
|
||||
|
||||
pub fn ipv6addr_is_loopback(addr: &Ipv6Addr) -> bool {
|
||||
addr.segments() == [0, 0, 0, 0, 0, 0, 0, 1]
|
||||
}
|
||||
|
||||
pub fn ipv6addr_is_global(addr: &Ipv6Addr) -> bool {
|
||||
match ipv6addr_multicast_scope(addr) {
|
||||
Some(Ipv6MulticastScope::Global) => true,
|
||||
None => ipv6addr_is_unicast_global(addr),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ipv6addr_is_unique_local(addr: &Ipv6Addr) -> bool {
|
||||
(addr.segments()[0] & 0xfe00) == 0xfc00
|
||||
}
|
||||
|
||||
pub fn ipv6addr_is_unicast_link_local_strict(addr: &Ipv6Addr) -> bool {
|
||||
(addr.segments()[0] & 0xffff) == 0xfe80
|
||||
&& (addr.segments()[1] & 0xffff) == 0
|
||||
&& (addr.segments()[2] & 0xffff) == 0
|
||||
&& (addr.segments()[3] & 0xffff) == 0
|
||||
}
|
||||
|
||||
pub fn ipv6addr_is_unicast_link_local(addr: &Ipv6Addr) -> bool {
|
||||
(addr.segments()[0] & 0xffc0) == 0xfe80
|
||||
}
|
||||
|
||||
pub fn ipv6addr_is_unicast_site_local(addr: &Ipv6Addr) -> bool {
|
||||
(addr.segments()[0] & 0xffc0) == 0xfec0
|
||||
}
|
||||
|
||||
pub fn ipv6addr_is_documentation(addr: &Ipv6Addr) -> bool {
|
||||
(addr.segments()[0] == 0x2001) && (addr.segments()[1] == 0xdb8)
|
||||
}
|
||||
|
||||
pub fn ipv6addr_is_unicast_global(addr: &Ipv6Addr) -> bool {
|
||||
!ipv6addr_is_multicast(addr)
|
||||
&& !ipv6addr_is_loopback(addr)
|
||||
&& !ipv6addr_is_unicast_link_local(addr)
|
||||
&& !ipv6addr_is_unique_local(addr)
|
||||
&& !ipv6addr_is_unspecified(addr)
|
||||
&& !ipv6addr_is_documentation(addr)
|
||||
}
|
||||
|
||||
pub fn ipv6addr_multicast_scope(addr: &Ipv6Addr) -> Option<Ipv6MulticastScope> {
|
||||
if ipv6addr_is_multicast(addr) {
|
||||
match addr.segments()[0] & 0x000f {
|
||||
1 => Some(Ipv6MulticastScope::InterfaceLocal),
|
||||
2 => Some(Ipv6MulticastScope::LinkLocal),
|
||||
3 => Some(Ipv6MulticastScope::RealmLocal),
|
||||
4 => Some(Ipv6MulticastScope::AdminLocal),
|
||||
5 => Some(Ipv6MulticastScope::SiteLocal),
|
||||
8 => Some(Ipv6MulticastScope::OrganizationLocal),
|
||||
14 => Some(Ipv6MulticastScope::Global),
|
||||
_ => None,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ipv6addr_is_multicast(addr: &Ipv6Addr) -> bool {
|
||||
(addr.segments()[0] & 0xff00) == 0xff00
|
||||
}
|
80
veilid-core/src/xx/mod.rs
Normal file
80
veilid-core/src/xx/mod.rs
Normal file
@@ -0,0 +1,80 @@
|
||||
// mod bump_port;
|
||||
mod eventual;
|
||||
mod eventual_base;
|
||||
mod eventual_value;
|
||||
mod eventual_value_clone;
|
||||
mod ip_addr_port;
|
||||
mod ip_extra;
|
||||
mod single_future;
|
||||
mod single_shot_eventual;
|
||||
mod tick_task;
|
||||
mod tools;
|
||||
|
||||
pub use cfg_if::*;
|
||||
pub use log::*;
|
||||
pub use parking_lot::*;
|
||||
pub use static_assertions::*;
|
||||
|
||||
pub type PinBox<T> = Pin<Box<T>>;
|
||||
pub type PinBoxFuture<T> = PinBox<dyn Future<Output = T> + 'static>;
|
||||
pub type PinBoxFutureLifetime<'a, T> = PinBox<dyn Future<Output = T> + 'a>;
|
||||
pub type SendPinBoxFuture<T> = PinBox<dyn Future<Output = T> + Send + 'static>;
|
||||
pub type SendPinBoxFutureLifetime<'a, T> = PinBox<dyn Future<Output = T> + Send + 'a>;
|
||||
|
||||
cfg_if! {
|
||||
if #[cfg(target_arch = "wasm32")] {
|
||||
extern crate alloc;
|
||||
pub use alloc::string::String;
|
||||
pub use alloc::vec::Vec;
|
||||
pub use alloc::collections::btree_map::BTreeMap;
|
||||
pub use alloc::collections::btree_set::BTreeSet;
|
||||
pub use alloc::boxed::Box;
|
||||
pub use alloc::borrow::{Cow, ToOwned};
|
||||
pub use wasm_bindgen::prelude::*;
|
||||
pub use core::cmp;
|
||||
pub use core::mem;
|
||||
pub use alloc::rc::Rc;
|
||||
pub use core::cell::RefCell;
|
||||
pub use core::task;
|
||||
pub use core::future::Future;
|
||||
pub use core::pin::Pin;
|
||||
pub use core::sync::atomic::{Ordering, AtomicBool};
|
||||
pub use alloc::sync::{Arc, Weak};
|
||||
pub use core::ops::{FnOnce, FnMut, Fn};
|
||||
pub use no_std_net::{ SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs, IpAddr, Ipv4Addr, Ipv6Addr };
|
||||
pub type SystemPinBoxFuture<T> = PinBox<dyn Future<Output = T> + 'static>;
|
||||
pub type SystemPinBoxFutureLifetime<'a, T> = PinBox<dyn Future<Output = T> + 'a>;
|
||||
} else {
|
||||
pub use std::string::String;
|
||||
pub use std::vec::Vec;
|
||||
pub use std::collections::btree_map::BTreeMap;
|
||||
pub use std::collections::btree_set::BTreeSet;
|
||||
pub use std::boxed::Box;
|
||||
pub use std::borrow::{Cow, ToOwned};
|
||||
pub use std::cmp;
|
||||
pub use std::mem;
|
||||
pub use std::sync::atomic::{Ordering, AtomicBool};
|
||||
pub use std::sync::{Arc, Weak};
|
||||
pub use std::rc::Rc;
|
||||
pub use std::cell::RefCell;
|
||||
pub use std::task;
|
||||
pub use std::ops::{FnOnce, FnMut, Fn};
|
||||
pub use async_std::future::Future;
|
||||
pub use async_std::pin::Pin;
|
||||
pub use std::net::{ SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs, IpAddr, Ipv4Addr, Ipv6Addr };
|
||||
pub type SystemPinBoxFuture<T> = PinBox<dyn Future<Output = T> + Send + 'static>;
|
||||
pub type SystemPinBoxFutureLifetime<'a, T> = PinBox<dyn Future<Output = T> + Send + 'a>;
|
||||
}
|
||||
}
|
||||
|
||||
// pub use bump_port::*;
|
||||
pub use eventual::*;
|
||||
pub use eventual_base::{EventualCommon, EventualResolvedFuture};
|
||||
pub use eventual_value::*;
|
||||
pub use eventual_value_clone::*;
|
||||
pub use ip_addr_port::*;
|
||||
pub use ip_extra::*;
|
||||
pub use single_future::*;
|
||||
pub use single_shot_eventual::*;
|
||||
pub use tick_task::*;
|
||||
pub use tools::*;
|
240
veilid-core/src/xx/single_future.rs
Normal file
240
veilid-core/src/xx/single_future.rs
Normal file
@@ -0,0 +1,240 @@
|
||||
use super::*;
|
||||
use crate::intf::*;
|
||||
use cfg_if::*;
|
||||
use core::task::Poll;
|
||||
use futures_util::poll;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct SingleFutureInner<T>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
locked: bool,
|
||||
join_handle: Option<JoinHandle<T>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SingleFuture<T>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
inner: Arc<Mutex<SingleFutureInner<T>>>,
|
||||
}
|
||||
|
||||
impl<T> Default for SingleFuture<T>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> SingleFuture<T>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
inner: Arc::new(Mutex::new(SingleFutureInner {
|
||||
locked: false,
|
||||
join_handle: None,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
fn try_lock(&self) -> Result<Option<JoinHandle<T>>, ()> {
|
||||
let mut inner = self.inner.lock();
|
||||
if inner.locked {
|
||||
// If already locked error out
|
||||
return Err(());
|
||||
}
|
||||
inner.locked = true;
|
||||
// If we got the lock, return what we have for a join handle if anything
|
||||
Ok(inner.join_handle.take())
|
||||
}
|
||||
|
||||
fn unlock(&self, jh: Option<JoinHandle<T>>) {
|
||||
let mut inner = self.inner.lock();
|
||||
assert_eq!(inner.locked, true);
|
||||
assert_eq!(inner.join_handle.is_none(), true);
|
||||
inner.locked = false;
|
||||
inner.join_handle = jh;
|
||||
}
|
||||
|
||||
// Check the result
|
||||
pub async fn check(&self) -> Result<Option<T>, ()> {
|
||||
let mut out: Option<T> = None;
|
||||
|
||||
// See if we have a result we can return
|
||||
let maybe_jh = match self.try_lock() {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
// If we are already polling somewhere else, don't hand back a result
|
||||
return Err(());
|
||||
}
|
||||
};
|
||||
if maybe_jh.is_some() {
|
||||
let mut jh = maybe_jh.unwrap();
|
||||
|
||||
// See if we finished, if so, return the value of the last execution
|
||||
if let Poll::Ready(r) = poll!(&mut jh) {
|
||||
out = Some(r);
|
||||
// Task finished, unlock with nothing
|
||||
self.unlock(None);
|
||||
} else {
|
||||
// Still running put the join handle back so we can check on it later
|
||||
self.unlock(Some(jh));
|
||||
}
|
||||
} else {
|
||||
// No task, unlock with nothing
|
||||
self.unlock(None);
|
||||
}
|
||||
|
||||
// Return the prior result if we have one
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// Wait for the result
|
||||
pub async fn join(&self) -> Result<Option<T>, ()> {
|
||||
let mut out: Option<T> = None;
|
||||
|
||||
// See if we have a result we can return
|
||||
let maybe_jh = match self.try_lock() {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
// If we are already polling somewhere else,
|
||||
// that's an error because you can only join
|
||||
// these things once
|
||||
return Err(());
|
||||
}
|
||||
};
|
||||
if maybe_jh.is_some() {
|
||||
let jh = maybe_jh.unwrap();
|
||||
// Wait for return value of the last execution
|
||||
out = Some(jh.await);
|
||||
// Task finished, unlock with nothing
|
||||
} else {
|
||||
// No task, unlock with nothing
|
||||
}
|
||||
self.unlock(None);
|
||||
|
||||
// Return the prior result if we have one
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// Cancel
|
||||
pub async fn cancel(&self) -> Result<Option<T>, ()> {
|
||||
let mut out: Option<T> = None;
|
||||
|
||||
// See if we have a result we can return
|
||||
let maybe_jh = match self.try_lock() {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
// If we are already polling somewhere else, don't hand back a result
|
||||
return Err(());
|
||||
}
|
||||
};
|
||||
if maybe_jh.is_some() {
|
||||
let mut jh = maybe_jh.unwrap();
|
||||
|
||||
// See if we finished, if so, return the value of the last execution
|
||||
if let Poll::Ready(r) = poll!(&mut jh) {
|
||||
out = Some(r);
|
||||
// Task finished, unlock with nothing
|
||||
} else {
|
||||
// Still running but drop the join handle anyway to cancel the task, unlock with nothing
|
||||
}
|
||||
}
|
||||
self.unlock(None);
|
||||
|
||||
// Return the prior result if we have one
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// Possibly spawn the future possibly returning the value of the last execution
|
||||
cfg_if! {
|
||||
if #[cfg(target_arch = "wasm32")] {
|
||||
pub async fn single_spawn(
|
||||
&self,
|
||||
future: impl Future<Output = T> + 'static,
|
||||
) -> Result<Option<T>, ()> {
|
||||
let mut out: Option<T> = None;
|
||||
|
||||
// See if we have a result we can return
|
||||
let maybe_jh = match self.try_lock() {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
// If we are already polling somewhere else, don't hand back a result
|
||||
return Err(());
|
||||
}
|
||||
};
|
||||
let mut run = true;
|
||||
|
||||
if maybe_jh.is_some() {
|
||||
let mut jh = maybe_jh.unwrap();
|
||||
|
||||
// See if we finished, if so, return the value of the last execution
|
||||
if let Poll::Ready(r) = poll!(&mut jh) {
|
||||
out = Some(r);
|
||||
// Task finished, unlock with a new task
|
||||
} else {
|
||||
// Still running, don't run again, unlock with the current join handle
|
||||
run = false;
|
||||
self.unlock(Some(jh));
|
||||
}
|
||||
}
|
||||
|
||||
// Run if we should do that
|
||||
if run {
|
||||
self.unlock(Some(spawn_local(future)));
|
||||
}
|
||||
|
||||
// Return the prior result if we have one
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cfg_if! {
|
||||
if #[cfg(not(target_arch = "wasm32"))] {
|
||||
impl<T> SingleFuture<T>
|
||||
where
|
||||
T: 'static + Send,
|
||||
{
|
||||
pub async fn single_spawn(
|
||||
&self,
|
||||
future: impl Future<Output = T> + Send + 'static,
|
||||
) -> Result<Option<T>, ()> {
|
||||
let mut out: Option<T> = None;
|
||||
// See if we have a result we can return
|
||||
let maybe_jh = match self.try_lock() {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
// If we are already polling somewhere else, don't hand back a result
|
||||
return Err(());
|
||||
}
|
||||
};
|
||||
let mut run = true;
|
||||
if maybe_jh.is_some() {
|
||||
let mut jh = maybe_jh.unwrap();
|
||||
// See if we finished, if so, return the value of the last execution
|
||||
if let Poll::Ready(r) = poll!(&mut jh) {
|
||||
out = Some(r);
|
||||
// Task finished, unlock with a new task
|
||||
} else {
|
||||
// Still running, don't run again, unlock with the current join handle
|
||||
run = false;
|
||||
self.unlock(Some(jh));
|
||||
}
|
||||
}
|
||||
// Run if we should do that
|
||||
if run {
|
||||
self.unlock(Some(spawn(future)));
|
||||
}
|
||||
// Return the prior result if we have one
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
39
veilid-core/src/xx/single_shot_eventual.rs
Normal file
39
veilid-core/src/xx/single_shot_eventual.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
use super::*;
|
||||
|
||||
pub struct SingleShotEventual<T>
|
||||
where
|
||||
T: Unpin + Clone,
|
||||
{
|
||||
eventual: EventualValueClone<T>,
|
||||
drop_value: T,
|
||||
}
|
||||
|
||||
impl<T> Drop for SingleShotEventual<T>
|
||||
where
|
||||
T: Unpin + Clone,
|
||||
{
|
||||
fn drop(&mut self) {
|
||||
self.eventual.resolve(self.drop_value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> SingleShotEventual<T>
|
||||
where
|
||||
T: Unpin + Clone,
|
||||
{
|
||||
pub fn new(drop_value: T) -> Self {
|
||||
Self {
|
||||
eventual: EventualValueClone::new(),
|
||||
drop_value: drop_value,
|
||||
}
|
||||
}
|
||||
|
||||
// Can only call this once, it consumes the eventual
|
||||
pub fn resolve(self, value: T) -> EventualResolvedFuture<EventualValueClone<T>> {
|
||||
self.eventual.resolve(value)
|
||||
}
|
||||
|
||||
pub fn instance(&self) -> EventualValueCloneFuture<T> {
|
||||
self.eventual.instance()
|
||||
}
|
||||
}
|
95
veilid-core/src/xx/tick_task.rs
Normal file
95
veilid-core/src/xx/tick_task.rs
Normal file
@@ -0,0 +1,95 @@
|
||||
use super::*;
|
||||
use crate::intf::*;
|
||||
use core::sync::atomic::{AtomicU64, Ordering};
|
||||
use once_cell::sync::OnceCell;
|
||||
|
||||
cfg_if! {
|
||||
if #[cfg(target_arch = "wasm32")] {
|
||||
type TickTaskRoutine =
|
||||
dyn Fn(u64, u64) -> PinBoxFuture<Result<(), String>> + 'static;
|
||||
} else {
|
||||
type TickTaskRoutine =
|
||||
dyn Fn(u64, u64) -> SendPinBoxFuture<Result<(), String>> + Send + Sync + 'static;
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TickTask {
|
||||
last_timestamp_us: AtomicU64,
|
||||
tick_period_us: u64,
|
||||
routine: OnceCell<Box<TickTaskRoutine>>,
|
||||
single_future: SingleFuture<Result<(), String>>,
|
||||
}
|
||||
|
||||
impl TickTask {
|
||||
pub fn new_us(tick_period_us: u64) -> Self {
|
||||
Self {
|
||||
last_timestamp_us: AtomicU64::new(0),
|
||||
tick_period_us: tick_period_us,
|
||||
routine: OnceCell::new(),
|
||||
single_future: SingleFuture::new(),
|
||||
}
|
||||
}
|
||||
pub fn new(tick_period_sec: u32) -> Self {
|
||||
Self {
|
||||
last_timestamp_us: AtomicU64::new(0),
|
||||
tick_period_us: (tick_period_sec as u64) * 1000000u64,
|
||||
routine: OnceCell::new(),
|
||||
single_future: SingleFuture::new(),
|
||||
}
|
||||
}
|
||||
|
||||
cfg_if! {
|
||||
if #[cfg(target_arch = "wasm32")] {
|
||||
pub fn set_routine(
|
||||
&self,
|
||||
routine: impl Fn(u64, u64) -> PinBoxFuture<Result<(), String>> + 'static,
|
||||
) {
|
||||
self.routine.set(Box::new(routine)).map_err(drop).unwrap();
|
||||
}
|
||||
} else {
|
||||
pub fn set_routine(
|
||||
&self,
|
||||
routine: impl Fn(u64, u64) -> SendPinBoxFuture<Result<(), String>> + Send + Sync + 'static,
|
||||
) {
|
||||
self.routine.set(Box::new(routine)).map_err(drop).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn cancel(&self) -> Result<(), String> {
|
||||
match self.single_future.cancel().await {
|
||||
Ok(Some(Err(err))) => Err(err),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn tick(&self) -> Result<(), String> {
|
||||
let now = get_timestamp();
|
||||
let last_timestamp_us = self.last_timestamp_us.load(Ordering::Acquire);
|
||||
|
||||
if last_timestamp_us == 0u64 || (now - last_timestamp_us) >= self.tick_period_us {
|
||||
// Run the singlefuture
|
||||
match self
|
||||
.single_future
|
||||
.single_spawn(self.routine.get().unwrap()(last_timestamp_us, now))
|
||||
.await
|
||||
{
|
||||
Ok(Some(Err(err))) => {
|
||||
// If the last execution errored out then we should pass that error up
|
||||
self.last_timestamp_us.store(now, Ordering::Release);
|
||||
return Err(err);
|
||||
}
|
||||
Ok(None) | Err(()) => {
|
||||
// If the execution didn't happen this time because it was already running
|
||||
// then we should try again the next tick and not reset the timestamp so we try as soon as possible
|
||||
}
|
||||
_ => {
|
||||
// Execution happened, next execution attempt should happen only after tick period
|
||||
self.last_timestamp_us.store(now, Ordering::Release);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
101
veilid-core/src/xx/tools.rs
Normal file
101
veilid-core/src/xx/tools.rs
Normal file
@@ -0,0 +1,101 @@
|
||||
use crate::xx::*;
|
||||
use alloc::string::ToString;
|
||||
|
||||
pub fn split_port(name: &str) -> Result<(String, u16), ()> {
|
||||
if let Some(split) = name.rfind(':') {
|
||||
let hoststr = &name[0..split];
|
||||
let portstr = &name[split + 1..];
|
||||
let port: u16 = portstr.parse::<u16>().map_err(drop)?;
|
||||
|
||||
Ok((hoststr.to_string(), port))
|
||||
} else {
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn prepend_slash(s: String) -> String {
|
||||
if s.starts_with("/") {
|
||||
return s;
|
||||
}
|
||||
let mut out = "/".to_owned();
|
||||
out.push_str(s.as_str());
|
||||
out
|
||||
}
|
||||
|
||||
pub fn timestamp_to_secs(ts: u64) -> f64 {
|
||||
ts as f64 / 1000000.0f64
|
||||
}
|
||||
|
||||
pub fn secs_to_timestamp(secs: f64) -> u64 {
|
||||
(secs * 1000000.0f64) as u64
|
||||
}
|
||||
|
||||
// Calculate retry attempt with logarhythmic falloff
|
||||
pub fn retry_falloff_log(
|
||||
last_us: u64,
|
||||
cur_us: u64,
|
||||
interval_start_us: u64,
|
||||
interval_max_us: u64,
|
||||
interval_multiplier_us: f64,
|
||||
) -> bool {
|
||||
//
|
||||
if cur_us < interval_start_us {
|
||||
// Don't require a retry within the first 'interval_start_us' microseconds of the reliable time period
|
||||
false
|
||||
} else if cur_us >= last_us + interval_max_us {
|
||||
// Retry at least every 'interval_max_us' microseconds
|
||||
true
|
||||
} else {
|
||||
// Exponential falloff between 'interval_start_us' and 'interval_max_us' microseconds
|
||||
// Optimal equation here is: y = Sum[Power[b,x],{n,0,x}] --> y = (x+1)b^x
|
||||
// but we're just gonna simplify this to a log curve for speed
|
||||
let last_secs = timestamp_to_secs(last_us);
|
||||
let nth = (last_secs / timestamp_to_secs(interval_start_us))
|
||||
.log(interval_multiplier_us)
|
||||
.floor() as i32;
|
||||
let next_secs = timestamp_to_secs(interval_start_us) * interval_multiplier_us.powi(nth + 1);
|
||||
let next_us = secs_to_timestamp(next_secs);
|
||||
cur_us >= next_us
|
||||
}
|
||||
}
|
||||
|
||||
pub fn try_at_most_n_things<T, I, C, R>(max: usize, things: I, closure: C) -> Option<R>
|
||||
where
|
||||
I: IntoIterator<Item = T>,
|
||||
C: Fn(T) -> Option<R>,
|
||||
{
|
||||
let mut fails = 0usize;
|
||||
for thing in things.into_iter() {
|
||||
if let Some(r) = closure(thing) {
|
||||
return Some(r);
|
||||
}
|
||||
fails += 1;
|
||||
if fails >= max {
|
||||
break;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub async fn async_try_at_most_n_things<T, I, C, R, F>(
|
||||
max: usize,
|
||||
things: I,
|
||||
closure: C,
|
||||
) -> Option<R>
|
||||
where
|
||||
I: IntoIterator<Item = T>,
|
||||
C: Fn(T) -> F,
|
||||
F: Future<Output = Option<R>>,
|
||||
{
|
||||
let mut fails = 0usize;
|
||||
for thing in things.into_iter() {
|
||||
if let Some(r) = closure(thing).await {
|
||||
return Some(r);
|
||||
}
|
||||
fails += 1;
|
||||
if fails >= max {
|
||||
break;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
Reference in New Issue
Block a user