知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
fix(windows): the in-app update no longer gives up after 20 seconds: it keeps going while data arrives and logs why when it stops
wqugurue98a0457427c
diff --git a/windows/src/Cicada.Core/UpdateChecker.cs b/windows/src/Cicada.Core/UpdateChecker.csindex 4d83e3a..7b60835 100644--- a/windows/src/Cicada.Core/UpdateChecker.cs+++ b/windows/src/Cicada.Core/UpdateChecker.cs@@ -39,6 +39,11 @@ public sealed class UpdateCheckerpublic DateTimeOffset? LastChecked { get; private set; }public event Action? Changed;+ /// How long the feed, checksums.txt or the installer's headers may take to answer.+ public static readonly TimeSpan Within = TimeSpan.FromSeconds(30);+ /// The download fails when no bytes arrive for this long (not when it is merely slow).+ public TimeSpan Stall { get; set; } = TimeSpan.FromSeconds(30);+readonly HttpClient http;readonly Action<DateTimeOffset> remember;Timer? timer;@@ -48,8 +53,10 @@ public sealed class UpdateChecker{LastChecked = lastChecked;this.remember = remember;- http = handler is null ? new HttpClient() : new HttpClient(handler);- http.Timeout = TimeSpan.FromSeconds(20);+ http = new HttpClient(handler ?? Handler());+ // No overall timeout: an 85 MB installer on a slow line takes minutes. Each request has its+ // own limit instead (Within), and the download a stall limit (Stall).+ http.Timeout = System.Threading.Timeout.InfiniteTimeSpan;// GitHub's API refuses requests without a User-Agent.http.DefaultRequestHeaders.UserAgent.ParseAdd("Cicada-Windows");http.DefaultRequestHeaders.Accept.ParseAdd("application/vnd.github+json");@@ -91,11 +98,26 @@ public sealed class UpdateChecker{if (Uri.TryCreate(feed, UriKind.Absolute, out var uri) && uri.IsFile) return await File.ReadAllTextAsync(uri.LocalPath);if (!feed.Contains("://")) return await File.ReadAllTextAsync(feed);- using var r = await http.GetAsync(feed);+ using var cts = new CancellationTokenSource(Within);+ using var r = await http.GetAsync(feed, cts.Token);r.EnsureSuccessStatusCode();- return await r.Content.ReadAsStringAsync();+ return await r.Content.ReadAsStringAsync(cts.Token);}+ /// The default handler: sockets with a 4 MB receive buffer instead of Windows' 64 KB default.+ /// On the test VM's throttled direct path to GitHub it was never slower in paired runs and+ /// sometimes several times faster (once 14 MB/s against 0.07); the path itself swung so much+ /// that the gain isn't pinned down. A system proxy still applies: the callback then connects to it.+ static SocketsHttpHandler Handler() => new()+ {+ ConnectCallback = async (context, cancel) =>+ {+ var socket = new System.Net.Sockets.Socket(System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp) { NoDelay = true, ReceiveBufferSize = 4 << 20 };+ try { await socket.ConnectAsync(context.DnsEndPoint, cancel); return new System.Net.Sockets.NetworkStream(socket, ownsSocket: true); }+ catch { socket.Dispose(); throw; }+ },+ };+/// The zip this PC should run: ARM64 on an ARM PC (even when this copy is the emulated x64 one).public static string Arch => RuntimeInformation.OSArchitecture == Architecture.Arm64 ? "ARM64" : "x64";@@ -168,14 +190,19 @@ public sealed class UpdateCheckerDirectory.CreateDirectory(folder);var file = Path.Combine(folder, name);string? expected;+ var stage = "checksums";try{expected = ChecksumFor(await Read(u.Checksums), name);+ stage = "installer";await Fetch(u.Setup, file, u.Size, progress);}- catch (Exception e) when (e is HttpRequestException or IOException or TaskCanceledException)+ catch (Exception e) when (e is HttpRequestException or IOException or OperationCanceledException){- Log.Debug($"update: download failed {e.GetType().Name}");+ // Why, for the log: a stall, a refused connection, a 404…+ var why = e is OperationCanceledException ? (stage == "installer" && e.Data["stalled"] is true ? $"nothing arrived for {Stall.TotalSeconds:0} s" : "timed out") : e.Message;+ Log.Debug($"update: download failed at {stage}: {e.GetType().Name}: {why}{(e.InnerException is { } inner ? $" ({inner.GetType().Name}: {inner.Message})" : "")}");+ try { Directory.Delete(folder, true); } catch { }throw new Failure("下载失败");}string got;@@ -204,20 +231,30 @@ public sealed class UpdateCheckerasync Task Fetch(string url, string to, long expected, Action<double>? progress){if (Uri.TryCreate(url, UriKind.Absolute, out var uri) && uri.IsFile) { File.Copy(uri.LocalPath, to, true); progress?.Invoke(1); return; }- using var r = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);+ var started = DateTime.UtcNow;+ using var cts = new CancellationTokenSource(Within);+ using var r = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cts.Token);r.EnsureSuccessStatusCode();var total = r.Content.Headers.ContentLength ?? expected;- await using var src = await r.Content.ReadAsStreamAsync();+ await using var src = await r.Content.ReadAsStreamAsync(cts.Token);await using var dst = File.Create(to);- var buffer = new byte[81920];+ var buffer = new byte[1 << 17];long got = 0; int n, last = -1;- while ((n = await src.ReadAsync(buffer)) > 0)+ while (true){+ // The limit restarts with every read: slow is fine, stopped is not.+ cts.CancelAfter(Stall);+ try { n = await src.ReadAsync(buffer, cts.Token); }+ catch (OperationCanceledException e) { e.Data["stalled"] = true; Log.Debug($"update: stalled after {got} of {total} bytes"); throw; }+ if (n == 0) break;await dst.WriteAsync(buffer.AsMemory(0, n));got += n;// Whole percents only: each one re-renders the flyout and settings.if (total > 0 && (int)(got * 100 / total) is var pct && pct != last) { last = pct; progress?.Invoke(Math.Min(1, (double)got / total)); }}+ if (r.Content.Headers.ContentLength is { } length && got != length) throw new IOException($"the connection ended after {got} of {length} bytes");+ var seconds = Math.Max(0.001, (DateTime.UtcNow - started).TotalSeconds);+ Log.Debug($"update: fetched {got / 1e6:0.0} MB in {seconds:0.0} s ({got / 1e6 / seconds:0.0} MB/s)");}/// Why installing didn't work: a shared string key, said to the user (the browser fallback opens).diff --git a/windows/tests/Cicada.Tests/Program.cs b/windows/tests/Cicada.Tests/Program.csindex 893bf7d..6bfa19e 100644--- a/windows/tests/Cicada.Tests/Program.cs+++ b/windows/tests/Cicada.Tests/Program.cs@@ -1194,6 +1194,65 @@ static class TestsCheck(!File.Exists(got), "left-over installer removed");}+ /// A release served over HTTP: checksums.txt, then the installer through `body`.+ sealed class Release(byte[] installer, Func<byte[], Stream> body) : HttpMessageHandler+ {+ protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancel)+ {+ var name = Path.GetFileName(request.RequestUri!.LocalPath);+ HttpContent content = name == "checksums.txt"+ ? new StringContent($"{Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(installer))} Cicada-1.3.0-Windows-x64.exe\n")+ : new StreamContent(body(installer));+ if (name != "checksums.txt") content.Headers.ContentLength = installer.Length;+ return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = content });+ }+ }++ /// Sends `data` in `chunk`-sized pieces, then (when `stallAt` is reached) nothing at all.+ sealed class Trickle(byte[] data, int chunk, long stallAt = long.MaxValue) : Stream+ {+ long at;+ public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancel = default)+ {+ if (at >= stallAt) { await Task.Delay(Timeout.Infinite, cancel); }+ var n = (int)Math.Min(Math.Min(chunk, buffer.Length), data.Length - at);+ data.AsMemory((int)at, n).CopyTo(buffer);+ at += n;+ await Task.Yield();+ return n;+ }+ public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult();+ public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => false;+ public override long Length => data.Length; public override long Position { get => at; set => throw new NotSupportedException(); }+ public override void Flush() { }+ public override long Seek(long o, SeekOrigin s) => throw new NotSupportedException();+ public override void SetLength(long v) => throw new NotSupportedException();+ public override void Write(byte[] b, int o, int c) => throw new NotSupportedException();+ }++ /// A slow download keeps going and reports progress up to 100 %; one that stops sending fails+ /// after the stall limit, not after a fixed total time.+ public static async Task UpdateDownloadFailsOnAStallNotOnSlowness()+ {+ var installer = new byte[300_000];+ Random.Shared.NextBytes(installer);+ var u = new UpdateChecker.Update("1.3.0", "https://example.com", null, installer.Length,+ "https://example.com/Cicada-1.3.0-Windows-x64.exe", "https://example.com/checksums.txt");+ var progress = new List<double>();+ var slow = new UpdateChecker(null, _ => { }, new Release(installer, d => new Trickle(d, 1000))) { Stall = TimeSpan.FromMilliseconds(500) };+ var got = await slow.Download(u, progress.Add);+ Check(File.ReadAllBytes(got).AsSpan().SequenceEqual(installer), "whole file written");+ Equal(1.0, progress[^1], "progress reaches 100 %");+ Check(progress.Count <= 101, "whole percents only");+ UpdateChecker.CleanDownloads(Path.GetDirectoryName(Path.GetDirectoryName(got)));++ var stuck = new UpdateChecker(null, _ => { }, new Release(installer, d => new Trickle(d, 1000, stallAt: 100_000))) { Stall = TimeSpan.FromMilliseconds(300) };+ var t = DateTime.UtcNow;+ try { await stuck.Download(u); throw new Exception("a stalled download succeeded"); }+ catch (UpdateChecker.Failure f) { Equal("下载失败", f.Key, "stall reported as a failed download"); }+ Check((DateTime.UtcNow - t).TotalSeconds < 5, "fails soon after the stall");+ }+public static void UpdateSkipsReleasesWithoutAWindowsZip(){var list = UpdateChecker.Decode($"[{Rel("v1.6.0", "Cicada-1.6.0-macOS-AppleSilicon.zip")},{Rel("v1.5.0", "Cicada-1.5.0-Windows-x64.zip", "Cicada-1.5.0-Windows-ARM64.zip")}]")!;