Compare commits
No files matched your search
@@ -1,6 +1,8 @@
|
||||
name: AtomGit mirror
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '17 */3 * * *'
|
||||
workflow_run:
|
||||
workflows: [CI]
|
||||
types: [completed]
|
||||
@@ -8,8 +10,8 @@ on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
run_id:
|
||||
description: Original CI run that published the current GitHub release
|
||||
required: true
|
||||
description: Original CI run (optional; otherwise find the current published source)
|
||||
required: false
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
@@ -25,7 +27,7 @@ jobs:
|
||||
mirror:
|
||||
if: >-
|
||||
github.repository == 'TNTcraftHIM/Piik' && github.ref == 'refs/heads/main' &&
|
||||
(github.event_name == 'workflow_dispatch' ||
|
||||
(github.event_name == 'workflow_dispatch' || github.event_name == 'schedule' ||
|
||||
(github.event.workflow_run.event == 'push' &&
|
||||
github.event.workflow_run.head_branch == 'main'))
|
||||
runs-on: ubuntu-latest
|
||||
@@ -35,17 +37,30 @@ jobs:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
sparse-checkout-cone-mode: false
|
||||
sparse-checkout: |
|
||||
/scripts/
|
||||
/package.json
|
||||
/package-lock.json
|
||||
/.node-version
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: .node-version
|
||||
cache: npm
|
||||
- name: Check mirror readiness without build dependencies
|
||||
id: readiness
|
||||
run: node scripts/release-mirror-ready.mjs
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
- run: npm ci --ignore-scripts
|
||||
if: steps.readiness.outputs.status == 'ready'
|
||||
- name: Resolve the published source
|
||||
id: source
|
||||
if: steps.readiness.outputs.status == 'ready'
|
||||
run: node scripts/release-mirror-source.mjs "$PIIK_SOURCE_RUN_ID"
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PIIK_SOURCE_RUN_ID: ${{ inputs.run_id || github.event.workflow_run.id }}
|
||||
PIIK_SOURCE_RUN_ID: ${{ inputs.run_id }}
|
||||
- name: Download original Server artifacts
|
||||
if: steps.source.outputs.mirror == 'true'
|
||||
uses: actions/download-artifact@v8
|
||||
@@ -77,6 +92,6 @@ jobs:
|
||||
- name: Explain recovery
|
||||
if: failure() && steps.source.outputs.mirror == 'true'
|
||||
run: |
|
||||
printf 'Mirror failed; GitHub publication and Website are independent. Retry this workflow with original CI run %s. If artifacts expired, recover the retained original build output; do not rebuild this version. See docs/operations/github.md.\n' "$PIIK_SOURCE_RUN_ID" >> "$GITHUB_STEP_SUMMARY"
|
||||
printf 'Mirror failed; the scheduled check will retry from original CI run %s. GitHub publication and Website are independent. If artifacts expired, recover the retained original build output; do not rebuild this version. See docs/operations/github.md.\n' "$PIIK_SOURCE_RUN_ID" >> "$GITHUB_STEP_SUMMARY"
|
||||
env:
|
||||
PIIK_SOURCE_RUN_ID: ${{ steps.source.outputs.run_id }}
|
||||
@@ -87,6 +87,8 @@ jobs:
|
||||
PIIK_BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before }}
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
- name: Check npm dependency advisories
|
||||
run: npm audit --audit-level=high
|
||||
- name: Determine release identity
|
||||
id: release
|
||||
env:
|
||||
@@ -112,10 +114,10 @@ jobs:
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache-dependency-path: go.sum
|
||||
- name: Check Go core
|
||||
run: npm run check:go-core
|
||||
- name: Check reachable Go vulnerabilities
|
||||
run: npm run check:go-vuln
|
||||
- name: Check Go core
|
||||
run: npm run check:go-core
|
||||
- name: Check concurrent resource ownership with the race detector
|
||||
run: npm run check:go-race
|
||||
- name: Type-check and test
|
||||
|
||||
+2
-1
@@ -72,7 +72,7 @@ one complete, reviewed change; a contribution merge does not authorize publicati
|
||||
|
||||
1. Create one short-lived branch/worktree from exact canonical `main`, following the [branch naming convention](#commit-pr-and-branch-names).
|
||||
2. Update only the single durable owner for changed semantics and any materially changed current snapshot. If semantics remain disputed, record a hold and stop dependent work.
|
||||
3. Implement and run repository hygiene, `npm run check`, the relevant browser/network gates, and review in proportion to the whole acceptance boundary.
|
||||
3. Before release approval, review official security and patch releases for direct runtime/build dependencies and whether upstream now covers retained patches. Update for concrete fixes and verify the affected consumers; a newer version alone is not a release blocker. Run repository hygiene, dependency advisory checks, `npm run check`, and the relevant browser/network gates in proportion to the whole acceptance boundary. CI checks advisories before the full Go build and package matrix.
|
||||
4. Keep accepted truth checkpoints and dependent candidates on branches until the phase is complete. Rebase or rebuild a retained candidate from exact `main` only when starting a new phase, preserving main's owning truth on conflicts and transplanting only approved scoped code, tests, and new facts.
|
||||
5. Open one pull request for the complete phase, resolve required review/checks, meet the [release approval boundary](./docs/standards/versioning.md#automatic-publication) before a publishing merge, squash-merge it once, deploy that merged revision when authorized, perform scoped postflight, then audit references and reparse safety before cleanup.
|
||||
|
||||
@@ -165,6 +165,7 @@ Actions at review and acceptance boundaries; reuse passing results for unchanged
|
||||
code instead of repeatedly running the full platform matrix for one candidate.
|
||||
|
||||
- `npm run check` owns deterministic Web type-check, unit, and build acceptance.
|
||||
- `npm audit --audit-level=high` checks the locked Web/build dependencies for known high or critical advisories. It complements upstream release review; a clean database scan does not establish that no unpublished or newly disclosed fix exists.
|
||||
- `npm run check:go` owns Go formatting, unit tests, vet, Windows/Linux
|
||||
builds, Darwin builds on macOS, and the current platform's capture compile/probe.
|
||||
The server core is Go, so its acceptance runs here. It builds the Web UI first when
|
||||
|
||||
@@ -437,6 +437,12 @@ for current setup details.
|
||||
3. Camera video and microphone inputs are selected separately. For a built-in
|
||||
camera microphone or OBS audio, see [camera and audio inputs](./sharing.md#cameras-and-virtual-audio-inputs).
|
||||
|
||||
With a virtual mixer or several output devices, check where the app sends its
|
||||
sound. Without application exclusion, Windows App screen capture reads the
|
||||
default playback device. Select the app's window to capture its process audio,
|
||||
or route its sound to that default
|
||||
device before restarting screen sharing.
|
||||
|
||||
### Cannot hear someone speaking
|
||||
|
||||
For speech added through **Include my microphone**, check the picture's
|
||||
|
||||
@@ -359,6 +359,10 @@ Windows 需要用户授权;其他采集要求显示边框时,边框仍会保
|
||||
2. 房主应选择支持分享声音的来源,并在选源器中打开声音;可用声音取决于来源和平台。
|
||||
3. 摄像头画面与麦克风输入分别选择。内置麦克风或 OBS 音频的用法,见[摄像头与音频输入](./sharing.zh-CN.md#摄像头与虚拟音频输入)。
|
||||
|
||||
使用虚拟混音器或多个输出设备时,先检查应用把声音送到了哪里。未启用应用声音排除时,
|
||||
Windows App 的屏幕采集使用默认播放设备;可以改选该应用的窗口来采集程序声音,
|
||||
或把应用声音送到默认播放设备后重新分享屏幕。
|
||||
|
||||
### 听不到说话声
|
||||
|
||||
如果房主使用 **分享麦克风**,先检查画面的[来源声音](#有画面但没有来源声音),
|
||||
|
||||
@@ -94,24 +94,47 @@ Image checks, version identity and retries follow
|
||||
source and Release mirror. GitHub owns development, issues and original packages.
|
||||
AtomGit's configured repository synchronization handles branches, tags and commits;
|
||||
the **AtomGit mirror** GitHub workflow separately copies published binary assets.
|
||||
Git synchronization remains AtomGit's responsibility; this workflow does not push,
|
||||
create or change Git references, and does not ask users to synchronize them manually.
|
||||
Its repository Actions secret is `ATOMGIT_TOKEN`. Never put this token in source,
|
||||
a remote URL or a distributed package. GitHub publication keeps its scoped token.
|
||||
|
||||
After a completed main-push CI run, the workflow checks whether that run published
|
||||
the current stable GitHub release. A later failed container step does not prevent
|
||||
mirroring already-published packages. It downloads the matching run's complete
|
||||
After a completed main-push CI run, the workflow checks the current stable GitHub
|
||||
release and finds its original publishing CI run, even when the triggering run
|
||||
only updated tooling. A later failed container step does not prevent
|
||||
mirroring already-published packages. It downloads the source run's complete
|
||||
original Server and App artifacts and invokes `scripts/mirror-release.mjs`.
|
||||
Runs without the current published release are skipped. GitHub publication
|
||||
and **Website** do not depend on mirror success. An unfinished mirror remains a
|
||||
GitHub publication and **Website** do not depend on mirror success. An unfinished mirror remains a
|
||||
prerelease until every package passes anonymous full-download SHA-256 validation.
|
||||
This includes the original signed APK and its already-built ZIP wrapper.
|
||||
|
||||
Every three hours the same workflow also checks the latest GitHub release's mirror
|
||||
metadata. A stable mirror with the matching source marker and complete package
|
||||
inventory of uploaded attachments needs no further work; provider-generated source
|
||||
archives do not count as packages. A missing source commit or matching tag is
|
||||
reported as deferred until AtomGit's scheduled Git synchronization completes.
|
||||
Both outcomes use a sparse tools-only checkout and skip dependency installation
|
||||
and artifact downloads. API failures
|
||||
or conflicting source identities remain failures, not successful deferrals.
|
||||
|
||||
When ready, recovery locates the completed main-push CI run for that exact source,
|
||||
downloads its original artifacts and resumes the existing publisher. It never
|
||||
builds software. The publisher verifies every package anonymously before marking
|
||||
the mirror stable; the periodic metadata check reuses that completion boundary.
|
||||
Expired original artifacts require retained original build output, not rebuilding
|
||||
the same published version. A stable release missing packages is an explicit
|
||||
integrity failure and is never silently replaced.
|
||||
|
||||
For recovery, rerun **AtomGit mirror** with the original publishing CI run ID:
|
||||
|
||||
```sh
|
||||
gh workflow run atomgit-mirror.yml --repo TNTcraftHIM/Piik --ref main -f run_id=RUN_ID
|
||||
```
|
||||
|
||||
The run ID is optional for a manual status check; without it, the workflow uses
|
||||
the same latest-release lookup as its scheduled check. Ordinary delayed source
|
||||
synchronization or interrupted uploads need no manual trigger.
|
||||
|
||||
The source must be a completed main-push CI run matching the latest published
|
||||
GitHub release. The workflow runs trusted main tooling and treats artifacts only
|
||||
as data. A superseded release cannot complete a new mirror. Both publishers reject
|
||||
|
||||
@@ -8,6 +8,17 @@
|
||||
|
||||
## Windows Audio Exclusion
|
||||
|
||||
Default display capture reads the current default render endpoint; process
|
||||
inclusion/exclusion uses Windows'
|
||||
[endpoint-independent loopback](https://learn.microsoft.com/en-us/samples/microsoft/windows-classic-samples/applicationloopbackaudio-sample/).
|
||||
For [#534](https://github.com/TNTcraftHIM/Piik/issues/534), an isolated API control
|
||||
sent two tones only to an existing virtual endpoint without changing the default
|
||||
headset. Default capture returned no packets; excluding a silent test process
|
||||
received both tones. The real Go session also retained video and audio-output
|
||||
ownership through repeated exclusion/clear/off/on changes. The reporter's actual
|
||||
playback endpoint and first failing transition remain the next discriminator;
|
||||
these controls do not identify an exclusion-state leak.
|
||||
|
||||
A Windows 11 build 26200 check used two independent WinMM processes emitting
|
||||
500 Hz and 1500 Hz tones, through the production capture helper and Go PCM
|
||||
reader. Default-device loopback captured both at approximately 1799 amplitude;
|
||||
@@ -529,12 +540,20 @@ The reporter retracted the initial CBR bitrate-ceiling diagnosis after finding
|
||||
that the experimental fixture changed bitrate during the measured interval.
|
||||
That switching belongs to `PIIK_H264_FIXTURE` in `windows/main.cpp`, not live
|
||||
capture. The corrected experiment reports CBR reaching its requested bitrate.
|
||||
Production `h264_encoder.cpp` explicitly requests and validates Baseline; the
|
||||
Production `h264_encoder.cpp` explicitly requests and validates Constrained Baseline; the
|
||||
Browser's negotiated `profile-level-id` alone is not an inspection of emitted
|
||||
SPS. The later experimental CABAC result cannot establish the production
|
||||
Baseline bitstream's behavior. Microsoft's [encoder reference](https://learn.microsoft.com/en-us/windows/win32/medfound/h-264-video-encoder)
|
||||
distinguishes profile, rate control and optional quality/speed settings.
|
||||
|
||||
The MFT request uses `eAVEncH264VProfile_ConstrainedBase` (256), matching the
|
||||
negotiated coding-tool subset. Microsoft's [profile enumeration](https://learn.microsoft.com/en-us/windows/win32/api/codecapi/ne-codecapi-eavench264vprofile)
|
||||
distinguishes it from ordinary Baseline (66). In [#538](https://github.com/TNTcraftHIM/Piik/issues/538),
|
||||
an AMD encoder produced `420420` for 66 and `424020` for 256; only the latter
|
||||
passes the unchanged Constrained Baseline bitstream check. Request and readback
|
||||
must use the same profile; relaxing the emitted-SPS check would change the
|
||||
negotiated contract.
|
||||
|
||||
The original 720p comparison remains unresolved. An equal-content comparison
|
||||
must preserve actual bitrate, frame rate, latency and production codec settings,
|
||||
inspect the resulting bitstream and retain reference/decoded pictures. Raising
|
||||
|
||||
@@ -66,9 +66,16 @@ connection state. Android adds an explicit wake action. Browser and camera
|
||||
actions retain their own capability checks.
|
||||
A Site's explicit App action discovers the local approval
|
||||
page, where the user confirms its exact origin. The launcher lists approvals and
|
||||
revokes each independently. Starring one approved Site makes an ordinary App launch open it;
|
||||
without a star, the launcher opens. This preference grants no access and starts
|
||||
no room. Revoking that Site clears its star; other approvals leave it intact. Explicit CLI entry keeps
|
||||
revokes each independently. Starring an external Site makes an ordinary App launch
|
||||
open its fixed address without starting a room. Starring the current App-owned
|
||||
Site records its launch selection instead: the next App run starts that mode and
|
||||
enters its fresh ready address. The current runtime's exact origins determine
|
||||
ownership; a temporary invitation hostname alone does not. Without a startup
|
||||
choice, the launcher opens. This preference grants no access or capture permission.
|
||||
Its launcher checkbox can clear an App-owned choice; revoking its current origin
|
||||
also clears it. Other approvals leave the choice intact. Older saved temporary
|
||||
URLs have no ownership information: start the Site from the launcher and select
|
||||
the startup checkbox again on its current entry. Explicit CLI entry keeps
|
||||
precedence. The ready App button and terminal launcher address return to its
|
||||
management page in every mode. A pending or healthy Local/public room keeps its
|
||||
startup selection; reopening the launcher does not stop or replace that room.
|
||||
|
||||
+6
-1
@@ -1,12 +1,17 @@
|
||||
# Current TODO Ledger
|
||||
|
||||
Last reviewed: 2026-11-07
|
||||
Last reviewed: 2026-11-09
|
||||
|
||||
This ledger contains unfinished work and explicit owner holds. Product modules
|
||||
own behavior; research and Git/PRs own evidence and completed history.
|
||||
|
||||
## Now
|
||||
|
||||
- [ ] **Windows sound only works with exclusion (#534).** Compare the affected
|
||||
application's playback endpoint with Piik's default-endpoint capture. The
|
||||
[audio scope control](./research/native-client-media.md#windows-audio-exclusion)
|
||||
reproduces the contrast with another output device; locate the reporter's
|
||||
first failing transition before changing the capture owner.
|
||||
- [ ] **Blue-tinted sharing (#529).** Identify the source and affected receive
|
||||
path from [#529](https://github.com/TNTcraftHIM/Piik/issues/529): Piik version,
|
||||
platform, capture choice and matching source/Viewer screenshots. Compare
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
module github.com/TNTcraftHIM/Piik
|
||||
|
||||
go 1.27.3
|
||||
go 1.27.4
|
||||
|
||||
// Scoped NAT-PMP fixes; provenance and removal criteria: internal/thirdparty/README.md.
|
||||
replace github.com/netbirdio/go-nat => ./internal/thirdparty/go-nat
|
||||
|
||||
+22
-10
@@ -61,6 +61,7 @@ type Options struct {
|
||||
CaptureProcess string
|
||||
TunnelProcess string
|
||||
Ready func(string)
|
||||
localReady func(string, string)
|
||||
console *console
|
||||
logger *slog.Logger
|
||||
}
|
||||
@@ -274,7 +275,7 @@ func runLauncher(
|
||||
launcher.Options{
|
||||
DefaultMode: mode,
|
||||
StartupSite: startupSite,
|
||||
SaveStartupSite: func(site string) error {
|
||||
SaveStartupSite: func(site launcher.StartupIntent) error {
|
||||
return launcher.SaveStartupSite(configPath, site)
|
||||
},
|
||||
Sites: config.ApprovedSites(), Version: buildinfo.Version(), Revision: buildinfo.Revision,
|
||||
@@ -324,15 +325,18 @@ func runLauncher(
|
||||
if err != nil {
|
||||
return errors.Join(failure.NativeControl, err)
|
||||
}
|
||||
if !automatic && startupSite == "" {
|
||||
if !automatic && (startupSite.Site == "" || startupSite.Owned != nil) {
|
||||
if startupSite.Owned != nil {
|
||||
launch.Begin()
|
||||
}
|
||||
options.console.show(consoleView{state: "setup", entry: launch.URL()})
|
||||
options.console.openBrowser(launch.URL())
|
||||
options.console.openBrowser(launch.EntryURL())
|
||||
} else if initialConfig.Site != "" && !options.Local && !options.Link {
|
||||
// A starred Site changes only the opening page. --site also remains an
|
||||
// explicit approval shortcut; the launcher can start a Local room later.
|
||||
site := initialConfig.Site
|
||||
if !automatic {
|
||||
site = startupSite
|
||||
site = startupSite.Site
|
||||
}
|
||||
openSite(site, options, control.Endpoint().Port)
|
||||
}
|
||||
@@ -365,13 +369,14 @@ func runLauncher(
|
||||
if !directRoom {
|
||||
options.DisableBrowser = true
|
||||
}
|
||||
ready := make(chan string, 1)
|
||||
type localResult struct{ target, invitation string }
|
||||
ready := make(chan localResult, 1)
|
||||
onReady := options.Ready
|
||||
options.Ready = func(target string) {
|
||||
options.localReady = func(target, invitation string) {
|
||||
if onReady != nil {
|
||||
onReady(target)
|
||||
}
|
||||
ready <- target
|
||||
ready <- localResult{target, invitation}
|
||||
}
|
||||
runtimeContext, cancelRuntime := context.WithCancel(ctx)
|
||||
runtimeDone := make(chan struct{})
|
||||
@@ -383,7 +388,7 @@ func runLauncher(
|
||||
var exitErr error
|
||||
select {
|
||||
case target := <-ready:
|
||||
launch.SetResult(target, nil)
|
||||
launch.SetReady(target.target, target.invitation, selection)
|
||||
select {
|
||||
case <-runtimeDone:
|
||||
case exitErr = <-launch.Done():
|
||||
@@ -398,9 +403,14 @@ func runLauncher(
|
||||
return errors.Join(exitErr, runtimeErr)
|
||||
}
|
||||
var roomErr error
|
||||
startupOwned := startupSite.Owned
|
||||
for {
|
||||
var selection launcher.Selection
|
||||
if directRoom {
|
||||
if !automatic && startupOwned != nil {
|
||||
selection = launcher.Selection{Mode: startupOwned.Mode, LANAddress: startupOwned.LANAddress, LocalAccessPassword: initialConfig.LocalAccessPassword}
|
||||
startupOwned = nil
|
||||
launch.Begin()
|
||||
} else if directRoom {
|
||||
selection = launcher.Selection{Mode: launcher.ModeLocal, LocalAccessPassword: initialConfig.LocalAccessPassword}
|
||||
if initialOptions.Link {
|
||||
selection.Mode = launcher.ModeLink
|
||||
@@ -636,7 +646,9 @@ func runLocal(ctx context.Context, options Options, config appconfig.Config,
|
||||
if !options.DisableBrowser {
|
||||
options.console.openBrowser(launchURL)
|
||||
}
|
||||
if options.Ready != nil {
|
||||
if options.localReady != nil {
|
||||
options.localReady(launchURL, view.invite)
|
||||
} else if options.Ready != nil {
|
||||
options.Ready(launchURL)
|
||||
}
|
||||
var tunnelDone <-chan struct{}
|
||||
|
||||
+125
-3
@@ -40,7 +40,11 @@ func TestMain(tests *testing.M) {
|
||||
os.Exit(7)
|
||||
}
|
||||
if mode == "ready" || mode == "ready-failed" {
|
||||
fmt.Println(`{"message":"https://test-room.trycloudflare.com"}`)
|
||||
origin := os.Getenv("PIIK_APP_TUNNEL_ORIGIN")
|
||||
if origin == "" {
|
||||
origin = "https://test-room.trycloudflare.com"
|
||||
}
|
||||
fmt.Printf("{\"message\":%q}\n", origin)
|
||||
fmt.Println(`{"message":"Registered tunnel connection"}`)
|
||||
}
|
||||
if mode == "ready-failed" {
|
||||
@@ -421,7 +425,7 @@ func TestHungBrowserHandoffDoesNotBlockLauncherOrSiteExit(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if mode == "starred-site" || mode == "revoked-site" {
|
||||
if err := launcher.SaveStartupSite(configPath, "https://share.example"); err != nil {
|
||||
if err := launcher.SaveStartupSite(configPath, launcher.StartupIntent{Site: "https://share.example"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if mode == "starred-site" {
|
||||
@@ -430,7 +434,7 @@ func TestHungBrowserHandoffDoesNotBlockLauncherOrSiteExit(t *testing.T) {
|
||||
}
|
||||
if mode == "starred-second-site" {
|
||||
config.SetApprovedSites([]string{"https://first.example", "https://share.example"})
|
||||
if err := launcher.SaveStartupSite(configPath, "https://share.example"); err != nil {
|
||||
if err := launcher.SaveStartupSite(configPath, launcher.StartupIntent{Site: "https://share.example"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -634,6 +638,124 @@ func TestSavedSiteAllowsBrowserOriginAtNativeControl(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestOwnedStartupUsesFreshInvitation(t *testing.T) {
|
||||
t.Setenv("PIIK_APP_TUNNEL_FIXTURE", "ready")
|
||||
t.Setenv("PIIK_APP_TUNNEL_STARTED", filepath.Join(t.TempDir(), "started"))
|
||||
executable, _ := os.Executable()
|
||||
path := filepath.Join(t.TempDir(), "client.json")
|
||||
config, err := appconfig.LoadOrCreate(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old := "https://first-start.trycloudflare.com"
|
||||
config.SetApprovedSites([]string{old, "https://external.example"})
|
||||
for turn := 0; turn < 2; turn++ {
|
||||
invitation := old
|
||||
if turn == 1 {
|
||||
invitation = "https://next-start.trycloudflare.com"
|
||||
}
|
||||
t.Setenv("PIIK_APP_TUNNEL_ORIGIN", invitation)
|
||||
listener, err := net.Listen("tcp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
port := listener.Addr().(*net.TCPAddr).Port
|
||||
listener.Close()
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
t.Cleanup(cancel)
|
||||
control, err := loopback.Start(ctx, loopback.Options{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
opened := make(chan string, 4)
|
||||
console := newConsole(cancel, true)
|
||||
console.openURL = func(target string) error { opened <- target; return nil }
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- runLauncher(ctx, Options{Port: port, console: console, TunnelProcess: executable}, path, config, control, func(*Options, appconfig.Config) error { return nil })
|
||||
}()
|
||||
var entry string
|
||||
select {
|
||||
case entry = <-opened:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("missing startup entry")
|
||||
}
|
||||
parsed, _ := url.Parse(entry)
|
||||
origin := parsed.Scheme + "://" + parsed.Host
|
||||
api := origin + "/api/client-launcher"
|
||||
post := func(route, body string) map[string]any {
|
||||
req, _ := http.NewRequest(http.MethodPost, api+route, strings.NewReader(body))
|
||||
req.Header.Set("Origin", origin)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
response, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
var result map[string]any
|
||||
if err := json.NewDecoder(response.Body).Decode(&result); err != nil || response.StatusCode != 200 {
|
||||
t.Fatalf("%s: %d %+v %v", route, response.StatusCode, result, err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
if turn == 0 {
|
||||
post("/launch", `{"mode":"link","language":"en","localAccessPassword":""}`)
|
||||
} else if parsed.Query().Get("start") != "1" || strings.Contains(entry, old) {
|
||||
t.Fatalf("stale startup entry: %s", entry)
|
||||
}
|
||||
var state map[string]any
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
response, err := http.Get(api)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
json.NewDecoder(response.Body).Decode(&state)
|
||||
response.Body.Close()
|
||||
if state["target"] != "" {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("missing ready state: %+v", state)
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
if !strings.HasPrefix(state["target"].(string), fmt.Sprintf("http://127.0.0.1:%d/", port)) {
|
||||
t.Fatal(state)
|
||||
}
|
||||
if turn == 0 {
|
||||
result := post("/startup-site", fmt.Sprintf(`{"site":%q}`, old))
|
||||
if result["startupSite"] != old {
|
||||
t.Fatal(result)
|
||||
}
|
||||
stored, err := launcher.LoadStartupSite(path, config.ApprovedSites()...)
|
||||
if err != nil || stored.Owned == nil || stored.Owned.Mode != launcher.ModeLink || stored.Site != "" {
|
||||
t.Fatalf("not owned: %+v %v", stored, err)
|
||||
}
|
||||
} else {
|
||||
if state["startupSite"] != invitation {
|
||||
t.Fatalf("stale star: %+v", state)
|
||||
}
|
||||
post("/startup-site", `{"site":"https://external.example"}`)
|
||||
stored, err := launcher.LoadStartupSite(path, config.ApprovedSites()...)
|
||||
if err != nil || stored.Site != "https://external.example" || stored.Owned != nil {
|
||||
t.Fatalf("external startup changed: %+v %v", stored, err)
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("App did not retire")
|
||||
}
|
||||
control.Close()
|
||||
console.finish(nil, "")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOccupiedPortRejectsLinkBeforeStartingATunnel(t *testing.T) {
|
||||
listener, err := net.ListenTCP("tcp4", &net.TCPAddr{IP: net.IPv4zero})
|
||||
if err != nil {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package launcher
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"slices"
|
||||
@@ -31,26 +32,57 @@ func SaveMode(configPath string, mode Mode) error {
|
||||
return os.WriteFile(configPath+".mode", []byte(string(mode)+"\n"), 0o600)
|
||||
}
|
||||
|
||||
// Startup preference selects one approved origin; it never grants access.
|
||||
func LoadStartupSite(configPath string, approvedSites ...string) (string, error) {
|
||||
// StartupIntent selects an external origin or this App's launch, never access.
|
||||
type StartupIntent struct {
|
||||
Site string `json:"site,omitempty"`
|
||||
Owned *StartupLaunch `json:"owned,omitempty"`
|
||||
}
|
||||
|
||||
type StartupLaunch struct {
|
||||
Mode Mode `json:"mode"`
|
||||
LANAddress *string `json:"lanAddress,omitempty"`
|
||||
}
|
||||
|
||||
func LoadStartupSite(configPath string, approvedSites ...string) (StartupIntent, error) {
|
||||
payload, err := os.ReadFile(configPath + ".startup-site")
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return "", nil
|
||||
return StartupIntent{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
return StartupIntent{}, err
|
||||
}
|
||||
site := strings.TrimSpace(string(payload))
|
||||
if strings.HasPrefix(site, "{") {
|
||||
var intent StartupIntent
|
||||
if err := json.Unmarshal(payload, &intent); err != nil {
|
||||
return StartupIntent{}, err
|
||||
}
|
||||
if intent.Owned == nil || intent.Site != "" || !validMode(intent.Owned.Mode) {
|
||||
return StartupIntent{}, errors.New("invalid saved startup intent")
|
||||
}
|
||||
return intent, nil
|
||||
}
|
||||
if site == "" || slices.Contains(approvedSites, site) {
|
||||
return site, nil
|
||||
return StartupIntent{Site: site}, nil
|
||||
}
|
||||
// CLI/config changes also retire the old choice, rather than letting a
|
||||
// later approval of that same address resurrect it.
|
||||
return "", SaveStartupSite(configPath, "")
|
||||
return StartupIntent{}, SaveStartupSite(configPath, StartupIntent{})
|
||||
}
|
||||
|
||||
func SaveStartupSite(configPath, site string) error {
|
||||
return os.WriteFile(configPath+".startup-site", []byte(site+"\n"), 0o600)
|
||||
func SaveStartupSite(configPath string, intent StartupIntent) error {
|
||||
payload := []byte(intent.Site)
|
||||
if intent.Owned != nil {
|
||||
if intent.Site != "" || !validMode(intent.Owned.Mode) {
|
||||
return errors.New("invalid startup intent")
|
||||
}
|
||||
var err error
|
||||
payload, err = json.Marshal(intent)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return os.WriteFile(configPath+".startup-site", append(payload, '\n'), 0o600)
|
||||
}
|
||||
|
||||
func validMode(mode Mode) bool {
|
||||
|
||||
@@ -86,7 +86,7 @@ func TestStarredSiteSurvivesOtherApprovalsAndClearsOnRevocation(t *testing.T) {
|
||||
}
|
||||
sites := []string{"https://share.example"}
|
||||
server, err := Start(t.Context(), appAssets(), Options{Sites: sites, ControlPort: 39730,
|
||||
SaveStartupSite: func(site string) error { return SaveStartupSite(path, site) },
|
||||
SaveStartupSite: func(site StartupIntent) error { return SaveStartupSite(path, site) },
|
||||
ChangeSite: func(site string, allowed bool) ([]string, error) {
|
||||
sites = editSites(sites, site, allowed)
|
||||
return sites, nil
|
||||
@@ -121,8 +121,8 @@ func TestStarredSiteSurvivesOtherApprovalsAndClearsOnRevocation(t *testing.T) {
|
||||
if err != nil || response.StatusCode != test.status || state.StartupSite != test.want {
|
||||
t.Fatalf("%+v: %+v %v", test, state, err)
|
||||
}
|
||||
if saved, err := LoadStartupSite(path, state.Sites...); err != nil || saved != test.want {
|
||||
t.Fatalf("saved startup: %q %v", saved, err)
|
||||
if saved, err := LoadStartupSite(path, state.Sites...); err != nil || saved.Site != test.want {
|
||||
t.Fatalf("saved startup: %+v %v", saved, err)
|
||||
}
|
||||
entry := server.URL()
|
||||
if test.want != "" {
|
||||
|
||||
@@ -52,7 +52,7 @@ type Options struct {
|
||||
Modes []Mode
|
||||
DefaultMode Mode
|
||||
Sites []string
|
||||
StartupSite string
|
||||
StartupSite StartupIntent
|
||||
Version string
|
||||
Revision string
|
||||
ControlPort int
|
||||
@@ -60,7 +60,7 @@ type Options struct {
|
||||
Debug bool
|
||||
LANAddress string
|
||||
ChangeSite func(string, bool) ([]string, error)
|
||||
SaveStartupSite func(string) error
|
||||
SaveStartupSite func(StartupIntent) error
|
||||
EnableDebug func() error
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ type Server struct {
|
||||
static http.Handler
|
||||
client http.Handler
|
||||
sites []string
|
||||
startupSite string
|
||||
startupSite StartupIntent
|
||||
modes []Mode
|
||||
defaultMode Mode
|
||||
localAccessPassword string
|
||||
@@ -85,7 +85,7 @@ type Server struct {
|
||||
debug bool
|
||||
lanAddress string
|
||||
changeSite func(string, bool) ([]string, error)
|
||||
saveStartupSite func(string) error
|
||||
saveStartupSite func(StartupIntent) error
|
||||
enableDebug func() error
|
||||
selection chan Selection
|
||||
done chan error
|
||||
@@ -97,10 +97,12 @@ type Server struct {
|
||||
}
|
||||
|
||||
type launchAttempt struct {
|
||||
ready chan struct{}
|
||||
completed bool
|
||||
target string
|
||||
err error
|
||||
ready chan struct{}
|
||||
completed bool
|
||||
target string
|
||||
err error
|
||||
invitation string
|
||||
selection *Selection
|
||||
}
|
||||
|
||||
// Start serves the launcher page and its API on a loopback port. assets is the
|
||||
@@ -173,8 +175,11 @@ func (server *Server) EntryURL() string {
|
||||
server.mu.Lock()
|
||||
startup := server.startupSite
|
||||
server.mu.Unlock()
|
||||
if startup != "" {
|
||||
return EntryURL(startup+"/", server.controlPort)
|
||||
if startup.Owned != nil {
|
||||
return server.URL() + "?start=1"
|
||||
}
|
||||
if startup.Site != "" {
|
||||
return EntryURL(startup.Site+"/", server.controlPort)
|
||||
}
|
||||
return server.URL()
|
||||
}
|
||||
@@ -202,13 +207,50 @@ func (server *Server) begin() (*launchAttempt, bool) {
|
||||
return server.attempt, true
|
||||
}
|
||||
|
||||
// SetReady records the actual entry, invitation and selection together.
|
||||
func (server *Server) SetReady(target, invitation string, selection Selection) {
|
||||
server.mu.Lock()
|
||||
defer server.mu.Unlock()
|
||||
server.attempt.invitation, server.attempt.selection = invitation, &selection
|
||||
server.setResult(target, nil)
|
||||
}
|
||||
|
||||
func (server *Server) ownedOrigins() []string {
|
||||
if server.attempt == nil || server.attempt.err != nil || server.attempt.selection == nil {
|
||||
return []string{}
|
||||
}
|
||||
target, _ := url.Parse(server.attempt.target)
|
||||
return []string{target.Scheme + "://" + target.Host, server.attempt.invitation}
|
||||
}
|
||||
|
||||
func (server *Server) startupMode() Mode {
|
||||
if server.startupSite.Owned != nil {
|
||||
return server.startupSite.Owned.Mode
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (server *Server) startupOrigin() string {
|
||||
if server.startupSite.Owned == nil {
|
||||
return server.startupSite.Site
|
||||
}
|
||||
if server.attempt != nil && server.attempt.err == nil {
|
||||
return server.attempt.invitation
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// SetResult is called by the serial room owner after readiness or full retirement.
|
||||
func (server *Server) SetResult(target string, resultErr error) {
|
||||
server.mu.Lock()
|
||||
defer server.mu.Unlock()
|
||||
server.setResult(target, resultErr)
|
||||
}
|
||||
|
||||
func (server *Server) setResult(target string, resultErr error) {
|
||||
if resultErr == nil && !validTarget(target) {
|
||||
resultErr = errors.New("App target is invalid")
|
||||
}
|
||||
server.mu.Lock()
|
||||
defer server.mu.Unlock()
|
||||
attempt := server.attempt
|
||||
attempt.target = target
|
||||
attempt.err = resultErr
|
||||
@@ -300,7 +342,9 @@ func (server *Server) handleState(response http.ResponseWriter, request *http.Re
|
||||
}
|
||||
state := map[string]any{
|
||||
"sites": slices.Clone(server.sites),
|
||||
"startupSite": server.startupSite,
|
||||
"startupSite": server.startupOrigin(),
|
||||
"ownedSites": server.ownedOrigins(),
|
||||
"startupMode": server.startupMode(),
|
||||
"localAccessPassword": server.localAccessPassword,
|
||||
"version": server.version,
|
||||
"revision": server.revision,
|
||||
@@ -357,7 +401,7 @@ func (server *Server) handleSite(response http.ResponseWriter, request *http.Req
|
||||
server.mu.Lock()
|
||||
defer server.mu.Unlock()
|
||||
result := func() map[string]any {
|
||||
return map[string]any{"sites": slices.Clone(server.sites), "startupSite": server.startupSite}
|
||||
return map[string]any{"sites": slices.Clone(server.sites), "startupSite": server.startupOrigin(), "ownedSites": server.ownedOrigins(), "startupMode": server.startupMode()}
|
||||
}
|
||||
if startupOnly {
|
||||
if site != "" && !slices.Contains(server.sites, site) {
|
||||
@@ -368,11 +412,16 @@ func (server *Server) handleSite(response http.ResponseWriter, request *http.Req
|
||||
http.Error(response, "startup preference is unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if err := server.saveStartupSite(site); err != nil {
|
||||
intent := StartupIntent{Site: site}
|
||||
if site != "" && slices.Contains(server.ownedOrigins(), site) {
|
||||
selection := server.attempt.selection
|
||||
intent = StartupIntent{Owned: &StartupLaunch{Mode: selection.Mode, LANAddress: selection.LANAddress}}
|
||||
}
|
||||
if err := server.saveStartupSite(intent); err != nil {
|
||||
writeJSON(response, http.StatusServiceUnavailable, result())
|
||||
return
|
||||
}
|
||||
server.startupSite = site
|
||||
server.startupSite = intent
|
||||
writeJSON(response, http.StatusOK, result())
|
||||
return
|
||||
}
|
||||
@@ -383,9 +432,9 @@ func (server *Server) handleSite(response http.ResponseWriter, request *http.Req
|
||||
current, err := server.changeSite(site, *change.Allowed)
|
||||
// Permission can be revoked even if its media cleanup times out.
|
||||
server.sites = current
|
||||
if server.startupSite != "" && !slices.Contains(current, server.startupSite) {
|
||||
server.startupSite = ""
|
||||
err = errors.Join(err, server.saveStartupSite(""))
|
||||
if !*change.Allowed && (server.startupSite.Site == site || server.startupSite.Owned != nil && slices.Contains(server.ownedOrigins(), site)) {
|
||||
server.startupSite = StartupIntent{}
|
||||
err = errors.Join(err, server.saveStartupSite(StartupIntent{}))
|
||||
}
|
||||
if err != nil {
|
||||
failure := result()
|
||||
|
||||
@@ -516,13 +516,17 @@ func startStreamWithEnvironment(
|
||||
if len(environment) > 0 {
|
||||
command.Env = append(os.Environ(), environment...)
|
||||
}
|
||||
stdout, err := command.StdoutPipe()
|
||||
// Stream owns stdout until its consumer drains it; Wait must not close unread output.
|
||||
stdout, output, err := os.Pipe()
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
command.Stdout = output
|
||||
stdin, err := command.StdinPipe()
|
||||
if err != nil {
|
||||
_ = stdout.Close()
|
||||
_ = output.Close()
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
@@ -531,11 +535,14 @@ func startStreamWithEnvironment(
|
||||
command.Stderr = io.MultiWriter(stderr, trace)
|
||||
hideWindow(command)
|
||||
if err = command.Start(); err != nil {
|
||||
_ = stdout.Close()
|
||||
_ = output.Close()
|
||||
_ = trace.Close()
|
||||
cancel()
|
||||
logger.DebugContext(ctx, "piik-client", "event", "capture-process-start-failed", diagnostics.Error(err))
|
||||
return nil, fmt.Errorf("start native capture process: %w", err)
|
||||
}
|
||||
_ = output.Close() // Only the child keeps the write end alive.
|
||||
logger = logger.With("pid", command.Process.Pid)
|
||||
mode := "capture"
|
||||
if len(arguments) > 0 {
|
||||
@@ -747,6 +754,7 @@ func (stream *Stream) Close() error {
|
||||
<-stream.done
|
||||
stream.cancel()
|
||||
<-drained
|
||||
_ = stream.input.Close()
|
||||
})
|
||||
return stream.failure
|
||||
}
|
||||
@@ -94,6 +94,9 @@ func TestCaptureStopHelper(t *testing.T) {
|
||||
if err := writeFrame(os.Stdout, Frame{Kind: FrameStatus, Data: []byte("ready")}); err != nil {
|
||||
os.Exit(2)
|
||||
}
|
||||
if mode == "buffered-exit" {
|
||||
os.Exit(0)
|
||||
}
|
||||
if mode == "unresponsive" {
|
||||
time.Sleep(10 * time.Second)
|
||||
os.Exit(3)
|
||||
@@ -117,6 +120,34 @@ func TestCaptureStopHelper(t *testing.T) {
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
func TestCaptureOutputRemainsReadableAfterProcessExit(t *testing.T) {
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stream, err := startStreamWithEnvironment(t.Context(), executable,
|
||||
[]string{"-test.run=^TestCaptureStopHelper$"}, []string{"PIIK_CAPTURE_STOP_FIXTURE=buffered-exit"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer stream.Close()
|
||||
select {
|
||||
case err := <-stream.Done():
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("fixture did not exit before its buffered output was read")
|
||||
}
|
||||
frame, err := stream.Read()
|
||||
if err != nil || frame.Kind != FrameStatus || string(frame.Data) != "ready" {
|
||||
t.Fatalf("process retirement lost its final frame: %+v, %v", frame, err)
|
||||
}
|
||||
if _, err := stream.Read(); !errors.Is(err, io.EOF) {
|
||||
t.Fatalf("drained output did not end at EOF: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureFailureSurvivesProcessRetirementWithoutDebugLogging(t *testing.T) {
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
|
||||
@@ -461,22 +461,49 @@ func (c *Controller) availableViewers(includeBlocked bool) []*participant {
|
||||
return viewers
|
||||
}
|
||||
|
||||
// overflowChildren visits parents in participant order and returns each
|
||||
// parent's overflowing children newest first.
|
||||
// overflowChildren returns movable excess work in parent/newest order.
|
||||
// Only when no overloaded parent has a movable child does it return the
|
||||
// original newest-overflow failure work, before attempt ordering is applied.
|
||||
func (c *Controller) overflowChildren() []string {
|
||||
result := []string{}
|
||||
fallback := []string{}
|
||||
for _, parent := range c.participants.Values() {
|
||||
overflowing := c.overflowPeerChildren(parent.peerID)
|
||||
if len(overflowing) == 0 {
|
||||
continue
|
||||
}
|
||||
movable := []string{}
|
||||
for _, id := range c.childrenOf(parent.peerID) {
|
||||
edge, _ := c.upstreamByViewer.Get(id)
|
||||
child, _ := c.participants.Get(id)
|
||||
if edge.PhysicalActive && child != nil && child.sessionID != "" && !child.departureConfirmed &&
|
||||
len(c.buildCandidates(id, false)) > 0 {
|
||||
movable = append(movable, id)
|
||||
}
|
||||
}
|
||||
if len(movable) > 0 {
|
||||
sort.SliceStable(movable, func(i, j int) bool {
|
||||
left, _ := c.participants.Get(movable[i])
|
||||
right, _ := c.participants.Get(movable[j])
|
||||
return compareParticipant(right, left) < 0
|
||||
})
|
||||
result = append(result, movable...)
|
||||
continue
|
||||
}
|
||||
overflow := []string{}
|
||||
for _, id := range c.overflowPeerChildren(parent.peerID) {
|
||||
for _, id := range overflowing {
|
||||
child, _ := c.participants.Get(id)
|
||||
if child != nil && child.sessionID != "" && !child.departureConfirmed && !c.participantBlocked(child) {
|
||||
overflow = append(overflow, id)
|
||||
}
|
||||
}
|
||||
slices.Reverse(overflow)
|
||||
result = append(result, overflow...)
|
||||
fallback = append(fallback, overflow...)
|
||||
}
|
||||
return result
|
||||
if len(result) > 0 {
|
||||
return result
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
// overflowPeerChildren keeps the oldest physically active direct children
|
||||
|
||||
@@ -115,7 +115,7 @@ func (c *Controller) startPublicationAttach(nowMs int64) bool {
|
||||
}
|
||||
tuple.Publication = PublicationReuse
|
||||
}
|
||||
c.operation = &operation{
|
||||
op := &operation{
|
||||
childPeerID: childID, childSessionID: child.sessionID,
|
||||
demandPeerID: childID, demandSessionID: child.sessionID,
|
||||
reason: DemandPublicationAttach, baseRevision: c.revision,
|
||||
@@ -123,6 +123,12 @@ func (c *Controller) startPublicationAttach(nowMs int64) bool {
|
||||
videoGeneration: c.videoGeneration, attachConnectionID: edge.ConnectionID,
|
||||
candidates: []CandidatePlan{{Tuple: tuple, EndpointTransition: EndpointTransition{Kind: TransitionNone}}},
|
||||
}
|
||||
// A retained physical path may outlive its parent's signaling session.
|
||||
// Select only attachments that can pass the same ownership check at begin.
|
||||
if !c.publicationAttachOwned(op) {
|
||||
continue
|
||||
}
|
||||
c.operation = op
|
||||
return true
|
||||
}
|
||||
return false
|
||||
|
||||
@@ -2,6 +2,36 @@ package route
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestPublicationAttachmentWaitsForItsParentSessionWithoutBlockingOtherBranches(t *testing.T) {
|
||||
routes := voiceTree(t)
|
||||
routes.SetDefaultCapacity(2, ms(9))
|
||||
routes.UpsertParticipant(hostInput("host_session", 2), ms(9))
|
||||
addViewer(routes, C, 0, ms(10))
|
||||
commitRoomPeer(t, routes, 11, "voice-c")
|
||||
before := routes.Snapshot()
|
||||
routes.SetVideoPublication("share", false, 20)
|
||||
a := beginVideoAttach(t, routes, 21, A, "video-a")
|
||||
eq(t, routes.CandidateReady(a, 22, nil, CandidateProof{VideoGeneration: "share"}).Committed, true)
|
||||
routes.DisconnectSession(A, sessionOf(A))
|
||||
// A's proven physical path survives signaling grace, but it cannot own a
|
||||
// new attachment for B until its signaling session returns. C is independent.
|
||||
c := beginVideoAttach(t, routes, 23, C, "video-c")
|
||||
eq(t, routes.CandidateReady(c, 24, nil, CandidateProof{VideoGeneration: "share"}).Committed, true)
|
||||
for _, at := range []int64{25, 26, 50_000} {
|
||||
noOperation(t, routes.Reconcile(at).Operation)
|
||||
}
|
||||
for _, child := range []string{A, B, C} {
|
||||
previous, _ := before.UpstreamByViewer.Get(child)
|
||||
edge := edgeOf(t, routes, child)
|
||||
eq(t, edge.ConnectionID, previous.ConnectionID)
|
||||
eq(t, edge.Usable && edge.PhysicalActive, true)
|
||||
}
|
||||
routes.UpsertParticipant(viewerInput(A, "resumed-a", 1), ms(50_001))
|
||||
b := beginVideoAttach(t, routes, 50_002, B, "video-b")
|
||||
eq(t, routes.CandidateReady(b, 50_003, nil, CandidateProof{VideoGeneration: "share"}).Committed, true)
|
||||
noOperation(t, routes.Reconcile(50_004).Operation)
|
||||
}
|
||||
|
||||
func TestRoomVideoRecoveryPreservesLogicalConnection(t *testing.T) {
|
||||
routes := voiceTree(t)
|
||||
routes.SetVideoPublication("share", false, 10)
|
||||
|
||||
@@ -100,6 +100,133 @@ func TestRelayVolunteerTwentyChildPhysicalOverlapRequiresOptIn(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapacityReductionMovesFeasibleLeafBeforeRetiringRelaySubtree(t *testing.T) {
|
||||
join := func(t *testing.T, routes *Controller, id string, capacity int) {
|
||||
t.Helper()
|
||||
addViewer(routes, id, capacity, ms(1))
|
||||
must(t, routes.Reconcile(2).Operation)
|
||||
commitCurrent(t, routes, 3, id+"-connection")
|
||||
}
|
||||
for _, outcome := range []string{"commit", "failed-candidate", "exhausted-candidates", "all-unavailable", "multi-parent"} {
|
||||
t.Run(outcome, func(t *testing.T) {
|
||||
routes := newController(3, Options{QualityConvergenceEnabled: true,
|
||||
NatPredictionEnabled: outcome == "multi-parent"})
|
||||
if outcome == "multi-parent" {
|
||||
routes.SetEffectiveCapacity(HOST, "host_session", 1, nil)
|
||||
join(t, routes, A, 1)
|
||||
join(t, routes, C, 0)
|
||||
routes.SetEffectiveCapacity(HOST, "host_session", 2, nil)
|
||||
join(t, routes, B, 2)
|
||||
join(t, routes, D, 0)
|
||||
addViewer(routes, E, 1, ms(1))
|
||||
eq(t, must(t, routes.Reconcile(2).Operation).ChildPeerID, E)
|
||||
prepared := beginOperation(t, routes, BeginInput{NowMs: 3,
|
||||
ConnectionID: "first-nat-attempt", Reservation: direct()})
|
||||
eq(t, routes.CandidateFailed(guardFor(E, prepared.Current.Revision, "first-nat-attempt"), 4).Accepted, true)
|
||||
must(t, routes.Reconcile(5).Operation)
|
||||
commitCurrent(t, routes, 6, E+"-connection")
|
||||
routes.SetEffectiveCapacity(C, sessionOf(C), 1, nil)
|
||||
eq(t, edgeOf(t, routes, C).ParentPeerID, A)
|
||||
eq(t, edgeOf(t, routes, D).ParentPeerID, B)
|
||||
eq(t, edgeOf(t, routes, E).ParentPeerID, B)
|
||||
// A spent C->E opportunity cannot justify retiring C before
|
||||
// another overloaded parent's live child can move under it.
|
||||
routes.consumeCandidateOpportunity(C, *routes.planCandidate(C, peerTuple(E)))
|
||||
for _, parent := range []string{C, E} {
|
||||
routes.consumeCandidateOpportunity(D, *routes.planCandidate(D, peerTuple(parent)))
|
||||
}
|
||||
routes.SetEffectiveCapacity(A, sessionOf(A), 0, ms(10))
|
||||
routes.SetEffectiveCapacity(B, sessionOf(B), 1, ms(10))
|
||||
eq(t, len(routes.buildCandidates(C, false)), 0)
|
||||
// The feasible child has more past attempts: the existing NAT
|
||||
// sort must not promote another parent's unavailable fallback.
|
||||
eq(t, routes.viewerAttemptsStarted(E) > routes.viewerAttemptsStarted(C), true)
|
||||
result := routes.Reconcile(11)
|
||||
eq(t, len(result.FailedPeerIDs), 0)
|
||||
op := must(t, result.Operation)
|
||||
eq(t, op.ChildPeerID, E)
|
||||
eq(t, op.Candidates[0].Tuple.ParentPeerID, C)
|
||||
deadline := op.DeadlineAtMs
|
||||
eq(t, must(t, routes.Reconcile(12).Operation).DeadlineAtMs, deadline)
|
||||
for _, child := range []string{A, B, C, D, E} {
|
||||
eq(t, edgeOf(t, routes, child).PhysicalActive, true)
|
||||
}
|
||||
commitCurrent(t, routes, 13, "other-parent-to-live-subtree")
|
||||
eq(t, edgeOf(t, routes, E).ParentPeerID, C)
|
||||
eq(t, routes.physicalCopies(B), 1)
|
||||
eq(t, edgeOf(t, routes, C).PhysicalActive, true)
|
||||
return
|
||||
}
|
||||
// The ordinary join path reaches Host->{A,B,C}, C->D. Only D has
|
||||
// a spare slot; C cannot move under its own descendant.
|
||||
for _, viewer := range []struct {
|
||||
id string
|
||||
capacity int
|
||||
}{{A, 0}, {B, 0}, {C, 1}, {D, 1}} {
|
||||
join(t, routes, viewer.id, viewer.capacity)
|
||||
}
|
||||
eq(t, edgeOf(t, routes, D).ParentPeerID, C)
|
||||
if outcome == "all-unavailable" {
|
||||
routes.SetEffectiveCapacity(D, sessionOf(D), 0, ms(9))
|
||||
}
|
||||
routes.SetEffectiveCapacity(HOST, "host_session", 2, ms(10))
|
||||
result := routes.Reconcile(11)
|
||||
if outcome == "all-unavailable" {
|
||||
noOperation(t, result.Operation)
|
||||
eq(t, len(result.FailedPeerIDs), 2)
|
||||
eq(t, result.FailedPeerIDs[0], C)
|
||||
eq(t, result.FailedPeerIDs[1], D)
|
||||
eq(t, edgeOf(t, routes, C).PhysicalActive, false)
|
||||
eq(t, edgeOf(t, routes, D).PhysicalActive, false)
|
||||
return
|
||||
}
|
||||
op := must(t, result.Operation)
|
||||
eq(t, op.Reason, DemandCapacityReduction)
|
||||
eq(t, op.ChildPeerID, B) // Newest feasible leaf still leads.
|
||||
eq(t, op.Candidates[0].Tuple.ParentPeerID, D)
|
||||
deadline := op.DeadlineAtMs
|
||||
if outcome == "failed-candidate" || outcome == "exhausted-candidates" {
|
||||
prepared := beginOperation(t, routes, BeginInput{NowMs: 12,
|
||||
ConnectionID: "failed-leaf", Reservation: direct()})
|
||||
eq(t, routes.CandidateFailed(guardFor(B, prepared.Current.Revision, "failed-leaf"), 13).Accepted, true)
|
||||
op = must(t, routes.Reconcile(14).Operation)
|
||||
eq(t, op.ChildPeerID, A)
|
||||
eq(t, op.Reason, DemandCapacityReduction)
|
||||
eq(t, op.Candidates[0].Tuple.ParentPeerID, D)
|
||||
// Another reconciliation keeps this operation's original deadline.
|
||||
deadline = op.DeadlineAtMs
|
||||
eq(t, must(t, routes.Reconcile(15).Operation).DeadlineAtMs, deadline)
|
||||
}
|
||||
if outcome == "exhausted-candidates" {
|
||||
prepared := beginOperation(t, routes, BeginInput{NowMs: 16,
|
||||
ConnectionID: "last-leaf", Reservation: direct()})
|
||||
eq(t, routes.CandidateFailed(guardFor(A, prepared.Current.Revision, "last-leaf"), 17).Accepted, true)
|
||||
noOperation(t, routes.Reconcile(18).Operation)
|
||||
eq(t, edgeOf(t, routes, C).PhysicalActive, false)
|
||||
eq(t, edgeOf(t, routes, D).PhysicalActive, false)
|
||||
eq(t, routes.physicalCopies(HOST), 2)
|
||||
for now := deadline; now <= deadline+2; now++ {
|
||||
noOperation(t, routes.Reconcile(now).Operation)
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, child := range []string{A, B, C, D} {
|
||||
eq(t, edgeOf(t, routes, child).PhysicalActive, true)
|
||||
}
|
||||
moved := op.ChildPeerID
|
||||
commitCurrent(t, routes, 16, "leaf-to-descendant")
|
||||
eq(t, edgeOf(t, routes, moved).ParentPeerID, D)
|
||||
eq(t, routes.physicalCopies(HOST), 2)
|
||||
eq(t, edgeOf(t, routes, C).ParentPeerID, HOST)
|
||||
eq(t, edgeOf(t, routes, D).ParentPeerID, C)
|
||||
for now := deadline; now <= deadline+2; now++ {
|
||||
noOperation(t, routes.Reconcile(now).Operation)
|
||||
}
|
||||
routes.assertGraph()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHostVideoConnectionIdentityPreservesRoomPublication(t *testing.T) {
|
||||
routes := newController(2, Options{})
|
||||
routes.hydrateHostPublication("logical-publication", res("publication"), "old-video")
|
||||
|
||||
@@ -109,10 +109,8 @@ func (c *Controller) routeDemandReason(childPeerID string) DemandReason {
|
||||
if parent, ok := c.participants.Get(edge.ParentPeerID); ok && parent.departureConfirmed {
|
||||
return DemandParentDeparted
|
||||
}
|
||||
for _, overflowing := range c.overflowPeerChildren(edge.ParentPeerID) {
|
||||
if overflowing == childPeerID {
|
||||
return DemandCapacityReduction
|
||||
}
|
||||
if edge.PhysicalActive && len(c.overflowPeerChildren(edge.ParentPeerID)) > 0 {
|
||||
return DemandCapacityReduction
|
||||
}
|
||||
}
|
||||
return DemandEdgeUnavailable
|
||||
|
||||
@@ -1,6 +1,91 @@
|
||||
package signal
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
|
||||
)
|
||||
|
||||
func TestDisconnectedParentCannotTrapRoomCreationInPublicationPump(t *testing.T) {
|
||||
h := newRouterHarness(t, routerHarnessOptions{capacity: 1, fakeTimers: true})
|
||||
created := h.createRoom()
|
||||
host := h.connectHost(created, nil, "", "")
|
||||
viewer := h.connectViewer(created, "waiting-picture")
|
||||
h.complete(host)
|
||||
h.complete(viewer)
|
||||
prepared := h.waitPrepared(viewer.sessionID)
|
||||
h.routeReady(viewer, int64(prepared.Revision))
|
||||
h.settle()
|
||||
before := h.mustActiveEdge(created.RoomID, viewer.peerID)
|
||||
h.locked(func() {
|
||||
rm, _ := h.router.rooms.Get(created.RoomID)
|
||||
rm.roomMedia, rm.mediaGeneration = true, "room_media_12345678"
|
||||
rm.controller.SetVideoPublication("", false, h.router.now())
|
||||
rm.controller.SetVideoPublication(testShareGeneration, false, h.router.now())
|
||||
_, _ = h.store.DisconnectParticipant(created.RoomID, host.peerID, host.sessionID)
|
||||
rm.controller.DisconnectSession(host.peerID, host.sessionID)
|
||||
})
|
||||
// Use the production HTTP mutation's mutex, shared with this same router.
|
||||
server := &Server{store: h.store}
|
||||
h.router.mu = &server.mu
|
||||
now := h.router.now
|
||||
var stop atomic.Bool
|
||||
h.router.now = func() int64 {
|
||||
if stop.Load() {
|
||||
// Only the failing control uses this escape, so the old infinite pump
|
||||
// can release its test-owned goroutine and mutex before cleanup.
|
||||
panic("test cancels non-progressing pump")
|
||||
}
|
||||
return now()
|
||||
}
|
||||
pumping, pumped := make(chan struct{}), make(chan struct{})
|
||||
go func() {
|
||||
server.mu.Lock()
|
||||
defer server.mu.Unlock()
|
||||
defer close(pumped)
|
||||
close(pumping)
|
||||
rm, _ := h.router.rooms.Get(created.RoomID)
|
||||
revision := rm.controller.Revision()
|
||||
h.router.recoverPump(func() {
|
||||
h.router.pumpRoom(created.RoomID, rm, rm.controller, &revision, nil, false)
|
||||
})
|
||||
}()
|
||||
<-pumping
|
||||
roomCreated := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := server.CreateRoom(protocol.CodeEntryOpen, nil, "")
|
||||
roomCreated <- err
|
||||
}()
|
||||
blocked := false
|
||||
select {
|
||||
case err := <-roomCreated:
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
blocked = true
|
||||
stop.Store(true)
|
||||
select {
|
||||
case <-roomCreated:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("test pump did not retire after cancellation")
|
||||
}
|
||||
}
|
||||
<-pumped
|
||||
server.mu.Lock()
|
||||
h.router.mu, h.router.now = &h.mu, now
|
||||
server.mu.Unlock()
|
||||
if blocked {
|
||||
t.Fatal("publication attachment to an offline parent held the room-creation mutex")
|
||||
}
|
||||
rm, _ := h.router.rooms.Get(created.RoomID)
|
||||
after, ok := rm.controller.Snapshot().UpstreamByViewer.Get(viewer.peerID)
|
||||
if !ok || after.ConnectionID != before.connectionID || !after.Usable || !after.PhysicalActive {
|
||||
t.Fatal("waiting for its parent replaced the healthy room connection")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoppedShareReadyCannotCommitReplacementShare(t *testing.T) {
|
||||
h := newRouterHarness(t, routerHarnessOptions{capacity: 2, fakeTimers: true})
|
||||
|
||||
@@ -2794,7 +2794,7 @@ func TestSignalKeepsMediaIdentityThroughGraceWhilePresenceReturnsOnce(t *testing
|
||||
`{"fromPeerId":%q,"connectionId":"connection-during-grace","rebuild":false}`, firstViewerAuth.PeerID))
|
||||
}
|
||||
|
||||
func TestSignalAllowsRetainedChildRestartWhileRelayRepairsIngress(t *testing.T) {
|
||||
func TestSignalAllowsRetainedChildRestartWhileSourcePathRecovers(t *testing.T) {
|
||||
h := startHarness(t, harnessOptions{endpointMediaCopyCapacity: 1})
|
||||
host := openClient(t, h)
|
||||
hostAuth := authenticate(t, host, h.room, protocol.RoleHost, "restart-host-client", 0, "", presenceOptions{})
|
||||
@@ -2823,7 +2823,9 @@ func TestSignalAllowsRetainedChildRestartWhileRelayRepairsIngress(t *testing.T)
|
||||
"type": "route-failed", "phase": "active", "revision": relayEdge.revision,
|
||||
"connectionId": relayEdge.connectionID,
|
||||
})
|
||||
repair := nextPreparedRoute(t, relay)
|
||||
// A child's earlier prepare is still queued on its relay. Wait for the
|
||||
// committed failure update, not that unrelated preparation message.
|
||||
nextActiveRouteAfter(t, relay, active.Revision)
|
||||
h.locked(func() {
|
||||
rm, _ := h.server.router.rooms.Get(h.room.RoomID)
|
||||
snapshot := rm.controller.Snapshot()
|
||||
@@ -2859,8 +2861,8 @@ func TestSignalAllowsRetainedChildRestartWhileRelayRepairsIngress(t *testing.T)
|
||||
})
|
||||
expectMatch(t, relay.next("error").raw, `{"code":"FORBIDDEN"}`)
|
||||
relay.sendJSON(map[string]any{
|
||||
"type": "restart-request", "targetPeerId": repair.Assignment.Upstream.PeerID,
|
||||
"connectionId": repair.Candidate.ConnectionID, "rebuild": true,
|
||||
"type": "restart-request", "targetPeerId": hostAuth.PeerID,
|
||||
"connectionId": relayEdge.connectionID, "rebuild": true,
|
||||
})
|
||||
expectMatch(t, relay.next("error").raw, `{"code":"FORBIDDEN"}`)
|
||||
}
|
||||
|
||||
+37
-20
@@ -41,6 +41,7 @@ type Runtime struct {
|
||||
cancel context.CancelFunc
|
||||
once sync.Once
|
||||
url string
|
||||
invitation string
|
||||
configMu sync.Mutex
|
||||
configPath string
|
||||
config appconfig.Config
|
||||
@@ -144,7 +145,7 @@ func Start(platform Platform, lanAddress string, codecCapabilities string, dataD
|
||||
r.configMu.Unlock()
|
||||
return sites, err
|
||||
},
|
||||
SaveStartupSite: func(site string) error { return launcher.SaveStartupSite(r.configPath, site) },
|
||||
SaveStartupSite: func(site launcher.StartupIntent) error { return launcher.SaveStartupSite(r.configPath, site) },
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Join(err, r.Close())
|
||||
@@ -156,38 +157,52 @@ func Start(platform Platform, lanAddress string, codecCapabilities string, dataD
|
||||
if err != nil {
|
||||
return nil, errors.Join(err, r.Close())
|
||||
}
|
||||
if startup.Owned != nil {
|
||||
r.launcher.Begin()
|
||||
}
|
||||
r.launchDone = make(chan struct{})
|
||||
go func() {
|
||||
defer close(r.launchDone)
|
||||
r.runLauncher(lanAddress)
|
||||
r.runLauncher(lanAddress, startup.Owned)
|
||||
}()
|
||||
go r.watchServices()
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// Failed startup has already retired its resources before a new selection starts.
|
||||
func (r *Runtime) runLauncher(lanAddress string) {
|
||||
func (r *Runtime) runLauncher(lanAddress string, initial *launcher.StartupLaunch) {
|
||||
for {
|
||||
select {
|
||||
case selected := <-r.launcher.Selection():
|
||||
if err := launcher.SaveMode(r.configPath, selected.Mode); err != nil {
|
||||
slog.Debug("Could not save the launcher mode", diagnostics.Error(err))
|
||||
var selected launcher.Selection
|
||||
if initial != nil {
|
||||
r.configMu.Lock()
|
||||
selected = launcher.Selection{Mode: initial.Mode, LANAddress: initial.LANAddress, LocalAccessPassword: r.config.LocalAccessPassword}
|
||||
r.configMu.Unlock()
|
||||
initial = nil
|
||||
} else {
|
||||
select {
|
||||
case selected = <-r.launcher.Selection():
|
||||
case <-r.ctx.Done():
|
||||
return
|
||||
}
|
||||
target, err := r.startLocal(selected, lanAddress)
|
||||
}
|
||||
if err := launcher.SaveMode(r.configPath, selected.Mode); err != nil {
|
||||
slog.Debug("Could not save the launcher mode", diagnostics.Error(err))
|
||||
}
|
||||
target, err := r.startLocal(selected, lanAddress)
|
||||
if err != nil {
|
||||
r.launcher.SetResult(target, err)
|
||||
if err == nil {
|
||||
r.configMu.Lock()
|
||||
server, tunnel := r.server, r.tunnel
|
||||
r.configMu.Unlock()
|
||||
err = r.watchRoom(server, tunnel)
|
||||
if r.ctx.Err() != nil {
|
||||
r.closeErr = errors.Join(r.closeErr, err)
|
||||
return
|
||||
}
|
||||
r.launcher.SetResult("", err)
|
||||
}
|
||||
if err == nil {
|
||||
r.configMu.Lock()
|
||||
invitation, server, tunnel := r.invitation, r.server, r.tunnel
|
||||
r.configMu.Unlock()
|
||||
r.launcher.SetReady(target, invitation, selected)
|
||||
err = r.watchRoom(server, tunnel)
|
||||
if r.ctx.Err() != nil {
|
||||
r.closeErr = errors.Join(r.closeErr, err)
|
||||
return
|
||||
}
|
||||
case <-r.ctx.Done():
|
||||
return
|
||||
r.launcher.SetResult("", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -287,6 +302,7 @@ func (r *Runtime) startLocal(selection launcher.Selection, address string) (targ
|
||||
return "", err
|
||||
}
|
||||
r.server, r.tunnel, r.url = server, tunnel, target
|
||||
r.invitation = config.Origin(configuration.PublicBaseURL)
|
||||
committed = true
|
||||
r.configMu.Unlock()
|
||||
return target, nil
|
||||
@@ -325,6 +341,7 @@ func (r *Runtime) watchRoom(server *serverapp.Server, tunnel *publictunnel.Proce
|
||||
origin = r.localOrigin()
|
||||
}
|
||||
r.server, r.tunnel, r.url = nil, nil, ""
|
||||
r.invitation = ""
|
||||
}
|
||||
r.configMu.Unlock()
|
||||
if origin != "" {
|
||||
|
||||
@@ -110,7 +110,7 @@ func TestEntryTracksCurrentStartupPreferenceAndSiteRevocation(t *testing.T) {
|
||||
if err := appconfig.Save(configPath, appconfig.Config{Version: 1, Sites: []string{"https://first.example", "https://second.example"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := launcher.SaveStartupSite(configPath, "https://first.example"); err != nil {
|
||||
if err := launcher.SaveStartupSite(configPath, launcher.StartupIntent{Site: "https://first.example"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := Start(&testPlatform{}, "", `{"platform":"android","provider":"Android MediaCodec","systemAudio":true,"encoders":[]}`, directory, t.TempDir(), "", "piik://media")
|
||||
|
||||
@@ -60,7 +60,7 @@ func TestCloseJoinsLocalControlRetirementWithoutFalseError(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.launchDone = make(chan struct{})
|
||||
go func() { defer close(r.launchDone); r.runLauncher("") }()
|
||||
go func() { defer close(r.launchDone); r.runLauncher("", nil) }()
|
||||
launcherOrigin := strings.TrimSuffix(r.launcher.URL(), "/client")
|
||||
request, _ := http.NewRequest("POST", launcherOrigin+"/api/client-launcher/launch", strings.NewReader(`{"mode":"link","language":"en"}`))
|
||||
request.Header.Set("Origin", launcherOrigin)
|
||||
@@ -256,6 +256,42 @@ func TestStartupAndSiteRevocationCommitOneOriginAuthority(t *testing.T) {
|
||||
if status := <-launched; status != http.StatusOK {
|
||||
t.Fatalf("startup = %d", status)
|
||||
}
|
||||
platform.siteChanged = nil
|
||||
if post("site", `{"site":"https://android-fixture.trycloudflare.com","allowed":true}`) != 200 ||
|
||||
post("startup-site", `{"site":"https://android-fixture.trycloudflare.com"}`) != 200 {
|
||||
t.Fatal("owned startup preference was not saved")
|
||||
}
|
||||
if err := r.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err = Start(&testPlatform{}, "", `{"platform":"android","provider":"fixture","encoders":[]}`, dir, t.TempDir(), executable, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Close()
|
||||
if r.EntryURL() != r.URL()+"?start=1" {
|
||||
t.Fatal("mobile startup reused the old invitation")
|
||||
}
|
||||
deadline = time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
response, err := client.Get(strings.TrimSuffix(r.URL(), "/client") + "/api/client-launcher")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var state struct{ Target, StartupSite, StartupMode string }
|
||||
json.NewDecoder(response.Body).Decode(&state)
|
||||
response.Body.Close()
|
||||
if state.Target != "" {
|
||||
if state.Target == target || state.StartupSite != "https://android-fixture.trycloudflare.com" || state.StartupMode != "link" {
|
||||
t.Fatalf("bad restored startup: %+v", state)
|
||||
}
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("owned startup did not reach Ready without a browser command")
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
type runtimePlatform struct {
|
||||
@@ -369,7 +405,7 @@ func TestLauncherRetriesFailedStartupAndKeepsSuccessfulRoom(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.launchDone = make(chan struct{})
|
||||
go func() { defer close(r.launchDone); r.runLauncher("") }()
|
||||
go func() { defer close(r.launchDone); r.runLauncher("", nil) }()
|
||||
endpoint := strings.TrimSuffix(r.launcher.URL(), "/client") + "/api/client-launcher/launch"
|
||||
client := &http.Client{Timeout: 5 * time.Second}
|
||||
post := func(body string) *http.Response {
|
||||
|
||||
@@ -345,7 +345,8 @@ ComPtr<IMFMediaType> CreateOutputType(
|
||||
Check(type->SetUINT32(MF_MT_INTERLACE_MODE,
|
||||
MFVideoInterlace_Progressive),
|
||||
"output-type-interlace");
|
||||
Check(type->SetUINT32(MF_MT_MPEG2_PROFILE, eAVEncH264VProfile_Base),
|
||||
// Baseline alone does not require the constrained tools negotiated by WebRTC.
|
||||
Check(type->SetUINT32(MF_MT_MPEG2_PROFILE, eAVEncH264VProfile_ConstrainedBase),
|
||||
"output-type-profile");
|
||||
// MF recommends automatic level selection. Forcing a valid level can still
|
||||
// make hardware reject the type; validate the actual SPS instead.
|
||||
@@ -399,7 +400,7 @@ void ValidateMediaTypes(
|
||||
RequireTypeU32(output.Get(), MF_MT_AVG_BITRATE, profile.bit_rate,
|
||||
"output-type-bitrate");
|
||||
RequireTypeU32(output.Get(), MF_MT_MPEG2_PROFILE,
|
||||
eAVEncH264VProfile_Base, "output-type-profile");
|
||||
eAVEncH264VProfile_ConstrainedBase, "output-type-profile");
|
||||
|
||||
UINT32 width = 0;
|
||||
UINT32 height = 0;
|
||||
|
||||
@@ -13,15 +13,15 @@ fallback. Exit code zero requires all of these checks in one 360-frame run:
|
||||
|
||||
- adapter-LUID-bound hardware H.264 enumeration;
|
||||
- asynchronous and D3D11-aware transform readback;
|
||||
- exact low-latency, CBR, 3 Mbps and 60-frame GOP property
|
||||
readback, plus Baseline media-type request/readback and output-order
|
||||
- exact CBR, 3 Mbps and 60-frame GOP property
|
||||
readback, plus Constrained Baseline media-type request/readback and output-order
|
||||
no-reordering checks;
|
||||
- 360 GPU-surface NV12 inputs and 360 ordered outputs;
|
||||
- one live `3 Mbps -> 1.5 Mbps -> 3 Mbps` rate change whose three equal phases
|
||||
lower and then restore actual encoded bytes without recreating the MFT;
|
||||
- Annex-B SPS/PPS/IDR at frames 0, 60, 120, 180, 240, and 300;
|
||||
- an SPS `profile-level-id` exactly present in the fixture's default Pion
|
||||
mode-1 fmtp set; and
|
||||
- an SPS `profile-level-id` accepted by the production Constrained Baseline
|
||||
coding-tool and level check; and
|
||||
- process-and-adapter-attributed Windows `VideoEncode` activity.
|
||||
|
||||
The generated executable must stay outside the repository. From PowerShell:
|
||||
@@ -42,7 +42,7 @@ encoded bitstream. A nonzero exit is a measured no-go at the reported stage;
|
||||
it must not be worked around by adding a software retry.
|
||||
|
||||
Pion transport and browser decode remain separate from this offline fixture;
|
||||
the product path reuses its exact `42c01f`, Annex-B, adapter-bound hardware
|
||||
the product path reuses the same Constrained Baseline, Annex-B, adapter-bound hardware
|
||||
contract without adding those network concerns to this executable.
|
||||
|
||||
Primary API references, accessed 2026-08-20:
|
||||
|
||||
@@ -3,6 +3,7 @@ import { createHash } from "node:crypto";
|
||||
import { openAsBlob } from "node:fs";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { readReleaseArtifacts } from "./release-artifacts.mjs";
|
||||
import { mirrorSourceReady } from "./release-mirror-ready.mjs";
|
||||
|
||||
const [directory, version, revision, option] = process.argv.slice(2);
|
||||
if (option && option !== "--dry-run") {
|
||||
@@ -111,6 +112,8 @@ if (option === "--dry-run") {
|
||||
const body = `${source.body ?? ""}\n\nSource: https://github.com/${repository}/commit/${revision}\n\n${marker}\n`;
|
||||
if (!release || release.prerelease) requireLatestSource();
|
||||
if (!release) {
|
||||
if (!await mirrorSourceReady(version, revision, request))
|
||||
throw new Error("AtomGit Git synchronization is pending; the scheduled mirror check will resume after the matching commit and tag arrive");
|
||||
const repo = await request("");
|
||||
if (!repo || repo.private || !repo.default_branch) throw new Error("A public initialized AtomGit mirror is required");
|
||||
release = await request("/releases", "POST", {
|
||||
@@ -133,8 +136,9 @@ if (option === "--dry-run") {
|
||||
// Signed locations and callback headers are credentials; never log them.
|
||||
let response;
|
||||
try {
|
||||
// The signed APK exceeded three minutes on the cross-border upload path.
|
||||
response = await fetch(upload.url, { method: "PUT", redirect: "error", headers: upload.headers,
|
||||
body: await openAsBlob(file.path), signal: AbortSignal.timeout(180_000) });
|
||||
body: await openAsBlob(file.path), signal: AbortSignal.timeout(600_000) });
|
||||
if (!response.ok) throw new Error("HTTP " + response.status);
|
||||
await response.arrayBuffer();
|
||||
} catch (error) {
|
||||
|
||||
@@ -30,7 +30,7 @@ for (const server of servers) {
|
||||
}
|
||||
|
||||
function verifyImage(reference, server) {
|
||||
const metadata = JSON.parse(run("docker", "image", "inspect", reference))[0];
|
||||
const metadata = JSON.parse(run("docker", "image", "inspect", "--platform", `linux/${server.arch}`, reference))[0];
|
||||
assert.equal(metadata.Os, "linux");
|
||||
assert.equal(metadata.Architecture, server.arch);
|
||||
const labels = metadata.Config.Labels;
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { appendFileSync } from "node:fs";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
const repository = "TNTcraftHIM/Piik";
|
||||
export async function readMirror(path) {
|
||||
const response = await fetch(`https://api.atomgit.com/api/v5/repos/${repository}${path}`, {
|
||||
redirect: "error", signal: AbortSignal.timeout(30_000), headers: { Accept: "application/json" },
|
||||
});
|
||||
if (response.status === 404) return null;
|
||||
if (!response.ok) throw new Error(`AtomGit readiness ${path}: HTTP ${response.status}`);
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// Git synchronization belongs to AtomGit. Release creation must never create a tag.
|
||||
export async function mirrorSourceReady(version, revision, read = readMirror) {
|
||||
const commit = await read(`/commits/${revision}`);
|
||||
if (!commit) return false;
|
||||
if (commit.sha !== revision) throw new Error("AtomGit source commit differs from the published source");
|
||||
for (let page = 1; page <= 10; page++) {
|
||||
const tags = await read(`/tags?per_page=100&page=${page}`);
|
||||
if (!Array.isArray(tags)) throw new Error("Unexpected AtomGit tag list");
|
||||
const tag = tags.find(tag => tag.name === version);
|
||||
if (tag) {
|
||||
if (tag.commit?.sha !== revision) throw new Error("AtomGit release tag belongs to another source revision");
|
||||
return true;
|
||||
}
|
||||
if (tags.length < 100) return false;
|
||||
}
|
||||
throw new Error("AtomGit tag inventory exceeds 10 pages; source readiness cannot be determined");
|
||||
}
|
||||
|
||||
export async function mirrorReadiness(source, read = readMirror) {
|
||||
if (source.draft !== false || source.prerelease !== false || typeof source.tag_name !== "string"
|
||||
|| !/^[a-f0-9]{40}$/.test(source.target_commitish)) throw new Error("A published GitHub release with a full source SHA is required");
|
||||
const version = source.tag_name, revision = source.target_commitish;
|
||||
const mirror = await read(`/releases/tags/${encodeURIComponent(version)}`);
|
||||
if (mirror) {
|
||||
if (mirror.tag_name !== version || ![true, false].includes(mirror.prerelease)
|
||||
|| !mirror.body?.split(/\r?\n/).includes(`<!-- piik-source: ${revision} -->`))
|
||||
throw new Error("Existing mirror release belongs to a different or unknown source revision");
|
||||
const packages = source.assets?.filter(asset => asset.name?.startsWith("piik-"));
|
||||
const complete = packages?.length > 0 && Array.isArray(mirror.assets) && packages.every(asset => {
|
||||
const matches = mirror.assets.filter(candidate => candidate.type === "attach" && candidate.name === asset.name);
|
||||
return asset.state === "uploaded" && /^sha256:[a-f0-9]{64}$/.test(asset.digest ?? "")
|
||||
&& matches.length === 1 && matches[0].size === asset.size
|
||||
&& matches[0].browser_download_url === `https://atomgit.com/${repository}/releases/download/${version}/${asset.name}`;
|
||||
});
|
||||
if (!mirror.prerelease) {
|
||||
if (!complete) throw new Error("Published mirror is incomplete; it cannot be silently replaced");
|
||||
return { status: "complete", version, revision };
|
||||
}
|
||||
}
|
||||
return { status: await mirrorSourceReady(version, revision, read) ? "ready" : "deferred", version, revision };
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
const source = JSON.parse(execFileSync("gh", ["api", `repos/${repository}/releases/latest`], {
|
||||
encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 30_000,
|
||||
}));
|
||||
const result = await mirrorReadiness(source);
|
||||
if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `status=${result.status}\n`);
|
||||
if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY,
|
||||
result.status === "deferred" ? `Mirror ${result.version} deferred until AtomGit's scheduled Git synchronization supplies the matching commit and tag. The next mirror check will resume automatically.\n`
|
||||
: result.status === "complete" ? `Mirror ${result.version} is already stable with the complete published attachment inventory.\n`
|
||||
: `Mirror ${result.version} is ready to resume from original CI artifacts.\n`);
|
||||
console.log(JSON.stringify(result));
|
||||
}
|
||||
@@ -9,6 +9,15 @@ const gh = (path) => JSON.parse(execFileSync("gh", ["api", `repos/${repository}/
|
||||
}));
|
||||
|
||||
export function resolveMirrorSource(runId, automatic = false) {
|
||||
if (!runId && automatic) {
|
||||
const latest = gh("releases/latest");
|
||||
if (latest.draft !== false || latest.prerelease !== false || !isReleaseVersion(latest.tag_name)
|
||||
|| !/^[a-f0-9]{40}$/.test(latest.target_commitish)) throw new Error("A published stable GitHub release with a full source SHA is required");
|
||||
const runs = gh(`actions/workflows/repository-hygiene.yml/runs?event=push&branch=main&status=completed&head_sha=${latest.target_commitish}&per_page=100`);
|
||||
const source = runs.workflow_runs?.find(run => run.head_sha === latest.target_commitish);
|
||||
if (!source) throw new Error("The published release's original completed CI run is unavailable; do not rebuild its packages");
|
||||
return resolveMirrorSource(String(source.id), true);
|
||||
}
|
||||
if (!/^[1-9]\d*$/.test(runId) || !Number.isSafeInteger(Number(runId))) {
|
||||
throw new Error("Provide the original CI run's numeric ID");
|
||||
}
|
||||
@@ -34,7 +43,7 @@ export function resolveMirrorSource(runId, automatic = false) {
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
const source = resolveMirrorSource(process.argv[2], process.env.GITHUB_EVENT_NAME === "workflow_run");
|
||||
const source = resolveMirrorSource(process.argv[2], ["workflow_run", "schedule"].includes(process.env.GITHUB_EVENT_NAME) || !process.argv[2]);
|
||||
const output = { mirror: source !== null, ...source };
|
||||
if (process.env.GITHUB_OUTPUT) {
|
||||
appendFileSync(process.env.GITHUB_OUTPUT,
|
||||
|
||||
@@ -39,6 +39,8 @@ export function LauncherForm({
|
||||
onModeChange,
|
||||
sites,
|
||||
startupSite,
|
||||
ownedStartup,
|
||||
ownedSites = [],
|
||||
onToggleStartupSite,
|
||||
onRemoveSite,
|
||||
onSelectSite,
|
||||
@@ -60,6 +62,8 @@ export function LauncherForm({
|
||||
onModeChange: (mode: AppMode) => void;
|
||||
sites: readonly string[];
|
||||
startupSite: string;
|
||||
ownedStartup?: AppMode;
|
||||
ownedSites?: readonly string[];
|
||||
onToggleStartupSite: (site: string) => void;
|
||||
onRemoveSite: (site: string) => void;
|
||||
onSelectSite?: (site: string) => void;
|
||||
@@ -153,7 +157,7 @@ export function LauncherForm({
|
||||
{sites.length > 0 && <div className="lr-client-approved-sites" role="list">{sites.map((site, index) => <div key={site} className="lr-client-approved-site" role="listitem">
|
||||
<a href={entryURL(`${site}/#piik-client=1`)} target="_blank" rel="noopener noreferrer" onClick={onOpen}>{site}<span aria-hidden="true"> ↗</span></a>
|
||||
<div className="lr-client-site-actions">
|
||||
<Btn icon="star" title="client.connect.openOnStart" size="dense" pressed={startupSite === site}
|
||||
<Btn icon="star" title="client.connect.openOnStart" size="dense" pressed={startupSite === site || Boolean(ownedStartup && ownedSites.includes(site))}
|
||||
hint="hint-client-site" disabled={siteBusy} onClick={() => onToggleStartupSite(site)} />
|
||||
<Btn id={`${accessHintId}-remove-${index}`} icon="x" title="client.connect.remove" size="dense" hint="hint-close" disabled={siteBusy} onClick={() => {
|
||||
const button = standbyRef.current?.ownerDocument.activeElement;
|
||||
@@ -164,6 +168,11 @@ export function LauncherForm({
|
||||
</div>)}</div>}
|
||||
</section>
|
||||
|
||||
{ownedStartup && <label className="lr-client-approval-startup">
|
||||
<input type="checkbox" checked disabled={siteBusy} onChange={() => onToggleStartupSite("")} />
|
||||
<Glyph name="star" size={18} />
|
||||
<span className={vis ? "visually-hidden" : undefined}>{t("client.connect.openOwnedOnStart", { mode: t(ownedStartup === "local" ? "client.launch.local" : "client.launch.link") })}</span>
|
||||
</label>}
|
||||
{roomError}
|
||||
{target ? <a className="lr-btn is-primary" href={entryURL(target)} onClick={onOpen} aria-label={t("client.launch.go")}>
|
||||
<Glyph name="arrowRight" size={19} />{vis ? null : <span className="lr-cap">{t("client.launch.go")}</span>}
|
||||
|
||||
@@ -69,12 +69,12 @@ export function ResolutionControl({ value, limits, disabled, onChange }: {
|
||||
const controls = useRef<HTMLDivElement>(null);
|
||||
const [invalid, setInvalid] = useState(false);
|
||||
const errorId = useId();
|
||||
useEffect(() => setInvalid(false), [value.width, value.height]);
|
||||
const axes = ["width", "height"] as const;
|
||||
const reset = (container: HTMLElement) => {
|
||||
setInvalid(false);
|
||||
for (const axis of axes) container.querySelector<HTMLInputElement>(`input[name="${axis}"]`)!.value = String(value[axis]);
|
||||
};
|
||||
useEffect(() => { reset(controls.current!); }, [value.width, value.height]);
|
||||
const apply = (container: HTMLElement) => {
|
||||
const width = container.querySelector<HTMLInputElement>('input[name="width"]')!;
|
||||
const height = container.querySelector<HTMLInputElement>('input[name="height"]')!;
|
||||
@@ -108,7 +108,7 @@ export function ResolutionControl({ value, limits, disabled, onChange }: {
|
||||
width: String(limits.maxVideoResolution.width), height: String(limits.maxVideoResolution.height),
|
||||
pixels: limits.maxVideoPixels.toLocaleString("en-US"),
|
||||
})}>
|
||||
<span className="lr-input lr-video-size" key={`${value.width}x${value.height}`}
|
||||
<span className="lr-input lr-video-size"
|
||||
role="group" aria-label={t("host.advanced.resolution")}>
|
||||
{axes.map((axis, index) => <Fragment key={axis}>
|
||||
{index === 1 ? <span aria-hidden="true">×</span> : null}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
.lr-person-eyes { transform-origin: 24px 14.1px; }
|
||||
/* Keep the same SVG parts mounted so a second toggle reverses the gesture. */
|
||||
.lr-person-headset, .lr-person-collaboration { opacity: 0; }
|
||||
.lr-person-headset { color: var(--ink); }
|
||||
.lr-person-status[data-voice] .lr-person-headset,
|
||||
.lr-person-status[data-collaboration] .lr-person-collaboration { opacity: 1; }
|
||||
.lr-person-collaboration { transform: translateY(2px) scale(.94); transform-origin: 24px 40px; }
|
||||
|
||||
@@ -260,6 +260,7 @@ export const en: Record<CopyKey, string> = {
|
||||
"client.connect.standbyHint": "Click App at the top right of a Piik site, choose Open App page, then confirm Allow access.",
|
||||
"client.connect.remove": "Revoke this Site's App access",
|
||||
"client.connect.openOnStart": "Open this site when App starts",
|
||||
"client.connect.openOwnedOnStart": "Open my site when App starts ({mode})",
|
||||
"client.connect.manage": "App is ready. Manage App.",
|
||||
"client.connect.update": "App {current}. Update to {version}.",
|
||||
"client.connect.approveTitle": "Allow this Site to use Piik App?",
|
||||
|
||||
@@ -260,6 +260,7 @@ export const zh = {
|
||||
"client.connect.standbyHint": "在 Piik 站点右上角点击 App,选择「打开 App 页面」,再确认「允许使用」。",
|
||||
"client.connect.remove": "取消此站点的 App 授权",
|
||||
"client.connect.openOnStart": "启动 App 时打开此站点",
|
||||
"client.connect.openOwnedOnStart": "启动 App 时打开我的站点({mode})",
|
||||
"client.connect.manage": "App 已就绪,点击管理。",
|
||||
"client.connect.update": "App {current},可更新至 {version}。",
|
||||
"client.connect.approveTitle": "允许使用 Piik App?",
|
||||
|
||||
@@ -19,6 +19,8 @@ import { useReleaseUpdate } from "../lib/use-release-update";
|
||||
const launcherStateSchema = z.object({
|
||||
sites: z.array(z.string()),
|
||||
startupSite: z.string(),
|
||||
ownedSites: z.array(z.string()).default([]),
|
||||
startupMode: z.enum(["local", "link", ""]).nullish(),
|
||||
localAccessPassword: z.string(),
|
||||
defaultMode: z.enum(["local", "link"]),
|
||||
modes: z.array(z.enum(["local", "link"])).default(["local", "link"]),
|
||||
@@ -49,6 +51,8 @@ export function AppLauncherPage() {
|
||||
const [modes, setModes] = useState<readonly AppMode[]>(["local", "link"]);
|
||||
const [sites, setSites] = useState<string[]>([]);
|
||||
const [startupSite, setStartupSite] = useState("");
|
||||
const [ownedSites, setOwnedSites] = useState<string[]>([]);
|
||||
const [startupMode, setStartupMode] = useState<AppMode | undefined>();
|
||||
const [openOnApproval, setOpenOnApproval] = useState(false);
|
||||
const [localAccessPassword, setLocalAccessPassword] = useState("");
|
||||
const [error, setError] = useState<{ kind: "load" | "launch"; reason?: string; detail?: string } | null>(null);
|
||||
@@ -78,7 +82,7 @@ export function AppLauncherPage() {
|
||||
} catch { return false; }
|
||||
})();
|
||||
const approvalCurrent = validSite && sites.includes(requestedSite);
|
||||
const openSiteOnStart = Boolean(approvalCurrent && startupSite === requestedSite);
|
||||
const openSiteOnStart = Boolean(approvalCurrent && (startupSite === requestedSite || startupMode && ownedSites.includes(requestedSite)));
|
||||
|
||||
useEffect(() => {
|
||||
// The App's saved exact origin owns permission, including repeat connections.
|
||||
@@ -92,6 +96,7 @@ export function AppLauncherPage() {
|
||||
let current = true;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let restoredSettings = false;
|
||||
let enterOnReady = new URLSearchParams(window.location.search).get("start") === "1";
|
||||
let reading = false;
|
||||
const readState = () => {
|
||||
if (reading || !current) return;
|
||||
@@ -115,6 +120,7 @@ export function AppLauncherPage() {
|
||||
setModes(state.modes);
|
||||
setLocalAccessPassword(state.localAccessPassword);
|
||||
setLan(state.lan);
|
||||
if (state.startupMode && state.modes.includes(state.startupMode)) setMode(state.startupMode);
|
||||
restoredSettings = true;
|
||||
}
|
||||
setVersion(state.version === "development" && /^[a-f0-9]{40}$/i.test(state.revision)
|
||||
@@ -124,11 +130,17 @@ export function AppLauncherPage() {
|
||||
setStarting(state.starting === true);
|
||||
setSites(state.sites);
|
||||
setStartupSite(state.startupSite);
|
||||
setStartupMode(state.startupMode || undefined);
|
||||
setOwnedSites(state.ownedSites);
|
||||
setAppDebug(state.debug);
|
||||
setDebug(state.debug === true);
|
||||
setError(previous => state.detail ? { kind: "launch", reason: state.reason, detail: state.detail }
|
||||
: previous?.kind === "load" ? null : previous);
|
||||
: state.target || previous?.kind === "load" ? null : previous);
|
||||
setLoading(false);
|
||||
if (enterOnReady && (state.target || state.detail)) {
|
||||
enterOnReady = false;
|
||||
if (state.target) window.location.replace(launchURL(state.target, { debug: state.debug === true, controlPort: state.controlPort }));
|
||||
}
|
||||
if (state.starting) timer = setTimeout(() => void readState(), 750);
|
||||
setBuild({ version: state.version, revision: state.revision, packageTarget: state.packageTarget });
|
||||
})
|
||||
@@ -174,7 +186,7 @@ export function AppLauncherPage() {
|
||||
finally { finish(); setDebugBusy(false); }
|
||||
}
|
||||
|
||||
function launchURL(target: string): string {
|
||||
function launchURL(target: string, settings = { debug: debug, controlPort }): string {
|
||||
const theme = currentThemePreference();
|
||||
const presentation: ClientLaunchPresentation = {
|
||||
lang, vis, theme,
|
||||
@@ -183,7 +195,7 @@ export function AppLauncherPage() {
|
||||
...(theme !== null ? ["theme" as const] : []),
|
||||
],
|
||||
};
|
||||
return clientLaunchURL(target, presentation, debug, controlPort);
|
||||
return clientLaunchURL(target, presentation, settings.debug, settings.controlPort);
|
||||
}
|
||||
|
||||
async function launch(event: FormEvent<HTMLFormElement>): Promise<void> {
|
||||
@@ -237,10 +249,12 @@ export function AppLauncherPage() {
|
||||
body: JSON.stringify({ site: nextSite, ...(setting === "site" ? { allowed } : {}) }),
|
||||
signal: controller.signal,
|
||||
});
|
||||
const result = launcherStateSchema.pick({ sites: true, startupSite: true }).safeParse(await response.json().catch(() => null));
|
||||
const result = launcherStateSchema.pick({ sites: true, startupSite: true, startupMode: true, ownedSites: true }).safeParse(await response.json().catch(() => null));
|
||||
if (result.success) {
|
||||
setSites(result.data.sites);
|
||||
setStartupSite(result.data.startupSite);
|
||||
setStartupMode(result.data.startupMode || undefined);
|
||||
setOwnedSites(result.data.ownedSites);
|
||||
}
|
||||
if (response.status === 409 && result.success) {
|
||||
setSiteError(t("client.connect.changed"));
|
||||
@@ -356,7 +370,9 @@ export function AppLauncherPage() {
|
||||
setSiteError(undefined);
|
||||
}}
|
||||
startupSite={startupSite}
|
||||
onToggleStartupSite={site => void changeSite(startupSite === site ? "" : site, "startup-site")}
|
||||
ownedStartup={startupMode}
|
||||
ownedSites={ownedSites}
|
||||
onToggleStartupSite={site => void changeSite(startupSite === site || startupMode && ownedSites.includes(site) ? "" : site, "startup-site")}
|
||||
localAccessPassword={localAccessPassword}
|
||||
onModeChange={setMode}
|
||||
onRemoveSite={site => void changeSite(site, "site", false, false)}
|
||||
|
||||
@@ -1814,7 +1814,7 @@ body.lr-theater-open .lr-top { visibility: hidden; }
|
||||
.lr-top-right { gap: 8px; }
|
||||
.lr-leds { gap: 4px; padding: 6px; }
|
||||
.lr-top .lr-btn.is-compact { width: var(--control-compact-size); padding: 0; }
|
||||
.lr-top .lr-btn.is-compact .lr-cap { display: none; }
|
||||
.lr-top .lr-btn.is-compact .lr-cap:not([popover] .lr-cap) { display: none; }
|
||||
.lr-top .lr-header-options[popover] .lr-btn.is-compact { width: auto; padding-inline: 12px; }
|
||||
.lr-top .lr-header-options[popover] .lr-cap { display: inline; }
|
||||
.lr-top .lr-header-options[popover] .lr-help-content nav .lr-btn { width: 100%; }
|
||||
|
||||
@@ -19,7 +19,7 @@ function collect(node: ts.Node): void {
|
||||
if (ts.isVariableDeclaration(node) && /^launcher.*Schema$/.test(node.name.getText(source))) {
|
||||
declarations.push(`const ${node.getText(source)};`);
|
||||
}
|
||||
if (ts.isFunctionDeclaration(node) && ["beginStateChange", "changeSite", "approveSite", "enableDebug", "launch"].includes(node.name?.text ?? "")) {
|
||||
if (ts.isFunctionDeclaration(node) && ["beginStateChange", "changeSite", "approveSite", "enableDebug", "launchURL", "launch"].includes(node.name?.text ?? "")) {
|
||||
declarations.push(node.getText(source));
|
||||
}
|
||||
if (ts.isCallExpression(node) && node.expression.getText(source) === "useEffect"
|
||||
@@ -39,26 +39,26 @@ const saved = {
|
||||
revision: "test", version: "development", debug: false,
|
||||
lan: { addresses: [{ address: "192.0.2.1", name: "LAN" }], selected: "192.0.2.1" },
|
||||
};
|
||||
const response = (state: typeof saved & { detail?: string } = saved) => ({ ok: true, status: 200, json: async () => state });
|
||||
const response = (state: typeof saved & { detail?: string; target?: string } = saved) => ({ ok: true, status: 200, json: async () => state });
|
||||
|
||||
function mount(fetch: ReturnType<typeof vi.fn>, manualSite = false) {
|
||||
function mount(fetch: ReturnType<typeof vi.fn>, manualSite = false, { startup = false }: { startup?: boolean } = {}) {
|
||||
const state: Record<string, unknown> = {};
|
||||
const setters = Object.fromEntries([
|
||||
"Mode", "Modes", "LocalAccessPassword", "Lan", "Version", "ControlPort", "Target", "Starting", "Sites", "StartupSite",
|
||||
"Mode", "Modes", "LocalAccessPassword", "Lan", "Version", "ControlPort", "Target", "Starting", "Sites", "StartupSite", "StartupMode", "OwnedSites",
|
||||
"AppDebug", "Debug", "Error", "Loading", "Build", "RemoteControlPrototype",
|
||||
"SiteBusy", "SiteError", "DebugBusy", "DebugError", "Reload",
|
||||
].map(name => [`set${name}`, vi.fn((value: unknown) => {
|
||||
state[name] = typeof value === "function" ? value(state[name]) : value;
|
||||
})]));
|
||||
const window = Object.assign(new EventTarget(), { location: { replace: vi.fn() } });
|
||||
const window = Object.assign(new EventTarget(), { location: { replace: vi.fn(), search: startup ? "?start=1" : "" } });
|
||||
const timers = new Map<number, { callback: () => void; delay: number }>();
|
||||
let nextTimer = 0;
|
||||
const actions = runInNewContext(executable, {
|
||||
...setters, z, fetch, window,
|
||||
...setters, z, fetch, window, URLSearchParams,
|
||||
stateChanges: { current: { revision: 0, pending: 0 } },
|
||||
siteBusy: false, debugBusy: false, starting: false, sites: saved.sites, manualSite, openOnApproval: false,
|
||||
mode: "link", lang: "en", vis: false, debug: false, appDebug: false, localAccessPassword: "",
|
||||
consoleLanguage: () => "en", launchURL: (target: string) => target, t: (key: string) => key,
|
||||
consoleLanguage: () => "en", clientLaunchURL, currentThemePreference: () => null, hasCopyPreference: () => false, controlPort: undefined, t: (key: string) => key,
|
||||
AbortController,
|
||||
setTimeout: (callback: () => void, delay: number) => {
|
||||
const id = ++nextTimer;
|
||||
@@ -86,6 +86,32 @@ function mount(fetch: ReturnType<typeof vi.fn>, manualSite = false) {
|
||||
}
|
||||
|
||||
describe("App launcher state recovery", () => {
|
||||
it("offers an available mode after the saved startup mode becomes unavailable", async () => {
|
||||
const page = mount(vi.fn().mockResolvedValue({
|
||||
ok: true, status: 200, json: async () => ({
|
||||
...saved, modes: ["local"], startupMode: "link", detail: "public-link helper unavailable",
|
||||
}),
|
||||
}), false, { startup: true });
|
||||
try {
|
||||
await settle();
|
||||
expect(page.state).toMatchObject({ Mode: "local", StartupMode: "link", Error: { kind: "launch" } });
|
||||
expect(page.navigate).not.toHaveBeenCalled();
|
||||
} finally { page.cleanup(); }
|
||||
});
|
||||
it("replaces a failed launch response with the running App's state on return", async () => {
|
||||
const fetch = vi.fn().mockResolvedValueOnce(response(saved))
|
||||
.mockRejectedValueOnce(new Error("Startup response disconnected"));
|
||||
const page = mount(fetch);
|
||||
try {
|
||||
await settle();
|
||||
await page.launch({ preventDefault() {} });
|
||||
expect(page.state.Error).toEqual({ kind: "launch" });
|
||||
fetch.mockResolvedValueOnce(response({ ...saved, target: "http://127.0.0.1:8791/" }));
|
||||
page.focus(); await settle();
|
||||
expect(page.state).toMatchObject({ Target: "http://127.0.0.1:8791/", Starting: false, Error: null });
|
||||
expect(page.navigate).not.toHaveBeenCalled();
|
||||
} finally { page.cleanup(); }
|
||||
});
|
||||
it.each([
|
||||
["v2.4.1", "v2.4.1"],
|
||||
["development", "development (aaaaaaa)"],
|
||||
@@ -113,7 +139,7 @@ describe("App launcher state recovery", () => {
|
||||
expect(page.state).toMatchObject({ Starting: false, Error: { kind: "launch", detail: "Startup failed" } });
|
||||
fetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ target: "https://room.example/#piik-client=1" }) });
|
||||
await page.launch(event);
|
||||
expect(page.navigate).toHaveBeenCalledWith("https://room.example/#piik-client=1");
|
||||
expect(page.navigate).toHaveBeenCalledWith("https://room.example/#piik-client=1&piik-lang=en&piik-mode=text&piik-theme=system");
|
||||
page.cleanup();
|
||||
});
|
||||
|
||||
@@ -128,6 +154,7 @@ describe("App launcher state recovery", () => {
|
||||
expect(html).toContain('value="saved password"');
|
||||
expect(html).toMatch(/type="submit"[^>]*aria-label="(?:Retry|重试)"/);
|
||||
expect(html).toContain(saved.sites[0]);
|
||||
expect(html).toContain('aria-pressed="false"');
|
||||
});
|
||||
|
||||
it("reopens a healthy room without offering another mode or password", () => {
|
||||
@@ -181,7 +208,7 @@ describe("App launcher state recovery", () => {
|
||||
expect(page.state.SiteError).toBe("client.connect.saveFailed");
|
||||
fetch.mockResolvedValueOnce(response({ ...saved, sites: [...saved.sites, "https://next.example"] }));
|
||||
await page.approveSite("https://next.example");
|
||||
if (manual) expect(page.navigate).toHaveBeenCalledWith("https://next.example/#piik-client=1");
|
||||
if (manual) expect(page.navigate).toHaveBeenCalledWith("https://next.example/#piik-client=1&piik-lang=en&piik-mode=text&piik-theme=system");
|
||||
else expect(page.navigate).not.toHaveBeenCalled();
|
||||
expect(fetch.mock.calls[1]).toEqual(["/api/client-launcher/site", expect.objectContaining({
|
||||
body: JSON.stringify({ site: "https://next.example", allowed: true }),
|
||||
@@ -239,7 +266,7 @@ describe("App launcher state recovery", () => {
|
||||
expect(page.navigate).not.toHaveBeenCalled();
|
||||
fetch.mockResolvedValueOnce(response({ ...saved, sites: [...saved.sites, "https://next.example"] }));
|
||||
await page.approveSite("https://next.example");
|
||||
expect(page.navigate).toHaveBeenCalledWith("https://next.example/#piik-client=1");
|
||||
expect(page.navigate).toHaveBeenCalledWith("https://next.example/#piik-client=1&piik-lang=en&piik-mode=text&piik-theme=system");
|
||||
expect(page.state.SiteBusy).toBe(false);
|
||||
page.cleanup();
|
||||
});
|
||||
@@ -364,3 +391,69 @@ describe("App launcher state recovery", () => {
|
||||
page.cleanup();
|
||||
});
|
||||
});
|
||||
|
||||
it("enters the fresh App-owned startup result once with its current debug setting and port", async () => {
|
||||
vi.stubGlobal("window", { location: { href: "http://127.0.0.1:39731/client?start=1" } });
|
||||
const fetch = vi.fn().mockResolvedValueOnce(response({ ...saved, starting: true } as typeof saved));
|
||||
const page = mount(fetch, false, { startup: true });
|
||||
try {
|
||||
await settle();
|
||||
expect(page.navigate).not.toHaveBeenCalled();
|
||||
const fresh = "http://127.0.0.1:45678/#piik-client=1";
|
||||
fetch.mockResolvedValue({ ok: true, status: 200, json: async () => ({ ...saved, target: fresh, debug: true, controlPort: 39732 }) });
|
||||
page.retry();
|
||||
await settle();
|
||||
const destination = new URL(page.navigate.mock.calls[0]![0]);
|
||||
expect(destination.origin).toBe("http://127.0.0.1:45678");
|
||||
expect(destination.searchParams.get("debug")).toBe("1");
|
||||
expect(destination.searchParams.get("piik-client-port")).toBe("39732");
|
||||
page.focus();
|
||||
await settle();
|
||||
expect(page.navigate).toHaveBeenCalledTimes(1);
|
||||
expect(fetch.mock.calls.every(call => !call[1]?.method)).toBe(true);
|
||||
} finally {
|
||||
page.cleanup();
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves a failed owned startup available for manual retry", async () => {
|
||||
const fetch = vi.fn().mockResolvedValueOnce(response({ ...saved, detail: "tunnel failed" }));
|
||||
const page = mount(fetch, false, { startup: true });
|
||||
try {
|
||||
await settle();
|
||||
expect(page.state.Starting).toBe(false);
|
||||
expect(page.state.Error).toMatchObject({ kind: "launch" });
|
||||
fetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ target: "http://127.0.0.1:45678/" }) });
|
||||
await page.launch({ preventDefault() {} });
|
||||
expect(page.navigate).toHaveBeenCalledTimes(1);
|
||||
} finally { page.cleanup(); }
|
||||
});
|
||||
|
||||
it("clears an owned startup from the existing settings operation", async () => {
|
||||
const fetch = vi.fn().mockResolvedValueOnce({
|
||||
ok: true, status: 200, json: async () => ({ ...saved, startupMode: "link", ownedSites: ["https://current.example"] }),
|
||||
});
|
||||
const page = mount(fetch);
|
||||
try {
|
||||
await settle();
|
||||
expect(page.state.StartupMode).toBe("link");
|
||||
fetch.mockResolvedValueOnce(response(saved));
|
||||
expect(await page.changeSite("", "startup-site")).toBe(true);
|
||||
expect(JSON.parse(fetch.mock.calls[1]![1].body)).toEqual({ site: "" });
|
||||
expect(page.state.StartupMode).toBeUndefined();
|
||||
expect(page.navigate).not.toHaveBeenCalled();
|
||||
} finally { page.cleanup(); }
|
||||
});
|
||||
|
||||
|
||||
it.each(["local", "link"] as const)("names the owned startup site and saved %s mode", mode => {
|
||||
const html = renderToStaticMarkup(createElement(LauncherForm, {
|
||||
mode, sites: saved.sites, startupSite: "", ownedStartup: mode,
|
||||
onModeChange() {}, onToggleStartupSite() {}, onRemoveSite() {}, onSubmit() {},
|
||||
localAccessPassword: "", onLocalAccessPasswordChange() {},
|
||||
}));
|
||||
expect(html).toMatch(/my site|我的站点/);
|
||||
expect(html).toMatch(mode === "local" ? /Local room|本地房间/ : /Public invite|公网邀请/);
|
||||
expect(html).toMatch(/type="checkbox"[^>]*checked/);
|
||||
});
|
||||
@@ -36,7 +36,7 @@ async function publish(options: Scenario = {}) {
|
||||
const manifests = new Map<string, object>();
|
||||
if (options.existing) manifests.set(tag, index);
|
||||
if (options.partial) manifests.set(`${tag}-arm64`, {});
|
||||
const images = new Map(servers.map(server => [`${image}-${server.arch}`, server.arch]));
|
||||
const images = new Map(linuxServers.map(server => [`${image}-${server.arch}`, new Set([server.arch])]));
|
||||
command.mockReset().mockImplementation((program: string, args: string[]) => {
|
||||
if (program === "gh") {
|
||||
if (args[1].endsWith("/commits/" + version)) {
|
||||
@@ -53,9 +53,15 @@ async function publish(options: Scenario = {}) {
|
||||
digest: `sha256:${options.badArchive && server.arch === "arm64" ? "c".repeat(64) : server.sha256}` })) });
|
||||
}
|
||||
if (args[0] === "image" && args[1] === "inspect") {
|
||||
const arch = images.get(args[2]);
|
||||
const reference = args.at(-1)!;
|
||||
const stored = images.get(reference);
|
||||
// A multi-platform store retains both variants. Inspect defaults to the
|
||||
// host architecture, independently of the last platform pulled.
|
||||
const requested = args.includes("--platform") ? args[args.indexOf("--platform") + 1].slice("linux/".length) : undefined;
|
||||
const arch = requested ?? (stored?.has("amd64") ? "amd64" : [...stored ?? []][0]);
|
||||
expect(arch).toBeDefined();
|
||||
const remote = args[2].startsWith("ghcr.io/");
|
||||
expect(stored?.has(arch!)).toBe(true);
|
||||
const remote = reference.startsWith("ghcr.io/");
|
||||
return JSON.stringify([{ Os: "linux", Architecture: options.wrongPlatform && arch === "arm64" ? "amd64" : arch, Config: { Labels: {
|
||||
"org.opencontainers.image.version": version,
|
||||
"org.opencontainers.image.revision": (options.wrongImage && arch === "arm64") || (options.remoteMismatch && remote)
|
||||
@@ -78,7 +84,11 @@ async function publish(options: Scenario = {}) {
|
||||
}
|
||||
return JSON.stringify(manifests.get(reference));
|
||||
}
|
||||
if (args[0] === "pull") images.set(args[3], args[2].slice("linux/".length));
|
||||
if (args[0] === "pull") {
|
||||
const variants = images.get(args[3]) ?? new Set<string>();
|
||||
variants.add(args[2].slice("linux/".length));
|
||||
images.set(args[3], variants);
|
||||
}
|
||||
if (args[0] === "tag") images.set(args[2], images.get(args[1])!);
|
||||
if (args[0] === "push") manifests.set(args[1], {});
|
||||
if (args[0] === "buildx" && args[2] === "create") manifests.set(args[4], index);
|
||||
|
||||
@@ -53,7 +53,7 @@ describe("AtomGit mirror publication", () => {
|
||||
});
|
||||
async function mirror(options: { existing?: "pending" | "published" | "unknown"; corrupt?: boolean;
|
||||
wrongSource?: boolean; wrongDigest?: boolean; missing?: boolean; uploadFailure?: boolean | number;
|
||||
stale?: boolean; supersededDuringUpload?: boolean;
|
||||
stale?: boolean; supersededDuringUpload?: boolean; mirrorSourceMissing?: boolean;
|
||||
downloadFault?: { remaining: number; name: "TimeoutError" | "TypeError" };
|
||||
fault?: { method: string; remaining: number; status: number | "timeout" | "body-timeout" } } = {}) {
|
||||
const interrupted = (bytes: Uint8Array, error: Error) => {
|
||||
@@ -128,6 +128,8 @@ describe("AtomGit mirror publication", () => {
|
||||
? Response.json({ id: 42, tag_name: version, body: options.existing === "unknown" ? "unknown" : marker,
|
||||
prerelease: pending, assets: [...present] }) : new Response(null, { status: 404 });
|
||||
if (path === "") return Response.json({ private: false, default_branch: "master" });
|
||||
if (path === `/commits/${revision}`) return options.mirrorSourceMissing ? new Response(null, { status: 404 }) : Response.json({ sha: revision });
|
||||
if (path === "/tags?per_page=100&page=1") return Response.json([{ name: version, commit: { sha: revision } }]);
|
||||
if (path === "/releases" && method === "POST") {
|
||||
const body = JSON.parse(String(init?.body));
|
||||
expect(body.release_status).toBe("pre");
|
||||
@@ -165,6 +167,12 @@ describe("AtomGit mirror publication", () => {
|
||||
return { mutations, failure };
|
||||
}
|
||||
|
||||
it("waits for AtomGit Git synchronization without creating a release or tag", async () => {
|
||||
const result = await mirror({ mirrorSourceMissing: true });
|
||||
expect(result.failure).toContain("Git synchronization is pending");
|
||||
expect(result.mutations).toEqual([]);
|
||||
});
|
||||
|
||||
it("copies the published bytes, verifies anonymous downloads and marks stable last", async () => {
|
||||
const result = await mirror();
|
||||
expect(result.failure).toBeUndefined();
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { expect, test, vi } from "vitest";
|
||||
import { mirrorReadiness, mirrorSourceReady, readMirror } from "../scripts/release-mirror-ready.mjs";
|
||||
|
||||
const revision = "a".repeat(40), version = "v2.6.1";
|
||||
const asset = { name: "piik-app-fixture.zip", state: "uploaded", size: 1024, digest: `sha256:${"b".repeat(64)}` };
|
||||
const source = { tag_name: version, target_commitish: revision, draft: false, prerelease: false, assets: [asset] };
|
||||
const mirror = { tag_name: version, prerelease: false, body: `<!-- piik-source: ${revision} -->`, assets: [{
|
||||
type: "attach", name: asset.name, size: asset.size, browser_download_url: `https://atomgit.com/TNTcraftHIM/Piik/releases/download/${version}/${asset.name}`,
|
||||
}, ...["zip", "tar.gz", "tar.bz2", "tar"].map(extension => ({ type: "source", name: `${version}.${extension}` }))] };
|
||||
|
||||
test("a completed stable mirror needs only its metadata and no source search or package download", async () => {
|
||||
const read = vi.fn(async () => mirror);
|
||||
expect(await mirrorReadiness(source, read)).toEqual({ status: "complete", version, revision });
|
||||
expect(read.mock.calls).toEqual([[`/releases/tags/${version}`]]);
|
||||
});
|
||||
|
||||
test.each(["commit", "tag"])("missing synced %s defers without a Git mutation", async missing => {
|
||||
const read = vi.fn(async (path: string) => path.startsWith("/releases/") ? null
|
||||
: path.startsWith("/commits/") ? missing === "commit" ? null : { sha: revision } : []);
|
||||
expect(await mirrorReadiness(source, read)).toEqual({ status: "deferred", version, revision });
|
||||
});
|
||||
|
||||
test("a pending release resumes only after its exact tag and source exist", async () => {
|
||||
const read = vi.fn(async (path: string) => path.startsWith("/releases/") ? { ...mirror, prerelease: true, assets: [] }
|
||||
: path.startsWith("/commits/") ? { sha: revision } : [{ name: version, commit: { sha: revision } }]);
|
||||
expect(await mirrorReadiness(source, read)).toEqual({ status: "ready", version, revision });
|
||||
expect(read.mock.calls.every(([path]) => path.startsWith("/releases/") || path.startsWith("/commits/") || path.startsWith("/tags?"))).toBe(true);
|
||||
});
|
||||
|
||||
test("a missing attachment in a published release and a conflicting tag fail rather than silently repairing identity", async () => {
|
||||
await expect(mirrorReadiness(source, async () => ({ ...mirror, assets: [] }))).rejects.toThrow("incomplete");
|
||||
await expect(mirrorSourceReady(version, revision, async (path: string) => path.startsWith("/commits/")
|
||||
? { sha: revision } : [{ name: version, commit: { sha: "c".repeat(40) } }])).rejects.toThrow("another source");
|
||||
});
|
||||
|
||||
test("a provider source archive cannot stand in for a published package", async () => {
|
||||
await expect(mirrorReadiness(source, async () => ({ ...mirror,
|
||||
assets: mirror.assets.map(asset => ({ ...asset, type: "source" })),
|
||||
}))).rejects.toThrow("incomplete");
|
||||
});
|
||||
|
||||
test("a truncated tag inventory fails after ten pages rather than claiming the source is absent", async () => {
|
||||
const read = vi.fn(async (path: string) => path.startsWith("/commits/") ? { sha: revision }
|
||||
: Array.from({ length: 100 }, (_, index) => ({ name: `other-${index}`, commit: { sha: revision } })));
|
||||
await expect(mirrorSourceReady(version, revision, read)).rejects.toThrow("exceeds 10 pages");
|
||||
expect(read).toHaveBeenCalledTimes(11);
|
||||
expect(read.mock.calls.at(-1)).toEqual(["/tags?per_page=100&page=10"]);
|
||||
});
|
||||
|
||||
test("readiness treats an unavailable API as failure, not pending synchronization", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 503 })));
|
||||
try { await expect(readMirror("/commits/" + revision)).rejects.toThrow("HTTP 503"); }
|
||||
finally { vi.unstubAllGlobals(); }
|
||||
});
|
||||
@@ -25,6 +25,13 @@ function api(source = run, latest = release) {
|
||||
beforeEach(() => { command.mockReset(); api(); });
|
||||
|
||||
describe("mirror source authority", () => {
|
||||
it("scheduled recovery finds the original completed main CI by published source", () => {
|
||||
const existing = command.getMockImplementation()!;
|
||||
command.mockImplementation((program: string, args: string[]) => args[1].includes("actions/workflows/")
|
||||
? JSON.stringify({ workflow_runs: [run] }) : existing(program, args));
|
||||
expect(resolveMirrorSource("", true)).toEqual({ run_id: "12345", version: release.tag_name, revision });
|
||||
expect(command.mock.calls.some(([, args]) => args[1].includes(`head_sha=${revision}`))).toBe(true);
|
||||
});
|
||||
it("binds automatic and manual retries to the published source run", () => {
|
||||
const expected = { run_id: "12345", version: release.tag_name, revision };
|
||||
expect(resolveMirrorSource("12345", true)).toEqual(expected);
|
||||
|
||||
Reference in new issue
Block a user