Build & publish from Builder › Releases. Pick the yumush source once
Browse files at this commit9063f7e64d4e12a5309c76176b3922e29af80f79Parent: e4e5341- feat
- Build & publish from Builder › Releases. Pick the yumush source once
- the button refuses a dirty tree, builds linux x86_64 v1/v3 locally and windows v1/v3 inside the yumush-win dockur VM over ssh (started and stopped as needed, skipped if missing), shows per-job crate progress and the latest cargo line, then uploads and publishes the four binaries. Clients card shows every install (persistent install id) with user, device, running release/target, update state with live download percent, online/last seen
- server counts download progress while serving and clients report installing/ready/failed. Cargo aliases removed
21 changed files +1255 -54
- .cargo/config.toml +0 -4
- crates/client/lang/en/builder_release.txt +22 -0
- crates/client/lang/tr/builder_release.txt +22 -0
- crates/client/src/gui/builder.rs +1 -1
- crates/client/src/gui/builder/releases.rs +415 -8
- crates/client/src/lib.rs +1 -0
- crates/client/src/net/link.rs +5 -8
- crates/client/src/net/mod.rs +1 -1
- crates/client/src/release.rs +463 -0
- crates/client/src/settings.rs +12 -1
- crates/client/src/update.rs +92 -16
- crates/common/src/call.rs +6 -2
- crates/common/src/model.rs +22 -0
- crates/common/src/session.rs +1 -0
- crates/common/src/update.rs +19 -2
- crates/server/src/call/mod.rs +1 -0
- crates/server/src/call/release.rs +26 -2
- crates/server/src/db/release.rs +10 -0
- crates/server/src/hub.rs +18 -2
- crates/server/src/network.rs +2 -1
- crates/server/src/update.rs +116 -6
.cargo/config.tomlmodified+0 -4
| @@ -24,7 +24,3 @@ rustflags = [ | |||
| 24 | "-C", "link-arg=/OPT:REF", | 24 | "-C", "link-arg=/OPT:REF", |
| 25 | "-C", "link-arg=/OPT:ICF" | 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']"] | ||
crates/client/lang/en/builder_release.txtmodified+22 -0
| @@ -7,3 +7,25 @@ required = Required | |||
| 7 | publish = Publish | 7 | publish = Publish |
| 8 | confirm = Confirm | 8 | confirm = Confirm |
| 9 | no_releases = No releases | 9 | no_releases = No releases |
| 10 | +build = Build & publish | ||
| 11 | +choose_source = Choose source | ||
| 12 | +no_source = No source folder | ||
| 13 | +not_source = Not a release source | ||
| 14 | +cancel = Cancel | ||
| 15 | +waiting = Waiting | ||
| 16 | +done = Done | ||
| 17 | +skipped = Skipped | ||
| 18 | +failed = Failed | ||
| 19 | +linux_v1 = Linux v1 | ||
| 20 | +linux_v3 = Linux v3 | ||
| 21 | +windows_vm = Windows VM | ||
| 22 | +windows_v1 = Windows v1 | ||
| 23 | +windows_v3 = Windows v3 | ||
| 24 | +clients = Clients | ||
| 25 | +no_clients = No clients | ||
| 26 | +unknown = Unknown | ||
| 27 | +dev = Dev | ||
| 28 | +latest = Latest | ||
| 29 | +available = Available | ||
| 30 | +installing = Installing | ||
| 31 | +ready = Ready | ||
crates/client/lang/tr/builder_release.txtmodified+22 -0
| @@ -7,3 +7,25 @@ required = Zorunlu | |||
| 7 | publish = Yayınla | 7 | publish = Yayınla |
| 8 | confirm = Onayla | 8 | confirm = Onayla |
| 9 | no_releases = Sürüm yok | 9 | no_releases = Sürüm yok |
| 10 | +build = Derle ve yayınla | ||
| 11 | +choose_source = Kaynak seç | ||
| 12 | +no_source = Kaynak klasörü yok | ||
| 13 | +not_source = Geçerli bir sürüm kaynağı değil | ||
| 14 | +cancel = İptal | ||
| 15 | +waiting = Bekliyor | ||
| 16 | +done = Tamam | ||
| 17 | +skipped = Atlandı | ||
| 18 | +failed = Başarısız | ||
| 19 | +linux_v1 = Linux v1 | ||
| 20 | +linux_v3 = Linux v3 | ||
| 21 | +windows_vm = Windows VM | ||
| 22 | +windows_v1 = Windows v1 | ||
| 23 | +windows_v3 = Windows v3 | ||
| 24 | +clients = İstemciler | ||
| 25 | +no_clients = İstemci yok | ||
| 26 | +unknown = Bilinmiyor | ||
| 27 | +dev = Geliştirme | ||
| 28 | +latest = Güncel | ||
| 29 | +available = Mevcut | ||
| 30 | +installing = Kuruluyor | ||
| 31 | +ready = Hazır | ||
crates/client/src/gui/builder.rsmodified+1 -1
| @@ -380,7 +380,7 @@ impl Yumush { | |||
| 380 | ); | 380 | ); |
| 381 | } | 381 | } |
| 382 | 382 | ||
| 383 | - pub(super) fn releases_changed(&self, window: &mut Window, cx: &mut Context<Self>) { | 383 | + pub(super) fn releases_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 384 | if self.chat.view == View::Builder && self.chat.builder_tab == BuilderTab::Releases { | 384 | if self.chat.view == View::Builder && self.chat.builder_tab == BuilderTab::Releases { |
| 385 | self.load_releases(window, cx); | 385 | self.load_releases(window, cx); |
| 386 | } | 386 | } |
crates/client/src/gui/builder/releases.rsmodified+415 -8
| @@ -1,22 +1,28 @@ | |||
| 1 | use common::{ | 1 | use common::{ |
| 2 | - call::{ListReleases, PublishRelease, SetReleaseRequired}, | 2 | + call::{ListReleases, ListUpdateClients, PublishRelease, SetReleaseRequired}, |
| 3 | - model::{ReleaseInfo, Staged}, | 3 | + model::{ReleaseInfo, Staged, UpdateClient, UpdateState}, |
| 4 | }; | 4 | }; |
| 5 | use gpui_kit::{ | 5 | use gpui_kit::{ |
| 6 | AnyElement, Context, Div, Entity, Hsla, IntoElement, ParentElement, PathPromptOptions, Styled, | 6 | AnyElement, Context, Div, Entity, Hsla, IntoElement, ParentElement, PathPromptOptions, Styled, |
| 7 | - Window, assets::IconName, component::Icon, div, px, | 7 | + Task, Window, assets::IconName, component::Icon, div, px, |
| 8 | }; | 8 | }; |
| 9 | -use std::path::PathBuf; | 9 | +use std::{path::PathBuf, time::Duration}; |
| 10 | 10 | ||
| 11 | +use super::BuilderTab; | ||
| 11 | use super::ui::{card, card_header, confirmed, delete_icon_button, list_row, rows_body}; | 12 | use super::ui::{card, card_header, confirmed, delete_icon_button, list_row, rows_body}; |
| 12 | use crate::gui::{ | 13 | use crate::gui::{ |
| 13 | - Palette, Yumush, entity_action, millis_time, notify_error, | 14 | + Palette, Yumush, |
| 15 | + chat::View, | ||
| 16 | + entity_action, millis_time, notify_error, | ||
| 14 | parts::{self, Fill, Press}, | 17 | parts::{self, Fill, Press}, |
| 15 | storage, | 18 | storage, |
| 16 | style::{size, space, text}, | 19 | style::{size, space, text}, |
| 17 | text, | 20 | text, |
| 18 | }; | 21 | }; |
| 19 | use crate::lang::w; | 22 | use crate::lang::w; |
| 23 | +use crate::release::{Build, Event, Job, Level, PLAN, is_source}; | ||
| 24 | + | ||
| 25 | +const CLIENTS_TICK: Duration = Duration::from_secs(1); | ||
| 20 | 26 | ||
| 21 | #[derive(Default)] | 27 | #[derive(Default)] |
| 22 | pub(crate) struct Desk { | 28 | pub(crate) struct Desk { |
| @@ -26,6 +32,27 @@ pub(crate) struct Desk { | |||
| 26 | publishing: bool, | 32 | publishing: bool, |
| 27 | releases: Vec<ReleaseInfo>, | 33 | releases: Vec<ReleaseInfo>, |
| 28 | pending_required: Option<u64>, | 34 | pending_required: Option<u64>, |
| 35 | + build: Option<Build>, | ||
| 36 | + jobs: Vec<Row>, | ||
| 37 | + failed: bool, | ||
| 38 | + cancelled: bool, | ||
| 39 | + auto_publish: bool, | ||
| 40 | + clients: Vec<UpdateClient>, | ||
| 41 | + clients_task: Option<Task<()>>, | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +struct Row { | ||
| 45 | + job: Job, | ||
| 46 | + phase: Phase, | ||
| 47 | + line: String, | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +enum Phase { | ||
| 51 | + Waiting, | ||
| 52 | + Running { done: u32, total: u32 }, | ||
| 53 | + Done, | ||
| 54 | + Skipped(String), | ||
| 55 | + Failed(String), | ||
| 29 | } | 56 | } |
| 30 | 57 | ||
| 31 | struct Draft { | 58 | struct Draft { |
| @@ -62,6 +89,21 @@ impl Desk { | |||
| 62 | fn draft(&mut self, id: u64) -> Option<&mut Draft> { | 89 | fn draft(&mut self, id: u64) -> Option<&mut Draft> { |
| 63 | self.drafts.iter_mut().find(|draft| draft.id == id) | 90 | self.drafts.iter_mut().find(|draft| draft.id == id) |
| 64 | } | 91 | } |
| 92 | + | ||
| 93 | + fn row(&mut self, job: Job) -> Option<&mut Row> { | ||
| 94 | + self.jobs.iter_mut().find(|row| row.job == job) | ||
| 95 | + } | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +fn job_label(job: Job) -> &'static str { | ||
| 99 | + let w = &w().builder_release; | ||
| 100 | + match job { | ||
| 101 | + Job::Linux(Level::V1) => w.linux_v1, | ||
| 102 | + Job::Linux(Level::V3) => w.linux_v3, | ||
| 103 | + Job::WindowsStart => w.windows_vm, | ||
| 104 | + Job::Windows(Level::V1) => w.windows_v1, | ||
| 105 | + Job::Windows(Level::V3) => w.windows_v3, | ||
| 106 | + } | ||
| 65 | } | 107 | } |
| 66 | 108 | ||
| 67 | fn caption_text(value: impl Into<String>, color: Hsla) -> Div { | 109 | fn caption_text(value: impl Into<String>, color: Hsla) -> Div { |
| @@ -71,6 +113,134 @@ fn caption_text(value: impl Into<String>, color: Hsla) -> Div { | |||
| 71 | .child(value.into()) | 113 | .child(value.into()) |
| 72 | } | 114 | } |
| 73 | 115 | ||
| 116 | +fn job_row(row: &Row, palette: Palette) -> Div { | ||
| 117 | + let (status, detail): (Div, Option<Div>) = match &row.phase { | ||
| 118 | + Phase::Waiting => ( | ||
| 119 | + caption_text(w().builder_release.waiting, palette.muted), | ||
| 120 | + None, | ||
| 121 | + ), | ||
| 122 | + Phase::Running { done, total } => { | ||
| 123 | + let status = if *total == 0 { | ||
| 124 | + caption_text("…", palette.muted) | ||
| 125 | + } else { | ||
| 126 | + div() | ||
| 127 | + .flex() | ||
| 128 | + .items_center() | ||
| 129 | + .gap(px(space::SM)) | ||
| 130 | + .child(parts::track( | ||
| 131 | + Fill::Part(*done as f32 / *total as f32), | ||
| 132 | + false, | ||
| 133 | + palette.tokens, | ||
| 134 | + )) | ||
| 135 | + .child(caption_text(format!("{done}/{total}"), palette.muted)) | ||
| 136 | + }; | ||
| 137 | + (status, Some(caption_text(row.line.clone(), palette.muted))) | ||
| 138 | + } | ||
| 139 | + Phase::Done => (caption_text(w().builder_release.done, palette.ok), None), | ||
| 140 | + Phase::Skipped(reason) => ( | ||
| 141 | + caption_text(w().builder_release.skipped, palette.muted), | ||
| 142 | + Some(caption_text(reason.clone(), palette.muted)), | ||
| 143 | + ), | ||
| 144 | + Phase::Failed(reason) => ( | ||
| 145 | + caption_text(w().builder_release.failed, palette.danger), | ||
| 146 | + Some(caption_text(reason.clone(), palette.danger)), | ||
| 147 | + ), | ||
| 148 | + }; | ||
| 149 | + | ||
| 150 | + list_row() | ||
| 151 | + .child( | ||
| 152 | + div() | ||
| 153 | + .flex_1() | ||
| 154 | + .min_w_0() | ||
| 155 | + .flex() | ||
| 156 | + .flex_col() | ||
| 157 | + .child( | ||
| 158 | + div() | ||
| 159 | + .text_size(text(text::LABEL)) | ||
| 160 | + .text_color(palette.text) | ||
| 161 | + .child(job_label(row.job)), | ||
| 162 | + ) | ||
| 163 | + .children(detail.map(|detail| detail.truncate())), | ||
| 164 | + ) | ||
| 165 | + .child(status) | ||
| 166 | +} | ||
| 167 | + | ||
| 168 | +fn client_row(client: &UpdateClient, palette: Palette) -> Div { | ||
| 169 | + let name = client.user.clone().unwrap_or_else(|| client.device.clone()); | ||
| 170 | + let release = match (client.release, client.target.as_deref()) { | ||
| 171 | + (Some(seq), Some(target)) => format!("#{seq} · {target}"), | ||
| 172 | + _ => w().builder_release.unknown.to_string(), | ||
| 173 | + }; | ||
| 174 | + let state = match client.state { | ||
| 175 | + UpdateState::Unknown => caption_text(w().builder_release.dev, palette.muted), | ||
| 176 | + UpdateState::Latest => caption_text(w().builder_release.latest, palette.ok), | ||
| 177 | + UpdateState::Available { required, .. } => caption_text( | ||
| 178 | + if required { | ||
| 179 | + format!( | ||
| 180 | + "{} · {}", | ||
| 181 | + w().builder_release.available, | ||
| 182 | + w().builder_release.required | ||
| 183 | + ) | ||
| 184 | + } else { | ||
| 185 | + w().builder_release.available.to_string() | ||
| 186 | + }, | ||
| 187 | + palette.muted, | ||
| 188 | + ), | ||
| 189 | + UpdateState::Downloading { percent, .. } => div() | ||
| 190 | + .flex() | ||
| 191 | + .items_center() | ||
| 192 | + .gap(px(space::SM)) | ||
| 193 | + .child(parts::track( | ||
| 194 | + Fill::Part(f32::from(percent) / 100.), | ||
| 195 | + false, | ||
| 196 | + palette.tokens, | ||
| 197 | + )) | ||
| 198 | + .child(caption_text(format!("{percent}%"), palette.muted)), | ||
| 199 | + UpdateState::Installing { .. } => { | ||
| 200 | + caption_text(w().builder_release.installing, palette.muted) | ||
| 201 | + } | ||
| 202 | + UpdateState::Ready { .. } => caption_text(w().builder_release.ready, palette.ok), | ||
| 203 | + UpdateState::Failed { .. } => caption_text(w().builder_release.failed, palette.danger), | ||
| 204 | + }; | ||
| 205 | + let dot = div() | ||
| 206 | + .size(px(space::SM)) | ||
| 207 | + .flex_shrink_0() | ||
| 208 | + .rounded_full() | ||
| 209 | + .bg(if client.online { | ||
| 210 | + palette.ok | ||
| 211 | + } else { | ||
| 212 | + palette.muted | ||
| 213 | + }); | ||
| 214 | + let seen = (!client.online) | ||
| 215 | + .then(|| caption_text(millis_time(client.seen_ms, w().common.date), palette.muted)); | ||
| 216 | + | ||
| 217 | + list_row() | ||
| 218 | + .child( | ||
| 219 | + div() | ||
| 220 | + .flex_1() | ||
| 221 | + .min_w_0() | ||
| 222 | + .flex() | ||
| 223 | + .flex_col() | ||
| 224 | + .child( | ||
| 225 | + div() | ||
| 226 | + .truncate() | ||
| 227 | + .text_size(text(text::LABEL)) | ||
| 228 | + .text_color(palette.text) | ||
| 229 | + .child(name), | ||
| 230 | + ) | ||
| 231 | + .children( | ||
| 232 | + client | ||
| 233 | + .user | ||
| 234 | + .is_some() | ||
| 235 | + .then(|| caption_text(client.device.clone(), palette.muted)), | ||
| 236 | + ), | ||
| 237 | + ) | ||
| 238 | + .child(caption_text(release, palette.muted)) | ||
| 239 | + .child(state) | ||
| 240 | + .child(dot) | ||
| 241 | + .children(seen) | ||
| 242 | +} | ||
| 243 | + | ||
| 74 | fn draft_row(draft: &Draft, duplicate: bool, entity: &Entity<Yumush>, palette: Palette) -> Div { | 244 | fn draft_row(draft: &Draft, duplicate: bool, entity: &Entity<Yumush>, palette: Palette) -> Div { |
| 75 | let id = draft.id; | 245 | let id = draft.id; |
| 76 | let status = match &draft.stage { | 246 | let status = match &draft.stage { |
| @@ -203,14 +373,102 @@ fn release_row( | |||
| 203 | 373 | ||
| 204 | impl Yumush { | 374 | impl Yumush { |
| 205 | pub(super) fn releases_body(&self, entity: &Entity<Self>, palette: Palette) -> Vec<AnyElement> { | 375 | pub(super) fn releases_body(&self, entity: &Entity<Self>, palette: Palette) -> Vec<AnyElement> { |
| 206 | - let mut body = Vec::new(); | 376 | + let mut body = vec![self.build_card(entity, palette).into_any_element()]; |
| 207 | if !self.desk.drafts.is_empty() { | 377 | if !self.desk.drafts.is_empty() { |
| 208 | body.push(self.draft_card(entity, palette).into_any_element()); | 378 | body.push(self.draft_card(entity, palette).into_any_element()); |
| 209 | } | 379 | } |
| 380 | + body.push(self.clients_card(palette).into_any_element()); | ||
| 210 | body.push(self.releases_card(entity, palette).into_any_element()); | 381 | body.push(self.releases_card(entity, palette).into_any_element()); |
| 211 | body | 382 | body |
| 212 | } | 383 | } |
| 213 | 384 | ||
| 385 | + fn build_card(&self, entity: &Entity<Self>, palette: Palette) -> Div { | ||
| 386 | + let running = self.desk.build.is_some(); | ||
| 387 | + let source = self.settings.release_source.as_ref().map_or_else( | ||
| 388 | + || w().builder_release.no_source.to_string(), | ||
| 389 | + |path| path.display().to_string(), | ||
| 390 | + ); | ||
| 391 | + let choose = parts::button( | ||
| 392 | + "choose_release_source", | ||
| 393 | + w().builder_release.choose_source, | ||
| 394 | + Press::Plain, | ||
| 395 | + palette.tokens, | ||
| 396 | + entity_action(entity, |yumush, window, cx| { | ||
| 397 | + yumush.pick_release_source(window, cx) | ||
| 398 | + }), | ||
| 399 | + ); | ||
| 400 | + let build = if self.settings.release_source.is_some() && !running { | ||
| 401 | + parts::button( | ||
| 402 | + "build_release", | ||
| 403 | + w().builder_release.build, | ||
| 404 | + Press::Primary, | ||
| 405 | + palette.tokens, | ||
| 406 | + entity_action(entity, |yumush, window, cx| yumush.start_build(window, cx)), | ||
| 407 | + ) | ||
| 408 | + .into_any_element() | ||
| 409 | + } else { | ||
| 410 | + parts::button( | ||
| 411 | + "build_release", | ||
| 412 | + w().builder_release.build, | ||
| 413 | + Press::Primary, | ||
| 414 | + palette.tokens, | ||
| 415 | + |_, _| {}, | ||
| 416 | + ) | ||
| 417 | + .opacity(0.4) | ||
| 418 | + .into_any_element() | ||
| 419 | + }; | ||
| 420 | + let cancel = running.then(|| { | ||
| 421 | + parts::button( | ||
| 422 | + "cancel_release_build", | ||
| 423 | + w().builder_release.cancel, | ||
| 424 | + Press::Danger, | ||
| 425 | + palette.tokens, | ||
| 426 | + entity_action(entity, |yumush, _, cx| yumush.cancel_build(cx)), | ||
| 427 | + ) | ||
| 428 | + }); | ||
| 429 | + let rows: Vec<Div> = self | ||
| 430 | + .desk | ||
| 431 | + .jobs | ||
| 432 | + .iter() | ||
| 433 | + .map(|row| job_row(row, palette)) | ||
| 434 | + .collect(); | ||
| 435 | + | ||
| 436 | + card(palette) | ||
| 437 | + .child( | ||
| 438 | + list_row() | ||
| 439 | + .justify_between() | ||
| 440 | + .child( | ||
| 441 | + div() | ||
| 442 | + .flex_1() | ||
| 443 | + .min_w_0() | ||
| 444 | + .truncate() | ||
| 445 | + .text_size(text(text::LABEL)) | ||
| 446 | + .text_color(palette.muted) | ||
| 447 | + .child(source), | ||
| 448 | + ) | ||
| 449 | + .child(choose), | ||
| 450 | + ) | ||
| 451 | + .child(div().flex().flex_col().children(rows)) | ||
| 452 | + .child(list_row().justify_end().children(cancel).child(build)) | ||
| 453 | + } | ||
| 454 | + | ||
| 455 | + fn clients_card(&self, palette: Palette) -> Div { | ||
| 456 | + let rows: Vec<Div> = self | ||
| 457 | + .desk | ||
| 458 | + .clients | ||
| 459 | + .iter() | ||
| 460 | + .map(|client| client_row(client, palette)) | ||
| 461 | + .collect(); | ||
| 462 | + | ||
| 463 | + card(palette) | ||
| 464 | + .child(card_header( | ||
| 465 | + w().builder_release.clients, | ||
| 466 | + Vec::new(), | ||
| 467 | + palette, | ||
| 468 | + )) | ||
| 469 | + .child(rows_body(rows, w().builder_release.no_clients, palette)) | ||
| 470 | + } | ||
| 471 | + | ||
| 214 | fn draft_card(&self, entity: &Entity<Self>, palette: Palette) -> Div { | 472 | fn draft_card(&self, entity: &Entity<Self>, palette: Palette) -> Div { |
| 215 | let drafts = &self.desk.drafts; | 473 | let drafts = &self.desk.drafts; |
| 216 | let rows: Vec<Div> = drafts | 474 | let rows: Vec<Div> = drafts |
| @@ -275,7 +533,8 @@ impl Yumush { | |||
| 275 | .child(rows_body(rows, w().builder_release.no_releases, palette)) | 533 | .child(rows_body(rows, w().builder_release.no_releases, palette)) |
| 276 | } | 534 | } |
| 277 | 535 | ||
| 278 | - pub(super) fn load_releases(&self, window: &mut Window, cx: &mut Context<Self>) { | 536 | + pub(super) fn load_releases(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 537 | + self.watch_clients(cx); | ||
| 279 | self.fetch_builder( | 538 | self.fetch_builder( |
| 280 | window, | 539 | window, |
| 281 | cx, | 540 | cx, |
| @@ -287,6 +546,149 @@ impl Yumush { | |||
| 287 | ); | 546 | ); |
| 288 | } | 547 | } |
| 289 | 548 | ||
| 549 | + fn watch_clients(&mut self, cx: &mut Context<Self>) { | ||
| 550 | + if self.desk.clients_task.is_some() { | ||
| 551 | + return; | ||
| 552 | + } | ||
| 553 | + let network = self.network.clone(); | ||
| 554 | + self.desk.clients_task = Some(cx.spawn(async move |this, cx| { | ||
| 555 | + loop { | ||
| 556 | + let open = this | ||
| 557 | + .update(cx, |yumush, _| { | ||
| 558 | + yumush.chat.view == View::Builder | ||
| 559 | + && yumush.chat.builder_tab == BuilderTab::Releases | ||
| 560 | + }) | ||
| 561 | + .unwrap_or(false); | ||
| 562 | + if !open { | ||
| 563 | + let _ = this.update(cx, |yumush, _| yumush.desk.clients_task = None); | ||
| 564 | + break; | ||
| 565 | + } | ||
| 566 | + if let Ok(clients) = network.call(ListUpdateClients).await { | ||
| 567 | + let _ = this.update(cx, |yumush, cx| { | ||
| 568 | + yumush.desk.clients = clients; | ||
| 569 | + cx.notify(); | ||
| 570 | + }); | ||
| 571 | + } | ||
| 572 | + cx.background_executor().timer(CLIENTS_TICK).await; | ||
| 573 | + } | ||
| 574 | + })); | ||
| 575 | + } | ||
| 576 | + | ||
| 577 | + pub(super) fn pick_release_source(&self, window: &mut Window, cx: &mut Context<Self>) { | ||
| 578 | + let picked = cx.prompt_for_paths(PathPromptOptions { | ||
| 579 | + files: false, | ||
| 580 | + directories: true, | ||
| 581 | + multiple: false, | ||
| 582 | + prompt: None, | ||
| 583 | + }); | ||
| 584 | + | ||
| 585 | + cx.spawn_in(window, async move |this, cx| { | ||
| 586 | + let Ok(Ok(Some(paths))) = picked.await else { | ||
| 587 | + return; | ||
| 588 | + }; | ||
| 589 | + let Some(path) = paths.into_iter().next() else { | ||
| 590 | + return; | ||
| 591 | + }; | ||
| 592 | + if is_source(&path) { | ||
| 593 | + let _ = this.update_in(cx, |yumush, _, cx| { | ||
| 594 | + yumush.settings.release_source = Some(path); | ||
| 595 | + crate::settings::save(&yumush.settings); | ||
| 596 | + cx.notify(); | ||
| 597 | + }); | ||
| 598 | + } else { | ||
| 599 | + notify_error(&this, cx, w().builder_release.not_source); | ||
| 600 | + } | ||
| 601 | + }) | ||
| 602 | + .detach(); | ||
| 603 | + } | ||
| 604 | + | ||
| 605 | + fn start_build(&mut self, window: &mut Window, cx: &mut Context<Self>) { | ||
| 606 | + let Some(source) = self.settings.release_source.clone() else { | ||
| 607 | + return; | ||
| 608 | + }; | ||
| 609 | + if self.desk.build.is_some() { | ||
| 610 | + return; | ||
| 611 | + } | ||
| 612 | + let (build, mut events) = Build::start(source); | ||
| 613 | + self.desk.build = Some(build); | ||
| 614 | + self.desk.jobs = PLAN | ||
| 615 | + .iter() | ||
| 616 | + .map(|&job| Row { | ||
| 617 | + job, | ||
| 618 | + phase: Phase::Waiting, | ||
| 619 | + line: String::new(), | ||
| 620 | + }) | ||
| 621 | + .collect(); | ||
| 622 | + self.desk.failed = false; | ||
| 623 | + self.desk.cancelled = false; | ||
| 624 | + self.desk.auto_publish = false; | ||
| 625 | + | ||
| 626 | + cx.spawn_in(window, async move |this, cx| { | ||
| 627 | + while let Some(event) = events.recv().await { | ||
| 628 | + if this | ||
| 629 | + .update_in(cx, |yumush, window, cx| { | ||
| 630 | + yumush.build_event(event, window, cx) | ||
| 631 | + }) | ||
| 632 | + .is_err() | ||
| 633 | + { | ||
| 634 | + break; | ||
| 635 | + } | ||
| 636 | + } | ||
| 637 | + }) | ||
| 638 | + .detach(); | ||
| 639 | + cx.notify(); | ||
| 640 | + } | ||
| 641 | + | ||
| 642 | + fn cancel_build(&mut self, cx: &mut Context<Self>) { | ||
| 643 | + if let Some(build) = &self.desk.build { | ||
| 644 | + build.cancel(); | ||
| 645 | + } | ||
| 646 | + self.desk.cancelled = true; | ||
| 647 | + self.desk.auto_publish = false; | ||
| 648 | + cx.notify(); | ||
| 649 | + } | ||
| 650 | + | ||
| 651 | + fn build_event(&mut self, event: Event, window: &mut Window, cx: &mut Context<Self>) { | ||
| 652 | + match event { | ||
| 653 | + Event::Started(job) => self.set_phase(job, Phase::Running { done: 0, total: 0 }), | ||
| 654 | + Event::Progress { job, done, total } => { | ||
| 655 | + self.set_phase(job, Phase::Running { done, total }) | ||
| 656 | + } | ||
| 657 | + Event::Line(job, line) => { | ||
| 658 | + if let Some(row) = self.desk.row(job) { | ||
| 659 | + row.line = line; | ||
| 660 | + } | ||
| 661 | + } | ||
| 662 | + Event::Built(_, path) => self.stage_release_file(path, window, cx), | ||
| 663 | + Event::Finished(job) => self.set_phase(job, Phase::Done), | ||
| 664 | + Event::Skipped(job, reason) => self.set_phase(job, Phase::Skipped(reason)), | ||
| 665 | + Event::Failed(job, reason) => { | ||
| 666 | + self.desk.failed = true; | ||
| 667 | + self.set_phase(job, Phase::Failed(reason)); | ||
| 668 | + } | ||
| 669 | + Event::Done => { | ||
| 670 | + self.desk.build = None; | ||
| 671 | + self.desk.auto_publish = | ||
| 672 | + !self.desk.failed && !self.desk.cancelled && !self.desk.drafts.is_empty(); | ||
| 673 | + self.try_auto_publish(window, cx); | ||
| 674 | + } | ||
| 675 | + } | ||
| 676 | + cx.notify(); | ||
| 677 | + } | ||
| 678 | + | ||
| 679 | + fn set_phase(&mut self, job: Job, phase: Phase) { | ||
| 680 | + if let Some(row) = self.desk.row(job) { | ||
| 681 | + row.phase = phase; | ||
| 682 | + } | ||
| 683 | + } | ||
| 684 | + | ||
| 685 | + fn try_auto_publish(&mut self, window: &mut Window, cx: &mut Context<Self>) { | ||
| 686 | + if self.desk.auto_publish && self.desk.can_publish() { | ||
| 687 | + self.desk.auto_publish = false; | ||
| 688 | + self.publish_release(window, cx); | ||
| 689 | + } | ||
| 690 | + } | ||
| 691 | + | ||
| 290 | pub(super) fn pick_release_files(&self, window: &mut Window, cx: &mut Context<Self>) { | 692 | pub(super) fn pick_release_files(&self, window: &mut Window, cx: &mut Context<Self>) { |
| 291 | let picked = cx.prompt_for_paths(PathPromptOptions { | 693 | let picked = cx.prompt_for_paths(PathPromptOptions { |
| 292 | files: true, | 694 | files: true, |
| @@ -347,10 +749,14 @@ impl Yumush { | |||
| 347 | Ok(staged) => Stage::Ready(staged), | 749 | Ok(staged) => Stage::Ready(staged), |
| 348 | Err(error) => Stage::Failed(error.to_string()), | 750 | Err(error) => Stage::Failed(error.to_string()), |
| 349 | }; | 751 | }; |
| 350 | - let _ = this.update(cx, |yumush, cx| { | 752 | + let _ = this.update_in(cx, |yumush, window, cx| { |
| 753 | + if matches!(stage, Stage::Failed(_)) { | ||
| 754 | + yumush.desk.auto_publish = false; | ||
| 755 | + } | ||
| 351 | if let Some(draft) = yumush.desk.draft(id) { | 756 | if let Some(draft) = yumush.desk.draft(id) { |
| 352 | draft.stage = stage; | 757 | draft.stage = stage; |
| 353 | } | 758 | } |
| 759 | + yumush.try_auto_publish(window, cx); | ||
| 354 | cx.notify(); | 760 | cx.notify(); |
| 355 | }); | 761 | }); |
| 356 | }) | 762 | }) |
| @@ -360,6 +766,7 @@ impl Yumush { | |||
| 360 | 766 | ||
| 361 | fn remove_draft(&mut self, id: u64, cx: &mut Context<Self>) { | 767 | fn remove_draft(&mut self, id: u64, cx: &mut Context<Self>) { |
| 362 | self.desk.drafts.retain(|draft| draft.id != id); | 768 | self.desk.drafts.retain(|draft| draft.id != id); |
| 769 | + self.desk.auto_publish = false; | ||
| 363 | cx.notify(); | 770 | cx.notify(); |
| 364 | } | 771 | } |
| 365 | 772 | ||
crates/client/src/lib.rsmodified+1 -0
| @@ -15,6 +15,7 @@ pub mod logo; | |||
| 15 | pub mod marks; | 15 | pub mod marks; |
| 16 | pub mod media; | 16 | pub mod media; |
| 17 | pub mod net; | 17 | pub mod net; |
| 18 | +pub mod release; | ||
| 18 | pub mod settings; | 19 | pub mod settings; |
| 19 | pub mod share; | 20 | pub mod share; |
| 20 | pub mod tray; | 21 | pub mod tray; |
crates/client/src/net/link.rsmodified+5 -8
| @@ -282,6 +282,7 @@ async fn hello(connection: &quinn::Connection, token: Option<String>) -> Result< | |||
| 282 | token, | 282 | token, |
| 283 | device: device_name(), | 283 | device: device_name(), |
| 284 | build: crate::update::build(), | 284 | build: crate::update::build(), |
| 285 | + install: crate::update::install_id(), | ||
| 285 | }; | 286 | }; |
| 286 | 287 | ||
| 287 | Ok(exchange(connection, &hello).await?.0) | 288 | Ok(exchange(connection, &hello).await?.0) |
| @@ -452,15 +453,9 @@ async fn actor( | |||
| 452 | continue; | 453 | continue; |
| 453 | } | 454 | } |
| 454 | }; | 455 | }; |
| 455 | - if matches!(result, Ok(_) | Err(LinkError::Outdated)) { | 456 | + if matches!(result, Err(LinkError::Outdated)) { |
| 456 | - let outdated = result.is_err(); | ||
| 457 | let _ = | 457 | let _ = |
| 458 | - tokio::time::timeout(UPDATE_CHECK, crate::update::check(&address, outdated)) | 458 | + tokio::time::timeout(UPDATE_CHECK, crate::update::check(address, true)).await; |
| 459 | - .await; | ||
| 460 | - if crate::update::phase().required() { | ||
| 461 | - while command_receiver.recv().await.is_some() {} | ||
| 462 | - return; | ||
| 463 | - } | ||
| 464 | } | 459 | } |
| 465 | match result { | 460 | match result { |
| 466 | Ok(connection) => break connection, | 461 | Ok(connection) => break connection, |
| @@ -535,6 +530,8 @@ async fn actor( | |||
| 535 | 530 | ||
| 536 | attempt = 0; | 531 | attempt = 0; |
| 537 | info!("connected"); | 532 | info!("connected"); |
| 533 | + crate::update::set_token(token.clone().filter(|_| welcome.user.is_some())); | ||
| 534 | + tokio::spawn(crate::update::check(server.borrow().clone(), false)); | ||
| 538 | shared.media.ready(connection.clone(), event_sender.clone()); | 535 | shared.media.ready(connection.clone(), event_sender.clone()); |
| 539 | if event_sender.send(NetworkEvent::Connected).await.is_err() { | 536 | if event_sender.send(NetworkEvent::Connected).await.is_err() { |
| 540 | return; | 537 | return; |
crates/client/src/net/mod.rsmodified+1 -1
| @@ -20,7 +20,7 @@ pub(crate) use link::dial; | |||
| 20 | pub use link::start; | 20 | pub use link::start; |
| 21 | use media::Media; | 21 | use media::Media; |
| 22 | 22 | ||
| 23 | -fn device_name() -> String { | 23 | +pub(crate) fn device_name() -> String { |
| 24 | let host = gethostname::gethostname() | 24 | let host = gethostname::gethostname() |
| 25 | .to_string_lossy() | 25 | .to_string_lossy() |
| 26 | .trim() | 26 | .trim() |
crates/client/src/release.rsadded+463 -0
| @@ -0,0 +1,463 @@ | |||
| 1 | +use std::fs; | ||
| 2 | +use std::io::{BufReader, Read}; | ||
| 3 | +use std::path::{Path, PathBuf}; | ||
| 4 | +use std::process::{Child, Command, ExitStatus, Stdio}; | ||
| 5 | +use std::sync::atomic::{AtomicBool, Ordering}; | ||
| 6 | +use std::sync::{Arc, Mutex}; | ||
| 7 | +use std::thread; | ||
| 8 | +use std::time::{Duration, Instant}; | ||
| 9 | + | ||
| 10 | +use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel}; | ||
| 11 | + | ||
| 12 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 13 | +pub enum Level { | ||
| 14 | + V1, | ||
| 15 | + V3, | ||
| 16 | +} | ||
| 17 | + | ||
| 18 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 19 | +pub enum Job { | ||
| 20 | + Linux(Level), | ||
| 21 | + WindowsStart, | ||
| 22 | + Windows(Level), | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +pub const PLAN: [Job; 5] = [ | ||
| 26 | + Job::Linux(Level::V1), | ||
| 27 | + Job::Linux(Level::V3), | ||
| 28 | + Job::WindowsStart, | ||
| 29 | + Job::Windows(Level::V1), | ||
| 30 | + Job::Windows(Level::V3), | ||
| 31 | +]; | ||
| 32 | + | ||
| 33 | +#[derive(Debug, Clone, PartialEq)] | ||
| 34 | +pub enum Event { | ||
| 35 | + Started(Job), | ||
| 36 | + Progress { job: Job, done: u32, total: u32 }, | ||
| 37 | + Line(Job, String), | ||
| 38 | + Built(Job, PathBuf), | ||
| 39 | + Finished(Job), | ||
| 40 | + Skipped(Job, String), | ||
| 41 | + Failed(Job, String), | ||
| 42 | + Done, | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +const VM: &str = "yumush-win"; | ||
| 46 | +const TARGET: &str = "yumush@127.0.0.1"; | ||
| 47 | +const PORT: &str = "2222"; | ||
| 48 | +const EXTRACT: &str = "Remove-Item -Recurse -Force release -ErrorAction SilentlyContinue; New-Item -ItemType Directory release | Out-Null; tar xzf release.tgz -C release"; | ||
| 49 | + | ||
| 50 | +pub fn is_source(path: &Path) -> bool { | ||
| 51 | + path.join("crates/client/Cargo.toml").is_file() && path.join(".git").exists() | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +pub struct Build { | ||
| 55 | + cancel: Arc<AtomicBool>, | ||
| 56 | + child: Arc<Mutex<Option<Child>>>, | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +impl Build { | ||
| 60 | + pub fn start(source: PathBuf) -> (Self, UnboundedReceiver<Event>) { | ||
| 61 | + let (tx, rx) = unbounded_channel(); | ||
| 62 | + let build = Self { | ||
| 63 | + cancel: Arc::default(), | ||
| 64 | + child: Arc::default(), | ||
| 65 | + }; | ||
| 66 | + let cx = Cx { | ||
| 67 | + tx, | ||
| 68 | + cancel: build.cancel.clone(), | ||
| 69 | + child: build.child.clone(), | ||
| 70 | + }; | ||
| 71 | + thread::spawn(move || run(&source, &cx)); | ||
| 72 | + (build, rx) | ||
| 73 | + } | ||
| 74 | + | ||
| 75 | + pub fn cancel(&self) { | ||
| 76 | + self.cancel.store(true, Ordering::SeqCst); | ||
| 77 | + if let Some(child) = self.child.lock().unwrap().as_mut() { | ||
| 78 | + let _ = child.kill(); | ||
| 79 | + } | ||
| 80 | + } | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +#[derive(Clone)] | ||
| 84 | +struct Cx { | ||
| 85 | + tx: UnboundedSender<Event>, | ||
| 86 | + cancel: Arc<AtomicBool>, | ||
| 87 | + child: Arc<Mutex<Option<Child>>>, | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +impl Cx { | ||
| 91 | + fn send(&self, event: Event) { | ||
| 92 | + let _ = self.tx.send(event); | ||
| 93 | + } | ||
| 94 | + | ||
| 95 | + fn cancelled(&self) -> bool { | ||
| 96 | + self.cancel.load(Ordering::SeqCst) | ||
| 97 | + } | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +#[derive(Clone, Copy)] | ||
| 101 | +struct Vm { | ||
| 102 | + present: bool, | ||
| 103 | + started: bool, | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +fn run(source: &Path, cx: &Cx) { | ||
| 107 | + let key = dirs::home_dir() | ||
| 108 | + .unwrap_or_default() | ||
| 109 | + .join("vm/yumush-win/id_ed25519"); | ||
| 110 | + let vm = match preflight(source) { | ||
| 111 | + Ok(vm) => vm, | ||
| 112 | + Err(e) => { | ||
| 113 | + cx.send(Event::Failed(PLAN[0], e)); | ||
| 114 | + cx.send(Event::Done); | ||
| 115 | + return; | ||
| 116 | + } | ||
| 117 | + }; | ||
| 118 | + for job in PLAN { | ||
| 119 | + let result = if cx.cancelled() { | ||
| 120 | + Err("cancelled".to_string()) | ||
| 121 | + } else { | ||
| 122 | + run_job(job, source, &key, cx, vm) | ||
| 123 | + }; | ||
| 124 | + if let Err(e) = result { | ||
| 125 | + let e = if cx.cancelled() { | ||
| 126 | + "cancelled".to_string() | ||
| 127 | + } else { | ||
| 128 | + e | ||
| 129 | + }; | ||
| 130 | + cx.send(Event::Failed(job, e)); | ||
| 131 | + break; | ||
| 132 | + } | ||
| 133 | + } | ||
| 134 | + if vm.started { | ||
| 135 | + podman_ok(&["stop", VM]); | ||
| 136 | + } | ||
| 137 | + cx.send(Event::Done); | ||
| 138 | +} | ||
| 139 | + | ||
| 140 | +fn preflight(source: &Path) -> Result<Vm, String> { | ||
| 141 | + let dirty = Command::new("git") | ||
| 142 | + .arg("-C") | ||
| 143 | + .arg(source) | ||
| 144 | + .args(["status", "--porcelain"]) | ||
| 145 | + .output() | ||
| 146 | + .map_err(|e| e.to_string())?; | ||
| 147 | + if !dirty.stdout.is_empty() { | ||
| 148 | + return Err("uncommitted changes".into()); | ||
| 149 | + } | ||
| 150 | + fs::create_dir_all(source.join("dist")).map_err(|e| e.to_string())?; | ||
| 151 | + let present = podman_ok(&["container", "exists", VM]); | ||
| 152 | + let mut started = false; | ||
| 153 | + if present { | ||
| 154 | + let state = Command::new("podman") | ||
| 155 | + .args(["inspect", "-f", "{{.State.Running}}", VM]) | ||
| 156 | + .output() | ||
| 157 | + .map_err(|e| e.to_string())?; | ||
| 158 | + if String::from_utf8_lossy(&state.stdout).trim() == "false" { | ||
| 159 | + if !podman_ok(&["start", VM]) { | ||
| 160 | + return Err("podman start failed".into()); | ||
| 161 | + } | ||
| 162 | + started = true; | ||
| 163 | + } | ||
| 164 | + } | ||
| 165 | + Ok(Vm { present, started }) | ||
| 166 | +} | ||
| 167 | + | ||
| 168 | +fn run_job(job: Job, source: &Path, key: &Path, cx: &Cx, vm: Vm) -> Result<(), String> { | ||
| 169 | + match job { | ||
| 170 | + Job::Linux(level) => { | ||
| 171 | + if !cfg!(target_os = "linux") { | ||
| 172 | + return skip(cx, job, "not linux"); | ||
| 173 | + } | ||
| 174 | + cx.send(Event::Started(job)); | ||
| 175 | + build_linux(job, level, source, cx) | ||
| 176 | + } | ||
| 177 | + Job::WindowsStart => { | ||
| 178 | + if !vm.present { | ||
| 179 | + return skip(cx, job, "no yumush-win"); | ||
| 180 | + } | ||
| 181 | + cx.send(Event::Started(job)); | ||
| 182 | + start_windows(job, source, key, cx) | ||
| 183 | + } | ||
| 184 | + Job::Windows(level) => { | ||
| 185 | + if !vm.present { | ||
| 186 | + return skip(cx, job, "no yumush-win"); | ||
| 187 | + } | ||
| 188 | + cx.send(Event::Started(job)); | ||
| 189 | + build_windows(job, level, source, key, cx) | ||
| 190 | + } | ||
| 191 | + } | ||
| 192 | +} | ||
| 193 | + | ||
| 194 | +fn skip(cx: &Cx, job: Job, why: &str) -> Result<(), String> { | ||
| 195 | + cx.send(Event::Skipped(job, why.into())); | ||
| 196 | + Ok(()) | ||
| 197 | +} | ||
| 198 | + | ||
| 199 | +fn flags(level: Level) -> (&'static str, &'static str) { | ||
| 200 | + match level { | ||
| 201 | + Level::V1 => ("v1", "x86-64"), | ||
| 202 | + Level::V3 => ("v3", "x86-64-v3"), | ||
| 203 | + } | ||
| 204 | +} | ||
| 205 | + | ||
| 206 | +fn toml_text(cpu: &str) -> String { | ||
| 207 | + format!( | ||
| 208 | + "[target.'cfg(target_arch = \"x86_64\")']\nrustflags = [\"-C\", \"target-cpu={cpu}\"]\n" | ||
| 209 | + ) | ||
| 210 | +} | ||
| 211 | + | ||
| 212 | +fn build_linux(job: Job, level: Level, source: &Path, cx: &Cx) -> Result<(), String> { | ||
| 213 | + let (name, cpu) = flags(level); | ||
| 214 | + fs::write( | ||
| 215 | + source.join("dist").join(format!("{name}.toml")), | ||
| 216 | + toml_text(cpu), | ||
| 217 | + ) | ||
| 218 | + .map_err(|e| e.to_string())?; | ||
| 219 | + let mut cmd = Command::new("cargo"); | ||
| 220 | + cmd.current_dir(source) | ||
| 221 | + .args(["build", "--release", "-p", "client", "--target-dir"]) | ||
| 222 | + .arg(format!("target/release-{name}")) | ||
| 223 | + .arg("--config") | ||
| 224 | + .arg(format!("dist/{name}.toml")) | ||
| 225 | + .env("CARGO_TERM_PROGRESS_WHEN", "always") | ||
| 226 | + .env("CARGO_TERM_PROGRESS_WIDTH", "200") | ||
| 227 | + .env("CARGO_TERM_COLOR", "never") | ||
| 228 | + .stdout(Stdio::null()); | ||
| 229 | + stream(&mut cmd, job, cx)?; | ||
| 230 | + let dest = source.join("dist").join(format!("x86_64_{name}-linux")); | ||
| 231 | + fs::copy( | ||
| 232 | + source.join(format!("target/release-{name}/release/client")), | ||
| 233 | + &dest, | ||
| 234 | + ) | ||
| 235 | + .map_err(|e| e.to_string())?; | ||
| 236 | + cx.send(Event::Built(job, dest)); | ||
| 237 | + cx.send(Event::Finished(job)); | ||
| 238 | + Ok(()) | ||
| 239 | +} | ||
| 240 | + | ||
| 241 | +fn start_windows(job: Job, source: &Path, key: &Path, cx: &Cx) -> Result<(), String> { | ||
| 242 | + wait_ssh(job, key, cx)?; | ||
| 243 | + let tgz = source.join("dist/source.tgz"); | ||
| 244 | + check( | ||
| 245 | + Command::new("git") | ||
| 246 | + .arg("-C") | ||
| 247 | + .arg(source) | ||
| 248 | + .args(["archive", "--format=tar.gz", "-o"]) | ||
| 249 | + .arg(&tgz) | ||
| 250 | + .arg("HEAD"), | ||
| 251 | + )?; | ||
| 252 | + check(scp(key).arg(&tgz).arg(format!("{TARGET}:release.tgz")))?; | ||
| 253 | + stream(&mut ps(key, EXTRACT), job, cx)?; | ||
| 254 | + cx.send(Event::Finished(job)); | ||
| 255 | + Ok(()) | ||
| 256 | +} | ||
| 257 | + | ||
| 258 | +fn build_windows(job: Job, level: Level, source: &Path, key: &Path, cx: &Cx) -> Result<(), String> { | ||
| 259 | + let (name, cpu) = flags(level); | ||
| 260 | + let script = format!( | ||
| 261 | + r#"$ErrorActionPreference = 'Continue' | ||
| 262 | +Set-Location release | ||
| 263 | +$env:Path += ";$env:USERPROFILE\.cargo\bin" | ||
| 264 | +$env:CARGO_TERM_PROGRESS_WHEN = 'always'; $env:CARGO_TERM_PROGRESS_WIDTH = '200'; $env:CARGO_TERM_COLOR = 'never' | ||
| 265 | +@' | ||
| 266 | +{toml}'@ | Set-Content -Encoding ascii level.toml | ||
| 267 | +cargo build --release -p client --target-dir ..\target-release-{name} --config level.toml | ||
| 268 | +exit $LASTEXITCODE | ||
| 269 | +"#, | ||
| 270 | + toml = toml_text(cpu) | ||
| 271 | + ); | ||
| 272 | + stream(&mut ps(key, &script), job, cx)?; | ||
| 273 | + let dest = source.join("dist").join(format!("x86_64_{name}-windows")); | ||
| 274 | + check( | ||
| 275 | + scp(key) | ||
| 276 | + .arg(format!("{TARGET}:target-release-{name}/release/client.exe")) | ||
| 277 | + .arg(&dest), | ||
| 278 | + )?; | ||
| 279 | + cx.send(Event::Built(job, dest)); | ||
| 280 | + cx.send(Event::Finished(job)); | ||
| 281 | + Ok(()) | ||
| 282 | +} | ||
| 283 | + | ||
| 284 | +fn wait_ssh(job: Job, key: &Path, cx: &Cx) -> Result<(), String> { | ||
| 285 | + let deadline = Instant::now() + Duration::from_secs(600); | ||
| 286 | + while !ssh_ok(key) { | ||
| 287 | + if cx.cancelled() { | ||
| 288 | + return Err("cancelled".into()); | ||
| 289 | + } | ||
| 290 | + if Instant::now() >= deadline { | ||
| 291 | + return Err("ssh timeout".into()); | ||
| 292 | + } | ||
| 293 | + cx.send(Event::Line(job, "waiting for ssh".into())); | ||
| 294 | + thread::sleep(Duration::from_secs(5)); | ||
| 295 | + } | ||
| 296 | + Ok(()) | ||
| 297 | +} | ||
| 298 | + | ||
| 299 | +fn opts(key: &Path, port_flag: &str) -> Vec<String> { | ||
| 300 | + let mut args = vec!["-i".to_string(), key.display().to_string()]; | ||
| 301 | + for option in [ | ||
| 302 | + "StrictHostKeyChecking=no", | ||
| 303 | + "UserKnownHostsFile=/dev/null", | ||
| 304 | + "ConnectTimeout=10", | ||
| 305 | + "LogLevel=ERROR", | ||
| 306 | + ] { | ||
| 307 | + args.push("-o".into()); | ||
| 308 | + args.push(option.into()); | ||
| 309 | + } | ||
| 310 | + args.push(port_flag.into()); | ||
| 311 | + args.push(PORT.into()); | ||
| 312 | + args | ||
| 313 | +} | ||
| 314 | + | ||
| 315 | +fn ssh(key: &Path) -> Command { | ||
| 316 | + let mut cmd = Command::new("ssh"); | ||
| 317 | + cmd.args(opts(key, "-p")).arg(TARGET); | ||
| 318 | + cmd | ||
| 319 | +} | ||
| 320 | + | ||
| 321 | +fn scp(key: &Path) -> Command { | ||
| 322 | + let mut cmd = Command::new("scp"); | ||
| 323 | + cmd.arg("-q").args(opts(key, "-P")); | ||
| 324 | + cmd | ||
| 325 | +} | ||
| 326 | + | ||
| 327 | +fn ps(key: &Path, script: &str) -> Command { | ||
| 328 | + let bytes: Vec<u8> = script.encode_utf16().flat_map(u16::to_le_bytes).collect(); | ||
| 329 | + let mut cmd = ssh(key); | ||
| 330 | + cmd.args([ | ||
| 331 | + "powershell", | ||
| 332 | + "-NoProfile", | ||
| 333 | + "-NonInteractive", | ||
| 334 | + "-EncodedCommand", | ||
| 335 | + ]) | ||
| 336 | + .arg(base64(&bytes)) | ||
| 337 | + .stdout(Stdio::piped()); | ||
| 338 | + cmd | ||
| 339 | +} | ||
| 340 | + | ||
| 341 | +fn ssh_ok(key: &Path) -> bool { | ||
| 342 | + ssh(key) | ||
| 343 | + .args(["echo", "ok"]) | ||
| 344 | + .stdout(Stdio::null()) | ||
| 345 | + .stderr(Stdio::null()) | ||
| 346 | + .status() | ||
| 347 | + .is_ok_and(|s| s.success()) | ||
| 348 | +} | ||
| 349 | + | ||
| 350 | +fn podman_ok(args: &[&str]) -> bool { | ||
| 351 | + Command::new("podman") | ||
| 352 | + .args(args) | ||
| 353 | + .stdout(Stdio::null()) | ||
| 354 | + .stderr(Stdio::null()) | ||
| 355 | + .status() | ||
| 356 | + .is_ok_and(|s| s.success()) | ||
| 357 | +} | ||
| 358 | + | ||
| 359 | +fn check(cmd: &mut Command) -> Result<(), String> { | ||
| 360 | + let out = cmd.output().map_err(|e| e.to_string())?; | ||
| 361 | + if out.status.success() { | ||
| 362 | + Ok(()) | ||
| 363 | + } else { | ||
| 364 | + Err(String::from_utf8_lossy(&out.stderr).trim().to_string()) | ||
| 365 | + } | ||
| 366 | +} | ||
| 367 | + | ||
| 368 | +fn stream(cmd: &mut Command, job: Job, cx: &Cx) -> Result<(), String> { | ||
| 369 | + let mut child = cmd | ||
| 370 | + .stderr(Stdio::piped()) | ||
| 371 | + .spawn() | ||
| 372 | + .map_err(|e| e.to_string())?; | ||
| 373 | + let stdout = child.stdout.take(); | ||
| 374 | + let stderr = child.stderr.take(); | ||
| 375 | + *cx.child.lock().unwrap() = Some(child); | ||
| 376 | + let out = stdout.map(|o| { | ||
| 377 | + let cx = cx.clone(); | ||
| 378 | + thread::spawn(move || pump(o, job, &cx)) | ||
| 379 | + }); | ||
| 380 | + let err = stderr.map(|e| pump(e, job, cx)).unwrap_or_default(); | ||
| 381 | + if let Some(out) = out { | ||
| 382 | + let _ = out.join(); | ||
| 383 | + } | ||
| 384 | + let status = wait(cx)?; | ||
| 385 | + if status.success() { | ||
| 386 | + return Ok(()); | ||
| 387 | + } | ||
| 388 | + Err(if err.is_empty() { | ||
| 389 | + format!("exit {status}") | ||
| 390 | + } else { | ||
| 391 | + err | ||
| 392 | + }) | ||
| 393 | +} | ||
| 394 | + | ||
| 395 | +fn wait(cx: &Cx) -> Result<ExitStatus, String> { | ||
| 396 | + loop { | ||
| 397 | + let mut slot = cx.child.lock().unwrap(); | ||
| 398 | + if cx.cancelled() | ||
| 399 | + && let Some(child) = slot.as_mut() { | ||
| 400 | + let _ = child.kill(); | ||
| 401 | + } | ||
| 402 | + let Some(child) = slot.as_mut() else { | ||
| 403 | + return Err("no child".into()); | ||
| 404 | + }; | ||
| 405 | + if let Some(status) = child.try_wait().map_err(|e| e.to_string())? { | ||
| 406 | + return Ok(status); | ||
| 407 | + } | ||
| 408 | + drop(slot); | ||
| 409 | + thread::sleep(Duration::from_millis(100)); | ||
| 410 | + } | ||
| 411 | +} | ||
| 412 | + | ||
| 413 | +fn pump(reader: impl Read, job: Job, cx: &Cx) -> String { | ||
| 414 | + let mut last = String::new(); | ||
| 415 | + let mut piece = Vec::new(); | ||
| 416 | + for byte in BufReader::new(reader) | ||
| 417 | + .bytes() | ||
| 418 | + .map_while(Result::ok) | ||
| 419 | + .chain(*b"\n") | ||
| 420 | + { | ||
| 421 | + if byte != b'\r' && byte != b'\n' { | ||
| 422 | + piece.push(byte); | ||
| 423 | + continue; | ||
| 424 | + } | ||
| 425 | + let text = String::from_utf8_lossy(&piece).trim().to_string(); | ||
| 426 | + piece.clear(); | ||
| 427 | + if text.is_empty() { | ||
| 428 | + continue; | ||
| 429 | + } | ||
| 430 | + cx.send(progress(job, &text).unwrap_or_else(|| Event::Line(job, text.clone()))); | ||
| 431 | + last = text; | ||
| 432 | + } | ||
| 433 | + last | ||
| 434 | +} | ||
| 435 | + | ||
| 436 | +fn progress(job: Job, text: &str) -> Option<Event> { | ||
| 437 | + let rest = text.split_once("Building [")?.1.split_once(']')?.1; | ||
| 438 | + let (done, total) = rest.trim_start().split(':').next()?.split_once('/')?; | ||
| 439 | + Some(Event::Progress { | ||
| 440 | + job, | ||
| 441 | + done: done.trim().parse().ok()?, | ||
| 442 | + total: total.trim().parse().ok()?, | ||
| 443 | + }) | ||
| 444 | +} | ||
| 445 | + | ||
| 446 | +fn base64(bytes: &[u8]) -> String { | ||
| 447 | + const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; | ||
| 448 | + let mut out = String::new(); | ||
| 449 | + for chunk in bytes.chunks(3) { | ||
| 450 | + let n = chunk | ||
| 451 | + .iter() | ||
| 452 | + .enumerate() | ||
| 453 | + .fold(0u32, |n, (i, &b)| n | (b as u32) << (16 - 8 * i)); | ||
| 454 | + for i in 0..4 { | ||
| 455 | + if i <= chunk.len() { | ||
| 456 | + out.push(TABLE[(n >> (18 - 6 * i)) as usize & 63] as char); | ||
| 457 | + } else { | ||
| 458 | + out.push('='); | ||
| 459 | + } | ||
| 460 | + } | ||
| 461 | + } | ||
| 462 | + out | ||
| 463 | +} | ||
crates/client/src/settings.rsmodified+12 -1
| @@ -1,4 +1,4 @@ | |||
| 1 | -use std::{collections::BTreeMap, fmt::Display, ops::RangeInclusive}; | 1 | +use std::{collections::BTreeMap, fmt::Display, ops::RangeInclusive, path::PathBuf}; |
| 2 | 2 | ||
| 3 | use common::{ | 3 | use common::{ |
| 4 | config::Config, | 4 | config::Config, |
| @@ -224,6 +224,7 @@ pub struct Settings { | |||
| 224 | pub clock_seconds: bool, | 224 | pub clock_seconds: bool, |
| 225 | pub jump_usage: BTreeMap<String, u32>, | 225 | pub jump_usage: BTreeMap<String, u32>, |
| 226 | pub last_chats: BTreeMap<Id, Id>, | 226 | pub last_chats: BTreeMap<Id, Id>, |
| 227 | + pub release_source: Option<PathBuf>, | ||
| 227 | } | 228 | } |
| 228 | 229 | ||
| 229 | impl Settings { | 230 | impl Settings { |
| @@ -253,6 +254,7 @@ impl Default for Settings { | |||
| 253 | clock_seconds: false, | 254 | clock_seconds: false, |
| 254 | jump_usage: BTreeMap::new(), | 255 | jump_usage: BTreeMap::new(), |
| 255 | last_chats: BTreeMap::new(), | 256 | last_chats: BTreeMap::new(), |
| 257 | + release_source: None, | ||
| 256 | } | 258 | } |
| 257 | } | 259 | } |
| 258 | } | 260 | } |
| @@ -388,6 +390,7 @@ pub fn load() -> Settings { | |||
| 388 | .collect() | 390 | .collect() |
| 389 | }) | 391 | }) |
| 390 | .unwrap_or_default(), | 392 | .unwrap_or_default(), |
| 393 | + release_source: text("release.source").map(PathBuf::from), | ||
| 391 | } | 394 | } |
| 392 | } | 395 | } |
| 393 | 396 | ||
| @@ -469,6 +472,14 @@ pub fn save(settings: &Settings) { | |||
| 469 | .collect::<Vec<_>>() | 472 | .collect::<Vec<_>>() |
| 470 | .join("\t"), | 473 | .join("\t"), |
| 471 | ), | 474 | ), |
| 475 | + line( | ||
| 476 | + "release.source", | ||
| 477 | + settings | ||
| 478 | + .release_source | ||
| 479 | + .as_ref() | ||
| 480 | + .map(|path| path.display().to_string()) | ||
| 481 | + .unwrap_or_default(), | ||
| 482 | + ), | ||
| 472 | line( | 483 | line( |
| 473 | "last_chats", | 484 | "last_chats", |
| 474 | settings | 485 | settings |
crates/client/src/update.rsmodified+92 -16
| @@ -6,7 +6,7 @@ use std::{ | |||
| 6 | 6 | ||
| 7 | use common::{ | 7 | use common::{ |
| 8 | frame::{self, Sending, UP_MAX}, | 8 | frame::{self, Sending, UP_MAX}, |
| 9 | - update::{ALPN, Ask, FILE_MAX, Offer, Sha, Status, sha256}, | 9 | + update::{ALPN, Ask, FILE_MAX, Install, Me, Offer, Progress, Sha, Status, sha256}, |
| 10 | }; | 10 | }; |
| 11 | use tokio::sync::watch; | 11 | use tokio::sync::watch; |
| 12 | use tracing::{info, warn}; | 12 | use tracing::{info, warn}; |
| @@ -61,6 +61,30 @@ impl Phase { | |||
| 61 | 61 | ||
| 62 | static PHASE: LazyLock<watch::Sender<Phase>> = LazyLock::new(|| watch::channel(Phase::Idle).0); | 62 | static PHASE: LazyLock<watch::Sender<Phase>> = LazyLock::new(|| watch::channel(Phase::Idle).0); |
| 63 | static SERVER: Mutex<Option<crate::Server>> = Mutex::new(None); | 63 | static SERVER: Mutex<Option<crate::Server>> = Mutex::new(None); |
| 64 | +static TOKEN: Mutex<Option<String>> = Mutex::new(None); | ||
| 65 | +static INSTALL: LazyLock<Install> = LazyLock::new(|| { | ||
| 66 | + let path = crate::config_dir().map(|dir| dir.join("install")); | ||
| 67 | + if let Some(saved) = path | ||
| 68 | + .as_ref() | ||
| 69 | + .and_then(|path| std::fs::read(path).ok()) | ||
| 70 | + .and_then(|bytes| Install::try_from(bytes).ok()) | ||
| 71 | + { | ||
| 72 | + return saved; | ||
| 73 | + } | ||
| 74 | + let random = |salt: u64| { | ||
| 75 | + use std::hash::BuildHasher; | ||
| 76 | + std::collections::hash_map::RandomState::new() | ||
| 77 | + .hash_one((salt, std::time::SystemTime::now())) | ||
| 78 | + }; | ||
| 79 | + let mut fresh = [0u8; 16]; | ||
| 80 | + fresh[..8].copy_from_slice(&random(1).to_le_bytes()); | ||
| 81 | + fresh[8..].copy_from_slice(&random(2).to_le_bytes()); | ||
| 82 | + if let Some(path) = path { | ||
| 83 | + let _ = path.parent().map(std::fs::create_dir_all); | ||
| 84 | + let _ = std::fs::write(path, fresh); | ||
| 85 | + } | ||
| 86 | + fresh | ||
| 87 | +}); | ||
| 64 | static BUILD: LazyLock<Option<Sha>> = LazyLock::new(|| { | 88 | static BUILD: LazyLock<Option<Sha>> = LazyLock::new(|| { |
| 65 | if cfg!(debug_assertions) { | 89 | if cfg!(debug_assertions) { |
| 66 | return None; | 90 | return None; |
| @@ -83,6 +107,23 @@ pub fn build() -> Option<Sha> { | |||
| 83 | *BUILD | 107 | *BUILD |
| 84 | } | 108 | } |
| 85 | 109 | ||
| 110 | +pub fn install_id() -> Install { | ||
| 111 | + *INSTALL | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +pub(crate) fn set_token(token: Option<String>) { | ||
| 115 | + *TOKEN.lock().unwrap() = token; | ||
| 116 | +} | ||
| 117 | + | ||
| 118 | +fn me() -> Option<Me> { | ||
| 119 | + Some(Me { | ||
| 120 | + install: install_id(), | ||
| 121 | + device: crate::net::device_name(), | ||
| 122 | + token: TOKEN.lock().unwrap().clone(), | ||
| 123 | + build: build().filter(|_| usable())?, | ||
| 124 | + }) | ||
| 125 | +} | ||
| 126 | + | ||
| 86 | fn set(phase: Phase) { | 127 | fn set(phase: Phase) { |
| 87 | PHASE.send_replace(phase); | 128 | PHASE.send_replace(phase); |
| 88 | } | 129 | } |
| @@ -121,8 +162,8 @@ fn usable() -> bool { | |||
| 121 | !std::env::args().any(|arg| arg == crate::instance::MULTI) | 162 | !std::env::args().any(|arg| arg == crate::instance::MULTI) |
| 122 | } | 163 | } |
| 123 | 164 | ||
| 124 | -pub(crate) async fn check(server: &crate::Server, outdated: bool) { | 165 | +pub(crate) async fn check(server: crate::Server, outdated: bool) { |
| 125 | - let Some(build) = build().filter(|_| usable()) else { | 166 | + let Some(me) = me() else { |
| 126 | return; | 167 | return; |
| 127 | }; | 168 | }; |
| 128 | *SERVER.lock().unwrap() = Some(server.clone()); | 169 | *SERVER.lock().unwrap() = Some(server.clone()); |
| @@ -130,10 +171,10 @@ pub(crate) async fn check(server: &crate::Server, outdated: bool) { | |||
| 130 | return; | 171 | return; |
| 131 | } | 172 | } |
| 132 | let ask = Ask::Check { | 173 | let ask = Ask::Check { |
| 133 | - build, | 174 | + me, |
| 134 | targets: targets(), | 175 | targets: targets(), |
| 135 | }; | 176 | }; |
| 136 | - let status = crate::net::dial(server, ALPN, async |connection| { | 177 | + let status = crate::net::dial(&server, ALPN, async |connection| { |
| 137 | let (send, mut receive) = connection.open_bi().await.ok()?; | 178 | let (send, mut receive) = connection.open_bi().await.ok()?; |
| 138 | let mut send = Sending::new(send); | 179 | let mut send = Sending::new(send); |
| 139 | frame::write(&mut send, &ask, UP_MAX).await.ok()?; | 180 | frame::write(&mut send, &ask, UP_MAX).await.ok()?; |
| @@ -171,7 +212,7 @@ pub fn recheck() { | |||
| 171 | .enable_all() | 212 | .enable_all() |
| 172 | .build() | 213 | .build() |
| 173 | { | 214 | { |
| 174 | - runtime.block_on(check(&server, false)); | 215 | + runtime.block_on(check(server, false)); |
| 175 | } | 216 | } |
| 176 | }); | 217 | }); |
| 177 | } | 218 | } |
| @@ -187,40 +228,75 @@ pub fn install() { | |||
| 187 | let Some(exe) = crate::exe() else { | 228 | let Some(exe) = crate::exe() else { |
| 188 | return; | 229 | return; |
| 189 | }; | 230 | }; |
| 231 | + let Some(me) = me() else { | ||
| 232 | + return; | ||
| 233 | + }; | ||
| 190 | set(Phase::Downloading { offer, done: 0 }); | 234 | set(Phase::Downloading { offer, done: 0 }); |
| 191 | std::thread::spawn(move || { | 235 | std::thread::spawn(move || { |
| 192 | - let installed = tokio::runtime::Builder::new_current_thread() | 236 | + let Ok(runtime) = tokio::runtime::Builder::new_current_thread() |
| 193 | .enable_all() | 237 | .enable_all() |
| 194 | .build() | 238 | .build() |
| 195 | - .map_err(Fail::from) | 239 | + else { |
| 196 | - .and_then(|runtime| runtime.block_on(download(&server, offer))) | 240 | + set(Phase::Failed(offer)); |
| 197 | - .and_then(|packed| unpack(offer, &packed, exe)); | 241 | + return; |
| 198 | - match installed { | 242 | + }; |
| 243 | + let installed = runtime | ||
| 244 | + .block_on(download(&server, me.clone(), offer)) | ||
| 245 | + .and_then(|packed| { | ||
| 246 | + runtime.block_on(report(&server, me.clone(), Progress::Installing)); | ||
| 247 | + unpack(offer, &packed, exe) | ||
| 248 | + }); | ||
| 249 | + let progress = match installed { | ||
| 199 | Ok(()) => { | 250 | Ok(()) => { |
| 200 | info!("update: release {} installed", offer.seq); | 251 | info!("update: release {} installed", offer.seq); |
| 201 | set(Phase::Ready(offer)); | 252 | set(Phase::Ready(offer)); |
| 202 | - if offer.required { | 253 | + Progress::Ready |
| 203 | - restart(); | ||
| 204 | - } | ||
| 205 | } | 254 | } |
| 206 | Err(error) => { | 255 | Err(error) => { |
| 207 | warn!("update: {error}"); | 256 | warn!("update: {error}"); |
| 208 | set(Phase::Failed(offer)); | 257 | set(Phase::Failed(offer)); |
| 258 | + Progress::Failed | ||
| 209 | } | 259 | } |
| 260 | + }; | ||
| 261 | + runtime.block_on(report(&server, me, progress)); | ||
| 262 | + if progress == Progress::Ready && offer.required { | ||
| 263 | + restart(); | ||
| 210 | } | 264 | } |
| 211 | }); | 265 | }); |
| 212 | } | 266 | } |
| 213 | 267 | ||
| 214 | type Fail = Box<dyn std::error::Error + Send + Sync>; | 268 | type Fail = Box<dyn std::error::Error + Send + Sync>; |
| 215 | 269 | ||
| 216 | -async fn download(server: &crate::Server, offer: Offer) -> Result<Vec<u8>, Fail> { | 270 | +async fn report(server: &crate::Server, me: Me, progress: Progress) { |
| 271 | + let _ = crate::net::dial(server, ALPN, async |connection| { | ||
| 272 | + let (send, mut receive) = connection.open_bi().await.ok()?; | ||
| 273 | + let mut send = Sending::new(send); | ||
| 274 | + frame::write(&mut send, &Ask::Report { me, progress }, UP_MAX) | ||
| 275 | + .await | ||
| 276 | + .ok()?; | ||
| 277 | + send.finish().ok()?; | ||
| 278 | + receive.read_to_end(0).await.ok()?; | ||
| 279 | + Some(()) | ||
| 280 | + }) | ||
| 281 | + .await; | ||
| 282 | +} | ||
| 283 | + | ||
| 284 | +async fn download(server: &crate::Server, me: Me, offer: Offer) -> Result<Vec<u8>, Fail> { | ||
| 217 | if offer.packed > FILE_MAX || offer.size > FILE_MAX { | 285 | if offer.packed > FILE_MAX || offer.size > FILE_MAX { |
| 218 | return Err("too large".into()); | 286 | return Err("too large".into()); |
| 219 | } | 287 | } |
| 220 | crate::net::dial(server, ALPN, async |connection| { | 288 | crate::net::dial(server, ALPN, async |connection| { |
| 221 | let (send, mut receive) = connection.open_bi().await?; | 289 | let (send, mut receive) = connection.open_bi().await?; |
| 222 | let mut send = Sending::new(send); | 290 | let mut send = Sending::new(send); |
| 223 | - frame::write(&mut send, &Ask::Download { file: offer.file }, UP_MAX).await?; | 291 | + frame::write( |
| 292 | + &mut send, | ||
| 293 | + &Ask::Download { | ||
| 294 | + me, | ||
| 295 | + file: offer.file, | ||
| 296 | + }, | ||
| 297 | + UP_MAX, | ||
| 298 | + ) | ||
| 299 | + .await?; | ||
| 224 | send.finish()?; | 300 | send.finish()?; |
| 225 | let mut packed = Vec::with_capacity(offer.packed as usize); | 301 | let mut packed = Vec::with_capacity(offer.packed as usize); |
| 226 | let mut chunk = vec![0u8; CHUNK]; | 302 | let mut chunk = vec![0u8; CHUNK]; |
crates/common/src/call.rsmodified+6 -2
| @@ -8,8 +8,8 @@ use crate::{ | |||
| 8 | Account, AdminActionKind, AdminLogEntry, AttachmentInfo, BackupInfo, Ban, BanScope, | 8 | Account, AdminActionKind, AdminLogEntry, AttachmentInfo, BackupInfo, Ban, BanScope, |
| 9 | Community, CommunitySummary, CommunityUsage, DayStat, Edit, Friends, Id, Invitation, | 9 | Community, CommunitySummary, CommunityUsage, DayStat, Edit, Friends, Id, Invitation, |
| 10 | InviteCode, LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, ReleaseInfo, | 10 | InviteCode, LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, ReleaseInfo, |
| 11 | - Report, ReportStatus, ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, | 11 | + Report, ReportStatus, ServerBan, ServerSettings, SessionInfo, Unread, UpdateClient, Usage, |
| 12 | - VoiceRoom, | 12 | + User, VoiceRoom, |
| 13 | }, | 13 | }, |
| 14 | share::{Codec, Kind, Quality, Share, Source}, | 14 | share::{Codec, Kind, Quality, Share, Source}, |
| 15 | stats::Stats, | 15 | stats::Stats, |
| @@ -628,6 +628,9 @@ pub struct ListBackups; | |||
| 628 | #[derive(Debug, Clone, Encode, Decode)] | 628 | #[derive(Debug, Clone, Encode, Decode)] |
| 629 | pub struct ListReleases; | 629 | pub struct ListReleases; |
| 630 | 630 | ||
| 631 | +#[derive(Debug, Clone, Encode, Decode)] | ||
| 632 | +pub struct ListUpdateClients; | ||
| 633 | + | ||
| 631 | #[derive(Debug, Clone, Encode, Decode)] | 634 | #[derive(Debug, Clone, Encode, Decode)] |
| 632 | pub struct PublishRelease { | 635 | pub struct PublishRelease { |
| 633 | pub files: Vec<crate::update::Sha>, | 636 | pub files: Vec<crate::update::Sha>, |
| @@ -780,6 +783,7 @@ calls! { | |||
| 780 | ListBackups: Builder -> Vec<BackupInfo>; | 783 | ListBackups: Builder -> Vec<BackupInfo>; |
| 781 | DeleteBackup: Builder -> (); | 784 | DeleteBackup: Builder -> (); |
| 782 | ListReleases: Builder -> Vec<ReleaseInfo>; | 785 | ListReleases: Builder -> Vec<ReleaseInfo>; |
| 786 | + ListUpdateClients: Builder -> Vec<UpdateClient>; | ||
| 783 | PublishRelease: Builder -> ReleaseInfo; | 787 | PublishRelease: Builder -> ReleaseInfo; |
| 784 | SetReleaseRequired: Builder -> (); | 788 | SetReleaseRequired: Builder -> (); |
| 785 | FollowStats: Builder -> Option<Stats>; | 789 | FollowStats: Builder -> Option<Stats>; |
crates/common/src/model.rsmodified+22 -0
| @@ -455,6 +455,28 @@ pub struct ReleaseInfo { | |||
| 455 | pub files: Vec<ReleaseFile>, | 455 | pub files: Vec<ReleaseFile>, |
| 456 | } | 456 | } |
| 457 | 457 | ||
| 458 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] | ||
| 459 | +pub enum UpdateState { | ||
| 460 | + Unknown, | ||
| 461 | + Latest, | ||
| 462 | + Available { seq: u64, required: bool }, | ||
| 463 | + Downloading { seq: u64, percent: u8 }, | ||
| 464 | + Installing { seq: u64 }, | ||
| 465 | + Ready { seq: u64 }, | ||
| 466 | + Failed { seq: u64 }, | ||
| 467 | +} | ||
| 468 | + | ||
| 469 | +#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | ||
| 470 | +pub struct UpdateClient { | ||
| 471 | + pub user: Option<String>, | ||
| 472 | + pub device: String, | ||
| 473 | + pub release: Option<u64>, | ||
| 474 | + pub target: Option<String>, | ||
| 475 | + pub state: UpdateState, | ||
| 476 | + pub online: bool, | ||
| 477 | + pub seen_ms: u64, | ||
| 478 | +} | ||
| 479 | + | ||
| 458 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 480 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| 459 | pub struct BackupInfo { | 481 | pub struct BackupInfo { |
| 460 | pub name: String, | 482 | pub name: String, |
crates/common/src/session.rsmodified+1 -0
| @@ -7,6 +7,7 @@ pub struct Hello { | |||
| 7 | pub token: Option<String>, | 7 | pub token: Option<String>, |
| 8 | pub device: String, | 8 | pub device: String, |
| 9 | pub build: Option<crate::update::Sha>, | 9 | pub build: Option<crate::update::Sha>, |
| 10 | + pub install: crate::update::Install, | ||
| 10 | } | 11 | } |
| 11 | 12 | ||
| 12 | #[derive(Debug, Clone, Encode, Decode)] | 13 | #[derive(Debug, Clone, Encode, Decode)] |
crates/common/src/update.rsmodified+19 -2
| @@ -6,11 +6,28 @@ pub const MARK: &str = "yumush-target:"; | |||
| 6 | const TARGET_MAX: usize = 32; | 6 | const TARGET_MAX: usize = 32; |
| 7 | 7 | ||
| 8 | pub type Sha = [u8; 32]; | 8 | pub type Sha = [u8; 32]; |
| 9 | +pub type Install = [u8; 16]; | ||
| 10 | + | ||
| 11 | +#[derive(Debug, Clone, Encode, Decode)] | ||
| 12 | +pub struct Me { | ||
| 13 | + pub install: Install, | ||
| 14 | + pub device: String, | ||
| 15 | + pub token: Option<String>, | ||
| 16 | + pub build: Sha, | ||
| 17 | +} | ||
| 9 | 18 | ||
| 10 | #[derive(Debug, Clone, Encode, Decode)] | 19 | #[derive(Debug, Clone, Encode, Decode)] |
| 11 | pub enum Ask { | 20 | pub enum Ask { |
| 12 | - Check { build: Sha, targets: Vec<String> }, | 21 | + Check { me: Me, targets: Vec<String> }, |
| 13 | - Download { file: Sha }, | 22 | + Download { me: Me, file: Sha }, |
| 23 | + Report { me: Me, progress: Progress }, | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] | ||
| 27 | +pub enum Progress { | ||
| 28 | + Installing, | ||
| 29 | + Ready, | ||
| 30 | + Failed, | ||
| 14 | } | 31 | } |
| 15 | 32 | ||
| 16 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] | 33 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] |
crates/server/src/call/mod.rsmodified+1 -0
| @@ -220,6 +220,7 @@ pub(crate) async fn dispatch(request: Request, cx: &mut Cx<'_>) -> Vec<u8> { | |||
| 220 | Request::PushStats(call) => serve(call, cx).await, | 220 | Request::PushStats(call) => serve(call, cx).await, |
| 221 | Request::GetServerStats(call) => serve(call, cx).await, | 221 | Request::GetServerStats(call) => serve(call, cx).await, |
| 222 | Request::ListReleases(call) => serve(call, cx).await, | 222 | Request::ListReleases(call) => serve(call, cx).await, |
| 223 | + Request::ListUpdateClients(call) => serve(call, cx).await, | ||
| 223 | Request::PublishRelease(call) => serve(call, cx).await, | 224 | Request::PublishRelease(call) => serve(call, cx).await, |
| 224 | Request::SetReleaseRequired(call) => serve(call, cx).await, | 225 | Request::SetReleaseRequired(call) => serve(call, cx).await, |
| 225 | } | 226 | } |
crates/server/src/call/release.rsmodified+26 -2
| @@ -1,7 +1,7 @@ | |||
| 1 | use common::{ | 1 | use common::{ |
| 2 | - call::{ListReleases, PublishRelease, SetReleaseRequired}, | 2 | + call::{ListReleases, ListUpdateClients, PublishRelease, SetReleaseRequired}, |
| 3 | event::Event, | 3 | event::Event, |
| 4 | - model::{AdminAction, ReleaseFile, ReleaseInfo}, | 4 | + model::{AdminAction, ReleaseFile, ReleaseInfo, UpdateClient}, |
| 5 | update::Sha, | 5 | update::Sha, |
| 6 | }; | 6 | }; |
| 7 | 7 | ||
| @@ -42,6 +42,30 @@ impl Handle for ListReleases { | |||
| 42 | } | 42 | } |
| 43 | } | 43 | } |
| 44 | 44 | ||
| 45 | +impl Handle for ListUpdateClients { | ||
| 46 | + async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<UpdateClient>, ServerError> { | ||
| 47 | + let online = cx.sh.services.hub.installs(); | ||
| 48 | + let mut clients = Vec::new(); | ||
| 49 | + for (install, seen) in cx.sh.releases.recent() { | ||
| 50 | + let (release, target) = db::release::of_file(&seen.build, cx.db) | ||
| 51 | + .await? | ||
| 52 | + .map_or((None, None), |(seq, target)| (Some(seq), Some(target))); | ||
| 53 | + clients.push(UpdateClient { | ||
| 54 | + user: seen.user, | ||
| 55 | + device: seen.device, | ||
| 56 | + release, | ||
| 57 | + target, | ||
| 58 | + state: seen.state, | ||
| 59 | + online: online.contains(&install), | ||
| 60 | + seen_ms: seen.seen_ms, | ||
| 61 | + }); | ||
| 62 | + } | ||
| 63 | + clients.sort_by(|a, b| b.online.cmp(&a.online).then(b.seen_ms.cmp(&a.seen_ms))); | ||
| 64 | + | ||
| 65 | + Ok(clients) | ||
| 66 | + } | ||
| 67 | +} | ||
| 68 | + | ||
| 45 | impl Handle for PublishRelease { | 69 | impl Handle for PublishRelease { |
| 46 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<ReleaseInfo, ServerError> { | 70 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<ReleaseInfo, ServerError> { |
| 47 | let me = me.user()?; | 71 | let me = me.user()?; |
crates/server/src/db/release.rsmodified+10 -0
| @@ -35,6 +35,16 @@ pub async fn seq_of(file: &Sha, db: &Connection) -> Result<Option<u64>, ServerEr | |||
| 35 | .await | 35 | .await |
| 36 | } | 36 | } |
| 37 | 37 | ||
| 38 | +pub async fn of_file(file: &Sha, db: &Connection) -> Result<Option<(u64, String)>, ServerError> { | ||
| 39 | + maybe( | ||
| 40 | + db, | ||
| 41 | + "SELECT seq, target FROM release_file WHERE file = ?1", | ||
| 42 | + (&file[..],), | ||
| 43 | + |r| Ok((r.get()?, r.get()?)), | ||
| 44 | + ) | ||
| 45 | + .await | ||
| 46 | +} | ||
| 47 | + | ||
| 38 | pub async fn latest(target: &str, db: &Connection) -> Result<Option<(u64, Staged)>, ServerError> { | 48 | pub async fn latest(target: &str, db: &Connection) -> Result<Option<(u64, Staged)>, ServerError> { |
| 39 | maybe( | 49 | maybe( |
| 40 | db, | 50 | db, |
crates/server/src/hub.rsmodified+18 -2
| @@ -7,7 +7,11 @@ use std::{ | |||
| 7 | }; | 7 | }; |
| 8 | 8 | ||
| 9 | use bytes::Bytes; | 9 | use bytes::Bytes; |
| 10 | -use common::{model::Id, transport::Close, update::Sha}; | 10 | +use common::{ |
| 11 | + model::Id, | ||
| 12 | + transport::Close, | ||
| 13 | + update::{Install, Sha}, | ||
| 14 | +}; | ||
| 11 | use quinn::Connection; | 15 | use quinn::Connection; |
| 12 | use tokio::sync::mpsc::{self, error::TrySendError}; | 16 | use tokio::sync::mpsc::{self, error::TrySendError}; |
| 13 | use tracing::warn; | 17 | use tracing::warn; |
| @@ -28,6 +32,7 @@ pub struct Client { | |||
| 28 | pub conn: Option<Connection>, | 32 | pub conn: Option<Connection>, |
| 29 | pub me: Option<Signed>, | 33 | pub me: Option<Signed>, |
| 30 | pub build: Option<Sha>, | 34 | pub build: Option<Sha>, |
| 35 | + pub install: Install, | ||
| 31 | tx: mpsc::Sender<Bytes>, | 36 | tx: mpsc::Sender<Bytes>, |
| 32 | pub closed: AtomicBool, | 37 | pub closed: AtomicBool, |
| 33 | watching: Mutex<Option<Id>>, | 38 | watching: Mutex<Option<Id>>, |
| @@ -39,6 +44,7 @@ impl Client { | |||
| 39 | conn: Option<Connection>, | 44 | conn: Option<Connection>, |
| 40 | me: Option<Signed>, | 45 | me: Option<Signed>, |
| 41 | build: Option<Sha>, | 46 | build: Option<Sha>, |
| 47 | + install: Install, | ||
| 42 | ) -> (Arc<Self>, mpsc::Receiver<Bytes>) { | 48 | ) -> (Arc<Self>, mpsc::Receiver<Bytes>) { |
| 43 | let (tx, rx) = mpsc::channel(QUEUE_LENGTH); | 49 | let (tx, rx) = mpsc::channel(QUEUE_LENGTH); |
| 44 | let client = Arc::new(Self { | 50 | let client = Arc::new(Self { |
| @@ -46,6 +52,7 @@ impl Client { | |||
| 46 | conn, | 52 | conn, |
| 47 | me, | 53 | me, |
| 48 | build, | 54 | build, |
| 55 | + install, | ||
| 49 | tx, | 56 | tx, |
| 50 | closed: AtomicBool::new(false), | 57 | closed: AtomicBool::new(false), |
| 51 | watching: Mutex::new(None), | 58 | watching: Mutex::new(None), |
| @@ -56,7 +63,7 @@ impl Client { | |||
| 56 | } | 63 | } |
| 57 | 64 | ||
| 58 | pub fn detached(me: Option<Signed>) -> Arc<Self> { | 65 | pub fn detached(me: Option<Signed>) -> Arc<Self> { |
| 59 | - Self::new(None, me, None).0 | 66 | + Self::new(None, me, None, Install::default()).0 |
| 60 | } | 67 | } |
| 61 | 68 | ||
| 62 | pub fn user_id(&self) -> Option<Id> { | 69 | pub fn user_id(&self) -> Option<Id> { |
| @@ -172,6 +179,15 @@ impl Hub { | |||
| 172 | .collect() | 179 | .collect() |
| 173 | } | 180 | } |
| 174 | 181 | ||
| 182 | + pub fn installs(&self) -> Vec<Install> { | ||
| 183 | + self.0 | ||
| 184 | + .lock() | ||
| 185 | + .unwrap() | ||
| 186 | + .values() | ||
| 187 | + .map(|client| client.install) | ||
| 188 | + .collect() | ||
| 189 | + } | ||
| 190 | + | ||
| 175 | pub fn all(&self) -> Vec<ConnId> { | 191 | pub fn all(&self) -> Vec<ConnId> { |
| 176 | self.0.lock().unwrap().keys().copied().collect() | 192 | self.0.lock().unwrap().keys().copied().collect() |
| 177 | } | 193 | } |
crates/server/src/network.rsmodified+2 -1
| @@ -231,9 +231,10 @@ async fn greet(connection: &Connection, shared: &Shared) -> Result<Option<Pendin | |||
| 231 | let mut reply_stream = Sending::new(send_stream); | 231 | let mut reply_stream = Sending::new(send_stream); |
| 232 | let hello: Hello = frame::read(&mut receive_stream, UP_MAX).await?; | 232 | let hello: Hello = frame::read(&mut receive_stream, UP_MAX).await?; |
| 233 | let build = hello.build; | 233 | let build = hello.build; |
| 234 | + let install = hello.install; | ||
| 234 | match admit(hello, connection, shared).await { | 235 | match admit(hello, connection, shared).await { |
| 235 | Ok((me, user)) => { | 236 | Ok((me, user)) => { |
| 236 | - let (client, events) = Client::new(Some(connection.clone()), me, build); | 237 | + let (client, events) = Client::new(Some(connection.clone()), me, build, install); |
| 237 | 238 | ||
| 238 | Ok(Some(Pending { | 239 | Ok(Some(Pending { |
| 239 | client, | 240 | client, |
crates/server/src/update.rsmodified+116 -6
| @@ -8,20 +8,25 @@ use std::{ | |||
| 8 | use common::{ | 8 | use common::{ |
| 9 | error::{Error as CommonError, ReleaseProblem}, | 9 | error::{Error as CommonError, ReleaseProblem}, |
| 10 | frame::{self, DOWN_MAX, Sending, UP_MAX}, | 10 | frame::{self, DOWN_MAX, Sending, UP_MAX}, |
| 11 | - model::{Staged, User}, | 11 | + model::{Staged, UpdateState, User}, |
| 12 | open::Stage, | 12 | open::Stage, |
| 13 | permission, | 13 | permission, |
| 14 | - update::{Ask, FILE_MAX, Offer, Sha, Status, hex, sha256, target_of}, | 14 | + time::now_ms, |
| 15 | + update::{Ask, FILE_MAX, Install, Me, Offer, Progress, Sha, Status, hex, sha256, target_of}, | ||
| 15 | }; | 16 | }; |
| 16 | use quinn::{Connection, RecvStream, VarInt}; | 17 | use quinn::{Connection, RecvStream, VarInt}; |
| 18 | +use tokio::io::AsyncReadExt; | ||
| 17 | use tracing::warn; | 19 | use tracing::warn; |
| 18 | 20 | ||
| 19 | use crate::{ | 21 | use crate::{ |
| 22 | + authentication, | ||
| 20 | db::{self, Connection as DbConnection, Db}, | 23 | db::{self, Connection as DbConnection, Db}, |
| 21 | error::{ServerError, ensure, ensure_with}, | 24 | error::{ServerError, ensure, ensure_with}, |
| 22 | }; | 25 | }; |
| 23 | 26 | ||
| 24 | const PACK_LEVEL: i32 = 19; | 27 | const PACK_LEVEL: i32 = 19; |
| 28 | +const BOARD_KEEP_MS: u64 = 7 * 24 * 60 * 60 * 1000; | ||
| 29 | +const CHUNK: usize = 64 << 10; | ||
| 25 | 30 | ||
| 26 | fn path_of(directory: &Path, file: &Sha) -> PathBuf { | 31 | fn path_of(directory: &Path, file: &Sha) -> PathBuf { |
| 27 | directory.join(format!("{}.zst", hex(file))) | 32 | directory.join(format!("{}.zst", hex(file))) |
| @@ -35,10 +40,20 @@ fn pack(bytes: &[u8], path: &Path) -> std::io::Result<u64> { | |||
| 35 | Ok(encoder.finish()?.metadata()?.len()) | 40 | Ok(encoder.finish()?.metadata()?.len()) |
| 36 | } | 41 | } |
| 37 | 42 | ||
| 43 | +#[derive(Clone)] | ||
| 44 | +pub struct Seen { | ||
| 45 | + pub user: Option<String>, | ||
| 46 | + pub device: String, | ||
| 47 | + pub build: Sha, | ||
| 48 | + pub state: UpdateState, | ||
| 49 | + pub seen_ms: u64, | ||
| 50 | +} | ||
| 51 | + | ||
| 38 | #[derive(Clone, Default)] | 52 | #[derive(Clone, Default)] |
| 39 | pub struct Releases { | 53 | pub struct Releases { |
| 40 | directory: PathBuf, | 54 | directory: PathBuf, |
| 41 | staged: Arc<Mutex<HashMap<Sha, Staged>>>, | 55 | staged: Arc<Mutex<HashMap<Sha, Staged>>>, |
| 56 | + board: Arc<Mutex<HashMap<Install, Seen>>>, | ||
| 42 | } | 57 | } |
| 43 | 58 | ||
| 44 | impl Releases { | 59 | impl Releases { |
| @@ -55,9 +70,36 @@ impl Releases { | |||
| 55 | Ok(Self { | 70 | Ok(Self { |
| 56 | directory, | 71 | directory, |
| 57 | staged: Default::default(), | 72 | staged: Default::default(), |
| 73 | + board: Default::default(), | ||
| 58 | }) | 74 | }) |
| 59 | } | 75 | } |
| 60 | 76 | ||
| 77 | + pub fn record(&self, me: &Me, user: Option<String>, state: UpdateState) { | ||
| 78 | + let mut board = self.board.lock().unwrap(); | ||
| 79 | + let user = user.or_else(|| board.get(&me.install).and_then(|seen| seen.user.clone())); | ||
| 80 | + board.insert( | ||
| 81 | + me.install, | ||
| 82 | + Seen { | ||
| 83 | + user, | ||
| 84 | + device: me.device.clone(), | ||
| 85 | + build: me.build, | ||
| 86 | + state, | ||
| 87 | + seen_ms: now_ms(), | ||
| 88 | + }, | ||
| 89 | + ); | ||
| 90 | + } | ||
| 91 | + | ||
| 92 | + pub fn recent(&self) -> Vec<(Install, Seen)> { | ||
| 93 | + let since = now_ms().saturating_sub(BOARD_KEEP_MS); | ||
| 94 | + let mut board = self.board.lock().unwrap(); | ||
| 95 | + board.retain(|_, seen| seen.seen_ms >= since); | ||
| 96 | + | ||
| 97 | + board | ||
| 98 | + .iter() | ||
| 99 | + .map(|(install, seen)| (*install, seen.clone())) | ||
| 100 | + .collect() | ||
| 101 | + } | ||
| 102 | + | ||
| 61 | pub async fn stage( | 103 | pub async fn stage( |
| 62 | &self, | 104 | &self, |
| 63 | user: Option<&User>, | 105 | user: Option<&User>, |
| @@ -172,19 +214,56 @@ impl Releases { | |||
| 172 | 214 | ||
| 173 | async fn answer(&self, ask: Ask, db: &Db, mut send: Sending) -> Result<(), ServerError> { | 215 | async fn answer(&self, ask: Ask, db: &Db, mut send: Sending) -> Result<(), ServerError> { |
| 174 | match ask { | 216 | match ask { |
| 175 | - Ask::Check { build, targets } => { | 217 | + Ask::Check { me, targets } => { |
| 176 | let status = db | 218 | let status = db |
| 177 | - .run(async |conn| status(build, &targets, conn).await) | 219 | + .run(async |conn| status(me.build, &targets, conn).await) |
| 178 | .await?; | 220 | .await?; |
| 221 | + self.record(&me, who(&me, db).await, state_of(status)); | ||
| 179 | frame::write(&mut send, &status, DOWN_MAX).await?; | 222 | frame::write(&mut send, &status, DOWN_MAX).await?; |
| 180 | } | 223 | } |
| 181 | - Ask::Download { file } => { | 224 | + Ask::Download { me, file } => { |
| 182 | let live = db.run(async |conn| db::release::live(conn).await).await?; | 225 | let live = db.run(async |conn| db::release::live(conn).await).await?; |
| 183 | if live.contains(&file) { | 226 | if live.contains(&file) { |
| 227 | + let user = who(&me, db).await; | ||
| 228 | + let seq = db | ||
| 229 | + .run(async |conn| db::release::seq_of(&file, conn).await) | ||
| 230 | + .await? | ||
| 231 | + .unwrap_or_default(); | ||
| 184 | let mut packed = tokio::fs::File::open(path_of(&self.directory, &file)).await?; | 232 | let mut packed = tokio::fs::File::open(path_of(&self.directory, &file)).await?; |
| 185 | - tokio::io::copy(&mut packed, send.get()).await?; | 233 | + let total = packed.metadata().await?.len().max(1); |
| 234 | + let mut buffer = vec![0u8; CHUNK]; | ||
| 235 | + let mut sent = 0; | ||
| 236 | + let mut shown = 0; | ||
| 237 | + loop { | ||
| 238 | + let read = packed.read(&mut buffer).await?; | ||
| 239 | + if read == 0 { | ||
| 240 | + break; | ||
| 241 | + } | ||
| 242 | + send.get().write_all(&buffer[..read]).await?; | ||
| 243 | + sent += read as u64; | ||
| 244 | + let percent = (sent * 100 / total) as u8; | ||
| 245 | + if percent != shown { | ||
| 246 | + shown = percent; | ||
| 247 | + let state = UpdateState::Downloading { seq, percent }; | ||
| 248 | + self.record(&me, user.clone(), state); | ||
| 249 | + } | ||
| 250 | + } | ||
| 186 | } | 251 | } |
| 187 | } | 252 | } |
| 253 | + Ask::Report { me, progress } => { | ||
| 254 | + let seq = self | ||
| 255 | + .board | ||
| 256 | + .lock() | ||
| 257 | + .unwrap() | ||
| 258 | + .get(&me.install) | ||
| 259 | + .map_or(0, |seen| seq_in(&seen.state)); | ||
| 260 | + let state = match progress { | ||
| 261 | + Progress::Installing => UpdateState::Installing { seq }, | ||
| 262 | + Progress::Ready => UpdateState::Ready { seq }, | ||
| 263 | + Progress::Failed => UpdateState::Failed { seq }, | ||
| 264 | + }; | ||
| 265 | + self.record(&me, who(&me, db).await, state); | ||
| 266 | + } | ||
| 188 | } | 267 | } |
| 189 | send.finish()?; | 268 | send.finish()?; |
| 190 | 269 | ||
| @@ -192,6 +271,37 @@ impl Releases { | |||
| 192 | } | 271 | } |
| 193 | } | 272 | } |
| 194 | 273 | ||
| 274 | +async fn who(me: &Me, db: &Db) -> Option<String> { | ||
| 275 | + let token = me.token.clone()?; | ||
| 276 | + | ||
| 277 | + db.run(async |conn| authentication::resume(&token, conn).await) | ||
| 278 | + .await | ||
| 279 | + .ok() | ||
| 280 | + .map(|(_, user)| user.username) | ||
| 281 | +} | ||
| 282 | + | ||
| 283 | +fn state_of(status: Status) -> UpdateState { | ||
| 284 | + match status { | ||
| 285 | + Status::Unknown => UpdateState::Unknown, | ||
| 286 | + Status::Latest => UpdateState::Latest, | ||
| 287 | + Status::Offer(offer) => UpdateState::Available { | ||
| 288 | + seq: offer.seq, | ||
| 289 | + required: offer.required, | ||
| 290 | + }, | ||
| 291 | + } | ||
| 292 | +} | ||
| 293 | + | ||
| 294 | +fn seq_in(state: &UpdateState) -> u64 { | ||
| 295 | + match *state { | ||
| 296 | + UpdateState::Available { seq, .. } | ||
| 297 | + | UpdateState::Downloading { seq, .. } | ||
| 298 | + | UpdateState::Installing { seq } | ||
| 299 | + | UpdateState::Ready { seq } | ||
| 300 | + | UpdateState::Failed { seq } => seq, | ||
| 301 | + UpdateState::Unknown | UpdateState::Latest => 0, | ||
| 302 | + } | ||
| 303 | +} | ||
| 304 | + | ||
| 195 | async fn status(build: Sha, targets: &[String], db: &DbConnection) -> Result<Status, ServerError> { | 305 | async fn status(build: Sha, targets: &[String], db: &DbConnection) -> Result<Status, ServerError> { |
| 196 | let Some(current) = db::release::seq_of(&build, db).await? else { | 306 | let Some(current) = db::release::seq_of(&build, db).await? else { |
| 197 | return Ok(Status::Unknown); | 307 | return Ok(Status::Unknown); |