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
|
pub mod approvals;
pub mod builds;
pub mod candidates;
pub mod migrations;
pub mod model;
// The queries this module owns, one module per aggregate. They are private:
// the interface is what `pub use` names below, not the file layout, so a
// caller cannot reach a query that was not chosen for export.
mod audit;
mod invariants;
mod metrics;
mod notices;
mod packages;
mod pkgbases;
mod publish_writes;
mod releases;
mod repos;
mod retention;
mod settings;
mod snapshots;
mod stage_b;
mod staleness;
mod subscriptions;
mod world;
pub use migrations::MIGRATIONS;
pub(crate) use model::StateEnum;
pub(crate) use model::json_or;
pub use model::{
BUILD_STEPS, BuildState, CandidateRow, CandidateState,
Identity, Recipe, ReleaseRow, ReleaseState,
SourceDigest, SourceEntry, StageBCacheRow, StepState,
SubscriptionState, UpstreamPin, WorldMember, candidate_kind,
notice_kind,
};
pub use audit::{AuditEntry, audit, audit_in, audit_system, list_audit};
pub use invariants::{approved_but_unbuilt, unapproved_index_entries};
pub use metrics::{
artifact_bytes_served, build_state_counts, count_index_packages, count_pending_reviews,
count_published_releases, count_subscriptions, count_unacknowledged_notices, last_gc_age_secs,
last_poll_age_secs, oldest_queued_age_secs, pending_review_ages_secs,
};
pub use notices::{acknowledge_notice, list_notices, put_notice_once};
pub use packages::{
accepted_recipe, builds_for_pkgbase, index_artifact, index_packages,
index_version, our_package_names,
};
pub use pkgbases::{
Pkgbase, accepted_release_for, cas_accepted_release, get_pkgbase, get_pkgbase_by_id, set_aur_head,
};
pub use publish_writes::{
NewRelease, accepted_pointer_in, artifact_path, cas_accepted_release_in,
insert_package_in, insert_release_in, remove_index_packages_in, remove_package_by_name_in,
};
pub use releases::{
accepted_release, all_published_releases, release_by_id, releases_for_pkgbase,
withdraw_release_in,
};
pub use repos::{ensure_repo, repo_id};
pub use retention::{
mark_release_purged, pkgbase_release_pointers, published_release_ids, record_gc_run,
release_artifact_paths, serving_release_ids,
};
pub use settings::{all_settings, set_setting, setting, setting_i64};
pub use snapshots::{SnapshotRow, put_snapshot, snapshot_by_commit, snapshot_by_id};
pub use stage_b::{stage_b_cache_get, stage_b_cache_put, stage_b_recent};
pub use staleness::{
NewArtifact, approval_note, candidate_snapshot_id, index_recipes,
insert_artifact_in, published_world_members, put_source_cache, served_vs_offered_pkgvers,
source_cache_path,
};
pub use subscriptions::{
due_subscriptions, get_subscription, list_subscriptions, note_check,
set_subscription_state, subscribe,
};
pub use world::{put_world_snapshot, world_members};
pub(crate) fn state_col<T: StateEnum>(col: usize, text: &str) -> rusqlite::Result<T> {
T::parse(text).ok_or_else(|| {
rusqlite::Error::FromSqlConversionFailure(
col,
rusqlite::types::Type::Text,
Box::new(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("{} has a state outside the state machine: {text:?}", T::KIND),
)),
)
})
}
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use crossbeam_channel::{bounded, unbounded, Sender};
use rusqlite::Connection;
use crate::config::Config;
use crate::error::{Error, Result};
fn open(path: &Path, read_only: bool) -> Result<Connection> {
let conn = if read_only {
Connection::open_with_flags(
path,
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
)
} else {
Connection::open(path)
}
.map_err(|e| Error::db(format!("open {}: {e}", path.display())))?;
configure(&conn, read_only)?;
Ok(conn)
}
fn configure(conn: &Connection, read_only: bool) -> Result<()> {
conn.pragma_update(None, "journal_mode", "WAL")
.and_then(|_| conn.pragma_update(None, "busy_timeout", 5000))
.and_then(|_| conn.pragma_update(None, "foreign_keys", "ON"))
.map_err(|e| Error::db(e.to_string()))?;
if !read_only {
conn.pragma_update(None, "synchronous", "FULL")
.map_err(|e| Error::db(e.to_string()))?;
}
Ok(())
}
pub fn migrate(path: &Path) -> Result<u32> {
let mut conn = open(path, false)?;
let mut applied = 0u32;
let current: u32 = conn
.pragma_query_value(None, "user_version", |r| r.get(0))
.map_err(|e| Error::db(e.to_string()))?;
for m in migrations::MIGRATIONS {
if m.version > current {
let tx = conn
.transaction()
.map_err(|e| Error::db(e.to_string()))?;
tx.execute_batch(m.sql)
.map_err(|e| Error::db(format!("migration {} ({}): {e}", m.version, m.name)))?;
tx.pragma_update(None, "user_version", m.version)
.map_err(|e| Error::db(e.to_string()))?;
tx.commit().map_err(|e| Error::db(e.to_string()))?;
applied += 1;
}
}
if applied > 0 {
let mut stmt = conn
.prepare("INSERT OR IGNORE INTO settings (key, value) VALUES (?1, ?2)")
.map_err(|e| Error::db(e.to_string()))?;
for (k, v) in migrations::DEFAULT_SETTINGS {
let _ = stmt.execute(rusqlite::params![k, *v]);
}
}
Ok(applied)
}
type BoxedCall = Box<dyn FnOnce(&mut Connection) + Send>;
enum Msg {
Call(BoxedCall),
Shutdown,
}
pub struct Writer {
tx: Sender<Msg>,
path: PathBuf,
alive: Arc<AtomicBool>,
}
impl Writer {
pub fn start(path: &Path) -> Result<Self> {
let conn = open(path, false)?;
let (tx, rx) = unbounded::<Msg>();
let alive = Arc::new(AtomicBool::new(true));
let alive_thread = alive.clone();
let thread_path = path.to_path_buf();
std::thread::Builder::new()
.name("db-writer".into())
.spawn(move || {
let mut conn = conn;
alive_thread.store(true, Ordering::SeqCst);
for msg in rx.iter() {
match msg {
Msg::Call(f) => f(&mut conn),
Msg::Shutdown => break,
}
}
let _ = conn.pragma_update(None, "wal_checkpoint", "TRUNCATE");
alive_thread.store(false, Ordering::SeqCst);
})
.map_err(|e| Error::db(format!("spawn writer: {e}")))?;
Ok(Self { tx, path: thread_path, alive })
}
pub fn path(&self) -> &Path {
&self.path
}
fn is_alive(&self) -> bool {
self.alive.load(Ordering::SeqCst)
}
pub(crate) fn call<T>(&self, f: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static) -> Result<T>
where
T: Send + 'static,
{
let (reply_tx, reply_rx) = bounded::<Result<T>>(1);
self.send(Box::new(move |conn| {
let _ = reply_tx.send(f(conn));
}))?;
reply_rx
.recv()
.map_err(|_| Error::db("writer actor gone"))?
}
pub(crate) fn tx<T>(
&self,
f: impl FnOnce(&mut rusqlite::Transaction<'_>) -> Result<T> + Send + 'static,
) -> Result<T>
where
T: Send + 'static,
{
self.call(move |conn| {
let mut tx = conn
.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
.map_err(|e| Error::db(e.to_string()))?;
let out = f(&mut tx)?;
tx.commit().map_err(|e| Error::db(e.to_string()))?;
Ok(out)
})
}
pub(crate) fn send(&self, f: BoxedCall) -> Result<()> {
if !self.is_alive() {
return Err(Error::db("writer actor gone"));
}
self.tx
.send(Msg::Call(f))
.map_err(|_| Error::db("writer actor gone"))
}
pub fn shutdown(&self) {
let _ = self.tx.send(Msg::Shutdown);
}
}
#[cfg(feature = "test-support")]
impl Writer {
pub fn tx_for_tests<T>(
&self,
f: impl FnOnce(&mut rusqlite::Transaction<'_>) -> Result<T> + Send + 'static,
) -> Result<T>
where
T: Send + 'static,
{
self.tx(f)
}
}
pub(crate) struct Readers {
path: PathBuf,
}
thread_local! {
static POOL: std::cell::RefCell<Vec<(PathBuf, Connection)>> = const { std::cell::RefCell::new(Vec::new()) };
}
impl Readers {
pub fn new(path: &Path) -> Self {
Self { path: path.to_path_buf() }
}
pub fn with<T>(&self, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
let path = self.path.clone();
POOL.with(|pool| {
let mut pool = pool.borrow_mut();
if pool.iter().position(|(p, _)| p == &path).is_none() {
pool.push((path.clone(), open(&path, true)?));
}
let idx = pool
.iter()
.position(|(p, _)| p == &path)
.ok_or_else(|| Error::db("reader pool lost entry"))?;
// We only ever use one connection at a time per thread, and `f`
// receives &Connection rather than &Readers, so it cannot re-enter.
let conn = &pool[idx].1;
f(conn)
})
}
}
#[derive(Clone)]
pub struct Db {
pub writer: Arc<Writer>,
pub(crate) readers: Arc<Readers>,
}
impl Db {
pub fn open(cfg: &Config) -> Result<Self> {
let path = cfg.db_path();
migrate(&path)?;
Self::open_migrated(&path)
}
pub fn open_migrated(path: &Path) -> Result<Self> {
Ok(Self {
writer: Arc::new(Writer::start(path)?),
readers: Arc::new(Readers::new(path)),
})
}
pub fn read<T>(&self, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
self.readers.with(f)
}
}
pub fn backup_to(writer: &Writer, dest: &Path) -> Result<()> {
let dest_s = dest.display().to_string();
writer.call(move |conn| {
conn.execute("VACUUM INTO ?1", rusqlite::params![dest_s])
.map_err(|e| Error::db(e.to_string()))?;
Ok(())
})
}
pub fn schema_version(path: &Path) -> Result<i64> {
let conn = rusqlite::Connection::open(path)
.map_err(|e| Error::db(format!("{} does not open: {e}", path.display())))?;
conn.query_row("PRAGMA user_version", [], |r| r.get(0))
.map_err(|e| Error::db(format!("{} has no schema version: {e}", path.display())))
}
|