use core::any::TypeId;
use smol_bytes::Utf8Bytes;
use crate::{
arrange::{DriverKind, FanoutKind, GraphBuilder, NodeId},
drive::{AckMode, ChannelOptions, Effect, Listen, Streams, TracingLevel},
operator::Driven,
resource::ResourceDemand,
};
use super::{
ArrangementError, ChannelShelf, Goodbye, GrantsNoStoreError, LaunchError, NodeWiring, Plan,
Refusal, UnknownGrantError, UnknownUpstreamError, UpstreamWiring,
};
#[cfg(test)]
mod tests;
#[derive(Debug, Clone, Copy)]
pub struct Upstream {
upstream: TypeId,
named: &'static str,
listen: Listen,
ack: AckMode,
channel: Option<ChannelOptions>,
}
impl Upstream {
#[inline]
#[must_use]
pub const fn of<U: 'static>(named: &'static str) -> Self {
Self {
upstream: TypeId::of::<U>(),
named,
listen: Listen::Channel,
ack: AckMode::Local,
channel: None,
}
}
#[inline]
#[must_use]
pub const fn listening(mut self, listen: Listen) -> Self {
self.listen = listen;
self
}
#[inline]
#[must_use]
pub const fn acking(mut self, ack: AckMode) -> Self {
self.ack = ack;
self
}
#[inline]
#[must_use]
pub const fn channelled(mut self, channel: ChannelOptions) -> Self {
self.channel = Some(channel);
self
}
#[inline]
#[must_use]
pub const fn upstream(&self) -> TypeId {
self.upstream
}
#[inline]
#[must_use]
pub const fn named(&self) -> &'static str {
self.named
}
#[inline]
#[must_use]
pub const fn listen(&self) -> Listen {
self.listen
}
#[inline]
#[must_use]
pub const fn ack(&self) -> AckMode {
self.ack
}
#[inline]
#[must_use]
pub const fn channel(&self) -> Option<ChannelOptions> {
self.channel
}
#[inline]
fn wiring(&self) -> UpstreamWiring {
let wiring = UpstreamWiring::new(self.listen, self.ack);
match self.channel {
Some(channel) => wiring.with_channel(channel),
None => wiring,
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct Grant {
node: TypeId,
clock: &'static str,
named: &'static str,
}
impl Grant {
#[inline]
#[must_use]
pub const fn of<N: 'static>(clock: &'static str, named: &'static str) -> Self {
Self {
node: TypeId::of::<N>(),
clock,
named,
}
}
#[inline]
#[must_use]
pub const fn node(&self) -> TypeId {
self.node
}
#[inline]
#[must_use]
pub const fn clock(&self) -> &'static str {
self.clock
}
#[inline]
#[must_use]
pub const fn named(&self) -> &'static str {
self.named
}
}
#[diagnostic::on_unimplemented(
note = "a node the graph root launches states its facts through `Declared` — the five node \
macros emit one, and a hand-written node writes one",
note = "if `{Self}` is a resource rather than a node, mark its field `#[ingraph(resource)]`"
)]
pub trait Declared: Sized + 'static {
const EFFECT: Effect;
const HOLDS_LANE: bool = false;
const DRIVER: DriverKind = DriverKind::Thread;
type Pair;
type Wires<O>;
type Attribution<O>: Default;
type Mode;
const UPSTREAMS: &'static [Upstream] = &[];
const GRANTS: &'static [Grant] = &[];
const DEMANDS: &'static [fn() -> ResourceDemand] = &[];
const TRACING: TracingLevel = TracingLevel::Info;
type Channels: ChannelShelf;
type Options;
const TEARDOWN: bool = false;
#[inline]
fn goodbye(self) -> Goodbye {
drop(self);
Box::pin(core::future::ready(Ok(())))
}
#[inline]
fn demands() -> impl Iterator<Item = ResourceDemand> {
Self::DEMANDS.iter().map(|mint| mint())
}
}
#[derive(Default)]
pub struct Blueprint {
builder: GraphBuilder,
nodes: Vec<Declaration>,
}
impl core::fmt::Debug for Blueprint {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Blueprint")
.field("nodes", &self.nodes.len())
.field(
"upstreams",
&self
.nodes
.iter()
.map(|node| node.upstreams.len())
.sum::<usize>(),
)
.finish()
}
}
#[derive(Debug)]
struct Declaration {
mount: Utf8Bytes,
identity: TypeId,
wiring: NodeWiring,
upstreams: &'static [Upstream],
grants: &'static [Grant],
demands: Vec<ResourceDemand>,
}
impl Blueprint {
#[inline]
#[must_use]
pub fn new() -> Self {
Self {
builder: GraphBuilder::new(),
nodes: Vec::new(),
}
}
#[inline]
pub fn node<N>(&mut self, mount: impl Into<Utf8Bytes>) -> NodeId
where
N: Declared + Driven<<N as Declared>::Mode>,
{
let mount = mount.into();
let handle = if N::UPSTREAMS.is_empty() {
self.builder.source::<N>(mount.clone(), N::DRIVER)
} else {
self.builder.node::<N>(mount.clone(), N::DRIVER)
};
self.entered::<N>(mount);
handle.id()
}
#[inline]
pub fn stream<N>(&mut self, mount: impl Into<Utf8Bytes>) -> NodeId
where
N: Declared + Streams<<N as Declared>::Mode>,
{
let mount = mount.into();
let handle = if N::UPSTREAMS.is_empty() {
self.builder.streaming_source::<N>(mount.clone(), N::DRIVER)
} else {
self.builder.streaming::<N>(mount.clone(), N::DRIVER)
};
self.entered::<N>(mount);
handle.id()
}
#[inline]
pub fn autonomous<N>(&mut self, mount: impl Into<Utf8Bytes>) -> NodeId
where
N: Declared + crate::Runs<<N as Declared>::Mode>,
{
let mount = mount.into();
let handle = if N::UPSTREAMS.is_empty() {
self
.builder
.autonomous_source::<N>(mount.clone(), N::DRIVER)
} else {
self.builder.autonomous::<N>(mount.clone(), N::DRIVER)
};
self.entered::<N>(mount);
handle.id()
}
fn entered<N>(&mut self, mount: Utf8Bytes)
where
N: Declared,
{
let upstreams = N::UPSTREAMS;
let wiring = {
let wiring = NodeWiring::new(N::EFFECT).tracing(N::TRACING);
let wiring = if N::HOLDS_LANE {
wiring.landing()
} else {
wiring
};
if upstreams.len() > 1 {
wiring.drawing()
} else {
wiring
}
};
self.nodes.push(Declaration {
mount,
identity: TypeId::of::<N>(),
wiring,
upstreams,
grants: N::GRANTS,
demands: N::demands().collect(),
});
}
#[inline]
pub fn origin<S>(&mut self, mount: impl Into<Utf8Bytes>) -> NodeId
where
S: crate::DeclaredOrigin + crate::Lived<<S as crate::DeclaredOrigin>::Mode>,
{
let mount = mount.into();
let handle = self.builder.origin::<S>(mount.clone(), DriverKind::Thread);
self.nodes.push(Declaration {
mount,
identity: TypeId::of::<S>(),
wiring: NodeWiring::new(Effect::Pure).originating(),
upstreams: &[],
grants: &[],
demands: Vec::new(),
});
handle.id()
}
pub fn into_plan(self) -> Result<Plan, LaunchError> {
let Self { mut builder, nodes } = self;
let mut refusals = Vec::new();
let mut edges = Vec::new();
for (position, node) in nodes.iter().enumerate() {
let consumer = NodeId::new(position);
for upstream in node.upstreams {
match nodes
.iter()
.position(|other| other.identity == upstream.upstream())
{
Some(producer) => edges.push((
builder.join(NodeId::new(producer), consumer, FanoutKind::Broadcast),
upstream.wiring(),
)),
None => refusals.push(Refusal::UnknownUpstream(UnknownUpstreamError::new(
node.mount.clone(),
upstream.named(),
))),
}
}
for grant in node.grants {
match nodes.iter().find(|other| other.identity == grant.node()) {
Some(granted) if granted.wiring.effect().is_pure() => {
refusals.push(Refusal::GrantsNoStore(GrantsNoStoreError::new(
node.mount.clone(),
grant.clock(),
granted.mount.clone(),
grant.named(),
)));
}
Some(_) => {}
None => refusals.push(Refusal::UnknownGrant(UnknownGrantError::new(
node.mount.clone(),
grant.clock(),
grant.named(),
))),
}
}
}
if !refusals.is_empty() {
return Err(LaunchError::Refused(refusals));
}
let graph = builder.validate().map_err(|error| {
LaunchError::Refused(vec![Refusal::Arrangement(ArrangementError::new(
error.to_string(),
))])
})?;
let mut plan = Plan::new(graph);
for (position, node) in nodes.iter().enumerate() {
plan = plan.wiring(NodeId::new(position), node.wiring);
for demand in &node.demands {
plan = plan.demanding(NodeId::new(position), *demand);
}
}
for (edge, wiring) in edges {
plan = plan.upstream(edge, wiring);
}
Ok(plan)
}
}