tuitbot-core 0.1.47

Core library for Tuitbot autonomous X growth assistant
Documentation
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
//! CRUD operations for discovered tweets.
//!
//! Provides functions to insert, query, and update tweets discovered
//! from X search results.

use super::accounts::DEFAULT_ACCOUNT_ID;
use super::DbPool;
use crate::error::StorageError;

/// A tweet discovered from X search matching configured keywords.
#[derive(Debug, Clone, sqlx::FromRow, serde::Serialize)]
pub struct DiscoveredTweet {
    /// X tweet ID (globally unique).
    pub id: String,
    /// X user ID of tweet author.
    pub author_id: String,
    /// @handle of tweet author.
    pub author_username: String,
    /// Full tweet text.
    pub content: String,
    /// Likes at discovery time.
    pub like_count: i64,
    /// Retweets at discovery time.
    pub retweet_count: i64,
    /// Replies at discovery time.
    pub reply_count: i64,
    /// Impressions if available.
    pub impression_count: Option<i64>,
    /// Computed relevance score (0-100).
    pub relevance_score: Option<f64>,
    /// Which keyword triggered discovery.
    pub matched_keyword: Option<String>,
    /// ISO-8601 UTC timestamp of discovery.
    pub discovered_at: String,
    /// Whether a reply has been sent (0 = no, 1 = yes).
    pub replied_to: i64,
}

/// Insert a discovered tweet for a specific account. Uses `INSERT OR IGNORE` to handle duplicates gracefully.
pub async fn insert_discovered_tweet_for(
    pool: &DbPool,
    account_id: &str,
    tweet: &DiscoveredTweet,
) -> Result<(), StorageError> {
    sqlx::query(
        "INSERT OR IGNORE INTO discovered_tweets \
         (account_id, id, author_id, author_username, content, like_count, retweet_count, \
          reply_count, impression_count, relevance_score, matched_keyword, \
          discovered_at, replied_to) \
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
    )
    .bind(account_id)
    .bind(&tweet.id)
    .bind(&tweet.author_id)
    .bind(&tweet.author_username)
    .bind(&tweet.content)
    .bind(tweet.like_count)
    .bind(tweet.retweet_count)
    .bind(tweet.reply_count)
    .bind(tweet.impression_count)
    .bind(tweet.relevance_score)
    .bind(&tweet.matched_keyword)
    .bind(&tweet.discovered_at)
    .bind(tweet.replied_to)
    .execute(pool)
    .await
    .map_err(|e| StorageError::Query { source: e })?;

    Ok(())
}

/// Insert a discovered tweet. Uses `INSERT OR IGNORE` to handle duplicates gracefully.
pub async fn insert_discovered_tweet(
    pool: &DbPool,
    tweet: &DiscoveredTweet,
) -> Result<(), StorageError> {
    insert_discovered_tweet_for(pool, DEFAULT_ACCOUNT_ID, tweet).await
}

/// Fetch a single tweet by its X ID for a specific account. Returns `None` if not found.
pub async fn get_tweet_by_id_for(
    pool: &DbPool,
    account_id: &str,
    tweet_id: &str,
) -> Result<Option<DiscoveredTweet>, StorageError> {
    sqlx::query_as::<_, DiscoveredTweet>(
        "SELECT * FROM discovered_tweets WHERE account_id = ? AND id = ?",
    )
    .bind(account_id)
    .bind(tweet_id)
    .fetch_optional(pool)
    .await
    .map_err(|e| StorageError::Query { source: e })
}

/// Fetch a single tweet by its X ID. Returns `None` if not found.
pub async fn get_tweet_by_id(
    pool: &DbPool,
    tweet_id: &str,
) -> Result<Option<DiscoveredTweet>, StorageError> {
    get_tweet_by_id_for(pool, DEFAULT_ACCOUNT_ID, tweet_id).await
}

/// Mark a tweet as having been replied to for a specific account.
pub async fn mark_tweet_replied_for(
    pool: &DbPool,
    account_id: &str,
    tweet_id: &str,
) -> Result<(), StorageError> {
    sqlx::query("UPDATE discovered_tweets SET replied_to = 1 WHERE account_id = ? AND id = ?")
        .bind(account_id)
        .bind(tweet_id)
        .execute(pool)
        .await
        .map_err(|e| StorageError::Query { source: e })?;

    Ok(())
}

/// Mark a tweet as having been replied to.
pub async fn mark_tweet_replied(pool: &DbPool, tweet_id: &str) -> Result<(), StorageError> {
    mark_tweet_replied_for(pool, DEFAULT_ACCOUNT_ID, tweet_id).await
}

/// Fetch unreplied tweets with relevance score at or above the threshold for a specific account,
/// ordered by score descending.
pub async fn get_unreplied_tweets_above_score_for(
    pool: &DbPool,
    account_id: &str,
    threshold: f64,
) -> Result<Vec<DiscoveredTweet>, StorageError> {
    sqlx::query_as::<_, DiscoveredTweet>(
        "SELECT * FROM discovered_tweets \
         WHERE account_id = ? AND replied_to = 0 AND relevance_score >= ? \
         ORDER BY relevance_score DESC",
    )
    .bind(account_id)
    .bind(threshold)
    .fetch_all(pool)
    .await
    .map_err(|e| StorageError::Query { source: e })
}

/// Fetch unreplied tweets with relevance score at or above the threshold,
/// ordered by score descending.
pub async fn get_unreplied_tweets_above_score(
    pool: &DbPool,
    threshold: f64,
) -> Result<Vec<DiscoveredTweet>, StorageError> {
    get_unreplied_tweets_above_score_for(pool, DEFAULT_ACCOUNT_ID, threshold).await
}

/// Fetch discovered tweets above a score threshold for a specific account, ordered by discovery time (newest first).
pub async fn get_discovery_feed_for(
    pool: &DbPool,
    account_id: &str,
    min_score: f64,
    limit: u32,
) -> Result<Vec<DiscoveredTweet>, StorageError> {
    sqlx::query_as::<_, DiscoveredTweet>(
        "SELECT * FROM discovered_tweets \
         WHERE account_id = ? AND COALESCE(relevance_score, 0.0) >= ? \
         ORDER BY discovered_at DESC \
         LIMIT ?",
    )
    .bind(account_id)
    .bind(min_score)
    .bind(limit)
    .fetch_all(pool)
    .await
    .map_err(|e| StorageError::Query { source: e })
}

/// Fetch discovered tweets above a score threshold, ordered by discovery time (newest first).
pub async fn get_discovery_feed(
    pool: &DbPool,
    min_score: f64,
    limit: u32,
) -> Result<Vec<DiscoveredTweet>, StorageError> {
    get_discovery_feed_for(pool, DEFAULT_ACCOUNT_ID, min_score, limit).await
}

/// Fetch discovered tweets with advanced filters for a specific account: score range, keyword, and limit.
pub async fn get_discovery_feed_filtered_for(
    pool: &DbPool,
    account_id: &str,
    min_score: f64,
    max_score: Option<f64>,
    keyword: Option<&str>,
    limit: u32,
) -> Result<Vec<DiscoveredTweet>, StorageError> {
    let mut sql = String::from(
        "SELECT * FROM discovered_tweets WHERE account_id = ? AND COALESCE(relevance_score, 0.0) >= ?",
    );
    if max_score.is_some() {
        sql.push_str(" AND COALESCE(relevance_score, 0.0) <= ?");
    }
    if keyword.is_some() {
        sql.push_str(" AND matched_keyword = ?");
    }
    sql.push_str(" ORDER BY discovered_at DESC LIMIT ?");

    let mut query = sqlx::query_as::<_, DiscoveredTweet>(&sql)
        .bind(account_id)
        .bind(min_score);
    if let Some(max) = max_score {
        query = query.bind(max);
    }
    if let Some(kw) = keyword {
        query = query.bind(kw);
    }
    query = query.bind(limit);

    query
        .fetch_all(pool)
        .await
        .map_err(|e| StorageError::Query { source: e })
}

/// Fetch discovered tweets with advanced filters: score range, keyword, and limit.
pub async fn get_discovery_feed_filtered(
    pool: &DbPool,
    min_score: f64,
    max_score: Option<f64>,
    keyword: Option<&str>,
    limit: u32,
) -> Result<Vec<DiscoveredTweet>, StorageError> {
    get_discovery_feed_filtered_for(
        pool,
        DEFAULT_ACCOUNT_ID,
        min_score,
        max_score,
        keyword,
        limit,
    )
    .await
}

/// Get distinct matched keywords from discovered tweets for a specific account.
pub async fn get_distinct_keywords_for(
    pool: &DbPool,
    account_id: &str,
) -> Result<Vec<String>, StorageError> {
    let rows: Vec<(String,)> = sqlx::query_as(
        "SELECT DISTINCT matched_keyword FROM discovered_tweets \
         WHERE account_id = ? AND matched_keyword IS NOT NULL AND matched_keyword != '' \
         ORDER BY matched_keyword",
    )
    .bind(account_id)
    .fetch_all(pool)
    .await
    .map_err(|e| StorageError::Query { source: e })?;

    Ok(rows.into_iter().map(|(kw,)| kw).collect())
}

/// Get distinct matched keywords from discovered tweets.
pub async fn get_distinct_keywords(pool: &DbPool) -> Result<Vec<String>, StorageError> {
    get_distinct_keywords_for(pool, DEFAULT_ACCOUNT_ID).await
}

/// Check if a tweet exists in the database for a specific account.
pub async fn tweet_exists_for(
    pool: &DbPool,
    account_id: &str,
    tweet_id: &str,
) -> Result<bool, StorageError> {
    let row: (i64,) = sqlx::query_as(
        "SELECT EXISTS(SELECT 1 FROM discovered_tweets WHERE account_id = ? AND id = ?)",
    )
    .bind(account_id)
    .bind(tweet_id)
    .fetch_one(pool)
    .await
    .map_err(|e| StorageError::Query { source: e })?;

    Ok(row.0 == 1)
}

/// Check if a tweet exists in the database.
pub async fn tweet_exists(pool: &DbPool, tweet_id: &str) -> Result<bool, StorageError> {
    tweet_exists_for(pool, DEFAULT_ACCOUNT_ID, tweet_id).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::init_test_db;

    fn sample_tweet(id: &str, score: Option<f64>) -> DiscoveredTweet {
        DiscoveredTweet {
            id: id.to_string(),
            author_id: "user123".to_string(),
            author_username: "testuser".to_string(),
            content: "Test tweet content".to_string(),
            like_count: 10,
            retweet_count: 2,
            reply_count: 1,
            impression_count: Some(500),
            relevance_score: score,
            matched_keyword: Some("rust".to_string()),
            discovered_at: "2026-02-21T12:00:00Z".to_string(),
            replied_to: 0,
        }
    }

    #[tokio::test]
    async fn insert_and_retrieve_tweet() {
        let pool = init_test_db().await.expect("init db");
        let tweet = sample_tweet("tweet_1", Some(85.0));

        insert_discovered_tweet(&pool, &tweet)
            .await
            .expect("insert");
        let fetched = get_tweet_by_id(&pool, "tweet_1")
            .await
            .expect("get")
            .expect("should exist");

        assert_eq!(fetched.id, "tweet_1");
        assert_eq!(fetched.author_username, "testuser");
        assert_eq!(fetched.relevance_score, Some(85.0));
    }

    #[tokio::test]
    async fn duplicate_insert_is_ignored() {
        let pool = init_test_db().await.expect("init db");
        let tweet = sample_tweet("tweet_dup", Some(50.0));

        insert_discovered_tweet(&pool, &tweet).await.expect("first");
        insert_discovered_tweet(&pool, &tweet)
            .await
            .expect("duplicate should be ignored");
    }

    #[tokio::test]
    async fn get_nonexistent_tweet_returns_none() {
        let pool = init_test_db().await.expect("init db");
        let result = get_tweet_by_id(&pool, "nonexistent").await.expect("get");
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn mark_replied_and_query_unreplied() {
        let pool = init_test_db().await.expect("init db");

        let tweet1 = sample_tweet("t1", Some(90.0));
        let tweet2 = sample_tweet("t2", Some(80.0));
        let tweet3 = sample_tweet("t3", Some(60.0));

        insert_discovered_tweet(&pool, &tweet1).await.expect("ins1");
        insert_discovered_tweet(&pool, &tweet2).await.expect("ins2");
        insert_discovered_tweet(&pool, &tweet3).await.expect("ins3");

        mark_tweet_replied(&pool, "t1").await.expect("mark");

        let unreplied = get_unreplied_tweets_above_score(&pool, 70.0)
            .await
            .expect("query");
        assert_eq!(unreplied.len(), 1);
        assert_eq!(unreplied[0].id, "t2");
    }

    #[tokio::test]
    async fn tweet_exists_check() {
        let pool = init_test_db().await.expect("init db");
        let tweet = sample_tweet("exists_test", Some(50.0));

        assert!(!tweet_exists(&pool, "exists_test").await.expect("check"));
        insert_discovered_tweet(&pool, &tweet).await.expect("ins");
        assert!(tweet_exists(&pool, "exists_test").await.expect("check"));
    }

    #[tokio::test]
    async fn discovery_feed_returns_ordered_by_discovered_at() {
        let pool = init_test_db().await.expect("init db");

        let mut t1 = sample_tweet("feed_1", Some(80.0));
        t1.discovered_at = "2026-02-21T12:00:00Z".to_string();
        let mut t2 = sample_tweet("feed_2", Some(90.0));
        t2.discovered_at = "2026-02-21T13:00:00Z".to_string();

        insert_discovered_tweet(&pool, &t1).await.expect("ins1");
        insert_discovered_tweet(&pool, &t2).await.expect("ins2");

        let feed = get_discovery_feed(&pool, 70.0, 10).await.expect("feed");
        assert_eq!(feed.len(), 2);
        assert_eq!(feed[0].id, "feed_2", "newest should be first");
    }

    #[tokio::test]
    async fn discovery_feed_respects_min_score() {
        let pool = init_test_db().await.expect("init db");

        insert_discovered_tweet(&pool, &sample_tweet("low_1", Some(30.0)))
            .await
            .expect("ins");
        insert_discovered_tweet(&pool, &sample_tweet("high_1", Some(80.0)))
            .await
            .expect("ins");

        let feed = get_discovery_feed(&pool, 50.0, 10).await.expect("feed");
        assert_eq!(feed.len(), 1);
        assert_eq!(feed[0].id, "high_1");
    }

    #[tokio::test]
    async fn discovery_feed_respects_limit() {
        let pool = init_test_db().await.expect("init db");

        for i in 0..5 {
            insert_discovered_tweet(&pool, &sample_tweet(&format!("lim_{i}"), Some(80.0)))
                .await
                .expect("ins");
        }

        let feed = get_discovery_feed(&pool, 0.0, 3).await.expect("feed");
        assert_eq!(feed.len(), 3);
    }

    #[tokio::test]
    async fn discovery_feed_filtered_with_max_score() {
        let pool = init_test_db().await.expect("init db");

        insert_discovered_tweet(&pool, &sample_tweet("f_low", Some(30.0)))
            .await
            .expect("ins");
        insert_discovered_tweet(&pool, &sample_tweet("f_mid", Some(60.0)))
            .await
            .expect("ins");
        insert_discovered_tweet(&pool, &sample_tweet("f_high", Some(90.0)))
            .await
            .expect("ins");

        let feed = get_discovery_feed_filtered(&pool, 40.0, Some(70.0), None, 10)
            .await
            .expect("feed");
        assert_eq!(feed.len(), 1);
        assert_eq!(feed[0].id, "f_mid");
    }

    #[tokio::test]
    async fn discovery_feed_filtered_with_keyword() {
        let pool = init_test_db().await.expect("init db");

        let mut t1 = sample_tweet("kw_1", Some(80.0));
        t1.matched_keyword = Some("rust".to_string());
        let mut t2 = sample_tweet("kw_2", Some(80.0));
        t2.matched_keyword = Some("python".to_string());

        insert_discovered_tweet(&pool, &t1).await.expect("ins");
        insert_discovered_tweet(&pool, &t2).await.expect("ins");

        let feed = get_discovery_feed_filtered(&pool, 0.0, None, Some("rust"), 10)
            .await
            .expect("feed");
        assert_eq!(feed.len(), 1);
        assert_eq!(feed[0].id, "kw_1");
    }

    #[tokio::test]
    async fn get_distinct_keywords_returns_unique_sorted() {
        let pool = init_test_db().await.expect("init db");

        let mut t1 = sample_tweet("dk_1", Some(80.0));
        t1.matched_keyword = Some("rust".to_string());
        let mut t2 = sample_tweet("dk_2", Some(80.0));
        t2.matched_keyword = Some("python".to_string());
        let mut t3 = sample_tweet("dk_3", Some(80.0));
        t3.matched_keyword = Some("rust".to_string());

        insert_discovered_tweet(&pool, &t1).await.expect("ins");
        insert_discovered_tweet(&pool, &t2).await.expect("ins");
        insert_discovered_tweet(&pool, &t3).await.expect("ins");

        let keywords = get_distinct_keywords(&pool).await.expect("keywords");
        assert_eq!(keywords.len(), 2);
        assert_eq!(keywords[0], "python");
        assert_eq!(keywords[1], "rust");
    }

    #[tokio::test]
    async fn get_distinct_keywords_excludes_null_and_empty() {
        let pool = init_test_db().await.expect("init db");

        let mut t1 = sample_tweet("dk_null", Some(80.0));
        t1.matched_keyword = None;
        let mut t2 = sample_tweet("dk_empty", Some(80.0));
        t2.matched_keyword = Some(String::new());
        let mut t3 = sample_tweet("dk_valid", Some(80.0));
        t3.matched_keyword = Some("valid".to_string());

        insert_discovered_tweet(&pool, &t1).await.expect("ins");
        insert_discovered_tweet(&pool, &t2).await.expect("ins");
        insert_discovered_tweet(&pool, &t3).await.expect("ins");

        let keywords = get_distinct_keywords(&pool).await.expect("keywords");
        assert_eq!(keywords.len(), 1);
        assert_eq!(keywords[0], "valid");
    }

    #[tokio::test]
    async fn insert_and_retrieve_tweet_for_account() {
        let pool = init_test_db().await.expect("init db");
        let tweet = sample_tweet("acct_t1", Some(75.0));

        insert_discovered_tweet_for(&pool, "acct_a", &tweet)
            .await
            .expect("ins");

        // Should not be found under default account
        let result = get_tweet_by_id(&pool, "acct_t1").await.expect("get");
        assert!(result.is_none());

        // Should be found under acct_a
        let result = get_tweet_by_id_for(&pool, "acct_a", "acct_t1")
            .await
            .expect("get");
        assert!(result.is_some());
    }

    #[tokio::test]
    async fn tweet_exists_for_account_isolation() {
        let pool = init_test_db().await.expect("init db");
        let tweet = sample_tweet("iso_t1", Some(50.0));

        insert_discovered_tweet_for(&pool, "acct_x", &tweet)
            .await
            .expect("ins");

        assert!(tweet_exists_for(&pool, "acct_x", "iso_t1")
            .await
            .expect("check"));
        assert!(!tweet_exists_for(&pool, "acct_y", "iso_t1")
            .await
            .expect("check"));
    }

    #[tokio::test]
    async fn mark_tweet_replied_for_account_isolation() {
        let pool = init_test_db().await.expect("init db");
        let tweet = sample_tweet("mr_t1", Some(80.0));

        insert_discovered_tweet_for(&pool, "acct_r", &tweet)
            .await
            .expect("ins");
        mark_tweet_replied_for(&pool, "acct_r", "mr_t1")
            .await
            .expect("mark");

        let fetched = get_tweet_by_id_for(&pool, "acct_r", "mr_t1")
            .await
            .expect("get")
            .expect("exists");
        assert_eq!(fetched.replied_to, 1);
    }

    #[tokio::test]
    async fn sample_tweet_with_none_score() {
        let pool = init_test_db().await.expect("init db");
        let tweet = sample_tweet("none_score", None);

        insert_discovered_tweet(&pool, &tweet).await.expect("ins");
        let fetched = get_tweet_by_id(&pool, "none_score")
            .await
            .expect("get")
            .expect("exists");
        assert!(fetched.relevance_score.is_none());
    }
}