|
| 1 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 2 | +// you may not use this file except in compliance with the License. |
| 3 | +// You may obtain a copy of the License at |
| 4 | +// |
| 5 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +// |
| 7 | +// Unless required by applicable law or agreed to in writing, software |
| 8 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 9 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 10 | +// See the License for the specific language governing permissions and |
| 11 | +// limitations under the License. |
| 12 | + |
| 13 | +use super::config::PulsarConfig; |
| 14 | +use crate::runtime::buffer_and_event::BufferOrEvent; |
| 15 | +use crate::runtime::input::input_protocol::InputProtocol; |
| 16 | +use futures::StreamExt; |
| 17 | +use pulsar::consumer::SubType; |
| 18 | +use pulsar::{Consumer, Pulsar, TokioExecutor}; |
| 19 | +use std::cell::RefCell; |
| 20 | +use std::time::Duration; |
| 21 | + |
| 22 | +thread_local! { |
| 23 | + static PULSAR_RT: RefCell<Option<tokio::runtime::Runtime>> = RefCell::new(None); |
| 24 | + static PULSAR_CONSUMER: RefCell<Option<Consumer<Vec<u8>, TokioExecutor>>> = RefCell::new(None); |
| 25 | +} |
| 26 | + |
| 27 | +pub struct PulsarProtocol { |
| 28 | + config: PulsarConfig, |
| 29 | +} |
| 30 | + |
| 31 | +impl PulsarProtocol { |
| 32 | + pub fn new(config: PulsarConfig) -> Self { |
| 33 | + Self { config } |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +impl InputProtocol for PulsarProtocol { |
| 38 | + fn name(&self) -> String { |
| 39 | + format!("pulsar-{}", self.config.topic) |
| 40 | + } |
| 41 | + |
| 42 | + fn init(&self) -> Result<(), Box<dyn std::error::Error + Send>> { |
| 43 | + // Lazy init is done in poll() on the worker thread which owns the runtime/consumer. |
| 44 | + Ok(()) |
| 45 | + } |
| 46 | + |
| 47 | + fn poll( |
| 48 | + &self, |
| 49 | + timeout: Duration, |
| 50 | + ) -> Result<Option<BufferOrEvent>, Box<dyn std::error::Error + Send>> { |
| 51 | + PULSAR_RT.with(|rt_cell| { |
| 52 | + PULSAR_CONSUMER.with(|consumer_cell| { |
| 53 | + let mut rt_opt = rt_cell.borrow_mut(); |
| 54 | + let mut consumer_opt = consumer_cell.borrow_mut(); |
| 55 | + |
| 56 | + if consumer_opt.is_none() { |
| 57 | + let rt = tokio::runtime::Runtime::new() |
| 58 | + .map_err(|e| Box::new(std::io::Error::other(e)) as Box<dyn std::error::Error + Send>)?; |
| 59 | + let url = self.config.url.clone(); |
| 60 | + let topic = self.config.topic.clone(); |
| 61 | + let subscription = self.config.subscription.clone(); |
| 62 | + let sub_type = self.config.subscription_type.as_deref().unwrap_or("Exclusive"); |
| 63 | + let sub_type_enum = match sub_type.to_lowercase().as_str() { |
| 64 | + "shared" => SubType::Shared, |
| 65 | + "key_shared" => SubType::KeyShared, |
| 66 | + "failover" => SubType::Failover, |
| 67 | + _ => SubType::Exclusive, |
| 68 | + }; |
| 69 | + |
| 70 | + let consumer: Consumer<Vec<u8>, _> = rt |
| 71 | + .block_on(async { |
| 72 | + let pulsar = Pulsar::builder(&url, TokioExecutor).build().await?; |
| 73 | + let mut builder = pulsar |
| 74 | + .consumer() |
| 75 | + .with_topic(&topic) |
| 76 | + .with_subscription(&subscription) |
| 77 | + .with_subscription_type(sub_type_enum); |
| 78 | + let consumer = builder.build().await?; |
| 79 | + Result::<_, pulsar::Error>::Ok(consumer) |
| 80 | + }) |
| 81 | + .map_err(|e| Box::new(std::io::Error::other(e)) as Box<dyn std::error::Error + Send>)?; |
| 82 | + |
| 83 | + *rt_opt = Some(rt); |
| 84 | + *consumer_opt = Some(consumer); |
| 85 | + } |
| 86 | + |
| 87 | + let rt = rt_opt.as_ref().unwrap(); |
| 88 | + let consumer = consumer_opt.as_mut().unwrap(); |
| 89 | + |
| 90 | + let timeout_ms = timeout.as_millis() as u64; |
| 91 | + let topic = self.config.topic.clone(); |
| 92 | + let result = rt.block_on(async { |
| 93 | + let next_fut = consumer.next(); |
| 94 | + match tokio::time::timeout(Duration::from_millis(timeout_ms), next_fut).await { |
| 95 | + Ok(Some(Ok(msg))) => { |
| 96 | + let payload = msg.deserialize().unwrap_or_else(|_| msg.payload.data.clone()); |
| 97 | + let _ = consumer.ack(&msg).await; |
| 98 | + Some(Ok(payload)) |
| 99 | + } |
| 100 | + Ok(Some(Err(e))) => Some(Err(e)), |
| 101 | + Ok(None) | Err(_) => None, |
| 102 | + } |
| 103 | + }); |
| 104 | + |
| 105 | + match result { |
| 106 | + Some(Ok(payload)) => Ok(Some(BufferOrEvent::new_buffer( |
| 107 | + payload, |
| 108 | + Some(topic), |
| 109 | + false, |
| 110 | + false, |
| 111 | + ))), |
| 112 | + Some(Err(e)) => Err(Box::new(std::io::Error::other(e)) as Box<dyn std::error::Error + Send>), |
| 113 | + None => Ok(None), |
| 114 | + } |
| 115 | + }) |
| 116 | + }) |
| 117 | + } |
| 118 | +} |
0 commit comments