Files
piik/internal/app/portmapping/mapping_test.go
T
AAA 02e71621f2 feat(deploy): ship Server containers and repair NAT-PMP mappings (#400)
## Problem and outcome / 问题与结果

Self-hosting currently requires assembling a Server installation, while App port mappings can use the wrong external port or remain active after cancellation. This phase adds a verified Linux x64 Server image and Compose recipe, and repairs the existing NAT-PMP dependencies so mapping results, cancellation and cleanup follow the gateway response and request lifetime.

The image wraps the exact verified Server archive and is tested before publication. Version tags retain their original image; `latest` follows the latest published GitHub release. The two scoped dependency replacements retain upstream source, tests and licenses, with their removal criteria documented in `internal/thirdparty/README.md`.

Planned release: **v1.3.0** (compatible Docker distribution feature plus NAT fixes).

## Release notes

### 中文

- 新增 Linux x64 Docker 镜像与 Compose 部署方式,内置网页、信令和 STUN,可按需开启 SFU 兜底。提供部署、更新与备份教程。
- 修复 App 的 NAT-PMP 端口映射:正确使用路由器分配的外部端口,并在关闭时尝试删除映射。
- NAT-PMP 请求会随取消或超时结束,避免连接尝试结束后继续在后台重试。

已有配置和房间数据格式保持兼容,更新无需迁移。

### English

- Added a Linux x64 Docker image and Compose setup with the Web UI, signaling, STUN and optional SFU fallback, plus deployment, update and backup guides.
- Fixed App NAT-PMP mappings to use the external port assigned by the router and attempt mapping removal on shutdown.
- NAT-PMP requests now stop on cancellation or timeout, preventing retries from continuing after a connection attempt has ended.

Existing configuration and room data formats remain compatible; no migration is required.

## Verification / 验证

[Candidate CI](https://github.com/TNTcraftHIM/Piik/actions/runs/34761969362) passed for `1d8de6c4690434cd2cf44fbdee4f45b1776432fa`. The final two files changed after that run are documentation only (`docs/todo.md` and `docs/verification-status.md`), with repository hygiene checked separately.

- Web type checks, unit tests and production build; Go core tests, vet and target builds; NAT and media-edge race detection.
- Actual packaged-image checks with Docker Compose: production startup, embedded Web, UDP STUN, optional SFU startup, retained room authority across recreation, diagnostic ZIP export, non-root/read-only execution and clean shutdown.
- Windows x64, Linux x64 and macOS arm64 App packaging.
- Scoped NAT dependency regressions cover assigned ports, renewal, deletion, cancellation, lost replies and PCPv6 composition using real local UDP endpoints.

The publishing pipeline reruns the image checks for the merged release revision. First publication also requires making the GHCR package public and checking anonymous pulls of its version and `latest` tags. Representative physical routers, public-media networks and operator-specific HTTPS/firewall settings remain outside the container smoke test.

## Impact / 影响

No signaling, native-control or storage-format change. Existing App/Server installations remain compatible. Docker supports `linux/amd64` in this phase; its default is P2P, and SFU remains an explicit deployment option. Existing deployments keep their configuration.

README, bilingual self-hosting guides, container maintenance, versioning, dependency provenance and NAT evidence are updated. Completed feedback is removed from TODO; ongoing network evidence remains tracked there.
2026-09-13 23:09:14 +08:00

214 lines
5.4 KiB
Go

package portmapping
import (
"context"
"errors"
"sync"
"testing"
"time"
)
type fakeGateway struct {
mu sync.Mutex
added []int
deleted []int
addErr error
block chan struct{}
}
func (gateway *fakeGateway) AddPortMapping(
_ context.Context,
_ string,
port int,
_ string,
_ time.Duration,
) (int, error) {
gateway.mu.Lock()
gateway.added = append(gateway.added, port)
block := gateway.block
addErr := gateway.addErr
gateway.mu.Unlock()
if block != nil {
// Exercise the caller's bound even if a gateway fails to observe context.
<-block
}
if addErr != nil {
return 0, addErr
}
return port + 1, nil
}
func (gateway *fakeGateway) DeletePortMapping(
_ context.Context,
_ string,
port int,
) error {
gateway.mu.Lock()
defer gateway.mu.Unlock()
gateway.deleted = append(gateway.deleted, port)
return nil
}
func TestMappingCreatesOnceAndReleases(t *testing.T) {
original := discoverGateway
t.Cleanup(func() { discoverGateway = original })
fake := &fakeGateway{}
discoverGateway = func(context.Context) (gateway, error) {
return fake, nil
}
mapping := Start(43210)
if port := mapping.Prepare(); port != 43211 {
t.Fatalf("mapped port = %d, want 43211", port)
}
if port := mapping.Prepare(); port != 43211 {
t.Fatalf("cached mapped port = %d, want 43211", port)
}
mapping.Close()
mapping.Close()
fake.mu.Lock()
defer fake.mu.Unlock()
if len(fake.added) != 1 || fake.added[0] != 43210 {
t.Fatalf("added ports = %v, want [43210]", fake.added)
}
if len(fake.deleted) != 1 || fake.deleted[0] != 43210 {
t.Fatalf("deleted ports = %v, want [43210]", fake.deleted)
}
}
func TestMappingAbsenceLeavesICEAvailable(t *testing.T) {
original := discoverGateway
t.Cleanup(func() { discoverGateway = original })
discoverGateway = func(context.Context) (gateway, error) {
return nil, errors.New("no mapping service")
}
mapping := Start(43210)
mapping.Prepare()
mapping.Close()
}
func TestMappingFailureIsNotRetriedForEveryEdge(t *testing.T) {
original := discoverGateway
t.Cleanup(func() { discoverGateway = original })
fake := &fakeGateway{addErr: errors.New("mapping rejected")}
discoverGateway = func(context.Context) (gateway, error) {
return fake, nil
}
mapping := Start(43210)
mapping.Prepare()
mapping.Prepare()
mapping.Close()
fake.mu.Lock()
defer fake.mu.Unlock()
if len(fake.added) != 1 || len(fake.deleted) != 1 {
t.Fatalf("mapping calls = add %v delete %v", fake.added, fake.deleted)
}
}
func TestMappingAttemptStaysBoundedWhenTheClientIgnoresContext(t *testing.T) {
original := discoverGateway
t.Cleanup(func() { discoverGateway = original })
fake := &fakeGateway{block: make(chan struct{})}
discoverGateway = func(context.Context) (gateway, error) {
return fake, nil
}
t.Cleanup(func() { close(fake.block) })
mapping := Start(43210)
started := time.Now()
if port := mapping.Prepare(); port != 0 {
t.Fatalf("mapped port = %d, want 0 for an unanswered attempt", port)
}
if elapsed := time.Since(started); elapsed > attemptTimeout+2*time.Second {
t.Fatalf("Prepare blocked %v, want within the attempt bound", elapsed)
}
mapping.Close()
}
func TestCloseSkipsDeleteWhileAnAttemptIsStillAbandoned(t *testing.T) {
original := discoverGateway
t.Cleanup(func() { discoverGateway = original })
fake := &fakeGateway{}
discoverGateway = func(context.Context) (gateway, error) {
return fake, nil
}
mapping := Start(43210)
if port := mapping.Prepare(); port != 43211 {
t.Fatalf("mapped port = %d, want 43211", port)
}
mapping.mu.Lock()
mapping.renewAfter = time.Now().Add(-time.Second)
mapping.mu.Unlock()
fake.mu.Lock()
fake.block = make(chan struct{})
fake.mu.Unlock()
t.Cleanup(func() { close(fake.block) })
// The renewal attempt is abandoned after attemptTimeout while the fake
// keeps ignoring the context. Close must stay bounded and must not race
// the dependency's still-running call with a Delete.
mapping.Prepare()
started := time.Now()
mapping.Close()
if elapsed := time.Since(started); elapsed > 2*deleteTimeout+time.Second {
t.Fatalf("Close blocked %v, want a brief bounded wait", elapsed)
}
fake.mu.Lock()
defer fake.mu.Unlock()
if len(fake.added) != 2 || len(fake.deleted) != 0 {
t.Fatalf("mapping calls = add %v delete %v, want the Delete skipped",
fake.added, fake.deleted)
}
}
func TestRenewalFailureKeepsTheOriginalMappingOwnedUntilClose(t *testing.T) {
original := discoverGateway
t.Cleanup(func() { discoverGateway = original })
fake := &fakeGateway{}
discoverGateway = func(context.Context) (gateway, error) {
return fake, nil
}
mapping := Start(43210)
mapping.Prepare()
mapping.mu.Lock()
mapping.renewAfter = time.Now().Add(-time.Second)
mapping.mu.Unlock()
fake.mu.Lock()
fake.addErr = errors.New("renewal rejected")
fake.mu.Unlock()
mapping.Prepare()
mapping.Close()
fake.mu.Lock()
defer fake.mu.Unlock()
if len(fake.added) != 2 || len(fake.deleted) != 1 || fake.deleted[0] != 43210 {
t.Fatalf("mapping calls = add %v delete %v", fake.added, fake.deleted)
}
}
func TestMappingDiscoveryStopsWithTheShare(t *testing.T) {
original := discoverGateway
t.Cleanup(func() { discoverGateway = original })
discoverGateway = func(ctx context.Context) (gateway, error) {
<-ctx.Done()
return nil, ctx.Err()
}
mapping := Start(43210)
done := make(chan struct{})
go func() {
mapping.Close()
close(done)
}()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("mapping close did not cancel discovery")
}
}