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
use std::borrow::{Borrow, Cow};
use std::net::ToSocketAddrs;
use std::net;
use std::io::Write;
use record::Record;
#[cfg(not(feature = "time-as-integer"))]
use event_record::EventRecord;
use retry_conf::RetryConf;
use forwardable::forward::Forward;
use serde::ser::Serialize;
use serde_json;
use rmp_serde::encode::Serializer;
use error::FluentError;
#[derive(Debug, Clone, PartialEq)]
pub struct Fluent<'a, A>
where
A: ToSocketAddrs,
{
addr: A,
tag: Cow<'a, str>,
conf: RetryConf,
}
#[cfg(feature = "time-as-integer")]
type MsgPackSendType<T> where
T: Serialize = Record<T>;
#[cfg(not(feature = "time-as-integer"))]
type MsgPackSendType<T> where
T: Serialize = EventRecord<T>;
impl<'a, A: ToSocketAddrs> Fluent<'a, A> {
pub fn new<T>(addr: A, tag: T) -> Fluent<'a, A>
where
T: Into<Cow<'a, str>>,
{
Fluent {
addr: addr,
tag: tag.into(),
conf: RetryConf::new(),
}
}
pub fn new_with_conf<T>(addr: A, tag: T, conf: RetryConf) -> Fluent<'a, A>
where
T: Into<Cow<'a, str>>,
{
Fluent {
addr: addr,
tag: tag.into(),
conf: conf,
}
}
#[doc(hidden)]
pub fn get_addr(&self) -> &A {
self.addr.borrow()
}
#[doc(hidden)]
pub fn get_tag(&'a self) -> Cow<'a, str> {
Cow::Borrowed(&self.tag)
}
#[doc(hidden)]
pub fn get_conf(&self) -> Cow<RetryConf> {
Cow::Borrowed(&self.conf)
}
#[doc(hidden)]
pub fn closure_send_as_json<T: Serialize>(addr: &A, record: &Record<T>) -> Result<(), FluentError> {
let mut stream = net::TcpStream::connect(addr)?;
let message = serde_json::to_string(&record)?;
let result = stream.write(&message.into_bytes());
drop(stream);
match result {
Ok(_) => Ok(()),
Err(v) => Err(From::from(v)),
}
}
#[doc(hidden)]
pub fn closure_send_as_msgpack<T: Serialize>(addr: &A, record: &MsgPackSendType<T>) -> Result<(), FluentError> {
let mut stream = net::TcpStream::connect(addr)?;
let result = record.serialize(&mut Serializer::new(&mut stream));
match result {
Ok(_) => Ok(()),
Err(v) => Err(From::from(v)),
}
}
#[doc(hidden)]
pub fn closure_send_as_forward<T: Serialize>(addr: &A, forward: &Forward<T>) -> Result<(), FluentError> {
let mut stream = net::TcpStream::connect(addr)?;
let result = forward.serialize(&mut Serializer::new(&mut stream));
match result {
Ok(_) => Ok(()),
Err(v) => Err(From::from(v)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use retry_conf::RetryConf;
use std::borrow::Cow;
#[test]
fn create_fruently() {
let fruently = Fluent::new("127.0.0.1:24224", "test");
let expected = Fluent {
addr: "127.0.0.1:24224",
tag: Cow::Borrowed("test"),
conf: RetryConf::new(),
};
assert_eq!(expected, fruently);
}
}