Release management in Builder › Releases, optional vs required updates. Builder picks client binaries, each is uploaded with progress, checked (embedded yumush-target marker must be an exact x86_64 v1/v3 build, ELF/PE must match, never released before) and zstd-19 packed by the server (60 MB -> 20 MB)
Browse files at this commite4e5341d525a9b075117f3878e7882114bfdc39cParent: b9f353c- feat
- release management in Builder › Releases, optional vs required updates. Builder picks client binaries, each is uploaded with progress, checked (embedded yumush-target marker must be an exact x86_64 v1/v3 build, ELF/PE must match, never released before) and zstd-19 packed by the server (60 MB -> 20 MB)
- Publish only enables when every file is ready and targets are distinct
- any release can be flipped to required. Server keeps release/release_file tables, serves only the newest file per target and identifies clients by the sha256 of their exe (unknown builds are never touched). Clients check on every connect and on Event::Release: optional updates show an Update button with progress and Restart in the sidebar
- required ones (or an outdated protocol) block login with a full-screen progress view and restart by themselves. Builds come from cargo release-v1 / release-v3 aliases
- the release scripts are gone
44 changed files +1726 -196
- .cargo/config.toml +4 -0
- Cargo.lock +39 -0
- crates/client/Cargo.toml +1 -0
- crates/client/build.rs +40 -0
- crates/client/lang/en/builder.txt +1 -0
- crates/client/lang/en/builder_log.txt +4 -0
- crates/client/lang/en/builder_release.txt +9 -0
- crates/client/lang/en/update.txt +7 -0
- crates/client/lang/tr/builder.txt +1 -0
- crates/client/lang/tr/builder_log.txt +4 -0
- crates/client/lang/tr/builder_release.txt +9 -0
- crates/client/lang/tr/update.txt +7 -0
- crates/client/src/gui.rs +27 -2
- crates/client/src/gui/builder.rs +26 -1
- crates/client/src/gui/builder/log.rs +19 -1
- crates/client/src/gui/builder/releases.rs +442 -0
- crates/client/src/gui/chat.rs +1 -1
- crates/client/src/gui/sidebar.rs +1 -0
- crates/client/src/gui/update_view.rs +111 -0
- crates/client/src/net/events.rs +3 -0
- crates/client/src/net/link.rs +62 -4
- crates/client/src/net/mod.rs +18 -0
- crates/client/src/update.rs +251 -75
- crates/common/src/call.rs +21 -2
- crates/common/src/error.rs +18 -0
- crates/common/src/event.rs +1 -0
- crates/common/src/model.rs +30 -0
- crates/common/src/open.rs +6 -0
- crates/common/src/session.rs +1 -0
- crates/common/src/update.rs +80 -9
- crates/server/Cargo.toml +1 -0
- crates/server/src/authentication.rs +1 -1
- crates/server/src/call/mod.rs +4 -0
- crates/server/src/call/release.rs +84 -0
- crates/server/src/db/mod.rs +1 -0
- crates/server/src/db/release.rs +137 -0
- crates/server/src/db/schema.sql +15 -0
- crates/server/src/hub.rs +18 -3
- crates/server/src/lib.rs +6 -2
- crates/server/src/network.rs +19 -5
- crates/server/src/request.rs +1 -1
- crates/server/src/update.rs +195 -41
- packaging/release-windows.ps1 +0 -14
- packaging/release.sh +0 -34
.cargo/config.tomlmodified+4 -0
| @@ -24,3 +24,7 @@ rustflags = [ | ||
| 24 | 24 | "-C", "link-arg=/OPT:REF", |
| 25 | 25 | "-C", "link-arg=/OPT:ICF" |
| 26 | 26 | ] |
| 27 | + | |
| 28 | +[alias] | |
| 29 | +release-v1 = ["build", "--release", "-p", "client", "--target-dir", "target/v1", "--config", "target.'cfg(target_arch = \"x86_64\")'.rustflags = ['-C', 'target-cpu=x86-64']"] | |
| 30 | +release-v3 = ["build", "--release", "-p", "client", "--target-dir", "target/v3", "--config", "target.'cfg(target_arch = \"x86_64\")'.rustflags = ['-C', 'target-cpu=x86-64-v3']"] |
Cargo.lockmodified+39 -0
| @@ -1297,6 +1297,7 @@ dependencies = [ | ||
| 1297 | 1297 | "resvg 0.50.0", |
| 1298 | 1298 | "rtrb", |
| 1299 | 1299 | "rustls-platform-verifier", |
| 1300 | + "ruzstd", | |
| 1300 | 1301 | "self-replace", |
| 1301 | 1302 | "spectrum", |
| 1302 | 1303 | "sys-locale", |
| @@ -7892,6 +7893,15 @@ dependencies = [ | ||
| 7892 | 7893 | "unicode-script", |
| 7893 | 7894 | ] |
| 7894 | 7895 | |
| 7896 | +[[package]] | |
| 7897 | +name = "ruzstd" | |
| 7898 | +version = "0.9.1" | |
| 7899 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 7900 | +checksum = "69e4ce4a039f42bf25920b95667e4d789e98749ab11bbb8d2c2936f788421bb5" | |
| 7901 | +dependencies = [ | |
| 7902 | + "twox-hash", | |
| 7903 | +] | |
| 7904 | + | |
| 7895 | 7905 | [[package]] |
| 7896 | 7906 | name = "ryu" |
| 7897 | 7907 | version = "1.0.23" |
| @@ -8192,6 +8202,7 @@ dependencies = [ | ||
| 8192 | 8202 | "tracing-subscriber", |
| 8193 | 8203 | "turso", |
| 8194 | 8204 | "usage", |
| 8205 | + "zstd", | |
| 8195 | 8206 | ] |
| 8196 | 8207 | |
| 8197 | 8208 | [[package]] |
| @@ -11738,6 +11749,34 @@ dependencies = [ | ||
| 11738 | 11749 | "windows-sys 0.61.2", |
| 11739 | 11750 | ] |
| 11740 | 11751 | |
| 11752 | +[[package]] | |
| 11753 | +name = "zstd" | |
| 11754 | +version = "0.14.5" | |
| 11755 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 11756 | +checksum = "465cb081cac3a28a84ef547702dba1fe0f4a9f22e4e57a0b675ceee028c2af80" | |
| 11757 | +dependencies = [ | |
| 11758 | + "zstd-safe", | |
| 11759 | +] | |
| 11760 | + | |
| 11761 | +[[package]] | |
| 11762 | +name = "zstd-safe" | |
| 11763 | +version = "8.4.0" | |
| 11764 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 11765 | +checksum = "9b09bddd92c53b91833f4df03e0ea07e02d8367cfcd15a3b9acda94fc273f793" | |
| 11766 | +dependencies = [ | |
| 11767 | + "zstd-sys", | |
| 11768 | +] | |
| 11769 | + | |
| 11770 | +[[package]] | |
| 11771 | +name = "zstd-sys" | |
| 11772 | +version = "2.2.0+zstd.1.6.0" | |
| 11773 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 11774 | +checksum = "c3f4089cda6dda4dc43c43dd9f8964140064fd2f752f3da46c3a483c3c175160" | |
| 11775 | +dependencies = [ | |
| 11776 | + "cc", | |
| 11777 | + "pkg-config", | |
| 11778 | +] | |
| 11779 | + | |
| 11741 | 11780 | [[package]] |
| 11742 | 11781 | name = "zune-core" |
| 11743 | 11782 | version = "0.4.12" |
crates/client/Cargo.tomlmodified+1 -0
| @@ -35,6 +35,7 @@ image = { version = "0.25.10", default-features = false, features = ["jpeg", "pn | ||
| 35 | 35 | rtrb = "0.4.1" |
| 36 | 36 | gethostname = "1.1.0" |
| 37 | 37 | self-replace = "1.5.1" |
| 38 | +ruzstd = "0.9.1" | |
| 38 | 39 | rustls-platform-verifier = "0.7.1" |
| 39 | 40 | flate2 = "1.1.11" |
| 40 | 41 | emojis = "0.9.1" |
crates/client/build.rsmodified+40 -0
| @@ -20,12 +20,34 @@ const COLORS: [&str; 10] = [ | ||
| 20 | 20 | "ground", "raise", "hov", "press", "thread", "off", "faint", "dim", "paper", "bad", |
| 21 | 21 | ]; |
| 22 | 22 | const SCALES: [&str; 6] = ["space", "radius", "stroke", "text", "size", "leading"]; |
| 23 | +const V1: &[&str] = &["fxsr", "sse", "sse2"]; | |
| 24 | +const V3: &[&str] = &[ | |
| 25 | + "avx", | |
| 26 | + "avx2", | |
| 27 | + "bmi1", | |
| 28 | + "bmi2", | |
| 29 | + "cmpxchg16b", | |
| 30 | + "f16c", | |
| 31 | + "fma", | |
| 32 | + "fxsr", | |
| 33 | + "lzcnt", | |
| 34 | + "movbe", | |
| 35 | + "popcnt", | |
| 36 | + "sse", | |
| 37 | + "sse2", | |
| 38 | + "sse3", | |
| 39 | + "sse4.1", | |
| 40 | + "sse4.2", | |
| 41 | + "ssse3", | |
| 42 | + "xsave", | |
| 43 | +]; | |
| 23 | 44 | const MEDIA_FOUNDATION: [&str; 3] = ["mf.dll", "mfplat.dll", "mfreadwrite.dll"]; |
| 24 | 45 | |
| 25 | 46 | fn main() { |
| 26 | 47 | println!("cargo::rerun-if-changed={SOURCE}"); |
| 27 | 48 | icons(); |
| 28 | 49 | words(); |
| 50 | + target(); | |
| 29 | 51 | if env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") { |
| 30 | 52 | for dll in MEDIA_FOUNDATION { |
| 31 | 53 | println!("cargo::rustc-link-arg-bins=/DELAYLOAD:{dll}"); |
| @@ -346,3 +368,21 @@ fn holes(text: &str) -> Vec<String> { | ||
| 346 | 368 | holes.dedup(); |
| 347 | 369 | holes |
| 348 | 370 | } |
| 371 | + | |
| 372 | +fn target() { | |
| 373 | + let arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default(); | |
| 374 | + let os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(); | |
| 375 | + let features = env::var("CARGO_CFG_TARGET_FEATURE").unwrap_or_default(); | |
| 376 | + let mut features: Vec<&str> = features | |
| 377 | + .split(',') | |
| 378 | + .filter(|feature| !feature.is_empty() && *feature != "crt-static") | |
| 379 | + .collect(); | |
| 380 | + features.sort_unstable(); | |
| 381 | + let target = match (arch.as_str(), features.as_slice()) { | |
| 382 | + ("x86_64", V1) => format!("x86_64_v1-{os}"), | |
| 383 | + ("x86_64", V3) => format!("x86_64_v3-{os}"), | |
| 384 | + ("x86_64", _) => "custom".to_string(), | |
| 385 | + _ => format!("{arch}-{os}"), | |
| 386 | + }; | |
| 387 | + println!("cargo::rustc-env=YUMUSH_TARGET={target}"); | |
| 388 | +} |
crates/client/lang/en/builder.txtmodified+1 -0
| @@ -11,3 +11,4 @@ ghost = Ghost | ||
| 11 | 11 | refresh = Refresh |
| 12 | 12 | save = Save |
| 13 | 13 | export = Export |
| 14 | +releases = Releases |
crates/client/lang/en/builder_log.txtmodified+4 -0
| @@ -32,6 +32,10 @@ ghost_voice = {actor} listened in {community} as ghost for {seconds}s | ||
| 32 | 32 | backup_created = {actor} created backup {name} |
| 33 | 33 | backup_deleted = {actor} deleted backup {name} |
| 34 | 34 | backup_downloaded = {actor} exported backup {name} |
| 35 | +release_published = {actor} published release {seq} | |
| 36 | +release_published_required = {actor} published required release {seq} | |
| 37 | +release_required = {actor} made release {seq} required | |
| 38 | +release_optional = {actor} made release {seq} optional | |
| 35 | 39 | unknown_user = Unknown user |
| 36 | 40 | apply = Apply |
| 37 | 41 | no_entries = No entries |
crates/client/lang/en/builder_release.txtadded+9 -0
| @@ -0,0 +1,9 @@ | ||
| 1 | +add_files = Add files | |
| 2 | +draft = Upload | |
| 3 | +published = Published | |
| 4 | +compressing = Compressing | |
| 5 | +duplicate = Duplicate target | |
| 6 | +required = Required | |
| 7 | +publish = Publish | |
| 8 | +confirm = Confirm | |
| 9 | +no_releases = No releases |
crates/client/lang/en/update.txtadded+7 -0
| @@ -0,0 +1,7 @@ | ||
| 1 | +update = Update | |
| 2 | +restart = Restart | |
| 3 | +retry = Retry | |
| 4 | +required = Update required | |
| 5 | +downloading = Downloading | |
| 6 | +installing = Installing | |
| 7 | +restarting = Restarting |
crates/client/lang/tr/builder.txtmodified+1 -0
| @@ -11,3 +11,4 @@ ghost = Hayalet | ||
| 11 | 11 | refresh = Yenile |
| 12 | 12 | save = Kaydet |
| 13 | 13 | export = Dışa aktar |
| 14 | +releases = Sürümler |
crates/client/lang/tr/builder_log.txtmodified+4 -0
| @@ -32,6 +32,10 @@ ghost_voice = {actor} hayalet olarak dinledi: {community} ({seconds} sn) | ||
| 32 | 32 | backup_created = {actor} yedek oluşturdu: {name} |
| 33 | 33 | backup_deleted = {actor} yedeği sildi: {name} |
| 34 | 34 | backup_downloaded = {actor} yedeği dışa aktardı: {name} |
| 35 | +release_published = {actor} {seq}. sürümü yayınladı | |
| 36 | +release_published_required = {actor} zorunlu {seq}. sürümü yayınladı | |
| 37 | +release_required = {actor} {seq}. sürümü zorunlu yaptı | |
| 38 | +release_optional = {actor} {seq}. sürümü isteğe bağlı yaptı | |
| 35 | 39 | unknown_user = Bilinmeyen kullanıcı |
| 36 | 40 | apply = Uygula |
| 37 | 41 | no_entries = Kayıt yok |
crates/client/lang/tr/builder_release.txtadded+9 -0
| @@ -0,0 +1,9 @@ | ||
| 1 | +add_files = Dosya ekle | |
| 2 | +draft = Yükle | |
| 3 | +published = Yayınlananlar | |
| 4 | +compressing = Sıkıştırılıyor | |
| 5 | +duplicate = Aynı hedef tekrarlı | |
| 6 | +required = Zorunlu | |
| 7 | +publish = Yayınla | |
| 8 | +confirm = Onayla | |
| 9 | +no_releases = Sürüm yok |
crates/client/lang/tr/update.txtadded+7 -0
| @@ -0,0 +1,7 @@ | ||
| 1 | +update = Güncelle | |
| 2 | +restart = Yeniden başlat | |
| 3 | +retry = Tekrar dene | |
| 4 | +required = Güncelleme gerekli | |
| 5 | +downloading = İndiriliyor | |
| 6 | +installing = Kuruluyor | |
| 7 | +restarting = Yeniden başlatılıyor |
crates/client/src/gui.rsmodified+27 -2
| @@ -66,6 +66,7 @@ mod stream_stats; | ||
| 66 | 66 | pub mod style; |
| 67 | 67 | mod surface; |
| 68 | 68 | mod tow; |
| 69 | +mod update_view; | |
| 69 | 70 | mod voice_note; |
| 70 | 71 | mod voice_settings; |
| 71 | 72 | mod voice_stats; |
| @@ -603,6 +604,8 @@ pub struct Yumush { | ||
| 603 | 604 | deferred: Vec<NetworkEvent>, |
| 604 | 605 | backups: Vec<BackupInfo>, |
| 605 | 606 | pending_backup_delete: Option<String>, |
| 607 | + update: crate::update::Phase, | |
| 608 | + desk: builder::releases::Desk, | |
| 606 | 609 | share_apps: Vec<crate::share::audio::AudioApp>, |
| 607 | 610 | share_apps_seen: std::cell::Cell<Instant>, |
| 608 | 611 | share_apps_task: Option<gpui_kit::Task<()>>, |
| @@ -656,6 +659,23 @@ impl Yumush { | ||
| 656 | 659 | }) |
| 657 | 660 | .detach(); |
| 658 | 661 | |
| 662 | + let mut phase = crate::update::subscribe(); | |
| 663 | + cx.spawn(async move |this, cx| { | |
| 664 | + loop { | |
| 665 | + let now = *phase.borrow_and_update(); | |
| 666 | + let alive = this | |
| 667 | + .update(cx, |yumush, cx| { | |
| 668 | + yumush.update = now; | |
| 669 | + cx.notify(); | |
| 670 | + }) | |
| 671 | + .is_ok(); | |
| 672 | + if !alive || phase.changed().await.is_err() { | |
| 673 | + break; | |
| 674 | + } | |
| 675 | + } | |
| 676 | + }) | |
| 677 | + .detach(); | |
| 678 | + | |
| 659 | 679 | sidebar::wander(cx); |
| 660 | 680 | let voice = VoiceControls::new(&settings.voice, window, cx); |
| 661 | 681 | |
| @@ -685,6 +705,8 @@ impl Yumush { | ||
| 685 | 705 | deferred: Vec::new(), |
| 686 | 706 | backups: Vec::new(), |
| 687 | 707 | pending_backup_delete: None, |
| 708 | + update: crate::update::Phase::Idle, | |
| 709 | + desk: builder::releases::Desk::default(), | |
| 688 | 710 | share_apps: Vec::new(), |
| 689 | 711 | share_apps_seen: std::cell::Cell::new(Instant::now()), |
| 690 | 712 | share_apps_task: None, |
| @@ -1274,6 +1296,7 @@ impl Yumush { | ||
| 1274 | 1296 | self.apply_pushed(Event::CommunityDeleted { community_id }, cx); |
| 1275 | 1297 | } |
| 1276 | 1298 | Event::ReportCreated => self.report_created(window, cx), |
| 1299 | + Event::Release => self.releases_changed(window, cx), | |
| 1277 | 1300 | Event::SettingsUpdated(settings) => self.server = Some(settings), |
| 1278 | 1301 | event => { |
| 1279 | 1302 | let voice = matches!( |
| @@ -1464,11 +1487,13 @@ impl Render for Yumush { | ||
| 1464 | 1487 | self.schedule_pump(window, cx); |
| 1465 | 1488 | let palette = palette(cx); |
| 1466 | 1489 | let route = self.current_route; |
| 1490 | + let required = self.update.required(); | |
| 1467 | 1491 | let page = match route { |
| 1492 | + _ if required => self.update_required(palette).into_any_element(), | |
| 1468 | 1493 | Route::Login | Route::Register => self.auth_page(route, cx).into_any_element(), |
| 1469 | 1494 | Route::Chat => self.chat_page(cx).into_any_element(), |
| 1470 | 1495 | }; |
| 1471 | - let banner = (route == Route::Chat) | |
| 1496 | + let banner = (route == Route::Chat && !required) | |
| 1472 | 1497 | .then(|| connection_notice(&self.connection, palette)) |
| 1473 | 1498 | .flatten(); |
| 1474 | 1499 | |
| @@ -1510,7 +1535,7 @@ impl Render for Yumush { | ||
| 1510 | 1535 | .children(banner) |
| 1511 | 1536 | .child(div().flex_1().min_h_0().child(page)) |
| 1512 | 1537 | .children( |
| 1513 | - (route == Route::Chat) | |
| 1538 | + (route == Route::Chat && !required) | |
| 1514 | 1539 | .then(|| self.jump_box(palette, cx)) |
| 1515 | 1540 | .flatten(), |
| 1516 | 1541 | ) |
crates/client/src/gui/builder.rsmodified+26 -1
| @@ -4,6 +4,7 @@ mod communities; | ||
| 4 | 4 | mod log; |
| 5 | 5 | mod messages; |
| 6 | 6 | mod overview; |
| 7 | +pub(super) mod releases; | |
| 7 | 8 | mod reports; |
| 8 | 9 | mod server; |
| 9 | 10 | mod storage; |
| @@ -53,11 +54,12 @@ pub(super) enum BuilderTab { | ||
| 53 | 54 | Access, |
| 54 | 55 | Reports, |
| 55 | 56 | Server, |
| 57 | + Releases, | |
| 56 | 58 | Log, |
| 57 | 59 | } |
| 58 | 60 | |
| 59 | 61 | impl BuilderTab { |
| 60 | - pub(super) const ALL: [Self; 10] = [ | |
| 62 | + pub(super) const ALL: [Self; 11] = [ | |
| 61 | 63 | Self::Overview, |
| 62 | 64 | Self::Users, |
| 63 | 65 | Self::Communities, |
| @@ -67,6 +69,7 @@ impl BuilderTab { | ||
| 67 | 69 | Self::Access, |
| 68 | 70 | Self::Reports, |
| 69 | 71 | Self::Server, |
| 72 | + Self::Releases, | |
| 70 | 73 | Self::Log, |
| 71 | 74 | ]; |
| 72 | 75 | |
| @@ -81,6 +84,7 @@ impl BuilderTab { | ||
| 81 | 84 | Self::Access => "access", |
| 82 | 85 | Self::Reports => "reports", |
| 83 | 86 | Self::Server => "server", |
| 87 | + Self::Releases => "releases", | |
| 84 | 88 | Self::Log => "log", |
| 85 | 89 | } |
| 86 | 90 | } |
| @@ -97,6 +101,7 @@ impl BuilderTab { | ||
| 97 | 101 | Self::Access => w.access, |
| 98 | 102 | Self::Reports => w.reports, |
| 99 | 103 | Self::Server => w.server, |
| 104 | + Self::Releases => w.releases, | |
| 100 | 105 | Self::Log => w.log, |
| 101 | 106 | } |
| 102 | 107 | } |
| @@ -131,6 +136,7 @@ impl Yumush { | ||
| 131 | 136 | BuilderTab::Access => self.access_body(entity, palette), |
| 132 | 137 | BuilderTab::Reports => self.reports_body(entity, palette), |
| 133 | 138 | BuilderTab::Server => self.server_body(entity, palette), |
| 139 | + BuilderTab::Releases => self.releases_body(entity, palette), | |
| 134 | 140 | BuilderTab::Log => self.log_body(entity, palette), |
| 135 | 141 | }; |
| 136 | 142 | let mut sections = vec![ |
| @@ -187,6 +193,18 @@ impl Yumush { | ||
| 187 | 193 | ) |
| 188 | 194 | .into_any_element(), |
| 189 | 195 | ], |
| 196 | + BuilderTab::Releases => vec![ | |
| 197 | + parts::button( | |
| 198 | + "add_release_files".to_string(), | |
| 199 | + w().builder_release.add_files, | |
| 200 | + Press::Plain, | |
| 201 | + palette.tokens, | |
| 202 | + entity_action(entity, |yumush, window, cx| { | |
| 203 | + yumush.pick_release_files(window, cx) | |
| 204 | + }), | |
| 205 | + ) | |
| 206 | + .into_any_element(), | |
| 207 | + ], | |
| 190 | 208 | BuilderTab::Log => vec![ |
| 191 | 209 | icon_button( |
| 192 | 210 | "export_builder_log".to_string(), |
| @@ -282,6 +300,7 @@ impl Yumush { | ||
| 282 | 300 | BuilderTab::Access => self.load_access(window, cx), |
| 283 | 301 | BuilderTab::Reports => self.load_reports(window, cx), |
| 284 | 302 | BuilderTab::Server => {} |
| 303 | + BuilderTab::Releases => self.load_releases(window, cx), | |
| 285 | 304 | BuilderTab::Log => { |
| 286 | 305 | self.load_users(window, cx); |
| 287 | 306 | self.load_builder_logs(window, cx); |
| @@ -361,6 +380,12 @@ impl Yumush { | ||
| 361 | 380 | ); |
| 362 | 381 | } |
| 363 | 382 | |
| 383 | + pub(super) fn releases_changed(&self, window: &mut Window, cx: &mut Context<Self>) { | |
| 384 | + if self.chat.view == View::Builder && self.chat.builder_tab == BuilderTab::Releases { | |
| 385 | + self.load_releases(window, cx); | |
| 386 | + } | |
| 387 | + } | |
| 388 | + | |
| 364 | 389 | pub(super) fn voice_changed(&self, window: &mut Window, cx: &mut Context<Self>) { |
| 365 | 390 | if self.chat.view == View::Builder && self.chat.builder_tab == BuilderTab::Voice { |
| 366 | 391 | self.load_voice_rooms(window, cx); |
crates/client/src/gui/builder/log.rsmodified+19 -1
| @@ -75,6 +75,22 @@ fn builder_log_text(entry: &AdminLogEntry) -> String { | ||
| 75 | 75 | AdminAction::BackupCreated { name } => words.backup_created(actor, name), |
| 76 | 76 | AdminAction::BackupDeleted { name } => words.backup_deleted(actor, name), |
| 77 | 77 | AdminAction::BackupDownloaded { name } => words.backup_downloaded(actor, name), |
| 78 | + AdminAction::ReleasePublished { | |
| 79 | + seq, | |
| 80 | + required: true, | |
| 81 | + } => words.release_published_required(actor, seq), | |
| 82 | + AdminAction::ReleasePublished { | |
| 83 | + seq, | |
| 84 | + required: false, | |
| 85 | + } => words.release_published(actor, seq), | |
| 86 | + AdminAction::ReleaseRequired { | |
| 87 | + seq, | |
| 88 | + required: true, | |
| 89 | + } => words.release_required(actor, seq), | |
| 90 | + AdminAction::ReleaseRequired { | |
| 91 | + seq, | |
| 92 | + required: false, | |
| 93 | + } => words.release_optional(actor, seq), | |
| 78 | 94 | } |
| 79 | 95 | } |
| 80 | 96 | |
| @@ -166,7 +182,9 @@ fn action_icon(action: &AdminAction) -> IconName { | ||
| 166 | 182 | | AdminAction::GhostVoice { .. } => IconName::Eye, |
| 167 | 183 | AdminAction::BackupCreated { .. } |
| 168 | 184 | | AdminAction::BackupDeleted { .. } |
| 169 | - | AdminAction::BackupDownloaded { .. } => IconName::HardDrive, | |
| 185 | + | AdminAction::BackupDownloaded { .. } | |
| 186 | + | AdminAction::ReleasePublished { .. } | |
| 187 | + | AdminAction::ReleaseRequired { .. } => IconName::HardDrive, | |
| 170 | 188 | } |
| 171 | 189 | } |
| 172 | 190 |
crates/client/src/gui/builder/releases.rsadded+442 -0
| @@ -0,0 +1,442 @@ | ||
| 1 | +use common::{ | |
| 2 | + call::{ListReleases, PublishRelease, SetReleaseRequired}, | |
| 3 | + model::{ReleaseInfo, Staged}, | |
| 4 | +}; | |
| 5 | +use gpui_kit::{ | |
| 6 | + AnyElement, Context, Div, Entity, Hsla, IntoElement, ParentElement, PathPromptOptions, Styled, | |
| 7 | + Window, assets::IconName, component::Icon, div, px, | |
| 8 | +}; | |
| 9 | +use std::path::PathBuf; | |
| 10 | + | |
| 11 | +use super::ui::{card, card_header, confirmed, delete_icon_button, list_row, rows_body}; | |
| 12 | +use crate::gui::{ | |
| 13 | + Palette, Yumush, entity_action, millis_time, notify_error, | |
| 14 | + parts::{self, Fill, Press}, | |
| 15 | + storage, | |
| 16 | + style::{size, space, text}, | |
| 17 | + text, | |
| 18 | +}; | |
| 19 | +use crate::lang::w; | |
| 20 | + | |
| 21 | +#[derive(Default)] | |
| 22 | +pub(crate) struct Desk { | |
| 23 | + drafts: Vec<Draft>, | |
| 24 | + next: u64, | |
| 25 | + required: bool, | |
| 26 | + publishing: bool, | |
| 27 | + releases: Vec<ReleaseInfo>, | |
| 28 | + pending_required: Option<u64>, | |
| 29 | +} | |
| 30 | + | |
| 31 | +struct Draft { | |
| 32 | + id: u64, | |
| 33 | + name: String, | |
| 34 | + size: u64, | |
| 35 | + stage: Stage, | |
| 36 | +} | |
| 37 | + | |
| 38 | +enum Stage { | |
| 39 | + Uploading(u64), | |
| 40 | + Ready(Staged), | |
| 41 | + Failed(String), | |
| 42 | +} | |
| 43 | + | |
| 44 | +fn is_duplicate(drafts: &[Draft], index: usize) -> bool { | |
| 45 | + let Stage::Ready(staged) = &drafts[index].stage else { | |
| 46 | + return false; | |
| 47 | + }; | |
| 48 | + drafts[..index] | |
| 49 | + .iter() | |
| 50 | + .any(|draft| matches!(&draft.stage, Stage::Ready(other) if other.target == staged.target)) | |
| 51 | +} | |
| 52 | + | |
| 53 | +impl Desk { | |
| 54 | + fn can_publish(&self) -> bool { | |
| 55 | + !self.publishing | |
| 56 | + && !self.drafts.is_empty() | |
| 57 | + && self.drafts.iter().enumerate().all(|(index, draft)| { | |
| 58 | + matches!(draft.stage, Stage::Ready(_)) && !is_duplicate(&self.drafts, index) | |
| 59 | + }) | |
| 60 | + } | |
| 61 | + | |
| 62 | + fn draft(&mut self, id: u64) -> Option<&mut Draft> { | |
| 63 | + self.drafts.iter_mut().find(|draft| draft.id == id) | |
| 64 | + } | |
| 65 | +} | |
| 66 | + | |
| 67 | +fn caption_text(value: impl Into<String>, color: Hsla) -> Div { | |
| 68 | + div() | |
| 69 | + .text_size(text(text::CAPTION)) | |
| 70 | + .text_color(color) | |
| 71 | + .child(value.into()) | |
| 72 | +} | |
| 73 | + | |
| 74 | +fn draft_row(draft: &Draft, duplicate: bool, entity: &Entity<Yumush>, palette: Palette) -> Div { | |
| 75 | + let id = draft.id; | |
| 76 | + let status = match &draft.stage { | |
| 77 | + Stage::Uploading(sent) if *sent >= draft.size => { | |
| 78 | + caption_text(w().builder_release.compressing, palette.muted) | |
| 79 | + } | |
| 80 | + Stage::Uploading(sent) => { | |
| 81 | + let share = *sent as f32 / draft.size.max(1) as f32; | |
| 82 | + div() | |
| 83 | + .flex() | |
| 84 | + .items_center() | |
| 85 | + .gap(px(space::SM)) | |
| 86 | + .child(parts::track(Fill::Part(share), false, palette.tokens)) | |
| 87 | + .child(caption_text(format!("{:.0}%", share * 100.), palette.muted)) | |
| 88 | + } | |
| 89 | + Stage::Ready(_) if duplicate => caption_text(w().builder_release.duplicate, palette.danger), | |
| 90 | + Stage::Ready(staged) => caption_text( | |
| 91 | + format!( | |
| 92 | + "{} · {} → {}", | |
| 93 | + staged.target, | |
| 94 | + storage(staged.size), | |
| 95 | + storage(staged.packed) | |
| 96 | + ), | |
| 97 | + palette.muted, | |
| 98 | + ), | |
| 99 | + Stage::Failed(error) => caption_text(error.clone(), palette.danger), | |
| 100 | + }; | |
| 101 | + | |
| 102 | + list_row() | |
| 103 | + .child( | |
| 104 | + div() | |
| 105 | + .flex_1() | |
| 106 | + .min_w_0() | |
| 107 | + .flex() | |
| 108 | + .flex_col() | |
| 109 | + .child( | |
| 110 | + div() | |
| 111 | + .truncate() | |
| 112 | + .text_size(text(text::LABEL)) | |
| 113 | + .text_color(palette.text) | |
| 114 | + .child(draft.name.clone()), | |
| 115 | + ) | |
| 116 | + .child(status), | |
| 117 | + ) | |
| 118 | + .child(delete_icon_button( | |
| 119 | + format!("remove_draft_{id}"), | |
| 120 | + false, | |
| 121 | + palette, | |
| 122 | + entity_action(entity, move |yumush, _, cx| yumush.remove_draft(id, cx)), | |
| 123 | + )) | |
| 124 | +} | |
| 125 | + | |
| 126 | +fn release_row( | |
| 127 | + release: &ReleaseInfo, | |
| 128 | + pending: bool, | |
| 129 | + entity: &Entity<Yumush>, | |
| 130 | + palette: Palette, | |
| 131 | +) -> Div { | |
| 132 | + let seq = release.seq; | |
| 133 | + let required = release.required; | |
| 134 | + let targets = release | |
| 135 | + .files | |
| 136 | + .iter() | |
| 137 | + .map(|file| file.target.as_str()) | |
| 138 | + .collect::<Vec<_>>() | |
| 139 | + .join(", "); | |
| 140 | + let online: u64 = release.files.iter().map(|file| file.online).sum(); | |
| 141 | + let control = if pending && !required { | |
| 142 | + parts::button( | |
| 143 | + format!("confirm_release_{seq}"), | |
| 144 | + w().builder_release.confirm, | |
| 145 | + Press::Danger, | |
| 146 | + palette.tokens, | |
| 147 | + entity_action(entity, move |yumush, window, cx| { | |
| 148 | + yumush.set_release_required(seq, true, window, cx) | |
| 149 | + }), | |
| 150 | + ) | |
| 151 | + .into_any_element() | |
| 152 | + } else { | |
| 153 | + parts::toggle( | |
| 154 | + format!("release_required_{seq}"), | |
| 155 | + required, | |
| 156 | + palette.tokens, | |
| 157 | + entity_action(entity, move |yumush, window, cx| { | |
| 158 | + yumush.toggle_release_required(seq, !required, window, cx) | |
| 159 | + }), | |
| 160 | + ) | |
| 161 | + .into_any_element() | |
| 162 | + }; | |
| 163 | + | |
| 164 | + list_row() | |
| 165 | + .child( | |
| 166 | + div() | |
| 167 | + .flex_1() | |
| 168 | + .min_w_0() | |
| 169 | + .flex() | |
| 170 | + .flex_col() | |
| 171 | + .child( | |
| 172 | + div() | |
| 173 | + .text_size(text(text::LABEL)) | |
| 174 | + .text_color(palette.text) | |
| 175 | + .child(format!("#{seq}")), | |
| 176 | + ) | |
| 177 | + .child( | |
| 178 | + div() | |
| 179 | + .truncate() | |
| 180 | + .text_size(text(text::CAPTION)) | |
| 181 | + .text_color(palette.muted) | |
| 182 | + .child(targets), | |
| 183 | + ), | |
| 184 | + ) | |
| 185 | + .child(caption_text( | |
| 186 | + millis_time(release.created_ms, w().common.date), | |
| 187 | + palette.muted, | |
| 188 | + )) | |
| 189 | + .child( | |
| 190 | + div() | |
| 191 | + .flex() | |
| 192 | + .items_center() | |
| 193 | + .gap(px(space::XS)) | |
| 194 | + .child( | |
| 195 | + Icon::new(IconName::Users) | |
| 196 | + .size(px(size::ICON)) | |
| 197 | + .text_color(palette.muted), | |
| 198 | + ) | |
| 199 | + .child(caption_text(online.to_string(), palette.muted)), | |
| 200 | + ) | |
| 201 | + .child(control) | |
| 202 | +} | |
| 203 | + | |
| 204 | +impl Yumush { | |
| 205 | + pub(super) fn releases_body(&self, entity: &Entity<Self>, palette: Palette) -> Vec<AnyElement> { | |
| 206 | + let mut body = Vec::new(); | |
| 207 | + if !self.desk.drafts.is_empty() { | |
| 208 | + body.push(self.draft_card(entity, palette).into_any_element()); | |
| 209 | + } | |
| 210 | + body.push(self.releases_card(entity, palette).into_any_element()); | |
| 211 | + body | |
| 212 | + } | |
| 213 | + | |
| 214 | + fn draft_card(&self, entity: &Entity<Self>, palette: Palette) -> Div { | |
| 215 | + let drafts = &self.desk.drafts; | |
| 216 | + let rows: Vec<Div> = drafts | |
| 217 | + .iter() | |
| 218 | + .enumerate() | |
| 219 | + .map(|(index, draft)| draft_row(draft, is_duplicate(drafts, index), entity, palette)) | |
| 220 | + .collect(); | |
| 221 | + let publish = if self.desk.can_publish() { | |
| 222 | + parts::button( | |
| 223 | + "publish_release", | |
| 224 | + w().builder_release.publish, | |
| 225 | + Press::Primary, | |
| 226 | + palette.tokens, | |
| 227 | + entity_action(entity, |yumush, window, cx| { | |
| 228 | + yumush.publish_release(window, cx) | |
| 229 | + }), | |
| 230 | + ) | |
| 231 | + .into_any_element() | |
| 232 | + } else { | |
| 233 | + parts::button( | |
| 234 | + "publish_release", | |
| 235 | + w().builder_release.publish, | |
| 236 | + Press::Primary, | |
| 237 | + palette.tokens, | |
| 238 | + |_, _| {}, | |
| 239 | + ) | |
| 240 | + .opacity(0.4) | |
| 241 | + .into_any_element() | |
| 242 | + }; | |
| 243 | + let required = parts::labeled_toggle( | |
| 244 | + "release_draft_required", | |
| 245 | + w().builder_release.required, | |
| 246 | + self.desk.required, | |
| 247 | + palette.tokens, | |
| 248 | + entity_action(entity, |yumush, _, cx| { | |
| 249 | + yumush.desk.required = !yumush.desk.required; | |
| 250 | + cx.notify(); | |
| 251 | + }), | |
| 252 | + ); | |
| 253 | + | |
| 254 | + card(palette) | |
| 255 | + .child(card_header(w().builder_release.draft, Vec::new(), palette)) | |
| 256 | + .child(div().flex().flex_col().children(rows)) | |
| 257 | + .child(list_row().justify_between().child(required).child(publish)) | |
| 258 | + } | |
| 259 | + | |
| 260 | + fn releases_card(&self, entity: &Entity<Self>, palette: Palette) -> Div { | |
| 261 | + let pending = self.desk.pending_required; | |
| 262 | + let rows: Vec<Div> = self | |
| 263 | + .desk | |
| 264 | + .releases | |
| 265 | + .iter() | |
| 266 | + .map(|release| release_row(release, pending == Some(release.seq), entity, palette)) | |
| 267 | + .collect(); | |
| 268 | + | |
| 269 | + card(palette) | |
| 270 | + .child(card_header( | |
| 271 | + w().builder_release.published, | |
| 272 | + Vec::new(), | |
| 273 | + palette, | |
| 274 | + )) | |
| 275 | + .child(rows_body(rows, w().builder_release.no_releases, palette)) | |
| 276 | + } | |
| 277 | + | |
| 278 | + pub(super) fn load_releases(&self, window: &mut Window, cx: &mut Context<Self>) { | |
| 279 | + self.fetch_builder( | |
| 280 | + window, | |
| 281 | + cx, | |
| 282 | + |network| async move { network.call(ListReleases).await }, | |
| 283 | + |yumush, releases: Vec<ReleaseInfo>, cx| { | |
| 284 | + yumush.desk.releases = releases; | |
| 285 | + cx.notify(); | |
| 286 | + }, | |
| 287 | + ); | |
| 288 | + } | |
| 289 | + | |
| 290 | + pub(super) fn pick_release_files(&self, window: &mut Window, cx: &mut Context<Self>) { | |
| 291 | + let picked = cx.prompt_for_paths(PathPromptOptions { | |
| 292 | + files: true, | |
| 293 | + directories: false, | |
| 294 | + multiple: true, | |
| 295 | + prompt: None, | |
| 296 | + }); | |
| 297 | + | |
| 298 | + cx.spawn_in(window, async move |this, cx| { | |
| 299 | + let Ok(Ok(Some(paths))) = picked.await else { | |
| 300 | + return; | |
| 301 | + }; | |
| 302 | + let _ = this.update_in(cx, |yumush, window, cx| { | |
| 303 | + for path in paths { | |
| 304 | + yumush.stage_release_file(path, window, cx); | |
| 305 | + } | |
| 306 | + }); | |
| 307 | + }) | |
| 308 | + .detach(); | |
| 309 | + } | |
| 310 | + | |
| 311 | + fn stage_release_file(&mut self, path: PathBuf, window: &mut Window, cx: &mut Context<Self>) { | |
| 312 | + let id = self.desk.next; | |
| 313 | + self.desk.next += 1; | |
| 314 | + let name = path | |
| 315 | + .file_name() | |
| 316 | + .map(|name| name.to_string_lossy().into_owned()) | |
| 317 | + .unwrap_or_default(); | |
| 318 | + let size = std::fs::metadata(&path).map_or(0, |meta| meta.len()); | |
| 319 | + self.desk.drafts.push(Draft { | |
| 320 | + id, | |
| 321 | + name, | |
| 322 | + size, | |
| 323 | + stage: Stage::Uploading(0), | |
| 324 | + }); | |
| 325 | + | |
| 326 | + let (progress, mut sent) = tokio::sync::watch::channel(0u64); | |
| 327 | + cx.spawn_in(window, async move |this, cx| { | |
| 328 | + while sent.changed().await.is_ok() { | |
| 329 | + let bytes = *sent.borrow(); | |
| 330 | + let _ = this.update(cx, |yumush, cx| { | |
| 331 | + if let Some(draft) = yumush | |
| 332 | + .desk | |
| 333 | + .draft(id) | |
| 334 | + .filter(|draft| matches!(draft.stage, Stage::Uploading(_))) | |
| 335 | + { | |
| 336 | + draft.stage = Stage::Uploading(bytes); | |
| 337 | + } | |
| 338 | + cx.notify(); | |
| 339 | + }); | |
| 340 | + } | |
| 341 | + }) | |
| 342 | + .detach(); | |
| 343 | + | |
| 344 | + let network = self.network.clone(); | |
| 345 | + cx.spawn_in(window, async move |this, cx| { | |
| 346 | + let stage = match network.stage_release(path, progress).await { | |
| 347 | + Ok(staged) => Stage::Ready(staged), | |
| 348 | + Err(error) => Stage::Failed(error.to_string()), | |
| 349 | + }; | |
| 350 | + let _ = this.update(cx, |yumush, cx| { | |
| 351 | + if let Some(draft) = yumush.desk.draft(id) { | |
| 352 | + draft.stage = stage; | |
| 353 | + } | |
| 354 | + cx.notify(); | |
| 355 | + }); | |
| 356 | + }) | |
| 357 | + .detach(); | |
| 358 | + cx.notify(); | |
| 359 | + } | |
| 360 | + | |
| 361 | + fn remove_draft(&mut self, id: u64, cx: &mut Context<Self>) { | |
| 362 | + self.desk.drafts.retain(|draft| draft.id != id); | |
| 363 | + cx.notify(); | |
| 364 | + } | |
| 365 | + | |
| 366 | + fn publish_release(&mut self, window: &mut Window, cx: &mut Context<Self>) { | |
| 367 | + if !self.desk.can_publish() { | |
| 368 | + return; | |
| 369 | + } | |
| 370 | + let files = self | |
| 371 | + .desk | |
| 372 | + .drafts | |
| 373 | + .iter() | |
| 374 | + .filter_map(|draft| match &draft.stage { | |
| 375 | + Stage::Ready(staged) => Some(staged.file), | |
| 376 | + _ => None, | |
| 377 | + }) | |
| 378 | + .collect(); | |
| 379 | + let required = self.desk.required; | |
| 380 | + self.desk.publishing = true; | |
| 381 | + cx.notify(); | |
| 382 | + let network = self.network.clone(); | |
| 383 | + | |
| 384 | + cx.spawn_in(window, async move |this, cx| { | |
| 385 | + match network.call(PublishRelease { files, required }).await { | |
| 386 | + Ok(_) => { | |
| 387 | + let _ = this.update_in(cx, |yumush, window, cx| { | |
| 388 | + yumush.desk.drafts.clear(); | |
| 389 | + yumush.desk.required = false; | |
| 390 | + yumush.desk.publishing = false; | |
| 391 | + yumush.load_releases(window, cx); | |
| 392 | + }); | |
| 393 | + } | |
| 394 | + Err(error) => { | |
| 395 | + let _ = this.update(cx, |yumush, cx| { | |
| 396 | + yumush.desk.publishing = false; | |
| 397 | + cx.notify(); | |
| 398 | + }); | |
| 399 | + notify_error(&this, cx, error); | |
| 400 | + } | |
| 401 | + } | |
| 402 | + }) | |
| 403 | + .detach(); | |
| 404 | + } | |
| 405 | + | |
| 406 | + fn toggle_release_required( | |
| 407 | + &mut self, | |
| 408 | + seq: u64, | |
| 409 | + required: bool, | |
| 410 | + window: &mut Window, | |
| 411 | + cx: &mut Context<Self>, | |
| 412 | + ) { | |
| 413 | + if required && !confirmed(&mut self.desk.pending_required, seq) { | |
| 414 | + cx.notify(); | |
| 415 | + return; | |
| 416 | + } | |
| 417 | + self.set_release_required(seq, required, window, cx); | |
| 418 | + } | |
| 419 | + | |
| 420 | + fn set_release_required( | |
| 421 | + &self, | |
| 422 | + seq: u64, | |
| 423 | + required: bool, | |
| 424 | + window: &mut Window, | |
| 425 | + cx: &mut Context<Self>, | |
| 426 | + ) { | |
| 427 | + let network = self.network.clone(); | |
| 428 | + | |
| 429 | + cx.spawn_in(window, async move |this, cx| { | |
| 430 | + match network.call(SetReleaseRequired { seq, required }).await { | |
| 431 | + Ok(()) => { | |
| 432 | + let _ = this.update_in(cx, |yumush, window, cx| { | |
| 433 | + yumush.desk.pending_required = None; | |
| 434 | + yumush.load_releases(window, cx); | |
| 435 | + }); | |
| 436 | + } | |
| 437 | + Err(error) => notify_error(&this, cx, error), | |
| 438 | + } | |
| 439 | + }) | |
| 440 | + .detach(); | |
| 441 | + } | |
| 442 | +} |
crates/client/src/gui/chat.rsmodified+1 -1
| @@ -799,7 +799,7 @@ impl Chat { | ||
| 799 | 799 | followed.1 = stats; |
| 800 | 800 | } |
| 801 | 801 | } |
| 802 | - Event::ReportCreated | Event::SettingsUpdated(_) => {} | |
| 802 | + Event::ReportCreated | Event::SettingsUpdated(_) | Event::Release => {} | |
| 803 | 803 | } |
| 804 | 804 | } |
| 805 | 805 |
crates/client/src/gui/sidebar.rsmodified+1 -0
| @@ -201,6 +201,7 @@ impl Yumush { | ||
| 201 | 201 | fade, |
| 202 | 202 | )), |
| 203 | 203 | ) |
| 204 | + .children(self.update_control(palette)) | |
| 204 | 205 | .child( |
| 205 | 206 | self.folding( |
| 206 | 207 | "list_fold", |
crates/client/src/gui/update_view.rsadded+111 -0
| @@ -0,0 +1,111 @@ | ||
| 1 | +use crate::lang::w; | |
| 2 | +use crate::update::Phase; | |
| 3 | +use gpui_kit::{AnyElement, IntoElement, ParentElement, Styled, div, px}; | |
| 4 | + | |
| 5 | +use super::{ | |
| 6 | + Palette, Yumush, parts, | |
| 7 | + style::{size, space, text}, | |
| 8 | +}; | |
| 9 | + | |
| 10 | +fn percent(fraction: f32) -> String { | |
| 11 | + format!("{}%", (fraction * 100.) as u32) | |
| 12 | +} | |
| 13 | + | |
| 14 | +impl Yumush { | |
| 15 | + pub(super) fn update_control(&self, palette: Palette) -> Option<AnyElement> { | |
| 16 | + if self.update.required() { | |
| 17 | + return None; | |
| 18 | + } | |
| 19 | + let t = palette.tokens; | |
| 20 | + let (label, restart) = match self.update { | |
| 21 | + Phase::Idle => return None, | |
| 22 | + Phase::Available(_) => (w().update.update, false), | |
| 23 | + Phase::Ready(_) => (w().update.restart, true), | |
| 24 | + Phase::Failed(_) => (w().update.retry, false), | |
| 25 | + Phase::Downloading { .. } | Phase::Installing { .. } => { | |
| 26 | + let fraction = self.update.progress().unwrap_or_default(); | |
| 27 | + return Some( | |
| 28 | + div() | |
| 29 | + .flex() | |
| 30 | + .items_center() | |
| 31 | + .gap(px(space::SM)) | |
| 32 | + .child(parts::track(parts::Fill::Part(fraction), false, t).flex_1()) | |
| 33 | + .child( | |
| 34 | + div() | |
| 35 | + .text_size(t.text(text::CAPTION)) | |
| 36 | + .text_color(palette.muted) | |
| 37 | + .child(percent(fraction)), | |
| 38 | + ) | |
| 39 | + .into_any_element(), | |
| 40 | + ); | |
| 41 | + } | |
| 42 | + }; | |
| 43 | + Some( | |
| 44 | + parts::button( | |
| 45 | + "update_action", | |
| 46 | + label, | |
| 47 | + parts::Press::Plain, | |
| 48 | + t, | |
| 49 | + move |_, _| { | |
| 50 | + if restart { | |
| 51 | + crate::update::restart(); | |
| 52 | + } else { | |
| 53 | + crate::update::install(); | |
| 54 | + } | |
| 55 | + }, | |
| 56 | + ) | |
| 57 | + .into_any_element(), | |
| 58 | + ) | |
| 59 | + } | |
| 60 | + | |
| 61 | + pub(super) fn update_required(&self, palette: Palette) -> impl IntoElement { | |
| 62 | + let t = palette.tokens; | |
| 63 | + let status = match self.update { | |
| 64 | + Phase::Downloading { .. } => w().update.downloading, | |
| 65 | + Phase::Installing { .. } => w().update.installing, | |
| 66 | + Phase::Ready(_) => w().update.restarting, | |
| 67 | + _ => "", | |
| 68 | + }; | |
| 69 | + let label = match self.update.progress() { | |
| 70 | + Some(fraction) => format!("{status} {}", percent(fraction)), | |
| 71 | + None => status.to_string(), | |
| 72 | + }; | |
| 73 | + let failed = matches!(self.update, Phase::Failed(_)); | |
| 74 | + | |
| 75 | + div() | |
| 76 | + .size_full() | |
| 77 | + .flex() | |
| 78 | + .flex_col() | |
| 79 | + .items_center() | |
| 80 | + .justify_center() | |
| 81 | + .gap(px(space::LG)) | |
| 82 | + .child(parts::words( | |
| 83 | + w().update.required, | |
| 84 | + parts::Text::Title, | |
| 85 | + parts::Ink::Paper, | |
| 86 | + t, | |
| 87 | + )) | |
| 88 | + .children(self.update.progress().map(|fraction| { | |
| 89 | + div().w(px(size::SIDEBAR)).child(parts::track( | |
| 90 | + parts::Fill::Part(fraction), | |
| 91 | + false, | |
| 92 | + t, | |
| 93 | + )) | |
| 94 | + })) | |
| 95 | + .child(parts::words( | |
| 96 | + label, | |
| 97 | + parts::Text::Caption, | |
| 98 | + parts::Ink::Dim, | |
| 99 | + t, | |
| 100 | + )) | |
| 101 | + .children(failed.then(|| { | |
| 102 | + parts::button( | |
| 103 | + "update_retry", | |
| 104 | + w().update.retry, | |
| 105 | + parts::Press::Primary, | |
| 106 | + t, | |
| 107 | + |_, _| crate::update::install(), | |
| 108 | + ) | |
| 109 | + })) | |
| 110 | + } | |
| 111 | +} |
crates/client/src/net/events.rsmodified+3 -0
| @@ -18,6 +18,9 @@ pub(super) async fn event_receive_loop( | ||
| 18 | 18 | while let Ok(down) = frame::read::<Down>(&mut receive_stream, DOWN_MAX).await { |
| 19 | 19 | match down { |
| 20 | 20 | Down::Event(event) => { |
| 21 | + if matches!(*event, common::event::Event::Release) { | |
| 22 | + crate::update::recheck(); | |
| 23 | + } | |
| 21 | 24 | media.pushed(&event); |
| 22 | 25 | if event_sender |
| 23 | 26 | .send(NetworkEvent::Pushed(event)) |
crates/client/src/net/link.rsmodified+62 -4
| @@ -3,12 +3,13 @@ use std::{future::Future, net::SocketAddr, path::Path, sync::Arc, time::Duration | ||
| 3 | 3 | use common::{ |
| 4 | 4 | call::Call, |
| 5 | 5 | constant::{ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES}, |
| 6 | - error::Error, | |
| 6 | + error::{Error, ReleaseProblem}, | |
| 7 | 7 | frame::{self, DOWN_MAX, DecodeOwned, Encode, Sending, UP_MAX}, |
| 8 | - model::{Attachment, Id, User}, | |
| 9 | - open::{Blob, Open, Upload}, | |
| 8 | + model::{Attachment, Id, Staged, User}, | |
| 9 | + open::{Blob, Open, Stage, Upload}, | |
| 10 | 10 | session::{Hello, Welcome}, |
| 11 | 11 | transport::{ALPN, Close, transport}, |
| 12 | + update::{FILE_MAX, target_of}, | |
| 12 | 13 | validate::{validate_attachment_name, validate_attachment_size}, |
| 13 | 14 | }; |
| 14 | 15 | use quinn::rustls::{ |
| @@ -28,6 +29,7 @@ use super::{datagram::datagram_receive_loop, events::event_receive_loop, *}; | ||
| 28 | 29 | const CHANNEL_SIZE: usize = 32; |
| 29 | 30 | const BACKOFF_BASE_MILLIS: u64 = 250; |
| 30 | 31 | const BACKOFF_CAP_MILLIS: u64 = 8_000; |
| 32 | +const UPDATE_CHECK: Duration = Duration::from_secs(5); | |
| 31 | 33 | |
| 32 | 34 | pub fn start(server: crate::Server) -> (NetworkHandle, mpsc::Receiver<NetworkEvent>) { |
| 33 | 35 | let (command_sender, command_receiver) = mpsc::channel(CHANNEL_SIZE); |
| @@ -279,6 +281,7 @@ async fn hello(connection: &quinn::Connection, token: Option<String>) -> Result< | ||
| 279 | 281 | let hello = Hello { |
| 280 | 282 | token, |
| 281 | 283 | device: device_name(), |
| 284 | + build: crate::update::build(), | |
| 282 | 285 | }; |
| 283 | 286 | |
| 284 | 287 | Ok(exchange(connection, &hello).await?.0) |
| @@ -334,6 +337,49 @@ pub(super) async fn upload( | ||
| 334 | 337 | } |
| 335 | 338 | } |
| 336 | 339 | |
| 340 | +pub(super) async fn stage( | |
| 341 | + connection: &quinn::Connection, | |
| 342 | + path: &Path, | |
| 343 | + progress: &watch::Sender<u64>, | |
| 344 | +) -> Result<Staged, Fail> { | |
| 345 | + let bytes = tokio::fs::read(path).await?; | |
| 346 | + if bytes.len() as u64 > FILE_MAX { | |
| 347 | + return Err(Error::Release(ReleaseProblem::TooLarge).into()); | |
| 348 | + } | |
| 349 | + let (bytes, target) = tokio::task::spawn_blocking(move || { | |
| 350 | + let target = target_of(&bytes); | |
| 351 | + (bytes, target) | |
| 352 | + }) | |
| 353 | + .await | |
| 354 | + .map_err(|_| Fail::Protocol)?; | |
| 355 | + if target.is_none() { | |
| 356 | + return Err(Error::Release(ReleaseProblem::NotClient).into()); | |
| 357 | + } | |
| 358 | + | |
| 359 | + let (send_stream, mut receive_stream) = connection.open_bi().await?; | |
| 360 | + let mut send_stream = Sending::new(send_stream); | |
| 361 | + let header = Stage { | |
| 362 | + size: bytes.len() as u64, | |
| 363 | + }; | |
| 364 | + frame::write(&mut send_stream, &Open::Stage(header), UP_MAX).await?; | |
| 365 | + | |
| 366 | + let write = async move { | |
| 367 | + for (index, chunk) in bytes.chunks(ATTACHMENT_CHUNK_BYTES).enumerate() { | |
| 368 | + send_stream.get().write_all(chunk).await?; | |
| 369 | + progress.send_replace(((index * ATTACHMENT_CHUNK_BYTES) + chunk.len()) as u64); | |
| 370 | + } | |
| 371 | + Ok(send_stream.finish()?) | |
| 372 | + }; | |
| 373 | + let read = frame::read::<Result<Staged, Error>>(&mut receive_stream, DOWN_MAX); | |
| 374 | + let (sent, reply) = tokio::join!(write, read); | |
| 375 | + | |
| 376 | + match (sent, reply) { | |
| 377 | + (_, Ok(reply)) => Ok(reply?), | |
| 378 | + (Err(error), _) => Err(error), | |
| 379 | + (_, Err(error)) => Err(error.into()), | |
| 380 | + } | |
| 381 | +} | |
| 382 | + | |
| 337 | 383 | pub(super) async fn backup_download( |
| 338 | 384 | connection: &quinn::Connection, |
| 339 | 385 | name: &str, |
| @@ -407,7 +453,14 @@ async fn actor( | ||
| 407 | 453 | } |
| 408 | 454 | }; |
| 409 | 455 | if matches!(result, Ok(_) | Err(LinkError::Outdated)) { |
| 410 | - tokio::spawn(crate::update::check(address)); | |
| 456 | + let outdated = result.is_err(); | |
| 457 | + let _ = | |
| 458 | + tokio::time::timeout(UPDATE_CHECK, crate::update::check(&address, outdated)) | |
| 459 | + .await; | |
| 460 | + if crate::update::phase().required() { | |
| 461 | + while command_receiver.recv().await.is_some() {} | |
| 462 | + return; | |
| 463 | + } | |
| 411 | 464 | } |
| 412 | 465 | match result { |
| 413 | 466 | Ok(connection) => break connection, |
| @@ -522,6 +575,11 @@ async fn actor( | ||
| 522 | 575 | |
| 523 | 576 | answer(reply, async move { fetches.memory(&connection, blob).await }); |
| 524 | 577 | } |
| 578 | + Some(Command::Stage { path, progress, reply }) => { | |
| 579 | + let connection = connection.clone(); | |
| 580 | + | |
| 581 | + answer(reply, async move { stage(&connection, &path, &progress).await }); | |
| 582 | + } | |
| 525 | 583 | Some(Command::BackupDownload { name, path, reply }) => { |
| 526 | 584 | let connection = connection.clone(); |
| 527 | 585 | let fetches = shared.fetches.clone(); |
crates/client/src/net/mod.rsmodified+18 -0
| @@ -75,6 +75,11 @@ enum Command { | ||
| 75 | 75 | blob: Blob, |
| 76 | 76 | reply: oneshot::Sender<Result<Vec<u8>, Fail>>, |
| 77 | 77 | }, |
| 78 | + Stage { | |
| 79 | + path: PathBuf, | |
| 80 | + progress: tokio::sync::watch::Sender<u64>, | |
| 81 | + reply: oneshot::Sender<Result<common::model::Staged, Fail>>, | |
| 82 | + }, | |
| 78 | 83 | BackupDownload { |
| 79 | 84 | name: String, |
| 80 | 85 | path: PathBuf, |
| @@ -218,6 +223,19 @@ impl NetworkHandle { | ||
| 218 | 223 | self.ask(|reply| Command::Download { blob, reply }).await |
| 219 | 224 | } |
| 220 | 225 | |
| 226 | + pub async fn stage_release( | |
| 227 | + &self, | |
| 228 | + path: PathBuf, | |
| 229 | + progress: tokio::sync::watch::Sender<u64>, | |
| 230 | + ) -> Result<common::model::Staged, Fail> { | |
| 231 | + self.ask(|reply| Command::Stage { | |
| 232 | + path, | |
| 233 | + progress, | |
| 234 | + reply, | |
| 235 | + }) | |
| 236 | + .await | |
| 237 | + } | |
| 238 | + | |
| 221 | 239 | pub async fn download_backup(&self, name: &str, path: PathBuf) -> Result<(), Fail> { |
| 222 | 240 | self.ask(|reply| Command::BackupDownload { |
| 223 | 241 | name: name.to_string(), |
crates/client/src/update.rsmodified+251 -75
| @@ -1,113 +1,289 @@ | ||
| 1 | 1 | use std::{ |
| 2 | + io::Read, | |
| 2 | 3 | path::Path, |
| 3 | - sync::atomic::{AtomicBool, Ordering}, | |
| 4 | + sync::{LazyLock, Mutex}, | |
| 4 | 5 | }; |
| 5 | 6 | |
| 6 | 7 | use common::{ |
| 7 | 8 | frame::{self, Sending, UP_MAX}, |
| 8 | - update::{ALPN, Answer, Ask, FILE_MAX, sha256}, | |
| 9 | + update::{ALPN, Ask, FILE_MAX, Offer, Sha, Status, sha256}, | |
| 9 | 10 | }; |
| 11 | +use tokio::sync::watch; | |
| 10 | 12 | use tracing::{info, warn}; |
| 11 | 13 | |
| 12 | 14 | pub const RESTART: &str = "--restart"; |
| 13 | -const RELEASE: bool = option_env!("YUMUSH_RELEASE").is_some(); | |
| 15 | +pub const TARGET: &str = env!("YUMUSH_TARGET"); | |
| 16 | +const MARK: &str = concat!("yumush-target:", env!("YUMUSH_TARGET"), ";"); | |
| 17 | +const CHUNK: usize = 256 << 10; | |
| 14 | 18 | |
| 15 | -static CHECKING: AtomicBool = AtomicBool::new(false); | |
| 19 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 20 | +pub enum Phase { | |
| 21 | + Idle, | |
| 22 | + Available(Offer), | |
| 23 | + Downloading { offer: Offer, done: u64 }, | |
| 24 | + Installing { offer: Offer, done: u64 }, | |
| 25 | + Ready(Offer), | |
| 26 | + Failed(Offer), | |
| 27 | +} | |
| 16 | 28 | |
| 17 | -pub async fn check(server: crate::Server) { | |
| 18 | - if !RELEASE | |
| 19 | - || std::env::args().any(|arg| arg == crate::instance::MULTI) | |
| 20 | - || CHECKING.swap(true, Ordering::AcqRel) | |
| 21 | - { | |
| 22 | - return; | |
| 23 | - } | |
| 24 | - let result = match crate::exe() { | |
| 25 | - Some(exe) => update(&server, exe).await, | |
| 26 | - None => Err("no exe".into()), | |
| 27 | - }; | |
| 28 | - match result { | |
| 29 | - Ok(true) => restart(), | |
| 30 | - Ok(false) => {} | |
| 31 | - Err(error) => warn!("update: {error}"), | |
| 29 | +impl Phase { | |
| 30 | + pub fn offer(self) -> Option<Offer> { | |
| 31 | + match self { | |
| 32 | + Self::Idle => None, | |
| 33 | + Self::Available(offer) | |
| 34 | + | Self::Downloading { offer, .. } | |
| 35 | + | Self::Installing { offer, .. } | |
| 36 | + | Self::Ready(offer) | |
| 37 | + | Self::Failed(offer) => Some(offer), | |
| 38 | + } | |
| 32 | 39 | } |
| 33 | - CHECKING.store(false, Ordering::Release); | |
| 34 | -} | |
| 35 | 40 | |
| 36 | -type Fail = Box<dyn std::error::Error + Send + Sync>; | |
| 41 | + pub fn required(self) -> bool { | |
| 42 | + self.offer().is_some_and(|offer| offer.required) | |
| 43 | + } | |
| 37 | 44 | |
| 38 | -async fn update(server: &crate::Server, exe: &Path) -> Result<bool, Fail> { | |
| 39 | - let own = tokio::fs::read(exe).await?; | |
| 40 | - let ask = Ask { | |
| 41 | - target: target(), | |
| 42 | - sha256: sha256(&own), | |
| 43 | - }; | |
| 44 | - drop(own); | |
| 45 | - let fetched = crate::net::dial(server, ALPN, async |connection| { | |
| 46 | - fetch(connection, ask).await | |
| 47 | - }) | |
| 48 | - .await | |
| 49 | - .map_err(|error| error.to_string())?; | |
| 50 | - let Some(bytes) = fetched? else { | |
| 51 | - return Ok(false); | |
| 52 | - }; | |
| 53 | - let new = exe.with_extension("new"); | |
| 54 | - tokio::fs::write(&new, &bytes).await?; | |
| 55 | - let replaced = self_replace::self_replace(&new); | |
| 56 | - let _ = tokio::fs::remove_file(&new).await; | |
| 57 | - replaced?; | |
| 58 | - info!("update: installed"); | |
| 59 | - Ok(true) | |
| 60 | -} | |
| 61 | - | |
| 62 | -async fn fetch(connection: &quinn::Connection, ask: Ask) -> Result<Option<Vec<u8>>, Fail> { | |
| 63 | - let (send, mut receive) = connection.open_bi().await?; | |
| 64 | - let mut send = Sending::new(send); | |
| 65 | - frame::write(&mut send, &ask, UP_MAX).await?; | |
| 66 | - send.finish()?; | |
| 67 | - match frame::read::<Answer>(&mut receive, UP_MAX).await? { | |
| 68 | - Answer::Current => Ok(None), | |
| 69 | - Answer::Missing => Err(format!("server has no {}", ask.target).into()), | |
| 70 | - Answer::File { size, sha256: want } => { | |
| 71 | - if size > FILE_MAX { | |
| 72 | - return Err("too large".into()); | |
| 73 | - } | |
| 74 | - info!("update: downloading {size} bytes"); | |
| 75 | - let bytes = receive.read_to_end(size as usize).await?; | |
| 76 | - if bytes.len() as u64 != size || sha256(&bytes) != want { | |
| 77 | - return Err("corrupt download".into()); | |
| 78 | - } | |
| 79 | - Ok(Some(bytes)) | |
| 45 | + pub fn progress(self) -> Option<f32> { | |
| 46 | + let fraction = |done: u64, total: u64| (done as f32 / total.max(1) as f32).clamp(0., 1.); | |
| 47 | + match self { | |
| 48 | + Self::Downloading { offer, done } => Some(fraction(done, offer.packed)), | |
| 49 | + Self::Installing { offer, done } => Some(fraction(done, offer.size)), | |
| 50 | + _ => None, | |
| 80 | 51 | } |
| 81 | 52 | } |
| 53 | + | |
| 54 | + fn busy(self) -> bool { | |
| 55 | + matches!( | |
| 56 | + self, | |
| 57 | + Self::Downloading { .. } | Self::Installing { .. } | Self::Ready(_) | |
| 58 | + ) | |
| 59 | + } | |
| 60 | +} | |
| 61 | + | |
| 62 | +static PHASE: LazyLock<watch::Sender<Phase>> = LazyLock::new(|| watch::channel(Phase::Idle).0); | |
| 63 | +static SERVER: Mutex<Option<crate::Server>> = Mutex::new(None); | |
| 64 | +static BUILD: LazyLock<Option<Sha>> = LazyLock::new(|| { | |
| 65 | + if cfg!(debug_assertions) { | |
| 66 | + return None; | |
| 67 | + } | |
| 68 | + let exe = crate::exe()?; | |
| 69 | + let bytes = std::fs::read(exe).ok()?; | |
| 70 | + std::hint::black_box(MARK); | |
| 71 | + Some(sha256(&bytes)) | |
| 72 | +}); | |
| 73 | + | |
| 74 | +pub fn phase() -> Phase { | |
| 75 | + *PHASE.borrow() | |
| 76 | +} | |
| 77 | + | |
| 78 | +pub fn subscribe() -> watch::Receiver<Phase> { | |
| 79 | + PHASE.subscribe() | |
| 82 | 80 | } |
| 83 | 81 | |
| 84 | -fn target() -> String { | |
| 82 | +pub fn build() -> Option<Sha> { | |
| 83 | + *BUILD | |
| 84 | +} | |
| 85 | + | |
| 86 | +fn set(phase: Phase) { | |
| 87 | + PHASE.send_replace(phase); | |
| 88 | +} | |
| 89 | + | |
| 90 | +fn targets() -> Vec<String> { | |
| 85 | 91 | let os = std::env::consts::OS; |
| 86 | 92 | let arch = std::env::consts::ARCH; |
| 87 | - match level() { | |
| 88 | - Some(level) => format!("{arch}_{level}-{os}"), | |
| 89 | - None => format!("{arch}-{os}"), | |
| 93 | + if arch != "x86_64" { | |
| 94 | + return vec![TARGET.to_string()]; | |
| 95 | + } | |
| 96 | + let mut targets = Vec::new(); | |
| 97 | + if v3() { | |
| 98 | + targets.push(format!("{arch}_v3-{os}")); | |
| 90 | 99 | } |
| 100 | + targets.push(format!("{arch}_v1-{os}")); | |
| 101 | + targets | |
| 91 | 102 | } |
| 92 | 103 | |
| 93 | 104 | #[cfg(target_arch = "x86_64")] |
| 94 | -fn level() -> Option<&'static str> { | |
| 95 | - let v3 = std::arch::is_x86_feature_detected!("avx2") | |
| 105 | +fn v3() -> bool { | |
| 106 | + std::arch::is_x86_feature_detected!("avx2") | |
| 96 | 107 | && std::arch::is_x86_feature_detected!("bmi1") |
| 97 | 108 | && std::arch::is_x86_feature_detected!("bmi2") |
| 98 | 109 | && std::arch::is_x86_feature_detected!("fma") |
| 99 | 110 | && std::arch::is_x86_feature_detected!("lzcnt") |
| 100 | 111 | && std::arch::is_x86_feature_detected!("movbe") |
| 101 | - && std::arch::is_x86_feature_detected!("f16c"); | |
| 102 | - Some(if v3 { "v3" } else { "v1" }) | |
| 112 | + && std::arch::is_x86_feature_detected!("f16c") | |
| 103 | 113 | } |
| 104 | 114 | |
| 105 | 115 | #[cfg(not(target_arch = "x86_64"))] |
| 106 | -fn level() -> Option<&'static str> { | |
| 107 | - None | |
| 116 | +fn v3() -> bool { | |
| 117 | + false | |
| 118 | +} | |
| 119 | + | |
| 120 | +fn usable() -> bool { | |
| 121 | + !std::env::args().any(|arg| arg == crate::instance::MULTI) | |
| 122 | +} | |
| 123 | + | |
| 124 | +pub(crate) async fn check(server: &crate::Server, outdated: bool) { | |
| 125 | + let Some(build) = build().filter(|_| usable()) else { | |
| 126 | + return; | |
| 127 | + }; | |
| 128 | + *SERVER.lock().unwrap() = Some(server.clone()); | |
| 129 | + if phase().busy() { | |
| 130 | + return; | |
| 131 | + } | |
| 132 | + let ask = Ask::Check { | |
| 133 | + build, | |
| 134 | + targets: targets(), | |
| 135 | + }; | |
| 136 | + let status = crate::net::dial(server, ALPN, async |connection| { | |
| 137 | + let (send, mut receive) = connection.open_bi().await.ok()?; | |
| 138 | + let mut send = Sending::new(send); | |
| 139 | + frame::write(&mut send, &ask, UP_MAX).await.ok()?; | |
| 140 | + send.finish().ok()?; | |
| 141 | + frame::read::<Status>(&mut receive, UP_MAX).await.ok() | |
| 142 | + }) | |
| 143 | + .await; | |
| 144 | + let Ok(Some(status)) = status else { | |
| 145 | + warn!("update: check failed"); | |
| 146 | + return; | |
| 147 | + }; | |
| 148 | + if phase().busy() { | |
| 149 | + return; | |
| 150 | + } | |
| 151 | + match status { | |
| 152 | + Status::Offer(mut offer) => { | |
| 153 | + offer.required |= outdated; | |
| 154 | + if phase() != Phase::Failed(offer) { | |
| 155 | + set(Phase::Available(offer)); | |
| 156 | + } | |
| 157 | + if offer.required { | |
| 158 | + install(); | |
| 159 | + } | |
| 160 | + } | |
| 161 | + Status::Latest | Status::Unknown => set(Phase::Idle), | |
| 162 | + } | |
| 163 | +} | |
| 164 | + | |
| 165 | +pub fn recheck() { | |
| 166 | + let Some(server) = SERVER.lock().unwrap().clone() else { | |
| 167 | + return; | |
| 168 | + }; | |
| 169 | + std::thread::spawn(move || { | |
| 170 | + if let Ok(runtime) = tokio::runtime::Builder::new_current_thread() | |
| 171 | + .enable_all() | |
| 172 | + .build() | |
| 173 | + { | |
| 174 | + runtime.block_on(check(&server, false)); | |
| 175 | + } | |
| 176 | + }); | |
| 177 | +} | |
| 178 | + | |
| 179 | +pub fn install() { | |
| 180 | + let offer = match phase() { | |
| 181 | + Phase::Available(offer) | Phase::Failed(offer) => offer, | |
| 182 | + _ => return, | |
| 183 | + }; | |
| 184 | + let Some(server) = SERVER.lock().unwrap().clone() else { | |
| 185 | + return; | |
| 186 | + }; | |
| 187 | + let Some(exe) = crate::exe() else { | |
| 188 | + return; | |
| 189 | + }; | |
| 190 | + set(Phase::Downloading { offer, done: 0 }); | |
| 191 | + std::thread::spawn(move || { | |
| 192 | + let installed = tokio::runtime::Builder::new_current_thread() | |
| 193 | + .enable_all() | |
| 194 | + .build() | |
| 195 | + .map_err(Fail::from) | |
| 196 | + .and_then(|runtime| runtime.block_on(download(&server, offer))) | |
| 197 | + .and_then(|packed| unpack(offer, &packed, exe)); | |
| 198 | + match installed { | |
| 199 | + Ok(()) => { | |
| 200 | + info!("update: release {} installed", offer.seq); | |
| 201 | + set(Phase::Ready(offer)); | |
| 202 | + if offer.required { | |
| 203 | + restart(); | |
| 204 | + } | |
| 205 | + } | |
| 206 | + Err(error) => { | |
| 207 | + warn!("update: {error}"); | |
| 208 | + set(Phase::Failed(offer)); | |
| 209 | + } | |
| 210 | + } | |
| 211 | + }); | |
| 212 | +} | |
| 213 | + | |
| 214 | +type Fail = Box<dyn std::error::Error + Send + Sync>; | |
| 215 | + | |
| 216 | +async fn download(server: &crate::Server, offer: Offer) -> Result<Vec<u8>, Fail> { | |
| 217 | + if offer.packed > FILE_MAX || offer.size > FILE_MAX { | |
| 218 | + return Err("too large".into()); | |
| 219 | + } | |
| 220 | + crate::net::dial(server, ALPN, async |connection| { | |
| 221 | + let (send, mut receive) = connection.open_bi().await?; | |
| 222 | + let mut send = Sending::new(send); | |
| 223 | + frame::write(&mut send, &Ask::Download { file: offer.file }, UP_MAX).await?; | |
| 224 | + send.finish()?; | |
| 225 | + let mut packed = Vec::with_capacity(offer.packed as usize); | |
| 226 | + let mut chunk = vec![0u8; CHUNK]; | |
| 227 | + while let Some(read) = receive.read(&mut chunk).await? { | |
| 228 | + packed.extend_from_slice(&chunk[..read]); | |
| 229 | + if packed.len() as u64 > offer.packed { | |
| 230 | + return Err::<_, Fail>("too long".into()); | |
| 231 | + } | |
| 232 | + set(Phase::Downloading { | |
| 233 | + offer, | |
| 234 | + done: packed.len() as u64, | |
| 235 | + }); | |
| 236 | + } | |
| 237 | + if packed.len() as u64 != offer.packed { | |
| 238 | + return Err("short download".into()); | |
| 239 | + } | |
| 240 | + Ok(packed) | |
| 241 | + }) | |
| 242 | + .await | |
| 243 | + .map_err(|error| error.to_string())? | |
| 244 | +} | |
| 245 | + | |
| 246 | +fn unpack(offer: Offer, packed: &[u8], exe: &Path) -> Result<(), Fail> { | |
| 247 | + set(Phase::Installing { offer, done: 0 }); | |
| 248 | + let mut decoder = ruzstd::decoding::StreamingDecoder::new(packed)?; | |
| 249 | + let mut bytes = Vec::with_capacity(offer.size as usize); | |
| 250 | + let mut chunk = vec![0u8; CHUNK]; | |
| 251 | + loop { | |
| 252 | + let read = decoder.read(&mut chunk)?; | |
| 253 | + if read == 0 { | |
| 254 | + break; | |
| 255 | + } | |
| 256 | + bytes.extend_from_slice(&chunk[..read]); | |
| 257 | + if bytes.len() as u64 > offer.size { | |
| 258 | + return Err("too long".into()); | |
| 259 | + } | |
| 260 | + set(Phase::Installing { | |
| 261 | + offer, | |
| 262 | + done: bytes.len() as u64, | |
| 263 | + }); | |
| 264 | + } | |
| 265 | + if bytes.len() as u64 != offer.size || sha256(&bytes) != offer.file { | |
| 266 | + return Err("corrupt download".into()); | |
| 267 | + } | |
| 268 | + let new = exe.with_extension("new"); | |
| 269 | + write_executable(&new, &bytes)?; | |
| 270 | + let replaced = self_replace::self_replace(&new); | |
| 271 | + let _ = std::fs::remove_file(&new); | |
| 272 | + Ok(replaced?) | |
| 273 | +} | |
| 274 | + | |
| 275 | +fn write_executable(path: &Path, bytes: &[u8]) -> std::io::Result<()> { | |
| 276 | + use std::io::Write; | |
| 277 | + let mut options = std::fs::OpenOptions::new(); | |
| 278 | + options.write(true).create(true).truncate(true); | |
| 279 | + #[cfg(unix)] | |
| 280 | + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o755); | |
| 281 | + let mut file = options.open(path)?; | |
| 282 | + file.write_all(bytes)?; | |
| 283 | + file.sync_all() | |
| 108 | 284 | } |
| 109 | 285 | |
| 110 | -fn restart() { | |
| 286 | +pub fn restart() { | |
| 111 | 287 | let Some(exe) = crate::exe() else { |
| 112 | 288 | return; |
| 113 | 289 | }; |
crates/common/src/call.rsmodified+21 -2
| @@ -7,8 +7,9 @@ use crate::{ | ||
| 7 | 7 | model::{ |
| 8 | 8 | Account, AdminActionKind, AdminLogEntry, AttachmentInfo, BackupInfo, Ban, BanScope, |
| 9 | 9 | Community, CommunitySummary, CommunityUsage, DayStat, Edit, Friends, Id, Invitation, |
| 10 | - InviteCode, LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, Report, | |
| 11 | - ReportStatus, ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom, | |
| 10 | + InviteCode, LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, ReleaseInfo, | |
| 11 | + Report, ReportStatus, ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, | |
| 12 | + VoiceRoom, | |
| 12 | 13 | }, |
| 13 | 14 | share::{Codec, Kind, Quality, Share, Source}, |
| 14 | 15 | stats::Stats, |
| @@ -624,6 +625,21 @@ pub struct CreateBackup; | ||
| 624 | 625 | #[derive(Debug, Clone, Encode, Decode)] |
| 625 | 626 | pub struct ListBackups; |
| 626 | 627 | |
| 628 | +#[derive(Debug, Clone, Encode, Decode)] | |
| 629 | +pub struct ListReleases; | |
| 630 | + | |
| 631 | +#[derive(Debug, Clone, Encode, Decode)] | |
| 632 | +pub struct PublishRelease { | |
| 633 | + pub files: Vec<crate::update::Sha>, | |
| 634 | + pub required: bool, | |
| 635 | +} | |
| 636 | + | |
| 637 | +#[derive(Debug, Clone, Encode, Decode)] | |
| 638 | +pub struct SetReleaseRequired { | |
| 639 | + pub seq: u64, | |
| 640 | + pub required: bool, | |
| 641 | +} | |
| 642 | + | |
| 627 | 643 | #[derive(Debug, Clone, Encode, Decode)] |
| 628 | 644 | pub struct FollowStats { |
| 629 | 645 | pub user_id: Option<Id>, |
| @@ -763,6 +779,9 @@ calls! { | ||
| 763 | 779 | CreateBackup: Builder -> BackupInfo; |
| 764 | 780 | ListBackups: Builder -> Vec<BackupInfo>; |
| 765 | 781 | DeleteBackup: Builder -> (); |
| 782 | + ListReleases: Builder -> Vec<ReleaseInfo>; | |
| 783 | + PublishRelease: Builder -> ReleaseInfo; | |
| 784 | + SetReleaseRequired: Builder -> (); | |
| 766 | 785 | FollowStats: Builder -> Option<Stats>; |
| 767 | 786 | PushStats: User -> (); |
| 768 | 787 | GetServerStats: Builder -> Stats; |
crates/common/src/error.rsmodified+18 -0
| @@ -145,6 +145,24 @@ pub enum Error { | ||
| 145 | 145 | RateLimited { retry_after_seconds: u64 }, |
| 146 | 146 | #[error("{field} {}", .problem.describe(.field))] |
| 147 | 147 | Invalid { field: Field, problem: Problem }, |
| 148 | + #[error("{0}")] | |
| 149 | + Release(ReleaseProblem), | |
| 148 | 150 | #[error("server error")] |
| 149 | 151 | Server, |
| 150 | 152 | } |
| 153 | + | |
| 154 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode, thiserror::Error)] | |
| 155 | +pub enum ReleaseProblem { | |
| 156 | + #[error("not a yumush client")] | |
| 157 | + NotClient, | |
| 158 | + #[error("too large")] | |
| 159 | + TooLarge, | |
| 160 | + #[error("already in release {0}")] | |
| 161 | + Released(u64), | |
| 162 | + #[error("no files")] | |
| 163 | + Empty, | |
| 164 | + #[error("two files for one target")] | |
| 165 | + SameTarget, | |
| 166 | + #[error("file not staged")] | |
| 167 | + NotStaged, | |
| 168 | +} |
crates/common/src/event.rsmodified+1 -0
| @@ -86,6 +86,7 @@ pub enum Event { | ||
| 86 | 86 | user_id: Id, |
| 87 | 87 | stats: Stats, |
| 88 | 88 | }, |
| 89 | + Release, | |
| 89 | 90 | } |
| 90 | 91 | |
| 91 | 92 | #[derive(Debug, Clone, Encode, Decode)] |
crates/common/src/model.rsmodified+30 -0
| @@ -265,6 +265,8 @@ pub enum AdminAction { | ||
| 265 | 265 | BackupCreated { name: String }, |
| 266 | 266 | BackupDeleted { name: String }, |
| 267 | 267 | BackupDownloaded { name: String }, |
| 268 | + ReleasePublished { seq: u64, required: bool }, | |
| 269 | + ReleaseRequired { seq: u64, required: bool }, | |
| 268 | 270 | Community(LogAction), |
| 269 | 271 | } |
| 270 | 272 | |
| @@ -302,6 +304,8 @@ string_enum! { | ||
| 302 | 304 | BackupCreated => "backup_created", |
| 303 | 305 | BackupDeleted => "backup_deleted", |
| 304 | 306 | BackupDownloaded => "backup_downloaded", |
| 307 | + ReleasePublished => "release_published", | |
| 308 | + ReleaseRequired => "release_required", | |
| 305 | 309 | Community => "community", |
| 306 | 310 | } |
| 307 | 311 | } |
| @@ -340,6 +344,8 @@ impl AdminAction { | ||
| 340 | 344 | AdminAction::BackupCreated { .. } => AdminActionKind::BackupCreated, |
| 341 | 345 | AdminAction::BackupDeleted { .. } => AdminActionKind::BackupDeleted, |
| 342 | 346 | AdminAction::BackupDownloaded { .. } => AdminActionKind::BackupDownloaded, |
| 347 | + AdminAction::ReleasePublished { .. } => AdminActionKind::ReleasePublished, | |
| 348 | + AdminAction::ReleaseRequired { .. } => AdminActionKind::ReleaseRequired, | |
| 343 | 349 | AdminAction::Community(_) => AdminActionKind::Community, |
| 344 | 350 | } |
| 345 | 351 | } |
| @@ -425,6 +431,30 @@ pub struct AttachmentInfo { | ||
| 425 | 431 | pub community: String, |
| 426 | 432 | } |
| 427 | 433 | |
| 434 | +#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | |
| 435 | +pub struct Staged { | |
| 436 | + pub file: crate::update::Sha, | |
| 437 | + pub target: String, | |
| 438 | + pub size: u64, | |
| 439 | + pub packed: u64, | |
| 440 | +} | |
| 441 | + | |
| 442 | +#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | |
| 443 | +pub struct ReleaseFile { | |
| 444 | + pub target: String, | |
| 445 | + pub size: u64, | |
| 446 | + pub packed: u64, | |
| 447 | + pub online: u64, | |
| 448 | +} | |
| 449 | + | |
| 450 | +#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | |
| 451 | +pub struct ReleaseInfo { | |
| 452 | + pub seq: u64, | |
| 453 | + pub required: bool, | |
| 454 | + pub created_ms: u64, | |
| 455 | + pub files: Vec<ReleaseFile>, | |
| 456 | +} | |
| 457 | + | |
| 428 | 458 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| 429 | 459 | pub struct BackupInfo { |
| 430 | 460 | pub name: String, |
crates/common/src/open.rsmodified+6 -0
| @@ -7,6 +7,12 @@ pub enum Open { | ||
| 7 | 7 | Call(Box<Request>), |
| 8 | 8 | Upload(Upload), |
| 9 | 9 | Fetch(Blob), |
| 10 | + Stage(Stage), | |
| 11 | +} | |
| 12 | + | |
| 13 | +#[derive(Debug, Clone, Encode, Decode)] | |
| 14 | +pub struct Stage { | |
| 15 | + pub size: u64, | |
| 10 | 16 | } |
| 11 | 17 | |
| 12 | 18 | #[derive(Debug, Clone, Encode, Decode)] |
crates/common/src/session.rsmodified+1 -0
| @@ -6,6 +6,7 @@ use crate::model::User; | ||
| 6 | 6 | pub struct Hello { |
| 7 | 7 | pub token: Option<String>, |
| 8 | 8 | pub device: String, |
| 9 | + pub build: Option<crate::update::Sha>, | |
| 9 | 10 | } |
| 10 | 11 | |
| 11 | 12 | #[derive(Debug, Clone, Encode, Decode)] |
crates/common/src/update.rsmodified+80 -9
| @@ -2,29 +2,100 @@ use bitcode::{Decode, Encode}; | ||
| 2 | 2 | |
| 3 | 3 | pub const ALPN: &[u8] = b"yumush-update/1"; |
| 4 | 4 | pub const FILE_MAX: u64 = 512 << 20; |
| 5 | +pub const MARK: &str = "yumush-target:"; | |
| 6 | +const TARGET_MAX: usize = 32; | |
| 7 | + | |
| 8 | +pub type Sha = [u8; 32]; | |
| 5 | 9 | |
| 6 | 10 | #[derive(Debug, Clone, Encode, Decode)] |
| 7 | -pub struct Ask { | |
| 8 | - pub target: String, | |
| 9 | - pub sha256: [u8; 32], | |
| 11 | +pub enum Ask { | |
| 12 | + Check { build: Sha, targets: Vec<String> }, | |
| 13 | + Download { file: Sha }, | |
| 14 | +} | |
| 15 | + | |
| 16 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] | |
| 17 | +pub enum Status { | |
| 18 | + Unknown, | |
| 19 | + Latest, | |
| 20 | + Offer(Offer), | |
| 10 | 21 | } |
| 11 | 22 | |
| 12 | 23 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] |
| 13 | -pub enum Answer { | |
| 14 | - Current, | |
| 15 | - Missing, | |
| 16 | - File { size: u64, sha256: [u8; 32] }, | |
| 24 | +pub struct Offer { | |
| 25 | + pub seq: u64, | |
| 26 | + pub required: bool, | |
| 27 | + pub file: Sha, | |
| 28 | + pub size: u64, | |
| 29 | + pub packed: u64, | |
| 17 | 30 | } |
| 18 | 31 | |
| 19 | 32 | pub fn valid_target(target: &str) -> bool { |
| 20 | 33 | !target.is_empty() |
| 21 | - && target.len() <= 32 | |
| 34 | + && target.len() <= TARGET_MAX | |
| 22 | 35 | && target.bytes().all(|byte| { |
| 23 | 36 | byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_' || byte == b'-' |
| 24 | 37 | }) |
| 25 | 38 | } |
| 26 | 39 | |
| 27 | -pub fn sha256(bytes: &[u8]) -> [u8; 32] { | |
| 40 | +pub fn sha256(bytes: &[u8]) -> Sha { | |
| 28 | 41 | use sha2::Digest; |
| 29 | 42 | sha2::Sha256::digest(bytes).into() |
| 30 | 43 | } |
| 44 | + | |
| 45 | +pub fn hex(sha: &Sha) -> String { | |
| 46 | + sha.iter().map(|byte| format!("{byte:02x}")).collect() | |
| 47 | +} | |
| 48 | + | |
| 49 | +pub fn target_of(bytes: &[u8]) -> Option<String> { | |
| 50 | + let mark = MARK.as_bytes(); | |
| 51 | + let mut found: Option<String> = None; | |
| 52 | + let mut start = 0; | |
| 53 | + while let Some(offset) = bytes[start..] | |
| 54 | + .windows(mark.len()) | |
| 55 | + .position(|window| window == mark) | |
| 56 | + { | |
| 57 | + let after = start + offset + mark.len(); | |
| 58 | + start = after; | |
| 59 | + let tail = &bytes[after..bytes.len().min(after + TARGET_MAX + 1)]; | |
| 60 | + let Some(end) = tail.iter().position(|byte| *byte == b';') else { | |
| 61 | + continue; | |
| 62 | + }; | |
| 63 | + let Ok(target) = std::str::from_utf8(&tail[..end]) else { | |
| 64 | + continue; | |
| 65 | + }; | |
| 66 | + if !valid_target(target) { | |
| 67 | + continue; | |
| 68 | + } | |
| 69 | + match &found { | |
| 70 | + Some(seen) if seen != target => return None, | |
| 71 | + _ => found = Some(target.to_string()), | |
| 72 | + } | |
| 73 | + } | |
| 74 | + let target = found?; | |
| 75 | + let executable = if target.ends_with("-linux") { | |
| 76 | + bytes.starts_with(b"\x7fELF") | |
| 77 | + } else if target.ends_with("-windows") { | |
| 78 | + bytes.starts_with(b"MZ") | |
| 79 | + } else { | |
| 80 | + false | |
| 81 | + }; | |
| 82 | + executable.then_some(target) | |
| 83 | +} | |
| 84 | + | |
| 85 | +#[cfg(test)] | |
| 86 | +mod tests { | |
| 87 | + use super::*; | |
| 88 | + | |
| 89 | + #[test] | |
| 90 | + fn finds_target() { | |
| 91 | + let mut elf = b"\x7fELF....yumush-target:x86_64_v3-linux;...yumush-target:".to_vec(); | |
| 92 | + assert_eq!(target_of(&elf).as_deref(), Some("x86_64_v3-linux")); | |
| 93 | + elf.extend_from_slice(b"yumush-target:x86_64_v1-linux;"); | |
| 94 | + assert_eq!(target_of(&elf), None); | |
| 95 | + assert_eq!(target_of(b"MZ yumush-target:x86_64_v3-linux;"), None); | |
| 96 | + assert_eq!( | |
| 97 | + target_of(b"MZ yumush-target:x86_64_v1-windows;").as_deref(), | |
| 98 | + Some("x86_64_v1-windows") | |
| 99 | + ); | |
| 100 | + } | |
| 101 | +} |
crates/server/Cargo.tomlmodified+1 -0
| @@ -20,6 +20,7 @@ image = { version = "0.25.10", default-features = false, features = ["jpeg", "pn | ||
| 20 | 20 | thiserror = "2.0.21" |
| 21 | 21 | tracing = "0.1.44" |
| 22 | 22 | tracing-subscriber = "0.3.23" |
| 23 | +zstd = { version = "0.14.5", features = ["zstdmt"] } | |
| 23 | 24 | |
| 24 | 25 | [lints] |
| 25 | 26 | workspace = true |
crates/server/src/authentication.rsmodified+1 -1
| @@ -234,7 +234,7 @@ mod tests { | ||
| 234 | 234 | services: Services::default(), |
| 235 | 235 | directory: test::directory(), |
| 236 | 236 | backups: test::directory(), |
| 237 | - clients: Default::default(), | |
| 237 | + releases: Default::default(), | |
| 238 | 238 | }; |
| 239 | 239 | let client = Client::detached(None); |
| 240 | 240 |
crates/server/src/call/mod.rsmodified+4 -0
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | mod admin; |
| 2 | 2 | mod community; |
| 3 | 3 | mod message; |
| 4 | +mod release; | |
| 4 | 5 | mod social; |
| 5 | 6 | mod stats; |
| 6 | 7 | mod user; |
| @@ -218,5 +219,8 @@ pub(crate) async fn dispatch(request: Request, cx: &mut Cx<'_>) -> Vec<u8> { | ||
| 218 | 219 | Request::FollowStats(call) => serve(call, cx).await, |
| 219 | 220 | Request::PushStats(call) => serve(call, cx).await, |
| 220 | 221 | Request::GetServerStats(call) => serve(call, cx).await, |
| 222 | + Request::ListReleases(call) => serve(call, cx).await, | |
| 223 | + Request::PublishRelease(call) => serve(call, cx).await, | |
| 224 | + Request::SetReleaseRequired(call) => serve(call, cx).await, | |
| 221 | 225 | } |
| 222 | 226 | } |
crates/server/src/call/release.rsadded+84 -0
| @@ -0,0 +1,84 @@ | ||
| 1 | +use common::{ | |
| 2 | + call::{ListReleases, PublishRelease, SetReleaseRequired}, | |
| 3 | + event::Event, | |
| 4 | + model::{AdminAction, ReleaseFile, ReleaseInfo}, | |
| 5 | + update::Sha, | |
| 6 | +}; | |
| 7 | + | |
| 8 | +use super::{Cx, Handle, Me}; | |
| 9 | +use crate::{ | |
| 10 | + db::{self, log}, | |
| 11 | + error::ServerError, | |
| 12 | + publish::To, | |
| 13 | +}; | |
| 14 | + | |
| 15 | +fn info(entry: db::release::Entry, builds: &[Sha]) -> ReleaseInfo { | |
| 16 | + ReleaseInfo { | |
| 17 | + seq: entry.seq, | |
| 18 | + required: entry.required, | |
| 19 | + created_ms: entry.created_ms, | |
| 20 | + files: entry | |
| 21 | + .files | |
| 22 | + .into_iter() | |
| 23 | + .map(|file| ReleaseFile { | |
| 24 | + online: builds.iter().filter(|build| **build == file.file).count() as u64, | |
| 25 | + target: file.target, | |
| 26 | + size: file.size, | |
| 27 | + packed: file.packed, | |
| 28 | + }) | |
| 29 | + .collect(), | |
| 30 | + } | |
| 31 | +} | |
| 32 | + | |
| 33 | +impl Handle for ListReleases { | |
| 34 | + async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<ReleaseInfo>, ServerError> { | |
| 35 | + let builds = cx.sh.services.hub.builds(); | |
| 36 | + let entries = db::release::entries(cx.db).await?; | |
| 37 | + | |
| 38 | + Ok(entries | |
| 39 | + .into_iter() | |
| 40 | + .map(|entry| info(entry, &builds)) | |
| 41 | + .collect()) | |
| 42 | + } | |
| 43 | +} | |
| 44 | + | |
| 45 | +impl Handle for PublishRelease { | |
| 46 | + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<ReleaseInfo, ServerError> { | |
| 47 | + let me = me.user()?; | |
| 48 | + let files = cx.sh.releases.staged(&self.files)?; | |
| 49 | + let before = db::release::live(cx.db).await?; | |
| 50 | + let seq = db::release::insert(self.required, &files, cx.db).await?; | |
| 51 | + let after = db::release::live(cx.db).await?; | |
| 52 | + let action = AdminAction::ReleasePublished { | |
| 53 | + seq, | |
| 54 | + required: self.required, | |
| 55 | + }; | |
| 56 | + log::record_admin(Some(me.id), None, None, &action, cx.db).await?; | |
| 57 | + let entry = db::release::entry(seq, cx.db).await?; | |
| 58 | + | |
| 59 | + cx.sh.releases.unstage(&self.files); | |
| 60 | + let stopped: Vec<Sha> = before | |
| 61 | + .into_iter() | |
| 62 | + .filter(|file| !after.contains(file)) | |
| 63 | + .collect(); | |
| 64 | + cx.sh.releases.discard(&stopped); | |
| 65 | + cx.emit(To::Everyone, Event::Release); | |
| 66 | + | |
| 67 | + Ok(info(entry, &cx.sh.services.hub.builds())) | |
| 68 | + } | |
| 69 | +} | |
| 70 | + | |
| 71 | +impl Handle for SetReleaseRequired { | |
| 72 | + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | |
| 73 | + let me = me.user()?; | |
| 74 | + db::release::set_required(self.seq, self.required, cx.db).await?; | |
| 75 | + let action = AdminAction::ReleaseRequired { | |
| 76 | + seq: self.seq, | |
| 77 | + required: self.required, | |
| 78 | + }; | |
| 79 | + log::record_admin(Some(me.id), None, None, &action, cx.db).await?; | |
| 80 | + cx.emit(To::Everyone, Event::Release); | |
| 81 | + | |
| 82 | + Ok(()) | |
| 83 | + } | |
| 84 | +} |
crates/server/src/db/mod.rsmodified+1 -0
| @@ -9,6 +9,7 @@ pub mod member; | ||
| 9 | 9 | pub mod message; |
| 10 | 10 | pub mod poll; |
| 11 | 11 | pub mod registration_code; |
| 12 | +pub mod release; | |
| 12 | 13 | pub mod report; |
| 13 | 14 | pub mod server_ban; |
| 14 | 15 | pub mod session; |
crates/server/src/db/release.rsadded+137 -0
| @@ -0,0 +1,137 @@ | ||
| 1 | +use common::{model::Staged, time::now_ms, update::Sha}; | |
| 2 | + | |
| 3 | +use super::{Connection, all, maybe, one, run}; | |
| 4 | +use crate::error::ServerError; | |
| 5 | + | |
| 6 | +pub struct Entry { | |
| 7 | + pub seq: u64, | |
| 8 | + pub required: bool, | |
| 9 | + pub created_ms: u64, | |
| 10 | + pub files: Vec<Staged>, | |
| 11 | +} | |
| 12 | + | |
| 13 | +fn sha(bytes: Vec<u8>) -> Result<Sha, ServerError> { | |
| 14 | + bytes | |
| 15 | + .try_into() | |
| 16 | + .map_err(|_| ServerError::Internal("bad sha length".into())) | |
| 17 | +} | |
| 18 | + | |
| 19 | +fn staged(r: &mut super::Reader) -> Result<Staged, ServerError> { | |
| 20 | + Ok(Staged { | |
| 21 | + file: sha(r.get()?)?, | |
| 22 | + target: r.get()?, | |
| 23 | + size: r.get()?, | |
| 24 | + packed: r.get()?, | |
| 25 | + }) | |
| 26 | +} | |
| 27 | + | |
| 28 | +pub async fn seq_of(file: &Sha, db: &Connection) -> Result<Option<u64>, ServerError> { | |
| 29 | + maybe( | |
| 30 | + db, | |
| 31 | + "SELECT seq FROM release_file WHERE file = ?1", | |
| 32 | + (&file[..],), | |
| 33 | + |r| r.get(), | |
| 34 | + ) | |
| 35 | + .await | |
| 36 | +} | |
| 37 | + | |
| 38 | +pub async fn latest(target: &str, db: &Connection) -> Result<Option<(u64, Staged)>, ServerError> { | |
| 39 | + maybe( | |
| 40 | + db, | |
| 41 | + "SELECT seq, file, target, size, packed FROM release_file WHERE target = ?1 ORDER BY seq DESC LIMIT 1", | |
| 42 | + (target,), | |
| 43 | + |r| Ok((r.get()?, staged(r)?)), | |
| 44 | + ) | |
| 45 | + .await | |
| 46 | +} | |
| 47 | + | |
| 48 | +pub async fn live(db: &Connection) -> Result<Vec<Sha>, ServerError> { | |
| 49 | + all( | |
| 50 | + db, | |
| 51 | + "SELECT file FROM release_file AS f WHERE NOT EXISTS (SELECT 1 FROM release_file AS newer WHERE newer.target = f.target AND newer.seq > f.seq)", | |
| 52 | + (), | |
| 53 | + |r| sha(r.get()?), | |
| 54 | + ) | |
| 55 | + .await | |
| 56 | +} | |
| 57 | + | |
| 58 | +pub async fn required_after(seq: u64, db: &Connection) -> Result<Vec<String>, ServerError> { | |
| 59 | + all( | |
| 60 | + db, | |
| 61 | + "SELECT f.target FROM release AS r JOIN release_file AS f ON f.seq = r.seq WHERE r.seq > ?1 AND r.required = 1", | |
| 62 | + (seq,), | |
| 63 | + |r| r.get(), | |
| 64 | + ) | |
| 65 | + .await | |
| 66 | +} | |
| 67 | + | |
| 68 | +pub async fn insert(required: bool, files: &[Staged], db: &Connection) -> Result<u64, ServerError> { | |
| 69 | + let seq: u64 = one( | |
| 70 | + db, | |
| 71 | + "INSERT INTO release (seq, required, created_ms) VALUES ((SELECT COALESCE(MAX(seq), 0) + 1 FROM release), ?1, ?2) RETURNING seq", | |
| 72 | + (required, now_ms()), | |
| 73 | + |r| r.get(), | |
| 74 | + ) | |
| 75 | + .await?; | |
| 76 | + for file in files { | |
| 77 | + run( | |
| 78 | + db, | |
| 79 | + "INSERT INTO release_file (file, seq, target, size, packed) VALUES (?1, ?2, ?3, ?4, ?5)", | |
| 80 | + (&file.file[..], seq, file.target.as_str(), file.size, file.packed), | |
| 81 | + ) | |
| 82 | + .await?; | |
| 83 | + } | |
| 84 | + | |
| 85 | + Ok(seq) | |
| 86 | +} | |
| 87 | + | |
| 88 | +pub async fn set_required(seq: u64, required: bool, db: &Connection) -> Result<(), ServerError> { | |
| 89 | + let changed = run( | |
| 90 | + db, | |
| 91 | + "UPDATE release SET required = ?2 WHERE seq = ?1", | |
| 92 | + (seq, required), | |
| 93 | + ) | |
| 94 | + .await?; | |
| 95 | + if changed == 0 { | |
| 96 | + return Err(common::error::Error::NotFound.into()); | |
| 97 | + } | |
| 98 | + | |
| 99 | + Ok(()) | |
| 100 | +} | |
| 101 | + | |
| 102 | +pub async fn entry(seq: u64, db: &Connection) -> Result<Entry, ServerError> { | |
| 103 | + let (required, created_ms) = one( | |
| 104 | + db, | |
| 105 | + "SELECT required, created_ms FROM release WHERE seq = ?1", | |
| 106 | + (seq,), | |
| 107 | + |r| Ok((r.get::<bool>()?, r.get::<u64>()?)), | |
| 108 | + ) | |
| 109 | + .await?; | |
| 110 | + let files = all( | |
| 111 | + db, | |
| 112 | + "SELECT file, target, size, packed FROM release_file WHERE seq = ?1 ORDER BY target", | |
| 113 | + (seq,), | |
| 114 | + staged, | |
| 115 | + ) | |
| 116 | + .await?; | |
| 117 | + | |
| 118 | + Ok(Entry { | |
| 119 | + seq, | |
| 120 | + required, | |
| 121 | + created_ms, | |
| 122 | + files, | |
| 123 | + }) | |
| 124 | +} | |
| 125 | + | |
| 126 | +pub async fn entries(db: &Connection) -> Result<Vec<Entry>, ServerError> { | |
| 127 | + let seqs: Vec<u64> = all(db, "SELECT seq FROM release ORDER BY seq DESC", (), |r| { | |
| 128 | + r.get() | |
| 129 | + }) | |
| 130 | + .await?; | |
| 131 | + let mut entries = Vec::new(); | |
| 132 | + for seq in seqs { | |
| 133 | + entries.push(entry(seq, db).await?); | |
| 134 | + } | |
| 135 | + | |
| 136 | + Ok(entries) | |
| 137 | +} |
crates/server/src/db/schema.sqlmodified+15 -0
| @@ -226,3 +226,18 @@ CREATE TABLE server_settings ( | ||
| 226 | 226 | id INTEGER PRIMARY KEY CHECK (id = 1), |
| 227 | 227 | data BLOB NOT NULL |
| 228 | 228 | ) STRICT; |
| 229 | + | |
| 230 | +CREATE TABLE release ( | |
| 231 | + seq INTEGER PRIMARY KEY, | |
| 232 | + required INTEGER NOT NULL, | |
| 233 | + created_ms INTEGER NOT NULL | |
| 234 | +) STRICT; | |
| 235 | + | |
| 236 | +CREATE TABLE release_file ( | |
| 237 | + file BLOB PRIMARY KEY, | |
| 238 | + seq INTEGER NOT NULL REFERENCES release (seq), | |
| 239 | + target TEXT NOT NULL, | |
| 240 | + size INTEGER NOT NULL, | |
| 241 | + packed INTEGER NOT NULL, | |
| 242 | + UNIQUE (seq, target) | |
| 243 | +) STRICT; |
crates/server/src/hub.rsmodified+18 -3
| @@ -7,7 +7,7 @@ use std::{ | ||
| 7 | 7 | }; |
| 8 | 8 | |
| 9 | 9 | use bytes::Bytes; |
| 10 | -use common::{model::Id, transport::Close}; | |
| 10 | +use common::{model::Id, transport::Close, update::Sha}; | |
| 11 | 11 | use quinn::Connection; |
| 12 | 12 | use tokio::sync::mpsc::{self, error::TrySendError}; |
| 13 | 13 | use tracing::warn; |
| @@ -27,6 +27,7 @@ pub struct Client { | ||
| 27 | 27 | pub id: ConnId, |
| 28 | 28 | pub conn: Option<Connection>, |
| 29 | 29 | pub me: Option<Signed>, |
| 30 | + pub build: Option<Sha>, | |
| 30 | 31 | tx: mpsc::Sender<Bytes>, |
| 31 | 32 | pub closed: AtomicBool, |
| 32 | 33 | watching: Mutex<Option<Id>>, |
| @@ -34,12 +35,17 @@ pub struct Client { | ||
| 34 | 35 | } |
| 35 | 36 | |
| 36 | 37 | impl Client { |
| 37 | - pub fn new(conn: Option<Connection>, me: Option<Signed>) -> (Arc<Self>, mpsc::Receiver<Bytes>) { | |
| 38 | + pub fn new( | |
| 39 | + conn: Option<Connection>, | |
| 40 | + me: Option<Signed>, | |
| 41 | + build: Option<Sha>, | |
| 42 | + ) -> (Arc<Self>, mpsc::Receiver<Bytes>) { | |
| 38 | 43 | let (tx, rx) = mpsc::channel(QUEUE_LENGTH); |
| 39 | 44 | let client = Arc::new(Self { |
| 40 | 45 | id: NEXT_ID.fetch_add(1, Ordering::Relaxed), |
| 41 | 46 | conn, |
| 42 | 47 | me, |
| 48 | + build, | |
| 43 | 49 | tx, |
| 44 | 50 | closed: AtomicBool::new(false), |
| 45 | 51 | watching: Mutex::new(None), |
| @@ -50,7 +56,7 @@ impl Client { | ||
| 50 | 56 | } |
| 51 | 57 | |
| 52 | 58 | pub fn detached(me: Option<Signed>) -> Arc<Self> { |
| 53 | - Self::new(None, me).0 | |
| 59 | + Self::new(None, me, None).0 | |
| 54 | 60 | } |
| 55 | 61 | |
| 56 | 62 | pub fn user_id(&self) -> Option<Id> { |
| @@ -157,6 +163,15 @@ impl Hub { | ||
| 157 | 163 | total |
| 158 | 164 | } |
| 159 | 165 | |
| 166 | + pub fn builds(&self) -> Vec<Sha> { | |
| 167 | + self.0 | |
| 168 | + .lock() | |
| 169 | + .unwrap() | |
| 170 | + .values() | |
| 171 | + .filter_map(|client| client.build) | |
| 172 | + .collect() | |
| 173 | + } | |
| 174 | + | |
| 160 | 175 | pub fn all(&self) -> Vec<ConnId> { |
| 161 | 176 | self.0.lock().unwrap().keys().copied().collect() |
| 162 | 177 | } |
crates/server/src/lib.rsmodified+6 -2
| @@ -74,7 +74,11 @@ pub async fn showtime() -> Result<(), ServerError> { | ||
| 74 | 74 | let certificate = certificate::load(&config.certificate_path, &config.key_path)?; |
| 75 | 75 | let attachments = sibling_directory(&config.database_path, "attachments")?; |
| 76 | 76 | let backups = sibling_directory(&config.database_path, "backups")?; |
| 77 | - let clients = update::Clients::load(sibling_directory(&config.database_path, "clients")?).await; | |
| 77 | + let releases = update::Releases::load( | |
| 78 | + sibling_directory(&config.database_path, "clients")?, | |
| 79 | + &database, | |
| 80 | + ) | |
| 81 | + .await?; | |
| 78 | 82 | tokio::spawn(files::collect(database.clone(), attachments.clone())); |
| 79 | 83 | |
| 80 | 84 | network::serve( |
| @@ -83,7 +87,7 @@ pub async fn showtime() -> Result<(), ServerError> { | ||
| 83 | 87 | database, |
| 84 | 88 | attachments, |
| 85 | 89 | backups, |
| 86 | - clients, | |
| 90 | + releases, | |
| 87 | 91 | ) |
| 88 | 92 | .await |
| 89 | 93 | } |
crates/server/src/network.rsmodified+19 -5
| @@ -48,7 +48,7 @@ pub(crate) struct Shared { | ||
| 48 | 48 | pub(crate) services: Services, |
| 49 | 49 | pub(crate) directory: PathBuf, |
| 50 | 50 | pub(crate) backups: PathBuf, |
| 51 | - pub(crate) clients: crate::update::Clients, | |
| 51 | + pub(crate) releases: crate::update::Releases, | |
| 52 | 52 | } |
| 53 | 53 | |
| 54 | 54 | struct Pending { |
| @@ -64,7 +64,7 @@ pub async fn serve( | ||
| 64 | 64 | db: Db, |
| 65 | 65 | directory: PathBuf, |
| 66 | 66 | backups: PathBuf, |
| 67 | - clients: crate::update::Clients, | |
| 67 | + releases: crate::update::Releases, | |
| 68 | 68 | ) -> Result<(), ServerError> { |
| 69 | 69 | let endpoint = transport::endpoint( |
| 70 | 70 | server_address.parse()?, |
| @@ -78,7 +78,7 @@ pub async fn serve( | ||
| 78 | 78 | services: Services::default(), |
| 79 | 79 | directory, |
| 80 | 80 | backups, |
| 81 | - clients, | |
| 81 | + releases, | |
| 82 | 82 | }; |
| 83 | 83 | shared.services.machine.watch(shared.directory.clone()); |
| 84 | 84 | |
| @@ -116,7 +116,7 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Serv | ||
| 116 | 116 | .and_then(|data| data.downcast::<quinn::crypto::rustls::HandshakeData>().ok()) |
| 117 | 117 | .and_then(|data| data.protocol); |
| 118 | 118 | if alpn.as_deref() == Some(common::update::ALPN) { |
| 119 | - shared.clients.serve(connection).await; | |
| 119 | + shared.releases.serve(connection, &shared.db).await; | |
| 120 | 120 | return Ok(()); |
| 121 | 121 | } |
| 122 | 122 | let pending = match tokio::time::timeout(HELLO_DEADLINE, greet(&connection, &shared)).await { |
| @@ -230,9 +230,10 @@ async fn greet(connection: &Connection, shared: &Shared) -> Result<Option<Pendin | ||
| 230 | 230 | let (send_stream, mut receive_stream) = connection.accept_bi().await?; |
| 231 | 231 | let mut reply_stream = Sending::new(send_stream); |
| 232 | 232 | let hello: Hello = frame::read(&mut receive_stream, UP_MAX).await?; |
| 233 | + let build = hello.build; | |
| 233 | 234 | match admit(hello, connection, shared).await { |
| 234 | 235 | Ok((me, user)) => { |
| 235 | - let (client, events) = Client::new(Some(connection.clone()), me); | |
| 236 | + let (client, events) = Client::new(Some(connection.clone()), me, build); | |
| 236 | 237 | |
| 237 | 238 | Ok(Some(Pending { |
| 238 | 239 | client, |
| @@ -333,6 +334,19 @@ async fn route( | ||
| 333 | 334 | ) |
| 334 | 335 | .await |
| 335 | 336 | } |
| 337 | + Open::Stage(stage) => { | |
| 338 | + let user = signed_user(&client, &shared).await?; | |
| 339 | + shared | |
| 340 | + .releases | |
| 341 | + .stage( | |
| 342 | + user.as_ref(), | |
| 343 | + stage, | |
| 344 | + receive_stream, | |
| 345 | + send_stream, | |
| 346 | + &shared.db, | |
| 347 | + ) | |
| 348 | + .await | |
| 349 | + } | |
| 336 | 350 | Open::Fetch(blob) => { |
| 337 | 351 | let user = signed_user(&client, &shared).await?; |
| 338 | 352 | files::fetch( |
crates/server/src/request.rsmodified+1 -1
| @@ -373,7 +373,7 @@ mod tests { | ||
| 373 | 373 | services: services.clone(), |
| 374 | 374 | directory: test::directory(), |
| 375 | 375 | backups: test::directory(), |
| 376 | - clients: Default::default(), | |
| 376 | + releases: Default::default(), | |
| 377 | 377 | } |
| 378 | 378 | } |
| 379 | 379 |
crates/server/src/update.rsmodified+195 -41
| @@ -1,70 +1,224 @@ | ||
| 1 | -use std::{collections::HashMap, path::PathBuf, sync::Arc}; | |
| 1 | +use std::{ | |
| 2 | + collections::HashMap, | |
| 3 | + io::Write, | |
| 4 | + path::{Path, PathBuf}, | |
| 5 | + sync::{Arc, Mutex}, | |
| 6 | +}; | |
| 2 | 7 | |
| 3 | 8 | use common::{ |
| 4 | - frame::{self, Sending, UP_MAX}, | |
| 5 | - update::{Answer, Ask, valid_target}, | |
| 9 | + error::{Error as CommonError, ReleaseProblem}, | |
| 10 | + frame::{self, DOWN_MAX, Sending, UP_MAX}, | |
| 11 | + model::{Staged, User}, | |
| 12 | + open::Stage, | |
| 13 | + permission, | |
| 14 | + update::{Ask, FILE_MAX, Offer, Sha, Status, hex, sha256, target_of}, | |
| 15 | +}; | |
| 16 | +use quinn::{Connection, RecvStream, VarInt}; | |
| 17 | +use tracing::warn; | |
| 18 | + | |
| 19 | +use crate::{ | |
| 20 | + db::{self, Connection as DbConnection, Db}, | |
| 21 | + error::{ServerError, ensure, ensure_with}, | |
| 6 | 22 | }; |
| 7 | -use quinn::Connection; | |
| 8 | -use tracing::{info, warn}; | |
| 23 | + | |
| 24 | +const PACK_LEVEL: i32 = 19; | |
| 25 | + | |
| 26 | +fn path_of(directory: &Path, file: &Sha) -> PathBuf { | |
| 27 | + directory.join(format!("{}.zst", hex(file))) | |
| 28 | +} | |
| 29 | + | |
| 30 | +fn pack(bytes: &[u8], path: &Path) -> std::io::Result<u64> { | |
| 31 | + let mut encoder = zstd::Encoder::new(std::fs::File::create(path)?, PACK_LEVEL)?; | |
| 32 | + encoder.multithread(std::thread::available_parallelism()?.get() as u32)?; | |
| 33 | + encoder.write_all(bytes)?; | |
| 34 | + | |
| 35 | + Ok(encoder.finish()?.metadata()?.len()) | |
| 36 | +} | |
| 9 | 37 | |
| 10 | 38 | #[derive(Clone, Default)] |
| 11 | -pub struct Clients { | |
| 39 | +pub struct Releases { | |
| 12 | 40 | directory: PathBuf, |
| 13 | - files: Arc<HashMap<String, (u64, [u8; 32])>>, | |
| 41 | + staged: Arc<Mutex<HashMap<Sha, Staged>>>, | |
| 14 | 42 | } |
| 15 | 43 | |
| 16 | -impl Clients { | |
| 17 | - pub async fn load(directory: PathBuf) -> Self { | |
| 18 | - let mut files = HashMap::new(); | |
| 19 | - if let Ok(mut entries) = tokio::fs::read_dir(&directory).await { | |
| 20 | - while let Ok(Some(entry)) = entries.next_entry().await { | |
| 21 | - let target = entry.file_name().to_string_lossy().into_owned(); | |
| 22 | - if !valid_target(&target) { | |
| 23 | - continue; | |
| 24 | - } | |
| 25 | - match tokio::fs::read(entry.path()).await { | |
| 26 | - Ok(bytes) => { | |
| 27 | - info!("client {target} ready"); | |
| 28 | - files.insert(target, (bytes.len() as u64, common::update::sha256(&bytes))); | |
| 29 | - } | |
| 30 | - Err(error) => warn!("client {target}: {error}"), | |
| 31 | - } | |
| 44 | +impl Releases { | |
| 45 | + pub async fn load(directory: PathBuf, db: &Db) -> Result<Self, ServerError> { | |
| 46 | + let live = db.run(async |conn| db::release::live(conn).await).await?; | |
| 47 | + let keep: Vec<PathBuf> = live.iter().map(|file| path_of(&directory, file)).collect(); | |
| 48 | + for entry in std::fs::read_dir(&directory)? { | |
| 49 | + let path = entry?.path(); | |
| 50 | + if path.extension().is_some_and(|ext| ext == "zst") && !keep.contains(&path) { | |
| 51 | + let _ = std::fs::remove_file(&path); | |
| 32 | 52 | } |
| 33 | 53 | } |
| 34 | - Self { | |
| 54 | + | |
| 55 | + Ok(Self { | |
| 35 | 56 | directory, |
| 36 | - files: Arc::new(files), | |
| 57 | + staged: Default::default(), | |
| 58 | + }) | |
| 59 | + } | |
| 60 | + | |
| 61 | + pub async fn stage( | |
| 62 | + &self, | |
| 63 | + user: Option<&User>, | |
| 64 | + header: Stage, | |
| 65 | + mut receive_stream: RecvStream, | |
| 66 | + mut send_stream: Sending, | |
| 67 | + db: &Db, | |
| 68 | + ) -> Result<(), ServerError> { | |
| 69 | + let staged = self.store(user, header.size, &mut receive_stream, db).await; | |
| 70 | + let rejected = staged.is_err(); | |
| 71 | + let reply = staged.map_err(CommonError::from); | |
| 72 | + frame::write(&mut send_stream, &reply, DOWN_MAX).await?; | |
| 73 | + send_stream.finish()?; | |
| 74 | + if rejected { | |
| 75 | + let _ = receive_stream.stop(VarInt::from_u32(0)); | |
| 76 | + } | |
| 77 | + | |
| 78 | + Ok(()) | |
| 79 | + } | |
| 80 | + | |
| 81 | + async fn store( | |
| 82 | + &self, | |
| 83 | + user: Option<&User>, | |
| 84 | + size: u64, | |
| 85 | + receive: &mut RecvStream, | |
| 86 | + db: &Db, | |
| 87 | + ) -> Result<Staged, ServerError> { | |
| 88 | + let user = user.ok_or(CommonError::Unauthenticated)?; | |
| 89 | + ensure(permission::is_builder(user.role))?; | |
| 90 | + ensure_with( | |
| 91 | + size > 0 && size <= FILE_MAX, | |
| 92 | + CommonError::Release(ReleaseProblem::TooLarge), | |
| 93 | + )?; | |
| 94 | + let mut bytes = vec![0; size as usize]; | |
| 95 | + receive.read_exact(&mut bytes).await?; | |
| 96 | + | |
| 97 | + let file = sha256(&bytes); | |
| 98 | + let target = target_of(&bytes).ok_or(CommonError::Release(ReleaseProblem::NotClient))?; | |
| 99 | + if let Some(seq) = db | |
| 100 | + .run(async |conn| db::release::seq_of(&file, conn).await) | |
| 101 | + .await? | |
| 102 | + { | |
| 103 | + return Err(CommonError::Release(ReleaseProblem::Released(seq)).into()); | |
| 104 | + } | |
| 105 | + | |
| 106 | + let path = path_of(&self.directory, &file); | |
| 107 | + let job = path.clone(); | |
| 108 | + let packed = tokio::task::spawn_blocking(move || pack(&bytes, &job)).await?; | |
| 109 | + let packed = packed.inspect_err(|_| { | |
| 110 | + let _ = std::fs::remove_file(&path); | |
| 111 | + })?; | |
| 112 | + | |
| 113 | + let staged = Staged { | |
| 114 | + file, | |
| 115 | + target, | |
| 116 | + size, | |
| 117 | + packed, | |
| 118 | + }; | |
| 119 | + self.staged.lock().unwrap().insert(file, staged.clone()); | |
| 120 | + | |
| 121 | + Ok(staged) | |
| 122 | + } | |
| 123 | + | |
| 124 | + pub fn staged(&self, files: &[Sha]) -> Result<Vec<Staged>, ServerError> { | |
| 125 | + ensure_with( | |
| 126 | + !files.is_empty(), | |
| 127 | + CommonError::Release(ReleaseProblem::Empty), | |
| 128 | + )?; | |
| 129 | + let map = self.staged.lock().unwrap(); | |
| 130 | + let picked = files | |
| 131 | + .iter() | |
| 132 | + .map(|file| { | |
| 133 | + map.get(file) | |
| 134 | + .cloned() | |
| 135 | + .ok_or(CommonError::Release(ReleaseProblem::NotStaged)) | |
| 136 | + }) | |
| 137 | + .collect::<Result<Vec<_>, _>>()?; | |
| 138 | + let targets: std::collections::HashSet<&str> = | |
| 139 | + picked.iter().map(|staged| staged.target.as_str()).collect(); | |
| 140 | + ensure_with( | |
| 141 | + targets.len() == picked.len(), | |
| 142 | + CommonError::Release(ReleaseProblem::SameTarget), | |
| 143 | + )?; | |
| 144 | + | |
| 145 | + Ok(picked) | |
| 146 | + } | |
| 147 | + | |
| 148 | + pub fn unstage(&self, files: &[Sha]) { | |
| 149 | + let mut map = self.staged.lock().unwrap(); | |
| 150 | + for file in files { | |
| 151 | + map.remove(file); | |
| 152 | + } | |
| 153 | + } | |
| 154 | + | |
| 155 | + pub fn discard(&self, files: &[Sha]) { | |
| 156 | + for file in files { | |
| 157 | + let _ = std::fs::remove_file(path_of(&self.directory, file)); | |
| 37 | 158 | } |
| 38 | 159 | } |
| 39 | 160 | |
| 40 | - pub async fn serve(&self, connection: Connection) { | |
| 161 | + pub async fn serve(&self, connection: Connection, db: &Db) { | |
| 41 | 162 | while let Ok((send, mut receive)) = connection.accept_bi().await { |
| 42 | 163 | let Ok(ask) = frame::read::<Ask>(&mut receive, UP_MAX).await else { |
| 43 | 164 | return; |
| 44 | 165 | }; |
| 45 | - if let Err(error) = self.answer(ask, Sending::new(send)).await { | |
| 166 | + if let Err(error) = self.answer(ask, db, Sending::new(send)).await { | |
| 46 | 167 | warn!("update: {error}"); |
| 47 | 168 | return; |
| 48 | 169 | } |
| 49 | 170 | } |
| 50 | 171 | } |
| 51 | 172 | |
| 52 | - async fn answer(&self, ask: Ask, mut send: Sending) -> Result<(), Box<dyn std::error::Error>> { | |
| 53 | - let answer = match self.files.get(&ask.target) { | |
| 54 | - None => Answer::Missing, | |
| 55 | - Some((_, sha256)) if *sha256 == ask.sha256 => Answer::Current, | |
| 56 | - Some((size, sha256)) => Answer::File { | |
| 57 | - size: *size, | |
| 58 | - sha256: *sha256, | |
| 59 | - }, | |
| 60 | - }; | |
| 61 | - frame::write(&mut send, &answer, UP_MAX).await?; | |
| 62 | - if let Answer::File { .. } = answer { | |
| 63 | - info!("update: sending {}", ask.target); | |
| 64 | - let mut file = tokio::fs::File::open(self.directory.join(&ask.target)).await?; | |
| 65 | - tokio::io::copy(&mut file, send.get()).await?; | |
| 173 | + async fn answer(&self, ask: Ask, db: &Db, mut send: Sending) -> Result<(), ServerError> { | |
| 174 | + match ask { | |
| 175 | + Ask::Check { build, targets } => { | |
| 176 | + let status = db | |
| 177 | + .run(async |conn| status(build, &targets, conn).await) | |
| 178 | + .await?; | |
| 179 | + frame::write(&mut send, &status, DOWN_MAX).await?; | |
| 180 | + } | |
| 181 | + Ask::Download { file } => { | |
| 182 | + let live = db.run(async |conn| db::release::live(conn).await).await?; | |
| 183 | + if live.contains(&file) { | |
| 184 | + let mut packed = tokio::fs::File::open(path_of(&self.directory, &file)).await?; | |
| 185 | + tokio::io::copy(&mut packed, send.get()).await?; | |
| 186 | + } | |
| 187 | + } | |
| 66 | 188 | } |
| 67 | 189 | send.finish()?; |
| 190 | + | |
| 68 | 191 | Ok(()) |
| 69 | 192 | } |
| 70 | 193 | } |
| 194 | + | |
| 195 | +async fn status(build: Sha, targets: &[String], db: &DbConnection) -> Result<Status, ServerError> { | |
| 196 | + let Some(current) = db::release::seq_of(&build, db).await? else { | |
| 197 | + return Ok(Status::Unknown); | |
| 198 | + }; | |
| 199 | + let mut offered = None; | |
| 200 | + for target in targets { | |
| 201 | + offered = db::release::latest(target, db).await?; | |
| 202 | + if offered.is_some() { | |
| 203 | + break; | |
| 204 | + } | |
| 205 | + } | |
| 206 | + let Some((seq, live)) = offered else { | |
| 207 | + return Ok(Status::Latest); | |
| 208 | + }; | |
| 209 | + if live.file == build { | |
| 210 | + return Ok(Status::Latest); | |
| 211 | + } | |
| 212 | + let required = db::release::required_after(current, db) | |
| 213 | + .await? | |
| 214 | + .iter() | |
| 215 | + .any(|target| targets.contains(target)); | |
| 216 | + | |
| 217 | + Ok(Status::Offer(Offer { | |
| 218 | + seq, | |
| 219 | + required, | |
| 220 | + file: live.file, | |
| 221 | + size: live.size, | |
| 222 | + packed: live.packed, | |
| 223 | + })) | |
| 224 | +} |
packaging/release-windows.ps1deleted+0 -14
| @@ -1,14 +0,0 @@ | ||
| 1 | -param([Parameter(Mandatory)][string]$Levels) | |
| 2 | -$ErrorActionPreference = 'Stop' | |
| 3 | -Set-Location (Split-Path $PSScriptRoot) | |
| 4 | -$env:Path += ";$env:USERPROFILE\.cargo\bin" | |
| 5 | -$env:YUMUSH_RELEASE = '1' | |
| 6 | -New-Item -ItemType Directory -Force dist | Out-Null | |
| 7 | -foreach ($level in $Levels.Split(' ')) { | |
| 8 | - $cpu = if ($level -eq 'v1') { 'x86-64' } else { "x86-64-$level" } | |
| 9 | - $env:RUSTFLAGS = "-C target-feature=+crt-static -C target-cpu=$cpu" | |
| 10 | - $env:CARGO_TARGET_DIR = "..\target-release-$level" | |
| 11 | - cargo build --release --locked -p client | |
| 12 | - if ($LASTEXITCODE -ne 0) { throw 'build failed' } | |
| 13 | - Copy-Item "..\target-release-$level\release\client.exe" "dist\x86_64_$level-windows" | |
| 14 | -} |
packaging/release.shdeleted+0 -34
| @@ -1,34 +0,0 @@ | ||
| 1 | -#!/usr/bin/env bash | |
| 2 | -set -euo pipefail | |
| 3 | -ROOT="$(cd "$(dirname "$0")/.." && pwd)" | |
| 4 | -LEVELS="v1 v3" | |
| 5 | -DIST="$ROOT/dist" | |
| 6 | -cd "$ROOT" | |
| 7 | -[[ $# -eq 1 ]] || { echo "usage: $0 linux|windows" >&2; exit 1; } | |
| 8 | -mkdir -p "$DIST" | |
| 9 | - | |
| 10 | -case "$1" in | |
| 11 | -linux) | |
| 12 | - for level in $LEVELS; do | |
| 13 | - cpu="x86-64-$level"; [[ $level == v1 ]] && cpu="x86-64" | |
| 14 | - RUSTFLAGS="-C target-cpu=$cpu" CARGO_TARGET_DIR="target/release-$level" YUMUSH_RELEASE=1 \ | |
| 15 | - cargo build --release --locked -p client | |
| 16 | - cp "target/release-$level/release/client" "$DIST/x86_64_$level-linux" | |
| 17 | - done | |
| 18 | - ;; | |
| 19 | -windows) | |
| 20 | - ssh_win() { ssh -i ~/vm/yumush-win/id_ed25519 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=10 -o LogLevel=ERROR -p 2222 yumush@127.0.0.1 "$@"; } | |
| 21 | - scp_win() { scp -q -i ~/vm/yumush-win/id_ed25519 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR -P 2222 "$@"; } | |
| 22 | - TAR="$(mktemp --suffix=.tgz)" | |
| 23 | - trap 'rm -f "$TAR"' EXIT | |
| 24 | - git ls-files | tar czf "$TAR" -T - | |
| 25 | - ssh_win 'Remove-Item -Recurse -Force release -ErrorAction SilentlyContinue; New-Item -ItemType Directory release | Out-Null' | |
| 26 | - scp_win "$TAR" yumush@127.0.0.1:release.tgz | |
| 27 | - ssh_win "tar xmzf release.tgz -C release; powershell -NoProfile -ExecutionPolicy Bypass -File release\\packaging\\release-windows.ps1 -Levels '$LEVELS'" | |
| 28 | - for level in $LEVELS; do | |
| 29 | - scp_win "yumush@127.0.0.1:release/dist/x86_64_$level-windows" "$DIST/" | |
| 30 | - done | |
| 31 | - ;; | |
| 32 | -*) echo "usage: $0 linux|windows" >&2; exit 1 ;; | |
| 33 | -esac | |
| 34 | -echo "copy $DIST/* into the server's clients/ (next to the database), then restart the server" |