forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.7 MiB37e985dTahinli2 hours ago363 commits

server_settings.rs1377 lines, 37.3 KiBHistoryRawDownload
1use std::collections::{BTreeMap, BTreeSet};
2use std::net::IpAddr;
3use std::sync::{Arc, RwLock};
4
5use ipnet::IpNet;
6
7use crate::config::{
8 BannerLevel, Config, MailTransport, OrgCreation, R2Jurisdiction, Registration, StorageBackend,
9};
10use crate::error::{Error, Result};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum Kind {
14 Live,
15 Restart,
16 ReadOnly,
17}
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum Group {
21 General,
22 Limits,
23 Storage,
24 Backups,
25 Integrations,
26 Alerts,
27}
28
29impl Group {
30 pub const ALL: [Group; 6] = [
31 Group::General,
32 Group::Limits,
33 Group::Storage,
34 Group::Backups,
35 Group::Integrations,
36 Group::Alerts,
37 ];
38}
39
40string_enum!(Group {
41 General = "general",
42 Limits = "limits",
43 Storage = "storage",
44 Backups = "backups",
45 Integrations = "integrations",
46 Alerts = "alerts",
47});
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum Ty {
51 Bool,
52 Uint(u64, u64),
53 Text,
54 Path,
55 Choice(&'static [&'static str]),
56 List,
57 Secret,
58 Addr,
59}
60
61#[derive(Debug, Clone, Copy)]
62pub struct Field {
63 pub key: &'static str,
64 pub group: Group,
65 pub kind: Kind,
66 pub ty: Ty,
67 pub label: &'static str,
68 pub help: &'static str,
69 get: fn(&Config) -> String,
70 set: fn(&mut Config, &str),
71 check: fn(&str) -> Option<String>,
72}
73
74impl Field {
75 pub fn is_secret(&self) -> bool {
76 self.ty == Ty::Secret
77 }
78}
79
80fn no_check(_: &str) -> Option<String> {
81 None
82}
83
84fn expires_check(raw: &str) -> Option<String> {
85 (!raw.is_empty() && crate::config::parse_banner_expiry(raw).is_none())
86 .then(|| "must look like 2026-12-31 18:00".to_owned())
87}
88
89fn message_check(raw: &str) -> Option<String> {
90 (raw.chars().count() > 300).then(|| "must be at most 300 characters".to_owned())
91}
92
93fn proxies_check(raw: &str) -> Option<String> {
94 split_list(raw)
95 .into_iter()
96 .find(|item| item.parse::<IpNet>().is_err() && item.parse::<IpAddr>().is_err())
97 .map(|item| format!("invalid trusted proxy `{item}`"))
98}
99
100#[allow(clippy::too_many_arguments)]
101const fn f(
102 key: &'static str,
103 group: Group,
104 kind: Kind,
105 ty: Ty,
106 label: &'static str,
107 help: &'static str,
108 get: fn(&Config) -> String,
109 set: fn(&mut Config, &str),
110) -> Field {
111 Field {
112 key,
113 group,
114 kind,
115 ty,
116 label,
117 help,
118 get,
119 set,
120 check: no_check,
121 }
122}
123
124use Group::{Alerts, Backups, General, Integrations, Limits, Storage};
125use Kind::{Live as L, ReadOnly as R, Restart as X};
126
127const REGISTRATION: &[&str] = &[
128 Registration::Closed.as_str(),
129 Registration::Invite.as_str(),
130 Registration::Open.as_str(),
131];
132const BANNER_LEVEL: &[&str] = &[BannerLevel::Info.as_str(), BannerLevel::Warning.as_str()];
133const ORG_CREATION: &[&str] = &[OrgCreation::All.as_str(), OrgCreation::Admin.as_str()];
134const MAIL_TRANSPORT: &[&str] = &[MailTransport::Smtp.as_str(), MailTransport::Log.as_str()];
135const BACKEND: &[&str] = &[
136 StorageBackend::Fs.as_str(),
137 StorageBackend::S3.as_str(),
138 StorageBackend::R2.as_str(),
139];
140const JURISDICTION: &[&str] = &[
141 R2Jurisdiction::Global.as_str(),
142 R2Jurisdiction::Eu.as_str(),
143 R2Jurisdiction::Fedramp.as_str(),
144];
145const MB: Ty = Ty::Uint(1, 1_048_576);
146const PORT: Ty = Ty::Uint(1, 65_535);
147
148pub static FIELDS: &[Field] = &[
149 f(
150 "registration",
151 General,
152 L,
153 Ty::Choice(REGISTRATION),
154 "Registration",
155 "Who may create an account: closed, invite only, or open.",
156 |c| c.registration.as_str().into(),
157 |c, v| c.registration = v.parse().unwrap_or_default(),
158 ),
159 f(
160 "orgs.creation",
161 General,
162 L,
163 Ty::Choice(ORG_CREATION),
164 "Organization creation",
165 "Who may create an organization: all signed-in people, or admins only.",
166 |c| c.orgs.creation.as_str().into(),
167 |c, v| c.orgs.creation = v.parse().unwrap_or_default(),
168 ),
169 Field {
170 check: message_check,
171 ..f(
172 "banner.message",
173 General,
174 L,
175 Ty::Text,
176 "Announcement banner",
177 "One line shown under the header on every page. Empty hides it.",
178 |c| c.banner.message.clone(),
179 |c, v| c.banner.message = v.to_owned(),
180 )
181 },
182 f(
183 "banner.level",
184 General,
185 L,
186 Ty::Choice(BANNER_LEVEL),
187 "Banner level",
188 "Info or warning.",
189 |c| c.banner.level.as_str().into(),
190 |c, v| c.banner.level = v.parse().unwrap_or_default(),
191 ),
192 Field {
193 check: expires_check,
194 ..f(
195 "banner.expires",
196 General,
197 L,
198 Ty::Text,
199 "Banner expires (UTC)",
200 "As YYYY-MM-DD HH:MM. Empty keeps the banner until it is cleared.",
201 |c| c.banner.expires.clone(),
202 |c, v| c.banner.expires = v.to_owned(),
203 )
204 },
205 Field {
206 check: proxies_check,
207 ..f(
208 "trusted_proxies",
209 General,
210 L,
211 Ty::List,
212 "Trusted proxies",
213 "Addresses or CIDR networks whose X-Forwarded-For header is trusted. Comma separated.",
214 |c| {
215 c.trusted_proxies
216 .iter()
217 .map(ToString::to_string)
218 .collect::<Vec<_>>()
219 .join(", ")
220 },
221 |c, v| {
222 c.trusted_proxies = split_list(v)
223 .iter()
224 .filter_map(|e| {
225 e.parse::<IpNet>()
226 .ok()
227 .or_else(|| e.parse::<IpAddr>().ok().map(IpNet::from))
228 })
229 .collect()
230 },
231 )
232 },
233 f(
234 "base_url",
235 General,
236 X,
237 Ty::Text,
238 "Base URL",
239 "Public URL used in links and clone URLs.",
240 |c| c.base_url.clone(),
241 |c, v| c.base_url = v.to_owned(),
242 ),
243 f(
244 "user_content_base_url",
245 General,
246 X,
247 Ty::Text,
248 "User content URL",
249 "Separate origin that serves raw user files.",
250 |c| c.user_content_base_url.clone(),
251 |c, v| c.user_content_base_url = v.to_owned(),
252 ),
253 f(
254 "ssh_public_host",
255 General,
256 X,
257 Ty::Text,
258 "SSH host shown",
259 "Host in SSH clone URLs.",
260 |c| c.ssh_public_host.clone(),
261 |c, v| c.ssh_public_host = v.to_owned(),
262 ),
263 f(
264 "ssh_public_port",
265 General,
266 X,
267 PORT,
268 "SSH port shown",
269 "Port in SSH clone URLs.",
270 |c| c.ssh_public_port.to_string(),
271 |c, v| c.ssh_public_port = n(v) as u16,
272 ),
273 f(
274 "listen",
275 General,
276 R,
277 Ty::Addr,
278 "HTTP listen address",
279 "Set in the config file.",
280 |c| c.listen.to_string(),
281 |_, _| {},
282 ),
283 f(
284 "user_content_listen",
285 General,
286 R,
287 Ty::Addr,
288 "User content listen address",
289 "Set in the config file.",
290 |c| c.user_content_listen.to_string(),
291 |_, _| {},
292 ),
293 f(
294 "ssh_listen",
295 General,
296 R,
297 Ty::Addr,
298 "SSH listen address",
299 "Set in the config file.",
300 |c| c.ssh_listen.to_string(),
301 |_, _| {},
302 ),
303 f(
304 "database",
305 General,
306 R,
307 Ty::Path,
308 "Database file",
309 "Set in the config file.",
310 |c| c.database.to_string_lossy().into_owned(),
311 |_, _| {},
312 ),
313 f(
314 "data_dir",
315 General,
316 R,
317 Ty::Path,
318 "Data directory",
319 "Set in the config file.",
320 |c| c.data_dir.to_string_lossy().into_owned(),
321 |_, _| {},
322 ),
323 f(
324 "ci.enabled",
325 Limits,
326 L,
327 Ty::Bool,
328 "CI enabled",
329 "When off, pushes and pull requests create no runs.",
330 |c| c.ci.enabled.to_string(),
331 |c, v| c.ci.enabled = b(v),
332 ),
333 f(
334 "ci.max_log_mb",
335 Limits,
336 L,
337 MB,
338 "Largest job log (MiB)",
339 "A longer log is truncated.",
340 |c| c.ci.max_log_mb.to_string(),
341 |c, v| c.ci.max_log_mb = n(v),
342 ),
343 f(
344 "ci.max_artifact_mb",
345 Limits,
346 L,
347 MB,
348 "Largest artifact (MiB)",
349 "",
350 |c| c.ci.max_artifact_mb.to_string(),
351 |c, v| c.ci.max_artifact_mb = n(v),
352 ),
353 f(
354 "ci.max_artifacts_per_job",
355 Limits,
356 L,
357 Ty::Uint(1, 100_000),
358 "Artifacts per job",
359 "",
360 |c| c.ci.max_artifacts_per_job.to_string(),
361 |c, v| c.ci.max_artifacts_per_job = n(v) as u32,
362 ),
363 f(
364 "ci.max_job_artifacts_mb",
365 Limits,
366 L,
367 MB,
368 "Largest total of one job's artifacts (MiB)",
369 "",
370 |c| c.ci.max_job_artifacts_mb.to_string(),
371 |c, v| c.ci.max_job_artifacts_mb = n(v),
372 ),
373 f(
374 "ci.log_retention_days",
375 Limits,
376 L,
377 Ty::Uint(1, 36_500),
378 "Log retention (days)",
379 "",
380 |c| c.ci.log_retention_days.to_string(),
381 |c, v| c.ci.log_retention_days = n(v),
382 ),
383 f(
384 "ci.artifact_retention_days",
385 Limits,
386 L,
387 Ty::Uint(1, 36_500),
388 "Artifact retention (days)",
389 "",
390 |c| c.ci.artifact_retention_days.to_string(),
391 |c, v| c.ci.artifact_retention_days = n(v),
392 ),
393 f(
394 "ci.artifact_keep_runs",
395 Limits,
396 L,
397 Ty::Uint(0, 100_000),
398 "Artifact runs kept per repo",
399 "0 keeps all.",
400 |c| c.ci.artifact_keep_runs.to_string(),
401 |c, v| c.ci.artifact_keep_runs = n(v) as u32,
402 ),
403 f(
404 "ci.artifact_max_total_mb",
405 Limits,
406 L,
407 Ty::Uint(0, 100_000_000),
408 "Artifact disk limit (MiB)",
409 "Oldest runs' artifacts go first. 0 is no limit.",
410 |c| c.ci.artifact_max_total_mb.to_string(),
411 |c, v| c.ci.artifact_max_total_mb = n(v),
412 ),
413 f(
414 "ci.registration_token_hours",
415 Limits,
416 L,
417 Ty::Uint(1, 8_760),
418 "Runner token lifetime (hours)",
419 "How long a runner registration token stays valid.",
420 |c| c.ci.registration_token_hours.to_string(),
421 |c, v| c.ci.registration_token_hours = n(v) as u32,
422 ),
423 f(
424 "lfs.max_object_mb",
425 Limits,
426 L,
427 MB,
428 "Largest LFS object (MiB)",
429 "",
430 |c| c.lfs.max_object_mb.to_string(),
431 |c, v| c.lfs.max_object_mb = n(v),
432 ),
433 f(
434 "releases.max_asset_mb",
435 Limits,
436 L,
437 MB,
438 "Largest release asset (MiB)",
439 "",
440 |c| c.releases.max_asset_mb.to_string(),
441 |c, v| c.releases.max_asset_mb = n(v),
442 ),
443 f(
444 "storage.backend",
445 Storage,
446 X,
447 Ty::Choice(BACKEND),
448 "Backend",
449 "Where release assets and CI artifacts live: fs, r2 or s3.",
450 |c| c.storage.backend.as_str().into(),
451 |c, v| c.storage.backend = v.parse().unwrap_or_default(),
452 ),
453 f(
454 "storage.r2.account_id",
455 Storage,
456 X,
457 Ty::Text,
458 "R2 account id",
459 "32 character hex string from the Cloudflare dashboard.",
460 |c| c.storage.r2.account_id.clone(),
461 |c, v| c.storage.r2.account_id = v.to_owned(),
462 ),
463 f(
464 "storage.r2.bucket",
465 Storage,
466 X,
467 Ty::Text,
468 "R2 bucket",
469 "",
470 |c| c.storage.r2.bucket.clone(),
471 |c, v| c.storage.r2.bucket = v.to_owned(),
472 ),
473 f(
474 "storage.r2.jurisdiction",
475 Storage,
476 X,
477 Ty::Choice(JURISDICTION),
478 "R2 jurisdiction",
479 "eu, fedramp, or empty for the global default.",
480 |c| c.storage.r2.jurisdiction.as_str().into(),
481 |c, v| c.storage.r2.jurisdiction = v.parse().unwrap_or_default(),
482 ),
483 f(
484 "storage.r2.prefix",
485 Storage,
486 X,
487 Ty::Text,
488 "R2 key prefix",
489 "",
490 |c| c.storage.r2.prefix.clone(),
491 |c, v| c.storage.r2.prefix = v.to_owned(),
492 ),
493 f(
494 "storage.r2.access_key_id",
495 Storage,
496 X,
497 Ty::Text,
498 "R2 access key id",
499 "",
500 |c| c.storage.r2.access_key_id.clone(),
501 |c, v| c.storage.r2.access_key_id = v.to_owned(),
502 ),
503 f(
504 "storage.r2.secret_access_key_file",
505 Storage,
506 X,
507 Ty::Path,
508 "R2 secret key file",
509 "Path of the file that holds the secret access key. The key itself is never read here.",
510 |c| {
511 c.storage
512 .r2
513 .secret_access_key_file
514 .to_string_lossy()
515 .into_owned()
516 },
517 |c, v| c.storage.r2.secret_access_key_file = v.into(),
518 ),
519 f(
520 "storage.s3.bucket",
521 Storage,
522 X,
523 Ty::Text,
524 "S3 bucket",
525 "",
526 |c| c.storage.s3.bucket.clone(),
527 |c, v| c.storage.s3.bucket = v.to_owned(),
528 ),
529 f(
530 "storage.s3.region",
531 Storage,
532 X,
533 Ty::Text,
534 "S3 region",
535 "",
536 |c| c.storage.s3.region.clone(),
537 |c, v| c.storage.s3.region = v.to_owned(),
538 ),
539 f(
540 "storage.s3.endpoint",
541 Storage,
542 X,
543 Ty::Text,
544 "S3 endpoint",
545 "Leave empty for AWS.",
546 |c| c.storage.s3.endpoint.clone(),
547 |c, v| c.storage.s3.endpoint = v.to_owned(),
548 ),
549 f(
550 "storage.s3.prefix",
551 Storage,
552 X,
553 Ty::Text,
554 "S3 key prefix",
555 "",
556 |c| c.storage.s3.prefix.clone(),
557 |c, v| c.storage.s3.prefix = v.to_owned(),
558 ),
559 f(
560 "storage.s3.access_key_id",
561 Storage,
562 X,
563 Ty::Text,
564 "S3 access key id",
565 "",
566 |c| c.storage.s3.access_key_id.clone(),
567 |c, v| c.storage.s3.access_key_id = v.to_owned(),
568 ),
569 f(
570 "storage.s3.secret_access_key_file",
571 Storage,
572 X,
573 Ty::Path,
574 "S3 secret key file",
575 "Path of the file that holds the secret access key.",
576 |c| {
577 c.storage
578 .s3
579 .secret_access_key_file
580 .to_string_lossy()
581 .into_owned()
582 },
583 |c, v| c.storage.s3.secret_access_key_file = v.into(),
584 ),
585 f(
586 "storage.s3.allow_http",
587 Storage,
588 X,
589 Ty::Bool,
590 "S3 allow http",
591 "",
592 |c| c.storage.s3.allow_http.to_string(),
593 |c, v| c.storage.s3.allow_http = b(v),
594 ),
595 f(
596 "storage.s3.virtual_hosted_style",
597 Storage,
598 X,
599 Ty::Bool,
600 "S3 virtual hosted style",
601 "",
602 |c| c.storage.s3.virtual_hosted_style.to_string(),
603 |c, v| c.storage.s3.virtual_hosted_style = b(v),
604 ),
605 f(
606 "backup.dir",
607 Backups,
608 X,
609 Ty::Path,
610 "Backup directory",
611 "Empty turns scheduled backups off.",
612 |c| c.backup.dir.to_string_lossy().into_owned(),
613 |c, v| c.backup.dir = v.into(),
614 ),
615 f(
616 "backup.interval_hours",
617 Backups,
618 X,
619 Ty::Uint(1, 8_760),
620 "Backup interval (hours)",
621 "",
622 |c| c.backup.interval_hours.to_string(),
623 |c, v| c.backup.interval_hours = n(v),
624 ),
625 f(
626 "backup.keep",
627 Backups,
628 X,
629 Ty::Uint(1, 10_000),
630 "Backup sets kept",
631 "",
632 |c| c.backup.keep.to_string(),
633 |c, v| c.backup.keep = n(v) as usize,
634 ),
635 f(
636 "backup.fsck_interval_days",
637 Backups,
638 X,
639 Ty::Uint(1, 3_650),
640 "fsck interval (days)",
641 "",
642 |c| c.backup.fsck_interval_days.to_string(),
643 |c, v| c.backup.fsck_interval_days = n(v),
644 ),
645 f(
646 "backup.healthcheck_url",
647 Backups,
648 X,
649 Ty::Secret,
650 "Backup healthcheck URL",
651 "May hold a token, so it is write-only.",
652 |c| c.backup.healthcheck_url.clone(),
653 |c, v| c.backup.healthcheck_url = v.to_owned(),
654 ),
655 f(
656 "replication.target",
657 Backups,
658 X,
659 Ty::Text,
660 "Replication target",
661 "Empty turns standby replication off.",
662 |c| c.replication.target.clone(),
663 |c, v| c.replication.target = v.to_owned(),
664 ),
665 f(
666 "replication.ssh_port",
667 Backups,
668 X,
669 PORT,
670 "Replication SSH port",
671 "",
672 |c| c.replication.ssh_port.to_string(),
673 |c, v| c.replication.ssh_port = n(v) as u16,
674 ),
675 f(
676 "replication.identity_file",
677 Backups,
678 X,
679 Ty::Path,
680 "Replication identity file",
681 "",
682 |c| c.replication.identity_file.to_string_lossy().into_owned(),
683 |c, v| c.replication.identity_file = v.into(),
684 ),
685 f(
686 "replication.known_hosts_file",
687 Backups,
688 X,
689 Ty::Path,
690 "Replication known hosts file",
691 "",
692 |c| {
693 c.replication
694 .known_hosts_file
695 .to_string_lossy()
696 .into_owned()
697 },
698 |c, v| c.replication.known_hosts_file = v.into(),
699 ),
700 f(
701 "replication.db_snapshot_minutes",
702 Backups,
703 X,
704 Ty::Uint(1, 525_600),
705 "Database snapshot (minutes)",
706 "",
707 |c| c.replication.db_snapshot_minutes.to_string(),
708 |c, v| c.replication.db_snapshot_minutes = n(v),
709 ),
710 f(
711 "replication.reconcile_minutes",
712 Backups,
713 X,
714 Ty::Uint(1, 525_600),
715 "Reconcile (minutes)",
716 "",
717 |c| c.replication.reconcile_minutes.to_string(),
718 |c, v| c.replication.reconcile_minutes = n(v),
719 ),
720 f(
721 "replication.healthcheck_url",
722 Backups,
723 X,
724 Ty::Secret,
725 "Replication healthcheck URL",
726 "May hold a token, so it is write-only.",
727 |c| c.replication.healthcheck_url.clone(),
728 |c, v| c.replication.healthcheck_url = v.to_owned(),
729 ),
730 f(
731 "webhooks.allow_http",
732 Integrations,
733 X,
734 Ty::Bool,
735 "Allow http webhooks",
736 "Permit http:// hook URLs besides https://.",
737 |c| c.webhooks.allow_http.to_string(),
738 |c, v| c.webhooks.allow_http = b(v),
739 ),
740 f(
741 "webhooks.allowed_hosts",
742 Integrations,
743 X,
744 Ty::List,
745 "Webhook allowed hosts",
746 "Hostnames or CIDR networks reachable even when they resolve to internal addresses. Comma separated.",
747 |c| c.webhooks.allowed_hosts.join(", "),
748 |c, v| c.webhooks.allowed_hosts = split_list(v),
749 ),
750 f(
751 "mail.transport",
752 Integrations,
753 X,
754 Ty::Choice(MAIL_TRANSPORT),
755 "Mail transport",
756 "smtp sends mail, log writes it to a directory. The SMTP account is on the Mail page.",
757 |c| c.mail.transport.as_str().into(),
758 |c, v| c.mail.transport = v.parse().unwrap_or_default(),
759 ),
760 f(
761 "self_update.enabled",
762 Integrations,
763 X,
764 Ty::Bool,
765 "Self-update",
766 "Deploy the artifact of a green run of the forge's own repo.",
767 |c| c.self_update.enabled.to_string(),
768 |c, v| c.self_update.enabled = b(v),
769 ),
770 f(
771 "self_update.repo",
772 Integrations,
773 X,
774 Ty::Text,
775 "Self-update repo",
776 "As owner/name.",
777 |c| c.self_update.repo.clone(),
778 |c, v| c.self_update.repo = v.to_owned(),
779 ),
780 f(
781 "self_update.branch",
782 Integrations,
783 X,
784 Ty::Text,
785 "Self-update branch",
786 "",
787 |c| c.self_update.branch.clone(),
788 |c, v| c.self_update.branch = v.to_owned(),
789 ),
790 f(
791 "self_update.job",
792 Integrations,
793 X,
794 Ty::Text,
795 "Self-update job",
796 "",
797 |c| c.self_update.job.clone(),
798 |c, v| c.self_update.job = v.to_owned(),
799 ),
800 f(
801 "self_update.artifact",
802 Integrations,
803 X,
804 Ty::Text,
805 "Self-update artifact",
806 "{target} becomes this server's arch-os, e.g. forge-{target} is forge-x86_64-linux.",
807 |c| c.self_update.artifact.clone(),
808 |c, v| c.self_update.artifact = v.to_owned(),
809 ),
810 f(
811 "alerts.enabled",
812 Alerts,
813 L,
814 Ty::Bool,
815 "Admin alerts",
816 "Master switch. Off raises and sends nothing.",
817 |c| c.alerts.enabled.to_string(),
818 |c, v| c.alerts.enabled = b(v),
819 ),
820 f(
821 "alerts.email",
822 Alerts,
823 L,
824 Ty::Bool,
825 "Email alerts",
826 "Also email the admins who have a verified address.",
827 |c| c.alerts.email.to_string(),
828 |c, v| c.alerts.email = b(v),
829 ),
830 f(
831 "alerts.runner_offline_minutes",
832 Alerts,
833 L,
834 Ty::Uint(1, 1_440),
835 "Runner offline after (minutes)",
836 "A runner with no heartbeat for this long raises an alert.",
837 |c| c.alerts.runner_offline_minutes.to_string(),
838 |c, v| c.alerts.runner_offline_minutes = n(v),
839 ),
840 f(
841 "alerts.disk_free_percent",
842 Alerts,
843 L,
844 Ty::Uint(1, 90),
845 "Low disk space (percent free)",
846 "Alert when the data directory has less than this free.",
847 |c| c.alerts.disk_free_percent.to_string(),
848 |c, v| c.alerts.disk_free_percent = n(v),
849 ),
850 f(
851 "alerts.disk_free_gib",
852 Alerts,
853 L,
854 Ty::Uint(0, 100_000),
855 "Low disk space (GiB free)",
856 "Also alert under this many GiB. 0 turns this check off.",
857 |c| c.alerts.disk_free_gib.to_string(),
858 |c, v| c.alerts.disk_free_gib = n(v),
859 ),
860 f(
861 "alerts.on_runner_offline",
862 Alerts,
863 L,
864 Ty::Bool,
865 "Runner offline alerts",
866 "",
867 |c| c.alerts.on_runner_offline.to_string(),
868 |c, v| c.alerts.on_runner_offline = b(v),
869 ),
870 f(
871 "alerts.on_backup",
872 Alerts,
873 L,
874 Ty::Bool,
875 "Backup alerts",
876 "Failed, unverified or overdue backups, and failed fsck runs.",
877 |c| c.alerts.on_backup.to_string(),
878 |c, v| c.alerts.on_backup = b(v),
879 ),
880 f(
881 "alerts.on_disk",
882 Alerts,
883 L,
884 Ty::Bool,
885 "Disk space alerts",
886 "",
887 |c| c.alerts.on_disk.to_string(),
888 |c, v| c.alerts.on_disk = b(v),
889 ),
890 f(
891 "alerts.on_ci_killed",
892 Alerts,
893 L,
894 Ty::Bool,
895 "Killed CI job alerts",
896 "Jobs killed by SIGKILL or the OOM killer, once per run.",
897 |c| c.alerts.on_ci_killed.to_string(),
898 |c, v| c.alerts.on_ci_killed = b(v),
899 ),
900 f(
901 "alerts.on_self_update",
902 Alerts,
903 L,
904 Ty::Bool,
905 "Self-update alerts",
906 "Deployed, failed, and server restarted.",
907 |c| c.alerts.on_self_update.to_string(),
908 |c, v| c.alerts.on_self_update = b(v),
909 ),
910 f(
911 "alerts.on_replication",
912 Alerts,
913 L,
914 Ty::Bool,
915 "Replication alerts",
916 "Standby failing or lagging.",
917 |c| c.alerts.on_replication.to_string(),
918 |c, v| c.alerts.on_replication = b(v),
919 ),
920];
921
922pub fn field(key: &str) -> Option<&'static Field> {
923 FIELDS.iter().find(|f| f.key == key)
924}
925
926fn invalid(field: &Field, why: &str) -> Error {
927 Error::Invalid(format!("{}: {why}", field.label))
928}
929
930fn split_list(raw: &str) -> Vec<String> {
931 raw.split([',', '\n', '\r'])
932 .map(str::trim)
933 .filter(|s| !s.is_empty())
934 .map(str::to_owned)
935 .collect()
936}
937
938pub fn normalize(field: &Field, raw: &str) -> Result<String> {
939 let raw = raw.trim();
940 match field.ty {
941 Ty::Bool => match raw {
942 "true" | "on" => Ok("true".into()),
943 "false" | "off" | "" => Ok("false".into()),
944 _ => Err(invalid(field, "must be on or off")),
945 },
946 Ty::Uint(min, max) => {
947 let n: u64 = raw
948 .parse()
949 .map_err(|_| invalid(field, "must be a whole number"))?;
950 if n < min || n > max {
951 return Err(invalid(field, &format!("must be between {min} and {max}")));
952 }
953 Ok(n.to_string())
954 }
955 Ty::Choice(options) => {
956 if options.contains(&raw) {
957 Ok(raw.to_owned())
958 } else {
959 let shown: Vec<&str> = options
960 .iter()
961 .map(|o| if o.is_empty() { "(empty)" } else { o })
962 .collect();
963 Err(invalid(
964 field,
965 &format!("must be one of {}", shown.join(", ")),
966 ))
967 }
968 }
969 Ty::Text | Ty::Path | Ty::Secret | Ty::Addr => {
970 if raw.len() > 1024 || raw.chars().any(char::is_control) {
971 return Err(invalid(
972 field,
973 "must be one line of at most 1024 characters",
974 ));
975 }
976 if let Some(why) = (field.check)(raw) {
977 return Err(invalid(field, &why));
978 }
979 Ok(raw.to_owned())
980 }
981 Ty::List => {
982 let items = split_list(raw);
983 if items
984 .iter()
985 .any(|i| i.len() > 253 || i.chars().any(char::is_control))
986 {
987 return Err(invalid(field, "has an entry that is too long"));
988 }
989 if let Some(why) = (field.check)(raw) {
990 return Err(invalid(field, &why));
991 }
992 Ok(items.join(", "))
993 }
994 }
995}
996
997fn b(v: &str) -> bool {
998 v == "true"
999}
1000
1001fn n(v: &str) -> u64 {
1002 v.parse().unwrap_or_default()
1003}
1004
1005pub fn get(cfg: &Config, key: &str) -> String {
1006 field(key).map_or_else(String::new, |f| (f.get)(cfg))
1007}
1008
1009pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> {
1010 let field = field(key).ok_or_else(|| Error::Invalid(format!("unknown setting `{key}`")))?;
1011 if field.kind == Kind::ReadOnly {
1012 return Err(invalid(field, "is read-only"));
1013 }
1014 let v = normalize(field, raw)?;
1015 (field.set)(cfg, &v);
1016 Ok(())
1017}
1018
1019pub fn apply(file: &Config, overrides: &BTreeMap<String, String>) -> Result<Config> {
1020 let mut cfg = file.clone();
1021 for (key, value) in overrides {
1022 if field(key).is_some_and(|f| f.kind != Kind::ReadOnly) {
1023 set(&mut cfg, key, value)?;
1024 }
1025 }
1026 Ok(cfg)
1027}
1028
1029pub fn boot_config(file: &Config, overrides: &BTreeMap<String, String>) -> (Config, Option<Error>) {
1030 match apply(file, overrides).and_then(|c| c.validate().map(|()| c)) {
1031 Ok(config) => (config, None),
1032 Err(e) => (file.clone(), Some(e)),
1033 }
1034}
1035
1036pub fn live_view(boot: &Config, pending: &Config) -> Config {
1037 let mut cfg = boot.clone();
1038 for f in FIELDS.iter().filter(|f| f.kind == Kind::Live) {
1039 let _ = set(&mut cfg, f.key, &get(pending, f.key));
1040 }
1041 cfg
1042}
1043
1044#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1045pub enum Source {
1046 Default,
1047 File,
1048 Ui,
1049}
1050
1051#[derive(Debug, Clone)]
1052pub struct FieldView {
1053 pub field: &'static Field,
1054 pub value: String,
1055 pub file_value: String,
1056 pub source: Source,
1057 pub secret_set: bool,
1058 pub restart_pending: bool,
1059}
1060
1061pub struct Live {
1062 file: Arc<Config>,
1063 file_keys: BTreeSet<String>,
1064 boot: Arc<Config>,
1065 current: RwLock<Arc<Config>>,
1066}
1067
1068impl Live {
1069 pub fn new(file: Arc<Config>, file_keys: BTreeSet<String>, boot: Arc<Config>) -> Live {
1070 Live {
1071 current: RwLock::new(boot.clone()),
1072 file,
1073 file_keys,
1074 boot,
1075 }
1076 }
1077
1078 pub fn current(&self) -> Arc<Config> {
1079 self.current
1080 .read()
1081 .unwrap_or_else(|poisoned| poisoned.into_inner())
1082 .clone()
1083 }
1084
1085 pub fn publish(&self, overrides: &BTreeMap<String, String>) -> Result<()> {
1086 let pending = apply(&self.file, overrides)?;
1087 pending.validate()?;
1088 let live = live_view(&self.boot, &pending);
1089 *self
1090 .current
1091 .write()
1092 .unwrap_or_else(|poisoned| poisoned.into_inner()) = Arc::new(live);
1093 Ok(())
1094 }
1095
1096 pub fn views(&self, overrides: &BTreeMap<String, String>) -> Vec<FieldView> {
1097 let pending = apply(&self.file, overrides).unwrap_or_else(|_| (*self.file).clone());
1098 FIELDS
1099 .iter()
1100 .map(|field| {
1101 let secret = field.is_secret();
1102 let shown = |cfg: &Config| {
1103 if secret {
1104 String::new()
1105 } else {
1106 get(cfg, field.key)
1107 }
1108 };
1109 let editable = field.kind != Kind::ReadOnly;
1110 let source = if editable && overrides.contains_key(field.key) {
1111 Source::Ui
1112 } else if self.file_keys.contains(field.key) {
1113 Source::File
1114 } else {
1115 Source::Default
1116 };
1117 let effective = if editable { &pending } else { &*self.boot };
1118 FieldView {
1119 field,
1120 value: shown(effective),
1121 file_value: shown(&self.file),
1122 source,
1123 secret_set: secret && !get(effective, field.key).is_empty(),
1124 restart_pending: field.kind == Kind::Restart
1125 && get(&pending, field.key) != get(&self.boot, field.key),
1126 }
1127 })
1128 .collect()
1129 }
1130
1131 pub fn plan_save(
1132 &self,
1133 existing: &BTreeMap<String, String>,
1134 group: Group,
1135 submitted: &BTreeMap<String, String>,
1136 ) -> Result<SavePlan> {
1137 let before = apply(&self.file, existing)?;
1138 let mut sets = Vec::new();
1139 let mut clears = Vec::new();
1140 let mut next = existing.clone();
1141 for field in FIELDS
1142 .iter()
1143 .filter(|f| f.group == group && f.kind != Kind::ReadOnly)
1144 {
1145 let Some(raw) = submitted.get(field.key) else {
1146 continue;
1147 };
1148 if field.is_secret() && raw.trim().is_empty() {
1149 continue;
1150 }
1151 let value = normalize(field, raw)?;
1152 if field.is_secret() {
1153 sets.push((field.key.to_owned(), value.clone()));
1154 next.insert(field.key.to_owned(), value);
1155 continue;
1156 }
1157 let has_override = existing.contains_key(field.key);
1158 if value == get(&before, field.key) {
1159 continue;
1160 }
1161 if value == get(&self.file, field.key) {
1162 if has_override {
1163 clears.push(field.key.to_owned());
1164 next.remove(field.key);
1165 }
1166 continue;
1167 }
1168 sets.push((field.key.to_owned(), value.clone()));
1169 next.insert(field.key.to_owned(), value);
1170 }
1171 let pending = apply(&self.file, &next)?;
1172 pending.validate()?;
1173 Ok(SavePlan {
1174 sets,
1175 clears,
1176 overrides: next,
1177 })
1178 }
1179
1180 pub fn plan_reset(
1181 &self,
1182 existing: &BTreeMap<String, String>,
1183 key: &str,
1184 ) -> Result<BTreeMap<String, String>> {
1185 field(key).ok_or_else(|| Error::Invalid(format!("unknown setting `{key}`")))?;
1186 let mut next = existing.clone();
1187 next.remove(key);
1188 apply(&self.file, &next)?.validate()?;
1189 Ok(next)
1190 }
1191}
1192
1193#[derive(Debug)]
1194pub struct SavePlan {
1195 pub sets: Vec<(String, String)>,
1196 pub clears: Vec<String>,
1197 pub overrides: BTreeMap<String, String>,
1198}
1199
1200#[cfg(test)]
1201mod tests {
1202 use super::*;
1203
1204 fn base() -> Config {
1205 toml::from_str(
1206 r#"
1207database = "/tmp/f.db"
1208data_dir = "/tmp"
1209listen = "127.0.0.1:1"
1210base_url = "http://x"
1211user_content_base_url = "http://y"
1212ssh_listen = "127.0.0.1:2"
1213ssh_public_host = "h"
1214ssh_public_port = 22
1215registration = "closed"
1216[ci]
1217max_log_mb = 20
1218"#,
1219 )
1220 .expect("config")
1221 }
1222
1223 fn live() -> Live {
1224 let file = Arc::new(base());
1225 let keys = ["registration", "ci.max_log_mb"]
1226 .into_iter()
1227 .map(String::from)
1228 .collect();
1229 Live::new(file.clone(), keys, file)
1230 }
1231
1232 fn form(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
1233 pairs
1234 .iter()
1235 .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
1236 .collect()
1237 }
1238
1239 #[test]
1240 fn every_field_round_trips_through_get_and_set() {
1241 let cfg = base();
1242 for f in FIELDS.iter().filter(|f| f.kind != Kind::ReadOnly) {
1243 let mut copy = cfg.clone();
1244 set(&mut copy, f.key, &get(&cfg, f.key)).unwrap_or_else(|e| panic!("{}: {e}", f.key));
1245 assert_eq!(get(&copy, f.key), get(&cfg, f.key), "{}", f.key);
1246 }
1247 }
1248
1249 #[test]
1250 fn precedence_ui_over_file_over_default() {
1251 let live = live();
1252 let views = live.views(&BTreeMap::new());
1253 let find = |views: &[FieldView], key: &str| {
1254 views.iter().find(|v| v.field.key == key).cloned().unwrap()
1255 };
1256 assert_eq!(find(&views, "ci.max_log_mb").source, Source::File);
1257 assert_eq!(find(&views, "ci.max_log_mb").value, "20");
1258 assert_eq!(find(&views, "ci.max_artifact_mb").source, Source::Default);
1259 assert_eq!(find(&views, "ci.max_artifact_mb").value, "512");
1260
1261 let over = form(&[("ci.max_log_mb", "99")]);
1262 let views = live.views(&over);
1263 let v = find(&views, "ci.max_log_mb");
1264 assert_eq!(
1265 (v.source, v.value.as_str(), v.file_value.as_str()),
1266 (Source::Ui, "99", "20")
1267 );
1268 }
1269
1270 #[test]
1271 fn live_fields_apply_and_reset_restores_the_file_value() {
1272 let live = live();
1273 assert_eq!(live.current().ci.max_log_mb, 20);
1274 live.publish(&form(&[("ci.max_log_mb", "99"), ("registration", "open")]))
1275 .unwrap();
1276 assert_eq!(live.current().ci.max_log_mb, 99);
1277 assert_eq!(live.current().registration, Registration::Open);
1278 let next = live
1279 .plan_reset(&form(&[("ci.max_log_mb", "99")]), "ci.max_log_mb")
1280 .unwrap();
1281 live.publish(&next).unwrap();
1282 assert_eq!(live.current().ci.max_log_mb, 20);
1283 }
1284
1285 #[test]
1286 fn restart_fields_do_not_apply_until_boot() {
1287 let live = live();
1288 let over = form(&[("base_url", "https://new.example")]);
1289 live.publish(&over).unwrap();
1290 assert_eq!(live.current().base_url, "http://x");
1291 let v = live.views(&over);
1292 let v = v.iter().find(|v| v.field.key == "base_url").unwrap();
1293 assert!(v.restart_pending);
1294 let (boot, err) = boot_config(&base(), &over);
1295 assert!(err.is_none());
1296 assert_eq!(boot.base_url, "https://new.example");
1297 let after = Live::new(Arc::new(base()), Default::default(), Arc::new(boot));
1298 assert!(!after.views(&over).iter().any(|v| v.restart_pending));
1299 }
1300
1301 #[test]
1302 fn validation_rejects_bad_values() {
1303 let live = live();
1304 for (key, value) in [
1305 ("registration", "everyone"),
1306 ("ci.max_log_mb", "0"),
1307 ("ci.max_log_mb", "lots"),
1308 ("trusted_proxies", "not-an-ip"),
1309 ("ssh_public_port", "70000"),
1310 ("storage.r2.jurisdiction", "mars"),
1311 ("listen", "0.0.0.0:1"),
1312 ] {
1313 let mut cfg = base();
1314 assert!(set(&mut cfg, key, value).is_err(), "{key}={value}");
1315 }
1316 let group_form = form(&[("storage.backend", "r2")]);
1317 assert!(
1318 live.plan_save(&BTreeMap::new(), Group::Storage, &group_form)
1319 .is_err()
1320 );
1321 let group_form = form(&[("backup.dir", "/var/backups"), ("backup.keep", "5")]);
1322 assert!(
1323 live.plan_save(&BTreeMap::new(), Group::Backups, &group_form)
1324 .is_ok()
1325 );
1326 }
1327
1328 #[test]
1329 fn save_skips_unchanged_values_and_clears_when_back_at_the_file_value() {
1330 let live = live();
1331 let plan = live
1332 .plan_save(
1333 &BTreeMap::new(),
1334 Group::Limits,
1335 &form(&[
1336 ("ci.max_log_mb", "20"),
1337 ("ci.max_artifact_mb", "512"),
1338 ("ci.enabled", "false"),
1339 ]),
1340 )
1341 .unwrap();
1342 assert_eq!(
1343 plan.sets,
1344 vec![("ci.enabled".to_owned(), "false".to_owned())]
1345 );
1346 let existing = form(&[("ci.max_log_mb", "99")]);
1347 let plan = live
1348 .plan_save(&existing, Group::Limits, &form(&[("ci.max_log_mb", "20")]))
1349 .unwrap();
1350 assert_eq!(plan.clears, vec!["ci.max_log_mb".to_owned()]);
1351 assert!(plan.overrides.is_empty());
1352 }
1353
1354 #[test]
1355 fn secrets_are_never_in_a_view_and_blank_keeps_the_stored_value() {
1356 let live = live();
1357 let existing = form(&[("backup.healthcheck_url", "https://hc.example/token-123")]);
1358 let views = live.views(&existing);
1359 let v = views
1360 .iter()
1361 .find(|v| v.field.key == "backup.healthcheck_url")
1362 .unwrap();
1363 assert!(v.secret_set && v.value.is_empty() && v.file_value.is_empty());
1364 let plan = live
1365 .plan_save(
1366 &existing,
1367 Group::Backups,
1368 &form(&[("backup.healthcheck_url", "")]),
1369 )
1370 .unwrap();
1371 assert!(plan.sets.is_empty());
1372 assert_eq!(plan.overrides, existing);
1373 for view in &views {
1374 assert!(!view.value.contains("token-123"));
1375 }
1376 }
1377}