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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
#[macro_use]
extern crate log;
extern crate uuid;
extern crate url;
#[macro_use]
extern crate hyper;
extern crate hyper_native_tls;
#[macro_use]
extern crate derive_builder;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
#[macro_use]
extern crate error_chain;
extern crate metrics as libmetrics;
extern crate histogram;
use std::sync::Arc;
use std::thread::JoinHandle;
use std::env;
use uuid::Uuid;
use serde::{Deserialize, Deserializer};
use worker::{Worker, NakadiWorker, WorkerSettings};
mod tokenerrors;
pub mod metrics;
mod clienterrors;
mod connector;
pub mod worker;
pub use tokenerrors::*;
pub use clienterrors::*;
pub use self::connector::{NakadiConnector, Checkpoints, ReadsStream, HyperClientConnector,
ConnectorSettings, ConnectorSettingsBuilder, ProvidesStreamInfo};
#[derive(Clone, Debug)]
pub struct Token(pub String);
impl Token {
pub fn new<T: Into<String>>(token: T) -> Token {
Token(token.into())
}
}
pub trait ProvidesToken: Send + Sync + 'static {
fn get_token(&self) -> TokenResult<Option<Token>>;
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EventType(pub String);
impl EventType {
pub fn new<T: Into<String>>(value: T) -> EventType {
EventType(value.into())
}
}
#[derive(Clone, Debug)]
pub struct SubscriptionId(pub Uuid);
impl SubscriptionId {
pub fn nil() -> Self {
SubscriptionId(Uuid::nil())
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PartitionId(pub usize);
impl Deserialize for PartitionId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer
{
let v = String::deserialize(deserializer)?;
match v.parse() {
Ok(v) => Ok(PartitionId(v)),
Err(err) => {
Err(serde::de::Error::custom(format!("{} is not a usize required for \
PartitionId.",
err)))
}
}
}
}
#[derive(Debug, Deserialize)]
pub struct PartitionInfo {
partition: PartitionId,
stream_id: StreamId,
unconsumed_events: usize,
}
#[derive(Debug, Deserialize)]
pub struct EventTypeInfo {
event_type: EventType,
partitions: Vec<PartitionInfo>,
}
impl EventTypeInfo {
pub fn num_partitions(&self) -> usize {
self.partitions.len()
}
}
#[derive(Debug, Deserialize)]
pub struct StreamInfo {
#[serde(rename="items")]
event_types: Vec<EventTypeInfo>,
}
impl StreamInfo {
pub fn max_partitions(&self) -> usize {
self.event_types
.iter()
.map(|et| et.num_partitions())
.max()
.unwrap_or(0)
}
}
#[derive(Clone, Debug, Deserialize)]
pub struct StreamId(pub String);
impl StreamId {
pub fn new<T: Into<String>>(id: T) -> Self {
StreamId(id.into())
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Cursor {
pub partition: PartitionId,
pub offset: String,
pub event_type: EventType,
pub cursor_token: Uuid,
}
#[derive(Clone, Debug)]
pub struct BatchInfo {
pub stream_id: StreamId,
pub cursor: Cursor,
}
#[derive(Debug, Clone)]
pub enum AfterBatchAction {
Continue,
ContinueNoCheckpoint,
Stop,
Abort,
}
pub trait Handler: Send + Sync {
fn handle(&self, batch: &str, info: BatchInfo) -> AfterBatchAction;
}
impl<F> Handler for F
where F: Send + Sync + 'static + Fn(&str, BatchInfo) -> AfterBatchAction
{
fn handle(&self, batch: &str, info: BatchInfo) -> AfterBatchAction {
(*self)(batch, info)
}
}
pub struct NakadiClient<C: NakadiConnector> {
worker: NakadiWorker,
connector: Arc<C>,
}
impl<C: NakadiConnector> NakadiClient<C> {
pub fn new<H: Handler + 'static>(subscription_id: SubscriptionId,
connector: Arc<C>,
handler: H,
settings: WorkerSettings)
-> Result<(Self, JoinHandle<()>), String> {
let (worker, handle) =
NakadiWorker::new(connector.clone(), handler, subscription_id, settings)?;
Ok((NakadiClient {
worker: worker,
connector: connector,
},
handle))
}
pub fn from_env_with_subscription<H: Handler + 'static, T: ProvidesToken>
(subscription_id: SubscriptionId,
handler: H,
token_provider: T)
-> Result<(NakadiClient<HyperClientConnector>, JoinHandle<()>), String> {
let connector = HyperClientConnector::from_env(Box::new(token_provider))?;
let connector = Arc::new(connector);
let worker_settings = WorkerSettings::from_env()?;
let (worker, handle) =
NakadiWorker::new(connector.clone(), handler, subscription_id, worker_settings)?;
let client: NakadiClient<HyperClientConnector> = NakadiClient {
worker: worker,
connector: connector,
};
Ok((client, handle))
}
pub fn from_env<H: Handler + 'static, T: ProvidesToken>
(handler: H,
token_provider: T)
-> Result<(NakadiClient<HyperClientConnector>, JoinHandle<()>), String> {
let subscription_id: SubscriptionId = match env::var("NAKADION_SUBSCRIPTION_ID") {
Ok(env_val) => SubscriptionId(
env_val
.parse()
.map_err(|err| format!(
"Could not parse 'NAKADION_SUBSCRIPTION_ID': {}",
err))?),
Err(err) => {
return Err(format!("Could not get env var 'NAKADION_SUBSCRIPTION_ID': {}", err))
}
};
NakadiClient::<HyperClientConnector>::from_env_with_subscription(subscription_id,
handler,
token_provider)
}
pub fn connector(&self) -> &C {
&self.connector
}
}
impl<C: NakadiConnector> Worker for NakadiClient<C> {
fn is_running(&self) -> bool {
self.worker.is_running()
}
fn stop(&self) {
self.worker.stop();
}
fn subscription_id(&self) -> &SubscriptionId {
self.worker.subscription_id()
}
}