blob: 4f41f244784b658b8a0ace41e496d82439097bb3 [file] [log] [blame]
Allen George8b96bfb2016-11-02 08:01:08 -04001// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
Allen George7ddbcc02020-11-08 09:51:19 -050018use log::debug;
19
Allen George8b96bfb2016-11-02 08:01:08 -040020use std::collections::HashMap;
Allen Georgeef7a1892018-12-16 18:01:37 -050021use std::convert::Into;
Allen Georgebc1344d2017-04-28 10:22:03 -040022use std::fmt;
23use std::fmt::{Debug, Formatter};
Allen George0e22c362017-01-30 07:15:00 -050024use std::sync::{Arc, Mutex};
Allen George8b96bfb2016-11-02 08:01:08 -040025
Allen Georgeb0d14132020-03-29 11:48:55 -040026use crate::protocol::{TInputProtocol, TMessageIdentifier, TOutputProtocol, TStoredInputProtocol};
Allen George8b96bfb2016-11-02 08:01:08 -040027
Allen Georgeef7a1892018-12-16 18:01:37 -050028use super::{handle_process_result, TProcessor};
Allen Georgebc1344d2017-04-28 10:22:03 -040029
Allen George7ddbcc02020-11-08 09:51:19 -050030const MISSING_SEPARATOR_AND_NO_DEFAULT: &str =
Allen Georgeef7a1892018-12-16 18:01:37 -050031 "missing service separator and no default processor set";
Danny Browning77d96c12019-08-21 13:41:07 -060032type ThreadSafeProcessor = Box<dyn TProcessor + Send + Sync>;
Allen George8b96bfb2016-11-02 08:01:08 -040033
34/// A `TProcessor` that can demux service calls to multiple underlying
35/// Thrift services.
36///
37/// Users register service-specific `TProcessor` instances with a
38/// `TMultiplexedProcessor`, and then register that processor with a server
39/// implementation. Following that, all incoming service calls are automatically
40/// routed to the service-specific `TProcessor`.
41///
42/// A `TMultiplexedProcessor` can only handle messages sent by a
43/// `TMultiplexedOutputProtocol`.
Allen Georgebc1344d2017-04-28 10:22:03 -040044#[derive(Default)]
Allen George8b96bfb2016-11-02 08:01:08 -040045pub struct TMultiplexedProcessor {
Allen Georgebc1344d2017-04-28 10:22:03 -040046 stored: Mutex<StoredProcessors>,
47}
48
49#[derive(Default)]
50struct StoredProcessors {
51 processors: HashMap<String, Arc<ThreadSafeProcessor>>,
52 default_processor: Option<Arc<ThreadSafeProcessor>>,
Allen George8b96bfb2016-11-02 08:01:08 -040053}
54
55impl TMultiplexedProcessor {
Allen Georgebc1344d2017-04-28 10:22:03 -040056 /// Create a new `TMultiplexedProcessor` with no registered service-specific
57 /// processors.
58 pub fn new() -> TMultiplexedProcessor {
59 TMultiplexedProcessor {
Allen Georgeef7a1892018-12-16 18:01:37 -050060 stored: Mutex::new(StoredProcessors {
61 processors: HashMap::new(),
62 default_processor: None,
63 }),
Allen George8b96bfb2016-11-02 08:01:08 -040064 }
65 }
Allen George8b96bfb2016-11-02 08:01:08 -040066
Allen Georgebc1344d2017-04-28 10:22:03 -040067 /// Register a service-specific `processor` for the service named
68 /// `service_name`. This implementation is also backwards-compatible with
69 /// non-multiplexed clients. Set `as_default` to `true` to allow
70 /// non-namespaced requests to be dispatched to a default processor.
71 ///
72 /// Returns success if a new entry was inserted. Returns an error if:
73 /// * A processor exists for `service_name`
74 /// * You attempt to register a processor as default, and an existing default exists
Allen George7ddbcc02020-11-08 09:51:19 -050075 #[allow(clippy::map_entry)]
Allen Georgebc1344d2017-04-28 10:22:03 -040076 pub fn register<S: Into<String>>(
77 &mut self,
78 service_name: S,
Danny Browning77d96c12019-08-21 13:41:07 -060079 processor: Box<dyn TProcessor + Send + Sync>,
Allen Georgebc1344d2017-04-28 10:22:03 -040080 as_default: bool,
Allen Georgeb0d14132020-03-29 11:48:55 -040081 ) -> crate::Result<()> {
Allen Georgebc1344d2017-04-28 10:22:03 -040082 let mut stored = self.stored.lock().unwrap();
Allen George8b96bfb2016-11-02 08:01:08 -040083
Allen Georgebc1344d2017-04-28 10:22:03 -040084 let name = service_name.into();
85 if !stored.processors.contains_key(&name) {
86 let processor = Arc::new(processor);
Allen George8b96bfb2016-11-02 08:01:08 -040087
Allen Georgebc1344d2017-04-28 10:22:03 -040088 if as_default {
89 if stored.default_processor.is_none() {
90 stored.processors.insert(name, processor.clone());
91 stored.default_processor = Some(processor.clone());
92 Ok(())
93 } else {
94 Err("cannot reset default processor".into())
95 }
96 } else {
97 stored.processors.insert(name, processor);
98 Ok(())
99 }
100 } else {
Allen Georgeef7a1892018-12-16 18:01:37 -0500101 Err(format!("cannot overwrite existing processor for service {}", name).into())
Allen Georgebc1344d2017-04-28 10:22:03 -0400102 }
103 }
104
105 fn process_message(
106 &self,
107 msg_ident: &TMessageIdentifier,
Danny Browning77d96c12019-08-21 13:41:07 -0600108 i_prot: &mut dyn TInputProtocol,
109 o_prot: &mut dyn TOutputProtocol,
Allen Georgeb0d14132020-03-29 11:48:55 -0400110 ) -> crate::Result<()> {
Allen Georgebc1344d2017-04-28 10:22:03 -0400111 let (svc_name, svc_call) = split_ident_name(&msg_ident.name);
112 debug!("routing svc_name {:?} svc_call {}", &svc_name, &svc_call);
113
114 let processor: Option<Arc<ThreadSafeProcessor>> = {
115 let stored = self.stored.lock().unwrap();
116 if let Some(name) = svc_name {
117 stored.processors.get(name).cloned()
118 } else {
119 stored.default_processor.clone()
120 }
Allen George0e22c362017-01-30 07:15:00 -0500121 };
122
123 match processor {
124 Some(arc) => {
125 let new_msg_ident = TMessageIdentifier::new(
126 svc_call,
127 msg_ident.message_type,
128 msg_ident.sequence_number,
129 );
Allen George8b96bfb2016-11-02 08:01:08 -0400130 let mut proxy_i_prot = TStoredInputProtocol::new(i_prot, new_msg_ident);
Allen George0e22c362017-01-30 07:15:00 -0500131 (*arc).process(&mut proxy_i_prot, o_prot)
Allen George8b96bfb2016-11-02 08:01:08 -0400132 }
Allen Georgebc1344d2017-04-28 10:22:03 -0400133 None => Err(missing_processor_message(svc_name).into()),
134 }
135 }
136}
137
138impl TProcessor for TMultiplexedProcessor {
Allen Georgeb0d14132020-03-29 11:48:55 -0400139 fn process(&self, i_prot: &mut dyn TInputProtocol, o_prot: &mut dyn TOutputProtocol) -> crate::Result<()> {
Allen Georgebc1344d2017-04-28 10:22:03 -0400140 let msg_ident = i_prot.read_message_begin()?;
141
142 debug!("process incoming msg id:{:?}", &msg_ident);
143 let res = self.process_message(&msg_ident, i_prot, o_prot);
144
145 handle_process_result(&msg_ident, res, o_prot)
146 }
147}
148
149impl Debug for TMultiplexedProcessor {
Allen George7ddbcc02020-11-08 09:51:19 -0500150 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
Allen Georgebc1344d2017-04-28 10:22:03 -0400151 let stored = self.stored.lock().unwrap();
152 write!(
153 f,
154 "TMultiplexedProcess {{ registered_count: {:?} default: {:?} }}",
155 stored.processors.keys().len(),
156 stored.default_processor.is_some()
157 )
158 }
159}
160
161fn split_ident_name(ident_name: &str) -> (Option<&str>, &str) {
162 ident_name
163 .find(':')
Allen Georgeef7a1892018-12-16 18:01:37 -0500164 .map(|pos| {
165 let (svc_name, svc_call) = ident_name.split_at(pos);
166 let (_, svc_call) = svc_call.split_at(1); // remove colon from service call name
167 (Some(svc_name), svc_call)
168 })
Allen Georgebc1344d2017-04-28 10:22:03 -0400169 .or_else(|| Some((None, ident_name)))
170 .unwrap()
171}
172
173fn missing_processor_message(svc_name: Option<&str>) -> String {
174 match svc_name {
175 Some(name) => format!("no processor found for service {}", name),
176 None => MISSING_SEPARATOR_AND_NO_DEFAULT.to_owned(),
177 }
178}
179
180#[cfg(test)]
181mod tests {
182 use std::convert::Into;
Allen Georgebc1344d2017-04-28 10:22:03 -0400183 use std::sync::atomic::{AtomicBool, Ordering};
Allen Georgeef7a1892018-12-16 18:01:37 -0500184 use std::sync::Arc;
Allen Georgebc1344d2017-04-28 10:22:03 -0400185
Allen Georgeb0d14132020-03-29 11:48:55 -0400186 use crate::protocol::{TBinaryInputProtocol, TBinaryOutputProtocol, TMessageIdentifier, TMessageType};
187 use crate::transport::{ReadHalf, TBufferChannel, TIoChannel, WriteHalf};
188 use crate::{ApplicationError, ApplicationErrorKind};
Allen Georgebc1344d2017-04-28 10:22:03 -0400189
190 use super::*;
191
192 #[test]
193 fn should_split_name_into_proper_separator_and_service_call() {
194 let ident_name = "foo:bar_call";
195 let (serv, call) = split_ident_name(&ident_name);
196 assert_eq!(serv, Some("foo"));
197 assert_eq!(call, "bar_call");
198 }
199
200 #[test]
201 fn should_return_full_ident_if_no_separator_exists() {
202 let ident_name = "bar_call";
203 let (serv, call) = split_ident_name(&ident_name);
204 assert_eq!(serv, None);
205 assert_eq!(call, "bar_call");
206 }
207
208 #[test]
209 fn should_write_error_if_no_separator_found_and_no_default_processor_exists() {
210 let (mut i, mut o) = build_objects();
211
212 let sent_ident = TMessageIdentifier::new("foo", TMessageType::Call, 10);
213 o.write_message_begin(&sent_ident).unwrap();
214 o.flush().unwrap();
215 o.transport.copy_write_buffer_to_read_buffer();
216 o.transport.empty_write_buffer();
217
218 let p = TMultiplexedProcessor::new();
219 p.process(&mut i, &mut o).unwrap(); // at this point an error should be written out
220
Allen Georgeef7a1892018-12-16 18:01:37 -0500221 i.transport.set_readable_bytes(&o.transport.write_bytes());
Allen Georgebc1344d2017-04-28 10:22:03 -0400222 let rcvd_ident = i.read_message_begin().unwrap();
223 let expected_ident = TMessageIdentifier::new("foo", TMessageType::Exception, 10);
224 assert_eq!(rcvd_ident, expected_ident);
Allen Georgeb0d14132020-03-29 11:48:55 -0400225 let rcvd_err = crate::Error::read_application_error_from_in_protocol(&mut i).unwrap();
Allen Georgebc1344d2017-04-28 10:22:03 -0400226 let expected_err = ApplicationError::new(
227 ApplicationErrorKind::Unknown,
228 MISSING_SEPARATOR_AND_NO_DEFAULT,
229 );
230 assert_eq!(rcvd_err, expected_err);
231 }
232
233 #[test]
234 fn should_write_error_if_separator_exists_and_no_processor_found() {
235 let (mut i, mut o) = build_objects();
236
237 let sent_ident = TMessageIdentifier::new("missing:call", TMessageType::Call, 10);
238 o.write_message_begin(&sent_ident).unwrap();
239 o.flush().unwrap();
240 o.transport.copy_write_buffer_to_read_buffer();
241 o.transport.empty_write_buffer();
242
243 let p = TMultiplexedProcessor::new();
244 p.process(&mut i, &mut o).unwrap(); // at this point an error should be written out
245
Allen Georgeef7a1892018-12-16 18:01:37 -0500246 i.transport.set_readable_bytes(&o.transport.write_bytes());
Allen Georgebc1344d2017-04-28 10:22:03 -0400247 let rcvd_ident = i.read_message_begin().unwrap();
248 let expected_ident = TMessageIdentifier::new("missing:call", TMessageType::Exception, 10);
249 assert_eq!(rcvd_ident, expected_ident);
Allen Georgeb0d14132020-03-29 11:48:55 -0400250 let rcvd_err = crate::Error::read_application_error_from_in_protocol(&mut i).unwrap();
Allen Georgebc1344d2017-04-28 10:22:03 -0400251 let expected_err = ApplicationError::new(
252 ApplicationErrorKind::Unknown,
253 missing_processor_message(Some("missing")),
254 );
255 assert_eq!(rcvd_err, expected_err);
256 }
257
258 #[derive(Default)]
259 struct Service {
260 pub invoked: Arc<AtomicBool>,
261 }
262
263 impl TProcessor for Service {
Allen Georgeb0d14132020-03-29 11:48:55 -0400264 fn process(&self, _: &mut dyn TInputProtocol, _: &mut dyn TOutputProtocol) -> crate::Result<()> {
Allen Georgeef7a1892018-12-16 18:01:37 -0500265 let res = self
266 .invoked
Allen Georgebc1344d2017-04-28 10:22:03 -0400267 .compare_and_swap(false, true, Ordering::Relaxed);
268 if res {
269 Ok(())
270 } else {
271 Err("failed swap".into())
Allen George8b96bfb2016-11-02 08:01:08 -0400272 }
273 }
274 }
Allen Georgebc1344d2017-04-28 10:22:03 -0400275
276 #[test]
277 fn should_route_call_to_correct_processor() {
278 let (mut i, mut o) = build_objects();
279
280 // build the services
Allen Georgeef7a1892018-12-16 18:01:37 -0500281 let svc_1 = Service {
282 invoked: Arc::new(AtomicBool::new(false)),
283 };
Allen Georgebc1344d2017-04-28 10:22:03 -0400284 let atm_1 = svc_1.invoked.clone();
Allen Georgeef7a1892018-12-16 18:01:37 -0500285 let svc_2 = Service {
286 invoked: Arc::new(AtomicBool::new(false)),
287 };
Allen Georgebc1344d2017-04-28 10:22:03 -0400288 let atm_2 = svc_2.invoked.clone();
289
290 // register them
291 let mut p = TMultiplexedProcessor::new();
292 p.register("service_1", Box::new(svc_1), false).unwrap();
293 p.register("service_2", Box::new(svc_2), false).unwrap();
294
295 // make the service call
296 let sent_ident = TMessageIdentifier::new("service_1:call", TMessageType::Call, 10);
297 o.write_message_begin(&sent_ident).unwrap();
298 o.flush().unwrap();
299 o.transport.copy_write_buffer_to_read_buffer();
300 o.transport.empty_write_buffer();
301
302 p.process(&mut i, &mut o).unwrap();
303
304 // service 1 should have been invoked, not service 2
305 assert_eq!(atm_1.load(Ordering::Relaxed), true);
306 assert_eq!(atm_2.load(Ordering::Relaxed), false);
307 }
308
309 #[test]
310 fn should_route_call_to_correct_processor_if_no_separator_exists_and_default_processor_set() {
311 let (mut i, mut o) = build_objects();
312
313 // build the services
Allen Georgeef7a1892018-12-16 18:01:37 -0500314 let svc_1 = Service {
315 invoked: Arc::new(AtomicBool::new(false)),
316 };
Allen Georgebc1344d2017-04-28 10:22:03 -0400317 let atm_1 = svc_1.invoked.clone();
Allen Georgeef7a1892018-12-16 18:01:37 -0500318 let svc_2 = Service {
319 invoked: Arc::new(AtomicBool::new(false)),
320 };
Allen Georgebc1344d2017-04-28 10:22:03 -0400321 let atm_2 = svc_2.invoked.clone();
322
323 // register them
324 let mut p = TMultiplexedProcessor::new();
325 p.register("service_1", Box::new(svc_1), false).unwrap();
326 p.register("service_2", Box::new(svc_2), true).unwrap(); // second processor is default
327
328 // make the service call (it's an old client, so we have to be backwards compatible)
329 let sent_ident = TMessageIdentifier::new("old_call", TMessageType::Call, 10);
330 o.write_message_begin(&sent_ident).unwrap();
331 o.flush().unwrap();
332 o.transport.copy_write_buffer_to_read_buffer();
333 o.transport.empty_write_buffer();
334
335 p.process(&mut i, &mut o).unwrap();
336
337 // service 2 should have been invoked, not service 1
338 assert_eq!(atm_1.load(Ordering::Relaxed), false);
339 assert_eq!(atm_2.load(Ordering::Relaxed), true);
340 }
341
Allen Georgeef7a1892018-12-16 18:01:37 -0500342 fn build_objects() -> (
343 TBinaryInputProtocol<ReadHalf<TBufferChannel>>,
344 TBinaryOutputProtocol<WriteHalf<TBufferChannel>>,
345 ) {
Allen Georgebc1344d2017-04-28 10:22:03 -0400346 let c = TBufferChannel::with_capacity(128, 128);
347 let (r_c, w_c) = c.split().unwrap();
Allen Georgeef7a1892018-12-16 18:01:37 -0500348 (
349 TBinaryInputProtocol::new(r_c, true),
350 TBinaryOutputProtocol::new(w_c, true),
351 )
Allen Georgebc1344d2017-04-28 10:22:03 -0400352 }
Allen George8b96bfb2016-11-02 08:01:08 -0400353}