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
|
use anyhow::{Context, Result};
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
use sqlx::SqlitePool;
use std::path::Path;
pub struct MirrorDb {
pool: SqlitePool,
}
#[derive(Debug, sqlx::FromRow)]
pub struct RepoRecord {
pub id: i64,
pub pubkey: String,
pub identifier: String,
pub announcement_event_id: Option<String>,
pub last_seen_at: i64,
}
#[derive(Debug, sqlx::FromRow)]
pub struct ServerSyncRecord {
pub id: i64,
pub repo_id: i64,
pub server_domain: String,
pub git_synced: bool,
pub nostr_synced: bool,
pub last_sync_at: Option<i64>,
pub error: Option<String>,
}
#[derive(Debug, sqlx::FromRow)]
pub struct EventRecord {
pub id: i64,
pub event_id: String,
pub first_seen_at: i64,
}
impl MirrorDb {
pub async fn open(db_path: &Path) -> Result<Self> {
let opts = SqliteConnectOptions::new()
.filename(db_path)
.create_if_missing(true)
.journal_mode(sqlx::sqlite::SqliteJournalMode::Wal);
let pool = SqlitePoolOptions::new()
.max_connections(5)
.connect_with(opts)
.await
.with_context(|| format!("failed to open database at {:?}", db_path))?;
let db = Self { pool };
db.run_migrations().await?;
Ok(db)
}
async fn run_migrations(&self) -> Result<()> {
sqlx::query(
r#"
CREATE TABLE IF NOT EXISTS repos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
pubkey TEXT NOT NULL,
identifier TEXT NOT NULL,
announcement_event_id TEXT,
last_seen_at INTEGER NOT NULL,
UNIQUE(pubkey, identifier)
);
CREATE TABLE IF NOT EXISTS server_syncs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_id INTEGER NOT NULL REFERENCES repos(id),
server_domain TEXT NOT NULL,
git_synced INTEGER NOT NULL DEFAULT 0,
nostr_synced INTEGER NOT NULL DEFAULT 0,
last_sync_at INTEGER,
error TEXT,
UNIQUE(repo_id, server_domain)
);
CREATE TABLE IF NOT EXISTS seen_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
event_id TEXT NOT NULL UNIQUE,
first_seen_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_repos_pubkey ON repos(pubkey);
CREATE INDEX IF NOT EXISTS idx_server_syncs_repo ON server_syncs(repo_id);
CREATE INDEX IF NOT EXISTS idx_seen_events_id ON seen_events(event_id);
CREATE TABLE IF NOT EXISTS nip46_sessions (
npub TEXT PRIMARY KEY,
client_secret TEXT NOT NULL,
signer_pubkey TEXT,
connected INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS signing_queue (
id INTEGER PRIMARY KEY AUTOINCREMENT,
npub TEXT NOT NULL,
repo_identifier TEXT NOT NULL,
state_event_json TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
created_at INTEGER NOT NULL,
signed_at INTEGER,
error TEXT
);
"#,
)
.execute(&self.pool)
.await
.context("failed to run migrations")?;
Ok(())
}
pub async fn upsert_repo(
&self,
pubkey: &str,
identifier: &str,
event_id: &str,
) -> Result<i64> {
let now = chrono_now_secs();
let result = sqlx::query_as::<_, RepoRecord>(
"SELECT * FROM repos WHERE pubkey = ? AND identifier = ?",
)
.bind(pubkey)
.bind(identifier)
.fetch_optional(&self.pool)
.await?;
if let Some(existing) = result {
sqlx::query("UPDATE repos SET announcement_event_id = ?, last_seen_at = ? WHERE id = ?")
.bind(event_id)
.bind(now)
.bind(existing.id)
.execute(&self.pool)
.await?;
Ok(existing.id)
} else {
sqlx::query("INSERT INTO repos (pubkey, identifier, announcement_event_id, last_seen_at) VALUES (?, ?, ?, ?)")
.bind(pubkey)
.bind(identifier)
.bind(event_id)
.bind(now)
.execute(&self.pool)
.await?;
let row: (i64,) = sqlx::query_as("SELECT last_insert_rowid()")
.fetch_one(&self.pool)
.await?;
Ok(row.0)
}
}
pub async fn get_repos_needing_git_sync(&self, known_servers: &[String]) -> Result<Vec<(RepoRecord, Vec<String>)>> {
let repos = sqlx::query_as::<_, RepoRecord>("SELECT * FROM repos")
.fetch_all(&self.pool)
.await?;
let mut result = Vec::new();
for repo in repos {
let synced: Vec<String> = sqlx::query_scalar::<_, String>(
"SELECT server_domain FROM server_syncs WHERE repo_id = ? AND git_synced = 1",
)
.bind(repo.id)
.fetch_all(&self.pool)
.await?;
let missing: Vec<String> = known_servers
.iter()
.filter(|s| !synced.contains(s))
.cloned()
.collect();
if !missing.is_empty() {
result.push((repo, missing));
}
}
Ok(result)
}
pub async fn mark_git_synced(
&self,
repo_id: i64,
server_domain: &str,
) -> Result<()> {
let now = chrono_now_secs();
sqlx::query(
r#"INSERT INTO server_syncs (repo_id, server_domain, git_synced, nostr_synced, last_sync_at)
VALUES (?, ?, 1, 0, ?)
ON CONFLICT(repo_id, server_domain) DO UPDATE SET git_synced = 1, last_sync_at = ?, error = NULL"#,
)
.bind(repo_id)
.bind(server_domain)
.bind(now)
.bind(now)
.execute(&self.pool)
.await?;
Ok(())
}
pub async fn mark_nostr_synced(
&self,
repo_id: i64,
server_domain: &str,
) -> Result<()> {
let now = chrono_now_secs();
sqlx::query(
r#"INSERT INTO server_syncs (repo_id, server_domain, git_synced, nostr_synced, last_sync_at)
VALUES (?, ?, 0, 1, ?)
ON CONFLICT(repo_id, server_domain) DO UPDATE SET nostr_synced = 1, last_sync_at = ?, error = NULL"#,
)
.bind(repo_id)
.bind(server_domain)
.bind(now)
.bind(now)
.execute(&self.pool)
.await?;
Ok(())
}
pub async fn mark_sync_error(
&self,
repo_id: i64,
server_domain: &str,
error: &str,
) -> Result<()> {
let now = chrono_now_secs();
sqlx::query(
r#"INSERT INTO server_syncs (repo_id, server_domain, git_synced, nostr_synced, last_sync_at, error)
VALUES (?, ?, 0, 0, ?, ?)
ON CONFLICT(repo_id, server_domain) DO UPDATE SET error = ?, last_sync_at = ?"#,
)
.bind(repo_id)
.bind(server_domain)
.bind(now)
.bind(error)
.bind(error)
.bind(now)
.execute(&self.pool)
.await?;
Ok(())
}
pub async fn have_seen_event(&self, event_id: &str) -> Result<bool> {
let result: Option<(i64,)> = sqlx::query_as(
"SELECT id FROM seen_events WHERE event_id = ?",
)
.bind(event_id)
.fetch_optional(&self.pool)
.await?;
Ok(result.is_some())
}
pub async fn record_event(&self, event_id: &str) -> Result<()> {
let now = chrono_now_secs();
sqlx::query("INSERT OR IGNORE INTO seen_events (event_id, first_seen_at) VALUES (?, ?)")
.bind(event_id)
.bind(now)
.execute(&self.pool)
.await?;
Ok(())
}
pub async fn get_all_repos(&self) -> Result<Vec<RepoRecord>> {
let repos = sqlx::query_as::<_, RepoRecord>("SELECT * FROM repos ORDER BY last_seen_at DESC")
.fetch_all(&self.pool)
.await?;
Ok(repos)
}
pub async fn get_sync_summary(&self) -> Result<Vec<ServerSyncRecord>> {
let records = sqlx::query_as::<_, ServerSyncRecord>(
"SELECT * FROM server_syncs ORDER BY last_sync_at DESC NULLS LAST",
)
.fetch_all(&self.pool)
.await?;
Ok(records)
}
pub async fn get_nip46_session(&self, npub: &str) -> Result<Option<Nip46SessionRecord>> {
let result = sqlx::query_as::<_, Nip46SessionRecord>(
"SELECT * FROM nip46_sessions WHERE npub = ?",
)
.bind(npub)
.fetch_optional(&self.pool)
.await?;
Ok(result)
}
pub async fn upsert_nip46_session(
&self,
npub: &str,
client_secret: &str,
signer_pubkey: Option<&str>,
connected: bool,
) -> Result<()> {
sqlx::query(
r#"INSERT INTO nip46_sessions (npub, client_secret, signer_pubkey, connected)
VALUES (?, ?, ?, ?)
ON CONFLICT(npub) DO UPDATE SET client_secret = ?, signer_pubkey = ?, connected = ?"#,
)
.bind(npub)
.bind(client_secret)
.bind(signer_pubkey)
.bind(connected as i32)
.bind(client_secret)
.bind(signer_pubkey)
.bind(connected as i32)
.execute(&self.pool)
.await?;
Ok(())
}
pub async fn get_all_nip46_sessions(&self) -> Result<Vec<Nip46SessionRecord>> {
let records =
sqlx::query_as::<_, Nip46SessionRecord>("SELECT * FROM nip46_sessions")
.fetch_all(&self.pool)
.await?;
Ok(records)
}
}
#[derive(Debug, sqlx::FromRow)]
pub struct Nip46SessionRecord {
pub npub: String,
pub client_secret: String,
pub signer_pubkey: Option<String>,
pub connected: bool,
}
fn chrono_now_secs() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64
}
|