core-lightning/plugins/examples/cln-plugin-reentrant.rs
Christian Decker db3707f957 pytest: Highlight the re-entrancy issue for cln-plugin events
This was pointed out by Daywalker [1]: we are synchronously processing
events from `lightningd` which means that if processing one of the
hooks or requests was slow or delayed, we would not get notifications,
hooks, or RPC requests, massively impacting the flexbility.

This highlights the issue with a failing test (it times out), and in
the next commit we will isolate event processing into their own task,
so to free the event loop from having to wait for an eventual
response.

[1] https://community.corelightning.org/c/developers/hold-invoice-plugin#comment_wrapper_16754493
2023-04-13 18:13:28 -07:00

45 lines
1.1 KiB
Rust

use anyhow::Error;
use cln_plugin::{Builder, Plugin};
use serde_json::json;
use tokio::sync::broadcast;
#[derive(Clone)]
struct State {
tx: broadcast::Sender<()>,
}
#[tokio::main]
async fn main() -> Result<(), Error> {
let (tx, _) = broadcast::channel(4);
let state = State { tx };
if let Some(plugin) = Builder::new(tokio::io::stdin(), tokio::io::stdout())
.hook("htlc_accepted", htlc_accepted_handler)
.rpcmethod("release", "Release all HTLCs we currently hold", release)
.start(state)
.await?
{
plugin.join().await?;
Ok(())
} else {
Ok(())
}
}
/// Release all waiting HTLCs
async fn release(p: Plugin<State>, _v: serde_json::Value) -> Result<serde_json::Value, Error> {
p.state().tx.send(()).unwrap();
Ok(json!("Released!"))
}
async fn htlc_accepted_handler(
p: Plugin<State>,
v: serde_json::Value,
) -> Result<serde_json::Value, Error> {
log::info!("Holding on to incoming HTLC {:?}", v);
// Wait for `release` to be called.
p.state().tx.subscribe().recv().await.unwrap();
Ok(json!({"result": "continue"}))
}