steid

@jamesgill /

steid/src/application/instance.rs
Rust7.4 KBCode·Blame·History·Raw
1//! What an operator is told about a whole instance.
2//!
3//! Not a page and not an actor's view of anything: the caller is a control plane
4//! holding the operator token, which is a machine credential compared at the transport
5//! rather than a user of the site — see `AppConfig::operator_token`. So this use case
6//! takes no [`Actor`](crate::domain::Actor), and the one rule it does carry is about
7//! what may be said to *whom*: [`InstanceReport::claimed`] is public and everything
8//! else is not.
9
10use crate::domain::repository::{RepoRepository, UserRepository};
11
12use super::{
13 claim::is_claimed,
14 error::Result,
15 port::{DiskReport, DiskUsage},
16};
17
18/// The one fact about an instance that is safe to tell anybody.
19///
20/// A provisioner polls this between booting a machine and handing its owner a claim
21/// link, so it has to answer before anyone has signed in. It says nothing else:
22/// version, size and uptime are all fingerprinting material for a stranger and are
23/// gated behind the operator token.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub struct InstanceState {
26 pub claimed: bool,
27}
28
29/// Everything an operator may be told, the public fact included.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct InstanceReport {
32 pub claimed: bool,
33 /// Repositories on the machine, private ones counted — a size, not a listing.
34 pub repositories: u64,
35 /// Users on the machine. One, on a personal instance, until registration exists.
36 pub users: u64,
37 /// What the instance is costing on disk, and how much is left.
38 ///
39 /// `None` where it could not be measured, which is deliberate and is the same choice
40 /// `git_version` makes: an operator poll also carries whether the instance is
41 /// claimed and what version it runs, and a data directory that cannot be stat'd must
42 /// not take those down with it. The reason goes to the log.
43 pub disk: Option<DiskReport>,
44}
45
46/// Whether this instance has an owner yet, and nothing more.
47pub async fn instance_state(users: &impl UserRepository) -> Result<InstanceState> {
48 Ok(InstanceState {
49 claimed: is_claimed(users).await?,
50 })
51}
52
53/// The operator's view: the public fact plus the counts.
54///
55/// Two queries rather than one, because the two ports are separate and a join across
56/// them would be a repository that knows about both. At one row each on a local SQLite
57/// file, an operator poll is cheaper than the request that carried it.
58pub async fn describe_instance(
59 users: &impl UserRepository,
60 repos: &impl RepoRepository,
61 disk: &impl DiskUsage,
62) -> Result<InstanceReport> {
63 let user_count = users.count().await?;
64
65 Ok(InstanceReport {
66 // Derived from the count rather than asked for separately: a machine with a
67 // user is claimed, and two queries that could disagree is a bug waiting.
68 claimed: user_count > 0,
69 repositories: repos.count().await?,
70 users: user_count,
71 disk: match disk.measure().await {
72 Ok(report) => Some(report),
73 Err(error) => {
74 eprintln!("steid: {error}");
75 None
76 }
77 },
78 })
79}
80
81#[cfg(test)]
82mod tests {
83 use super::*;
84 use crate::{
85 domain::{
86 Email, OrgId, Organization, PasswordHash, RepoId, Repository, User, UserId, Visibility,
87 repository::OrgRepository,
88 },
89 infrastructure::{
90 disk::InMemoryDiskUsage,
91 repository::{InMemoryOrgRepo, InMemoryRepoRepo, InMemoryUserRepo},
92 },
93 };
94 use std::time::{Duration, SystemTime};
95
96 fn report() -> DiskReport {
97 DiskReport {
98 data_dir_bytes: 12,
99 filesystem_total_bytes: 200,
100 filesystem_free_bytes: 188,
101 }
102 }
103
104 fn disk() -> InMemoryDiskUsage {
105 InMemoryDiskUsage::new(report())
106 }
107
108 struct Fixture {
109 users: InMemoryUserRepo,
110 orgs: InMemoryOrgRepo,
111 repos: InMemoryRepoRepo,
112 }
113
114 fn fixture() -> Fixture {
115 Fixture {
116 users: InMemoryUserRepo::new(),
117 orgs: InMemoryOrgRepo::new(),
118 repos: InMemoryRepoRepo::new(),
119 }
120 }
121
122 impl Fixture {
123 async fn add_user(&self, handle: &str, email: &str) -> Organization {
124 let org = Organization::new(OrgId::generate(), handle, None).expect("valid org");
125 self.orgs.save(&org).await.expect("save org");
126
127 let user = User::new(
128 UserId::generate(),
129 Email::new(email).expect("valid email"),
130 PasswordHash::from_trusted("$argon2id$test"),
131 org.id.clone(),
132 );
133 self.users.save(&user).await.expect("save user");
134
135 org
136 }
137
138 async fn add_repo(&self, org: &Organization, name: &str, visibility: Visibility) {
139 let repo = Repository::new(
140 RepoId::generate(),
141 org.id.clone(),
142 name,
143 None,
144 visibility,
145 SystemTime::UNIX_EPOCH + Duration::from_secs(1_000),
146 )
147 .expect("valid repo");
148 self.repos.save(&repo).await.expect("save repo");
149 }
150 }
151
152 #[tokio::test]
153 async fn an_unclaimed_instance_says_so_and_counts_nothing() {
154 let f = fixture();
155
156 assert_eq!(
157 instance_state(&f.users).await.expect("state"),
158 InstanceState { claimed: false }
159 );
160 assert_eq!(
161 describe_instance(&f.users, &f.repos, &disk())
162 .await
163 .expect("report"),
164 InstanceReport {
165 claimed: false,
166 repositories: 0,
167 users: 0,
168 disk: Some(report()),
169 }
170 );
171 }
172
173 #[tokio::test]
174 async fn a_claimed_instance_reports_its_size() {
175 let f = fixture();
176 let org = f.add_user("james", "dev@example.com").await;
177 f.add_repo(&org, "steid", Visibility::Public).await;
178 // Private, so this is the check that the count is a size rather than a listing.
179 f.add_repo(&org, "notes", Visibility::Private).await;
180
181 assert!(instance_state(&f.users).await.expect("state").claimed);
182 assert_eq!(
183 describe_instance(&f.users, &f.repos, &disk())
184 .await
185 .expect("report"),
186 InstanceReport {
187 claimed: true,
188 repositories: 2,
189 users: 1,
190 disk: Some(report()),
191 }
192 );
193 }
194
195 #[tokio::test]
196 async fn a_disk_that_cannot_be_measured_omits_the_numbers_rather_than_failing() {
197 // The rest of the report is what a control plane polls for. A data directory
198 // that cannot be stat'd must not take `claimed` and the version down with it.
199 let f = fixture();
200
201 assert_eq!(
202 describe_instance(&f.users, &f.repos, &InMemoryDiskUsage::unmeasurable())
203 .await
204 .expect("the report still comes back")
205 .disk,
206 None
207 );
208 }
209
210 #[tokio::test]
211 async fn the_two_calls_agree_about_claimed() {
212 let f = fixture();
213 f.add_user("james", "dev@example.com").await;
214
215 assert_eq!(
216 instance_state(&f.users).await.expect("state").claimed,
217 describe_instance(&f.users, &f.repos, &disk())
218 .await
219 .expect("report")
220 .claimed,
221 "the public fact must not depend on which route asked for it"
222 );
223 }
224}