Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cln_plugin Refactor ConfigOption #7042

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 19 additions & 12 deletions plugins/examples/cln-plugin-startup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,28 @@
//! plugins using the Rust API against Core Lightning.
#[macro_use]
extern crate serde_json;
use cln_plugin::{messages, options, Builder, Error, Plugin};
use cln_plugin::options::{DefaultIntegerConfigOption, IntegerConfigOption};
use cln_plugin::{messages, Builder, Error, Plugin};
use tokio;

const TEST_NOTIF_TAG: &str = "test_custom_notification";

const TEST_OPTION: DefaultIntegerConfigOption = DefaultIntegerConfigOption::new_i64_with_default(
"test-option",
42,
"a test-option with default 42",
);

const TEST_OPTION_NO_DEFAULT: IntegerConfigOption =
IntegerConfigOption::new_i64_no_default("opt-option", "An option without a default");

#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
let state = ();

if let Some(plugin) = Builder::new(tokio::io::stdin(), tokio::io::stdout())
.option(options::ConfigOption::new(
"test-option",
options::Value::Integer(42),
"a test-option with default 42",
))
.option(options::ConfigOption::new(
"opt-option",
options::Value::OptInteger,
"An optional option",
))
.option(TEST_OPTION)
.option(TEST_OPTION_NO_DEFAULT)
.rpcmethod("testmethod", "This is a test", testmethod)
.rpcmethod(
"testoptions",
Expand All @@ -47,8 +49,13 @@ async fn main() -> Result<(), anyhow::Error> {
}

async fn testoptions(p: Plugin<()>, _v: serde_json::Value) -> Result<serde_json::Value, Error> {
let test_option = p.option(&TEST_OPTION)?;
let test_option_no_default = p
.option(&TEST_OPTION_NO_DEFAULT)?;

Ok(json!({
"opt-option": format!("{:?}", p.option("opt-option").unwrap())
"test-option": test_option,
"opt-option" : test_option_no_default
}))
}

Expand Down
26 changes: 12 additions & 14 deletions plugins/grpc-plugin/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use anyhow::{anyhow, Context, Result};
use anyhow::{Context, Result};
use cln_grpc::pb::node_server::NodeServer;
use cln_plugin::{options, Builder};
use log::{debug, warn};
Expand All @@ -14,6 +14,10 @@ struct PluginState {
ca_cert: Vec<u8>,
}

const OPTION_GRPC_PORT : options::IntegerConfigOption = options::ConfigOption::new_i64_no_default(
"grpc-port",
"Which port should the grpc plugin listen for incoming connections?");

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
debug!("Starting grpc plugin");
Expand All @@ -22,29 +26,23 @@ async fn main() -> Result<()> {
let directory = std::env::current_dir()?;

let plugin = match Builder::new(tokio::io::stdin(), tokio::io::stdout())
.option(options::ConfigOption::new(
"grpc-port",
options::Value::Integer(-1),
"Which port should the grpc plugin listen for incoming connections?",
))
.option(OPTION_GRPC_PORT)
.configure()
.await?
{
Some(p) => p,
None => return Ok(()),
};

let bind_port = match plugin.option("grpc-port") {
Some(options::Value::Integer(-1)) => {
log::info!("`grpc-port` option is not configured, exiting.");
let bind_port = match plugin.option(&OPTION_GRPC_PORT).unwrap() {
Some(port) => port,
None => {
log::info!("'grpc-port' options i not configured. exiting.");
plugin
.disable("`grpc-port` option is not configured.")
.disable("Missing 'grpc-port' option")
.await?;
return Ok(());
return Ok(())
}
Some(options::Value::Integer(i)) => i,
None => return Err(anyhow!("Missing 'grpc-port' option")),
Some(o) => return Err(anyhow!("grpc-port is not a valid integer: {:?}", o)),
};

let (identity, ca_cert) = tls::init(&directory)?;
Expand Down
117 changes: 67 additions & 50 deletions plugins/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use crate::codec::{JsonCodec, JsonRpcCodec};
pub use anyhow::anyhow;
use anyhow::Context;
use anyhow::{Context, Result};
use futures::sink::SinkExt;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
extern crate log;
use log::trace;
use messages::{Configuration, NotificationTopic, FeatureBits};
use options::ConfigOption;
use messages::{Configuration, FeatureBits, NotificationTopic};
use options::{OptionType, UntypedConfigOption};
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
Expand Down Expand Up @@ -43,11 +43,12 @@ where
output: Option<O>,

hooks: HashMap<String, Hook<S>>,
options: Vec<ConfigOption>,
options: HashMap<String, UntypedConfigOption>,
option_values: HashMap<String, Option<options::Value>>,
rpcmethods: HashMap<String, RpcMethod<S>>,
subscriptions: HashMap<String, Subscription<S>>,
notifications: Vec<NotificationTopic>,
custommessages : Vec<u16>,
custommessages: Vec<u16>,
featurebits: FeatureBits,
dynamic: bool,
// Do we want the plugin framework to automatically register a logging handler?
Expand All @@ -65,7 +66,8 @@ where
init_id: serde_json::Value,
input: FramedRead<I, JsonRpcCodec>,
output: Arc<Mutex<FramedWrite<O, JsonCodec>>>,
options: Vec<ConfigOption>,
options: HashMap<String, UntypedConfigOption>,
option_values: HashMap<String, Option<options::Value>>,
configuration: Configuration,
rpcmethods: HashMap<String, AsyncCallback<S>>,
hooks: HashMap<String, AsyncCallback<S>>,
Expand Down Expand Up @@ -99,7 +101,8 @@ where
/// The state gets cloned for each request
state: S,
/// "options" field of "init" message sent by cln
options: Vec<ConfigOption>,
options: HashMap<String, UntypedConfigOption>,
option_values: HashMap<String, Option<options::Value>>,
/// "configuration" field of "init" message sent by cln
configuration: Configuration,
/// A signal that allows us to wait on the plugin's shutdown.
Expand All @@ -120,18 +123,24 @@ where
output: Some(output),
hooks: HashMap::new(),
subscriptions: HashMap::new(),
options: vec![],
options: HashMap::new(),
// Should not be configured by user.
// This values are set when parsing the init-call
option_values: HashMap::new(),
rpcmethods: HashMap::new(),
notifications: vec![],
featurebits: FeatureBits::default(),
dynamic: false,
custommessages : vec![],
custommessages: vec![],
logging: true,
}
}

pub fn option(mut self, opt: options::ConfigOption) -> Builder<S, I, O> {
self.options.push(opt);
pub fn option<V: options::OptionType>(
mut self,
opt: options::ConfigOption<V>,
) -> Builder<S, I, O> {
self.options.insert(opt.name().to_string(), opt.build());
self
}

Expand Down Expand Up @@ -245,7 +254,7 @@ where

/// Tells lightningd explicitly to allow custommmessages of the provided
/// type
pub fn custommessages(mut self, custommessages : Vec<u16>) -> Self {
pub fn custommessages(mut self, custommessages: Vec<u16>) -> Self {
self.custommessages = custommessages;
self
}
Expand Down Expand Up @@ -331,6 +340,7 @@ where
notifications: self.notifications,
subscriptions,
options: self.options,
option_values: self.option_values,
configuration,
hooks: HashMap::new(),
}))
Expand Down Expand Up @@ -369,15 +379,15 @@ where
.collect();

messages::GetManifestResponse {
options: self.options.clone(),
options: self.options.values().cloned().collect(),
subscriptions: self.subscriptions.keys().map(|s| s.clone()).collect(),
hooks: self.hooks.keys().map(|s| s.clone()).collect(),
rpcmethods,
notifications: self.notifications.clone(),
featurebits: self.featurebits.clone(),
dynamic: self.dynamic,
nonnumericids: true,
custommessages : self.custommessages.clone()
custommessages: self.custommessages.clone(),
}
}

Expand All @@ -387,29 +397,21 @@ where

// Match up the ConfigOptions and fill in their values if we
// have a matching entry.
for opt in self.options.iter_mut() {
let val = call.options.get(opt.name());
opt.value = match (&opt, &opt.default(), &val) {
(_, OValue::String(_), Some(JValue::String(s))) => Some(OValue::String(s.clone())),
(_, OValue::OptString, Some(JValue::String(s))) => Some(OValue::String(s.clone())),
(_, OValue::OptString, None) => None,

(_, OValue::Integer(_), Some(JValue::Number(s))) => {
Some(OValue::Integer(s.as_i64().unwrap()))
}
(_, OValue::OptInteger, Some(JValue::Number(s))) => {
Some(OValue::Integer(s.as_i64().unwrap()))
}
(_, OValue::OptInteger, None) => None,

(_, OValue::Boolean(_), Some(JValue::Bool(s))) => Some(OValue::Boolean(*s)),
(_, OValue::OptBoolean, Some(JValue::Bool(s))) => Some(OValue::Boolean(*s)),
(_, OValue::OptBoolean, None) => None,

(o, _, _) => panic!("Type mismatch for option {:?}", o),
}
for (name, option) in self.options.iter() {
let json_value = call.options.get(name);
let default_value = option.default();

let option_value: Option<options::Value> = match (json_value, default_value) {
(None, None) => None,
(None, Some(default)) => Some(default.clone()),
(Some(JValue::String(s)), _) => Some(OValue::String(s.to_string())),
(Some(JValue::Number(i)), _) => Some(OValue::Integer(i.as_i64().unwrap())),
(Some(JValue::Bool(b)), _) => Some(OValue::Boolean(*b)),
_ => panic!("Type mismatch for option {}", name),
};

self.option_values.insert(name.to_string(), option_value);
}

Ok(call.configuration)
}
}
Expand Down Expand Up @@ -505,12 +507,19 @@ impl<S> Plugin<S>
where
S: Clone + Send,
{
pub fn option(&self, name: &str) -> Option<options::Value> {
self.options
.iter()
.filter(|o| o.name() == name)
.next()
.map(|co| co.value.clone().unwrap_or(co.default().clone()))
pub fn option_str(&self, name: &str) -> Result<Option<options::Value>> {
self.option_values
.get(name)
.ok_or(anyhow!("No option named {}", name))
.map(|c| c.clone())
}

pub fn option<OV: OptionType>(
&self,
config_option: &options::ConfigOption<OV>,
) -> Result<OV::OutputValue> {
let value = self.option_str(config_option.name())?;
Ok(OV::from_value(&value))
}
}

Expand All @@ -533,6 +542,7 @@ where
let plugin = Plugin {
state,
options: self.options,
option_values: self.option_values,
configuration: self.configuration,
wait_handle,
sender,
Expand Down Expand Up @@ -594,12 +604,19 @@ where
Ok(())
}

pub fn option(&self, name: &str) -> Option<options::Value> {
self.options
.iter()
.filter(|o| o.name() == name)
.next()
.map(|co| co.value.clone().unwrap_or(co.default().clone()))
pub fn option_str(&self, name: &str) -> Result<Option<options::Value>> {
self.option_values
.get(name)
.ok_or(anyhow!("No option named '{}'", name))
.map(|c| c.clone())
}

pub fn option<OV: OptionType>(
&self,
config_option: &options::ConfigOption<OV>,
) -> Result<OV::OutputValue> {
let value = self.option_str(config_option.name())?;
Ok(OV::from_value(&value))
}

/// return the cln configuration send to the
Expand Down Expand Up @@ -739,8 +756,8 @@ impl<S> Plugin<S>
where
S: Clone + Send,
{
pub fn options(&self) -> Vec<ConfigOption> {
self.options.clone()
pub fn options(&self) -> Vec<UntypedConfigOption> {
self.options.values().cloned().collect()
}
pub fn configuration(&self) -> Configuration {
self.configuration.clone()
Expand Down
6 changes: 3 additions & 3 deletions plugins/src/messages.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::options::ConfigOption;
use crate::options::UntypedConfigOption;
use serde::de::{self, Deserializer};
use serde::{Deserialize, Serialize};
use serde_json::Value;
Expand Down Expand Up @@ -171,7 +171,7 @@ impl NotificationTopic {

#[derive(Serialize, Default, Debug)]
pub(crate) struct GetManifestResponse {
pub(crate) options: Vec<ConfigOption>,
pub(crate) options: Vec<UntypedConfigOption>,
pub(crate) rpcmethods: Vec<RpcMethod>,
pub(crate) subscriptions: Vec<String>,
pub(crate) notifications: Vec<NotificationTopic>,
Expand All @@ -180,7 +180,7 @@ pub(crate) struct GetManifestResponse {
pub(crate) featurebits: FeatureBits,
pub(crate) nonnumericids: bool,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub(crate) custommessages : Vec<u16>
pub(crate) custommessages: Vec<u16>,
}

#[derive(Serialize, Default, Debug, Clone)]
Expand Down
Loading
Loading