use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, Mutex};
use serde_json::Value;
use super::codec::Message;
use super::protocol::{
ConfigGiven, ConfigLine, ConfigOpen, ConfigOrigin, ConfigReset, ConfigUpdate, ConfigValue, Failure, Handle, method,
};
use super::{Link, Route};
use crate::config::{Config, Origin, Sent, Snapshot, Watching};
use crate::sync::lock;
use crate::{Store, unix_millis};
use super::Answered;
#[derive(Debug, Default)]
pub(crate) struct Configs {
open: super::ByHandle<Config<Value>>,
follows: Mutex<HashMap<u32, Arc<Following>>>,
}
pub(crate) fn route(called: u16) -> Route {
match called {
method::CONFIG_FOLLOW => Route::Follow,
_ => Route::Worker,
}
}
pub(crate) fn call(store: &Store, configs: &Configs, called: u16, body: &[u8], read_only: bool) -> Answered {
match called {
method::CONFIG_OPEN => open(store, configs, &ConfigOpen::decode(body)?, read_only),
method::CONFIG_UPDATE => {
let update = ConfigUpdate::decode(body)?;
let config = configs.config(update.handle)?;
config.update_data(update.version, &json(&update.changes, "changes")?)?;
Ok(value(update.handle, &config))
}
method::CONFIG_RESET => {
let reset = ConfigReset::decode(body)?;
let config = configs.config(reset.handle)?;
if reset.path.is_empty() {
config.reset_all()?
} else {
config.reset(&reset.path)?
}
Ok(value(reset.handle, &config))
}
other => Err(Failure::unimplemented(format!("method {other:#06x}"))),
}
}
fn open(store: &Store, configs: &Configs, open: &ConfigOpen, read_only: bool) -> Answered {
let (declaration, layers) = (json(&open.declaration, "declaration")?, json(&open.layers, "layers")?);
let sent = Sent {
name: &open.name,
declaration: &declaration,
layers: &layers,
strict: open.strict,
remember: !read_only,
};
let config = store.config_sent(&sent)?;
let handle = configs.open.keep(config.clone());
Ok(value(handle, &config))
}
fn json(text: &str, what: &str) -> Result<Value, Failure> {
serde_json::from_str(text).map_err(|error| Failure::invalid(format!("a config's {what}: {error}")))
}
fn value(handle: u64, config: &Config<Value>) -> Vec<u8> {
message(handle, &config.get(), config).encode()
}
fn message(handle: u64, snapshot: &Snapshot<Value>, config: &Config<Value>) -> ConfigValue {
let explained = config.explain();
let lines = explained.settings.into_iter().map(|line| ConfigLine {
path: line.path,
value: line.value,
from: line.from,
over: line.over,
given: line
.given
.into_iter()
.map(|given| ConfigGiven { value: given.value, from: origin(given.from) })
.collect(),
});
ConfigValue {
handle,
version: snapshot.version(),
value: snapshot.to_string(),
lines: lines.collect(),
notes: explained.notes,
}
}
fn origin(from: Origin) -> ConfigOrigin {
let kind = |kind: &str| ConfigOrigin { kind: kind.to_owned(), ..ConfigOrigin::default() };
match from {
Origin::Declaration => kind("declaration"),
Origin::Layer { place } => ConfigOrigin { place: Some(place as u64), ..kind("layer") },
Origin::File { path } => ConfigOrigin { path: Some(path), ..kind("file") },
Origin::Env { variable, dotenv, file } => {
ConfigOrigin { variable: Some(variable), dotenv, file, ..kind("env") }
}
Origin::Change { version, at } => {
ConfigOrigin { version: Some(version), at: Some(unix_millis(at)), ..kind("change") }
}
}
}
impl Configs {
fn config(&self, handle: u64) -> Result<Config<Value>, Failure> {
self.open.get(handle, || format!("handle {handle} names no config opened here"))
}
pub(crate) fn grant(&self, stream: u32, credit: u32) {
let following = lock(&self.follows).get(&stream).cloned();
if let Some(following) = following {
following.grant(credit);
}
}
pub(crate) fn cancel(&self, stream: u32) -> bool {
let following = lock(&self.follows).remove(&stream);
if let Some(following) = following {
following.close(Err(Failure::cancelled("the client cancelled its follow")));
return true;
}
false
}
pub(crate) fn go_away(&self) {
let follows: Vec<_> = lock(&self.follows).drain().map(|(_, following)| following).collect();
for following in follows {
following.close(Err(Failure::unavailable("the server is closing; follow again on another connection")));
}
}
pub(crate) fn end(&self) {
let follows: Vec<_> = lock(&self.follows).drain().map(|(_, following)| following).collect();
for following in follows {
following.end();
}
self.open.clear();
}
}
pub(crate) fn follow(configs: &Configs, number: u32, body: &[u8], link: Link) -> Result<Arc<Following>, Failure> {
let handle = Handle::decode(body)?.handle;
let config = configs.config(handle)?;
let state = Mutex::new(FollowState { credit: link.credit, ..FollowState::default() });
let following = Arc::new(Following { handle, config, watching: Mutex::new(None), state, link });
lock(&configs.follows).insert(number, Arc::clone(&following));
Ok(following)
}
pub(crate) struct Following {
handle: u64,
config: Config<Value>,
watching: Mutex<Option<Watching>>,
state: Mutex<FollowState>,
link: Link,
}
#[derive(Default)]
struct FollowState {
credit: u64,
waiting: Option<Vec<u8>>,
ended: bool,
}
impl Following {
pub(crate) fn begin(self: &Arc<Self>) {
let me = Arc::downgrade(self);
let watching = self.config.watch(move |next, _| {
if let Some(following) = me.upgrade() {
following.push(message(following.handle, next, &following.config).encode());
}
});
*lock(&self.watching) = Some(watching);
}
fn push(&self, body: Vec<u8>) {
let mut state = lock(&self.state);
if !state.ended {
state.waiting = Some(body);
self.flush(&mut state);
}
}
fn grant(&self, credit: u32) {
let mut state = lock(&self.state);
state.credit += u64::from(credit);
self.flush(&mut state);
}
fn flush(&self, state: &mut FollowState) {
let credit = state.credit;
if let Some(body) = state.waiting.take_if(|body| body.len() as u64 <= credit) {
state.credit -= body.len() as u64;
(self.link.send)(body);
}
}
fn end(&self) -> bool {
if std::mem::replace(&mut lock(&self.state).ended, true) {
return false;
}
drop(lock(&self.watching).take());
true
}
fn close(&self, last: Answered) {
if self.end() {
(self.link.finish)(last);
}
}
}
impl fmt::Debug for Following {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Following").field("handle", &self.handle).finish_non_exhaustive()
}
}
#[cfg(test)]
#[path = "config_tests.rs"]
mod tests;