forked from LNP-WG/lnp-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.rs
257 lines (227 loc) · 7.69 KB
/
service.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
// LNP Node: node running lightning network protocol and generalized lightning
// channels.
// Written in 2020-2022 by
// Dr. Maxim Orlovsky <[email protected]>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the MIT License along with this software.
// If not, see <https://opensource.org/licenses/MIT>.
use std::fmt::Debug;
use internet2::zeromq::{self, ZmqSocketType};
use lnp_rpc::RpcMsg;
use microservices::esb::{self, ClientId};
use microservices::node::TryService;
use crate::bus::{self, BusMsg, CtlMsg, Report, ServiceBus};
use crate::rpc::{Failure, ServiceId};
use crate::{Config, Error};
/// An empty handler used for bridge interfaces in watcher and peer daemons
pub struct BridgeHandler;
impl esb::Handler<ServiceBus> for BridgeHandler {
type Request = BusMsg;
type Error = Error;
fn identity(&self) -> ServiceId { ServiceId::Loopback }
fn handle(
&mut self,
_: &mut Endpoints,
_: ServiceBus,
_: ServiceId,
_: BusMsg,
) -> Result<(), Error> {
// Bridge does not receive replies for now
Ok(())
}
fn handle_err(
&mut self,
_: &mut Endpoints,
err: esb::Error<ServiceId>,
) -> Result<(), Self::Error> {
// We simply propagate the error since it's already being reported
Err(err.into())
}
}
pub struct Service<Runtime>
where
Runtime: esb::Handler<ServiceBus, Request = BusMsg>,
esb::Error<ServiceId>: From<Runtime::Error>,
{
esb: esb::Controller<ServiceBus, BusMsg, Runtime>,
broker: bool,
}
impl<Runtime> Service<Runtime>
where
Runtime: esb::Handler<ServiceBus, Request = BusMsg>,
esb::Error<ServiceId>: From<Runtime::Error>,
{
pub fn run(config: Config<()>, runtime: Runtime, broker: bool) -> Result<(), Error> {
let service = Self::with(config, runtime, broker)?;
service.run_loop()?;
unreachable!()
}
fn with<Ext>(
config: Config<Ext>,
runtime: Runtime,
broker: bool,
) -> Result<Self, esb::Error<ServiceId>>
where
Ext: Clone + Eq + Debug,
{
let router = if !broker { Some(ServiceId::router()) } else { None };
let api_type =
if broker { ZmqSocketType::RouterBind } else { ZmqSocketType::RouterConnect };
let services = map! {
ServiceBus::Msg => esb::BusConfig::with_addr(
config.msg_endpoint,
api_type,
router.clone()
),
ServiceBus::Ctl => esb::BusConfig::with_addr(
config.ctl_endpoint,
api_type,
router.clone()
),
ServiceBus::Rpc => esb::BusConfig::with_addr(config.rpc_endpoint, api_type, router)
};
let esb = esb::Controller::with(services, runtime)?;
Ok(Self { esb, broker })
}
pub fn broker(config: Config<()>, runtime: Runtime) -> Result<Self, esb::Error<ServiceId>> {
Self::with(config, runtime, true)
}
#[allow(clippy::self_named_constructors)]
pub fn service<Ext>(
config: Config<Ext>,
runtime: Runtime,
) -> Result<Self, esb::Error<ServiceId>>
where
Ext: Clone + Eq + Debug,
{
Self::with(config, runtime, false)
}
pub fn is_broker(&self) -> bool { self.broker }
pub fn add_loopback(&mut self, socket: zmq::Socket) -> Result<(), esb::Error<ServiceId>> {
self.esb.add_service_bus(ServiceBus::Bridge, esb::BusConfig {
// This type is ignored, since we in fact create ZMQ_PAIR type
api_type: ZmqSocketType::Push,
carrier: zeromq::Carrier::Socket(socket),
router: None,
queued: true,
topic: None,
})
}
pub fn run_loop(mut self) -> Result<(), Error> {
if !self.is_broker() {
std::thread::sleep(core::time::Duration::from_secs(1));
self.esb.send_to(ServiceBus::Ctl, ServiceId::LnpBroker, BusMsg::Ctl(CtlMsg::Hello))?;
// self.esb.send_to(ServiceBus::Msg, ServiceId::Lnpd, BusMsg::Ctl(CtlMsg::Hello))?;
}
let identity = self.esb.handler().identity();
info!("{} started", identity);
self.esb.run_or_panic(&identity.to_string());
unreachable!()
}
}
pub type Endpoints = esb::EndpointList<ServiceBus>;
pub trait TryToServiceId {
fn try_to_service_id(&self) -> Option<ServiceId>;
}
impl TryToServiceId for ServiceId {
fn try_to_service_id(&self) -> Option<ServiceId> { Some(self.clone()) }
}
impl TryToServiceId for &Option<ServiceId> {
fn try_to_service_id(&self) -> Option<ServiceId> { (*self).clone() }
}
impl TryToServiceId for Option<ServiceId> {
fn try_to_service_id(&self) -> Option<ServiceId> { self.clone() }
}
pub trait Responder
where
Self: esb::Handler<ServiceBus>,
esb::Error<ServiceId>: From<Self::Error>,
{
/// Returns client which should receive status update reports
#[inline]
fn enquirer(&self) -> Option<ClientId> { None }
fn report_success(
&mut self,
endpoints: &mut Endpoints,
msg: Option<impl ToString>,
) -> Result<(), Error> {
if let Some(ref message) = msg {
info!("{}", message.to_string());
}
if let Some(client) = self.enquirer() {
let status = bus::Status::Success(msg.map(|m| m.to_string()).into());
let report = CtlMsg::Report(Report { client, status });
endpoints.send_to(
ServiceBus::Ctl,
self.identity(),
ServiceId::LnpBroker,
BusMsg::Ctl(report),
)?;
}
Ok(())
}
fn report_progress(
&mut self,
endpoints: &mut Endpoints,
msg: impl ToString,
) -> Result<(), Error> {
let msg = msg.to_string();
info!("{}", msg);
if let Some(client) = self.enquirer() {
let status = bus::Status::Progress(msg);
let report = CtlMsg::Report(Report { client, status });
endpoints.send_to(
ServiceBus::Ctl,
self.identity(),
ServiceId::LnpBroker,
BusMsg::Ctl(report),
)?;
}
Ok(())
}
fn report_failure(&mut self, endpoints: &mut Endpoints, failure: impl Into<Failure>) -> Error {
let failure = failure.into();
if let Some(client) = self.enquirer() {
let status = bus::Status::Failure(failure.clone());
let report = CtlMsg::Report(Report { client, status });
// Even if we fail, we still have to terminate :)
let _ = endpoints.send_to(
ServiceBus::Ctl,
self.identity(),
ServiceId::LnpBroker,
BusMsg::Ctl(report),
);
}
Error::Terminate(failure.to_string())
}
fn send_ctl(
&mut self,
endpoints: &mut Endpoints,
dest: impl TryToServiceId,
request: CtlMsg,
) -> Result<(), esb::Error<ServiceId>> {
if let Some(dest) = dest.try_to_service_id() {
endpoints.send_to(ServiceBus::Ctl, self.identity(), dest, BusMsg::Ctl(request))?;
}
Ok(())
}
#[inline]
fn send_rpc(
&self,
endpoints: &mut Endpoints,
client_id: ClientId,
message: impl Into<RpcMsg>,
) -> Result<(), esb::Error<ServiceId>> {
endpoints.send_to(
ServiceBus::Rpc,
self.identity(),
ServiceId::Client(client_id),
BusMsg::Rpc(message.into()),
)
}
}