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
pub(crate) mod core;
mod sender;
mod twitter_list_timeline;
use std::collections::HashSet;
use std::fs::File;
use std::io::{self, Write};
use std::mem;
use std::pin::Pin;
use std::task::Context;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use diesel::prelude::*;
use diesel::r2d2::{ConnectionManager, Pool};
use diesel::SqliteConnection;
use failure::{Fail, Fallible, ResultExt};
use futures::compat::Stream01CompatExt;
use futures::future;
use futures::{Future, Poll, StreamExt};
use hyper::client::connect::Connect;
use hyper::Client;
use twitter_stream::TwitterStream;
use crate::models;
use crate::rules::TopicId;
use crate::twitter;
use crate::util::Maybe;
use crate::Manifest;
use self::core::Core;
use self::sender::Sender;
use self::twitter_list_timeline::TwitterListTimeline;
pub struct App<C> {
core: Core<C>,
twitter_list: TwitterListTimeline,
twitter: TwitterStream,
twitter_done: bool,
sender: Sender,
}
#[cfg(feature = "native-tls")]
impl App<hyper_tls::HttpsConnector<hyper::client::HttpConnector>> {
pub async fn new(manifest: Manifest) -> Fallible<Self> {
let conn = hyper_tls::HttpsConnector::new(4).context("failed to initialize TLS client")?;
let client = Client::builder().build(conn);
Self::with_http_client(client, manifest).await
}
}
impl<C: Connect> App<C>
where
C: Connect + Sync + 'static,
C::Transport: 'static,
C::Future: 'static,
{
pub async fn with_http_client(client: Client<C>, manifest: Manifest) -> Fallible<Self> {
trace_fn!(App::<C>::with_http_client);
let core = Core::new(manifest, client).await?;
let twitter = core.init_twitter().await?;
let twitter_list = core.init_twitter_list()?;
Ok(App {
core,
twitter_list,
twitter,
twitter_done: false,
sender: Sender::new(),
})
}
pub fn set_twitter_dump(&mut self, twitter_dump: File) -> io::Result<()> {
self.core.set_twitter_dump(twitter_dump)
}
pub fn shutdown<'a>(&'a mut self) -> impl Future<Output = Fallible<()>> + 'a {
future::poll_fn(move |cx| {
match (
self.twitter_list
.poll_backfill(&mut self.core, &mut self.sender, cx)?,
self.sender.poll_done(&self.core, cx)?,
) {
(Poll::Ready(()), Poll::Ready(())) => Poll::Ready(Ok(())),
_ => Poll::Pending,
}
})
}
pub async fn reset(&mut self) -> Fallible<()> {
let twitter_list = if self.twitter_done {
self.twitter = self.core.init_twitter().await?;
self.twitter_done = false;
self.core.init_twitter_list()?
} else {
TwitterListTimeline::empty()
};
self.shutdown().await?;
debug_assert!(!self.sender.has_pending());
self.twitter_list = twitter_list;
Ok(())
}
pub async fn replace_manifest(
&mut self,
manifest: Manifest,
) -> Result<Manifest, (failure::Error, Manifest)> {
let old_pool = if manifest.database_url != self.manifest().database_url {
let pool = match Pool::new(ConnectionManager::new(manifest.database_url()))
.context("failed to initialize the connection pool")
{
Ok(pool) => pool,
Err(e) => return Err((e.into(), manifest)),
};
Some(mem::replace(self.core.database_pool_mut(), pool))
} else {
None
};
let old = mem::replace(self.manifest_mut(), manifest);
struct Guard<'a, C> {
this: &'a mut App<C>,
old: Option<Manifest>,
old_pool: Option<Pool<ConnectionManager<SqliteConnection>>>,
}
impl<C> Guard<'_, C> {
fn rollback(&mut self) -> Manifest {
if let Some(pool) = self.old_pool.take() {
*self.this.core.database_pool_mut() = pool;
}
mem::replace(self.this.manifest_mut(), self.old.take().unwrap())
}
}
impl<C> Drop for Guard<'_, C> {
fn drop(&mut self) {
self.rollback();
}
}
let mut guard = Guard {
this: self,
old: Some(old),
old_pool,
};
let catch = async {
let this = &mut guard.this;
let new = this.manifest();
let conn = this.core.conn()?;
let unauthed_users = new
.rule
.twitter_outboxes()
.chain(Some(new.twitter.user))
.filter(|user| !this.core.twitter_tokens.contains_key(&user))
.collect::<HashSet<_>>()
.into_iter()
.collect::<Vec<_>>();
let tokens: Vec<models::TwitterToken> = {
use crate::schema::twitter_tokens::dsl::*;
twitter_tokens
.filter(id.eq_any(&unauthed_users))
.load(&*conn)?
};
if unauthed_users.len() != tokens.len() {
return Err(unauthorized());
}
this.core
.twitter_tokens
.extend(tokens.into_iter().map(|token| (token.id, token.into())));
let new = this.manifest();
let old = guard.old.as_ref().unwrap();
if new.twitter.client.key != old.twitter.client.key
|| new.twitter.user != old.twitter.user
|| new
.rule
.twitter_topics()
.any(|user| !old.rule.contains_topic(&TopicId::Twitter(user)))
{
let twitter = this.core.init_twitter().await?;
let twitter_list = this.core.init_twitter_list()?;
this.twitter = twitter;
this.twitter_list = twitter_list;
this.twitter_done = false;
}
Ok(())
}
.await;
match catch {
Ok(()) => {
let old = guard.old.take().unwrap();
mem::forget(guard);
Ok(old)
}
Err(e) => {
let manifest = guard.rollback();
mem::forget(guard);
Err((e, manifest))
}
}
}
fn poll_twitter(&mut self, cx: &mut Context<'_>) -> Poll<Fallible<()>> {
while let Poll::Ready(v) = (&mut self.twitter).compat().poll_next_unpin(cx) {
let result = if let Some(r) = v {
r
} else {
self.twitter_done = true;
return Poll::Ready(Ok(()));
};
let json = result.map_err(|e| {
self.twitter_done = true;
e.context("error while listening to Twitter's Streaming API")
})?;
self.core.with_twitter_dump(|dump| {
dump.write_all(json.trim_end().as_bytes())?;
dump.write_all(b"\n")
})?;
let tweet = if let Maybe::Just(t) = json::from_str::<Maybe<twitter::Tweet>>(&json)? {
t
} else {
continue;
};
if log_enabled!(log::Level::Trace) {
let created_at = snowflake_to_system_time(tweet.id as u64);
match SystemTime::now().duration_since(created_at) {
Ok(latency) => trace!("Twitter stream latency: {:.2?}", latency),
Err(e) => trace!("Twitter stream latency: -{:.2?}", e.duration()),
}
}
let from = tweet.user.id;
let will_process = self.manifest().rule.contains_topic(&TopicId::Twitter(from))
&& tweet.in_reply_to_user_id.map_or(true, |to| {
self.manifest().rule.contains_topic(&TopicId::Twitter(to))
});
if will_process {
self.sender.send_tweet(tweet, &self.core)?;
}
}
Poll::Pending
}
}
impl<C> App<C> {
pub fn manifest(&self) -> &Manifest {
self.core.manifest()
}
pub fn manifest_mut(&mut self) -> &mut Manifest {
self.core.manifest_mut()
}
pub fn database_pool(&self) -> &Pool<ConnectionManager<SqliteConnection>> {
self.core.database_pool()
}
pub fn http_client(&self) -> &Client<C> {
self.core.http_client()
}
}
impl<C> Future for App<C>
where
C: Connect + Sync + 'static,
C::Transport: 'static,
C::Future: 'static,
{
type Output = Fallible<()>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Fallible<()>> {
trace_fn!(App::<C>::poll);
let this = self.get_mut();
let _ = this.twitter_list.poll(&this.core, &mut this.sender, cx)?;
let _ = this
.twitter_list
.poll_backfill(&mut this.core, &mut this.sender, cx)?;
if let Poll::Ready(result) = this.poll_twitter(cx) {
return Poll::Ready(result);
}
let _ = this.sender.poll_done(&this.core, cx)?;
Poll::Pending
}
}
fn snowflake_to_system_time(id: u64) -> SystemTime {
let snowflake_time_ms = id >> 22;
let timestamp = Duration::new(
snowflake_time_ms / 1_000 + 1_288_834_974,
(snowflake_time_ms as u32 % 1_000 + 657) * 1_000 * 1_000,
);
UNIX_EPOCH + timestamp
}
fn unauthorized() -> failure::Error {
failure::err_msg("not all Twitter users are authorized; please run `pipitor twitter-login`")
}