spring_stream/
lib.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
//! [![spring-rs](https://img.shields.io/github/stars/spring-rs/spring-rs)](https://spring-rs.github.io/docs/plugins/spring-stream)

pub mod config;
pub mod consumer;
pub mod extractor;
pub mod handler;

pub use consumer::{ConsumerOpts, Consumers};
#[cfg(feature = "file")]
pub use sea_streamer::file;
#[cfg(feature = "kafka")]
pub use sea_streamer::kafka;
#[cfg(feature = "redis")]
pub use sea_streamer::redis;
#[cfg(feature = "stdio")]
pub use sea_streamer::stdio;
pub use sea_streamer::ConsumerMode;
use spring::plugin::component::ComponentRef;
/////////////////stream-macros/////////////////////
pub use spring_macros::stream_listener;

use anyhow::Context;
use config::StreamConfig;
use sea_streamer::{
    Buffer, MessageHeader, Producer as _, SeaConsumer, SeaProducer, SeaStreamer, StreamKey,
    Streamer as _, StreamerUri,
};
#[cfg(feature = "json")]
use serde::Serialize;
use spring::async_trait;
use spring::config::ConfigRegistry;
use spring::error::Result;
use spring::{
    app::{App, AppBuilder},
    plugin::Plugin,
};
use std::ops::Deref;
use std::{str::FromStr, sync::Arc};

pub trait StreamConfigurator {
    fn add_consumer(&mut self, consumers: Consumers) -> &mut Self;
}

impl StreamConfigurator for AppBuilder {
    fn add_consumer(&mut self, new_consumers: Consumers) -> &mut Self {
        if let Some(consumers) = self.get_component_ref::<Consumers>() {
            unsafe {
                let raw_ptr = ComponentRef::into_raw(consumers);
                let consumers = &mut *(raw_ptr as *mut Consumers);
                consumers.merge(new_consumers);
            }
            self
        } else {
            self.add_component(new_consumers)
        }
    }
}

pub struct StreamPlugin;

#[async_trait]
impl Plugin for StreamPlugin {
    async fn build(&self, app: &mut AppBuilder) {
        let config = app
            .get_config::<StreamConfig>()
            .expect("sea-streamer plugin config load failed");

        let streamer = Streamer::new(config).await.expect("create streamer failed");

        if let Some(consumers) = app.get_component_ref::<Consumers>() {
            for consumer in consumers.deref().iter() {
                let consumer_instance = consumer
                    .new_instance(&streamer)
                    .await
                    .expect("create customer instance failed");
                app.add_scheduler(|app: Arc<App>| Box::new(consumer_instance.schedule(app)));
                tracing::info!(
                    "register scheduler for \"{:?}\" stream consumer",
                    consumer.stream_keys
                );
            }
        } else {
            tracing::info!("not consumer be registry");
        }
        let producer = streamer
            .create_generic_producer()
            .await
            .expect("create producer failed");

        app.add_component(producer);
    }
}

pub struct Streamer {
    streamer: SeaStreamer,
    config: StreamConfig,
}

impl Streamer {
    async fn new(config: StreamConfig) -> Result<Self> {
        let uri = StreamerUri::from_str(config.uri.as_str())
            .with_context(|| format!("parse stream server \"{}\" failed", config.uri))?;

        let streamer = SeaStreamer::connect(uri, config.connect_options())
            .await
            .with_context(|| format!("connect stream server \"{}\" failed", config.uri))?;

        Ok(Self { streamer, config })
    }

    async fn create_consumer(
        &self,
        stream_keys: &'static [&'static str],
        opts: ConsumerOpts,
    ) -> Result<SeaConsumer> {
        let consumer_options = self.config.new_consumer_options(opts);
        let mut consumer_stream_keys = Vec::with_capacity(stream_keys.len());
        for key in stream_keys {
            consumer_stream_keys.push(
                StreamKey::new(*key)
                    .with_context(|| format!("consumer stream key \"{}\" is valid", key))?,
            );
        }
        Ok(self
            .streamer
            .create_consumer(&consumer_stream_keys, consumer_options)
            .await
            .with_context(|| format!("create stream consumer failed: {:?}", stream_keys))?)
    }

    async fn create_generic_producer(&self) -> Result<Producer> {
        let producer_options = self.config.new_producer_options();
        let producer = self
            .streamer
            .create_generic_producer(producer_options)
            .await
            .context("create stream generic producer failed")?;
        Ok(Producer::new(producer))
    }
}

#[derive(Clone)]
pub struct Producer(Arc<SeaProducer>);

impl Producer {
    fn new(producer: SeaProducer) -> Self {
        Self(Arc::new(producer))
    }

    #[cfg(feature = "json")]
    pub async fn send_json<T: Serialize>(
        &self,
        stream_key: &str,
        payload: T,
    ) -> Result<MessageHeader> {
        let json = serde_json::to_string(&payload).context("json serialize failed")?;
        self.send_to(stream_key, json.as_str()).await
    }

    pub async fn send_to<S: Buffer>(&self, stream_key: &str, payload: S) -> Result<MessageHeader> {
        let producer_stream_key = StreamKey::new(stream_key)
            .with_context(|| format!("producer stream key \"{}\" is valid", stream_key))?;

        let header = self
            .0
            .send_to(&producer_stream_key, payload)
            .with_context(|| format!("send to stream key failed:{stream_key}"))?
            .await
            .with_context(|| {
                format!("await response for sending stream key failed:{stream_key}")
            })?;

        Ok(header)
    }
}