## Problem and outcome / 问题与结果 Bring Android into Piik's shared App workflow and make phone control usable without a separate Web UI. One signed APK covers ARM64 and x64; screen capture, room authority, routing, voice and site approval reuse the existing Go and Browser owners. Android opens the user's system browser rather than shipping an embedded browser. This phase also fixes capture replacement and encoding-clock failures, improves source-audio startup, contains recoverable input and transport failures, adds a bounded relay-volunteer setting and supports hostnames in `SFU_PUBLIC_IP`. The website separates desktop and mobile downloads, gives iOS users an online entry and aligns the bilingual installation guides. Related reports: #495, #499, #500, #501, #502 and #503. For #502, input execution failures now preserve authorization, and temporary target observations suspend rather than revoke it; the original Windows report remains open for candidate feedback. ## Release notes **Piik, now in your pocket.** Piik App now supports Android screen sharing, with touch controls for a friend's computer. **手机,也能开播。** Piik App 现已支持 Android 屏幕分享,也能用手机控制朋友的电脑。 ### English Piik v2.5.0 brings the App to Android and improves capture reliability, touch control and everyday startup. The existing 2.x compatibility baseline is unchanged. - **Android App:** share your screen, join room voice or control a supported computer. One APK supports ARM64 and x64, using your own browser and the same Piik interface. - **Phone controls:** use direct touch or a compact floating mouse with dragging, left/right buttons and a scroll wheel. Pinch to zoom and pan the picture while controlling. - **More reliable sharing:** keep video progressing through source and encoder-output changes, and improve low-bitrate recovery and stationary-screen keyframes. Correct Windows window-size handling and Linux NVENC settings; start optional source sound after video is ready. - **Smoother App entry:** retry failed startup in place, reopen the running room and retain the correct App connection when returning from the browser. Compress shared page assets to reduce loading traffic and keep microphone choices stable during ordinary page updates. - **Recovery stays local:** a rejected input or canceled source replacement no longer revokes remote-control permission. Full ICE candidate queues and failed audio-parameter updates retain healthy connections. A failed local room leaves the App and unrelated approved sites running. - **Connection settings:** relay volunteers can cap their downstream viewers. Self-hosted SFU setups can use a DNS hostname in `SFU_PUBLIC_IP`. - **Clearer help:** refine sharing-error guidance, preserve input-failure diagnostics without recording input content, and update the bilingual platform and network guides. Update both the App and your self-hosted site to use the new features. Android can control a supported computer; the Android device itself is not a controlled endpoint. If you previously installed a test APK, uninstall it once before installing this release: the official signing key is different. Uninstalling clears App-local site approvals and starred-site choices; browser settings remain in the browser. Later official releases can be installed over this one. ### 中文 Piik v2.5.0 带来 Android App,并改善采集稳定性、手机远控与日常启动体验。沿用现有 2.x 兼容基线。 - **Android App:** 分享手机画面、加入房间语音,或控制支持远控的电脑。一个安装包同时支持 ARM64 与 x64,使用自己的浏览器和熟悉的 Piik 界面。 - **手机远控:** 直接触摸操作,或展开小巧的悬浮鼠标,使用拖拽、左右键与滚轮;控制时也能双指缩放、移动画面。 - **分享更稳定:** 修复切换采集来源、编码输出时画面停止推进的问题,改善低码率恢复与静止画面的关键帧响应。修正 Windows 窗口尺寸处理和 Linux NVENC 设置,来源声音会在画面就绪后启动。 - **App 进出更顺畅:** 启动失败可原地重试,再次打开会回到正在运行的房间;从浏览器返回时保持连接到正确的 App。共用页面资源启用压缩,减少加载流量,麦克风选项不再随普通页面更新反复加载。 - **局部问题就地恢复:** 单次操作失败或取消换源不再撤销远控授权;ICE 候选队列满或音频参数调整失败时保留健康连接。本地房间故障不会连带停止 App 和其他已授权站点的分享。 - **连接设置:** 帮助转发的观众可设置承接人数上限;自部署 SFU 的 `SFU_PUBLIC_IP` 现在支持 DNS 主机名。 - **排查更直接:** 打磨分享失败提示,补充不记录输入内容的远控故障诊断,并更新中英文平台说明与网络指南。 使用新功能时,请一起更新 App 与自部署站点。Android 可作为控制端操作电脑,手机本身不作为被控端。 曾安装测试 APK 的用户需先卸载一次,再安装正式版,两者签名不同。卸载会清除 App 内的站点授权和收藏,浏览器设置仍保留在浏览器中;后续正式版可直接覆盖安装。 ## Verification / 验证 - Local full Web/type/build checks passed: 104 test files, 1,848 tests; the website and documentation builds passed. - Android full-App emulator acceptance covered real decoded screen sharing, concurrent 1080p/540p encoder allocation, live bitrate changes, stationary keyframes, Viewer departure, consent reuse/reentry and final capture-resource retirement. - A local universal release APK passed signing, package identity, version-code, ABI and non-debuggable checks using the permanent release key. GitHub Actions receives the same key through encrypted Secrets; manual candidate runs use a disposable candidate signer. - Windows real capture checks covered H264/VP8 window resizing and restoration. Source-audio startup and failure/close ordering passed focused runtime checks; Linux race checks passed. - Desktop/mobile website layouts were reviewed in English and Chinese, both themes, including grouped downloads, the iOS online entry and self-hosting links. - All three Server and six App candidate targets, including the signed Android universal APK, passed in https://github.com/TNTcraftHIM/Piik/actions/runs/40350004792. This uses the same release packaging path with publication disabled. - The complete network laboratory passed in https://github.com/TNTcraftHIM/Piik/actions/runs/40354253735: 43 expected scenario outcomes (37 media connections, six expected-unavailable controls), six negative controls, and complete process/network cleanup. - Recoverable-error checks cover real encrypted input replies and legacy opt-in, retained grants and held-key cleanup, real Windows target geometry recovery, candidate queue overflow, and audio-parameter retry on the existing edge. Android room failure and full shutdown use real launcher, control WebSocket and supervised-process checks; unrelated site resources remain intact. - The lifecycle fixes at `7eb04de373567cfe7aff2db6c93adf2a38e0b1aa` passed all nine package targets and Go/vulnerability/race/Web checks in https://github.com/TNTcraftHIM/Piik/actions/runs/40362794088, including macOS x64/ARM64 cgo and Android. Publication was skipped. - Final cross-review found and fixed the same candidate-overflow false failure in the SFU voice owner. Its real-Pion regression verifies the first 64 candidates remain queued, a valid answer drains them, and renegotiation succeeds. Independent reviews confirmed real SDP and authorization failures still propagate. - A real-browser before/after check reduced microphone enumeration from nine calls to one across eight ordinary Host rerenders. Changing the native client or switching to Browser capture still enumerates the new devices. The separate focused contribution #507 preserves input focus during queued floating-panel opening and is not attributed to this phase. - The verified Windows candidate and reproduction steps have been updated in #502. macOS/Linux physical-device coverage and iOS device acceptance keep their documented boundaries. ## Impact / 影响 - Planned release: **v2.5.0**; no public wire or storage version bump. - Android is a sharing and controlling endpoint, not a remotely controlled Android device. iOS is held outside this release. - New Android release target joins the existing complete-target, checksum, GitHub and Gitee artifact pipeline. Signing material stays outside Git; optional input SDKs/drivers are not bundled. - The owner authorized closure and publication after the final design review and acceptance checks. Restore the publication gate after the held focused contribution and merge this complete phase once; CI publishes only after its full checks and registered packages pass. - Current TODO, platform guidance, media/routing evidence and release operations retain their existing document owners; no additional audit ledger or changelog archive is introduced.
439 lines
15 KiB
Go
439 lines
15 KiB
Go
// Package app composes the shared HTTP service, site access, embedded assets,
|
|
// media listeners, and startup/shutdown lifecycle for Hosted Server and App.
|
|
//
|
|
// # Locking
|
|
//
|
|
// signal.Server owns the one mutex that guards the room store, the media router
|
|
// and every session. This package never takes it: everything a request can
|
|
// mutate goes through the signaling server. Server.mu below guards only this
|
|
// struct's own lifecycle bookkeeping.
|
|
//
|
|
// The lock order is one-directional: Server.mu may be held while the signaling
|
|
// mutex is taken (reconcile calls signal.New under it, and signal.New locks the
|
|
// server it is still building), never the reverse. Nothing reachable under the
|
|
// signaling mutex may take Server.mu, which is why the one callback this
|
|
// package hands to signal, SiteAccessAtUpgrade, only reads the lock-free
|
|
// site-access gate. Keep it that way or the two locks can deadlock.
|
|
package app
|
|
|
|
import (
|
|
"context"
|
|
"crypto/tls"
|
|
"errors"
|
|
"fmt"
|
|
"io/fs"
|
|
"log/slog"
|
|
"net"
|
|
"net/http"
|
|
"strconv"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/TNTcraftHIM/Piik/internal/diagnostics"
|
|
"github.com/TNTcraftHIM/Piik/internal/media/forwarding"
|
|
"github.com/TNTcraftHIM/Piik/internal/server/config"
|
|
"github.com/TNTcraftHIM/Piik/internal/server/room"
|
|
"github.com/TNTcraftHIM/Piik/internal/server/sfu"
|
|
"github.com/TNTcraftHIM/Piik/internal/server/signal"
|
|
"github.com/TNTcraftHIM/Piik/internal/server/stun"
|
|
"github.com/pion/ice/v4"
|
|
"github.com/pion/webrtc/v4"
|
|
)
|
|
|
|
// HTTP request, header and keep-alive deadlines.
|
|
const (
|
|
requestTimeout = 10 * time.Second
|
|
headersTimeout = 15 * time.Second
|
|
keepAliveTimeout = 5 * time.Second
|
|
)
|
|
|
|
// Options supplies service configuration and optional lifecycle dependencies.
|
|
type Options struct {
|
|
// Config is the loaded server configuration; cmd owns config.Load / Local.
|
|
Config config.Config
|
|
// Listeners transfers prebound HTTP/TLS sockets on successful New. The Local
|
|
// App serves its loopback and LAN entries through the same authority.
|
|
Listeners []net.Listener
|
|
// Assets is the built Browser UI. A nil FS serves the API only.
|
|
Assets fs.FS
|
|
// Now returns Unix milliseconds; nil uses the wall clock.
|
|
Now func() int64
|
|
// Logger receives the request-failure record; nil uses slog.Default().
|
|
Logger *slog.Logger
|
|
|
|
AuthenticationTimeoutMs int
|
|
ViewerDisconnectGraceMs int
|
|
HeartbeatIntervalMs int
|
|
MaxSignalConnections int
|
|
MaxUnauthenticatedSignalConnections int
|
|
SiteAccessTTLSeconds int
|
|
|
|
// AfterFunc is the signaling timer factory; nil uses time.AfterFunc.
|
|
AfterFunc func(time.Duration, func()) func() bool
|
|
// RoomStore replaces the store this package would build from Config.
|
|
RoomStore *room.Store
|
|
}
|
|
|
|
// Server owns one shared HTTP, room-authority and media service lifecycle.
|
|
type Server struct {
|
|
config config.Config
|
|
store *room.Store
|
|
siteAccess *siteAccessGate
|
|
frontend http.Handler
|
|
logger *slog.Logger
|
|
media *sfu.Media
|
|
mediaMux ice.UDPMux
|
|
signalOptions signal.Options
|
|
httpServer *http.Server
|
|
// Listen binds unless New received owned listeners. Shutdown waits for
|
|
// startupDone before reading them; closing before Listen also releases them.
|
|
listeners []net.Listener
|
|
// STUN shares the same startup/shutdown owner, never the advertised ICE URLs.
|
|
stunServer *stun.Server
|
|
|
|
// acceptingTraffic and signaling are read by request goroutines without
|
|
// a lock and written together under mu.
|
|
acceptingTraffic atomic.Bool
|
|
signaling atomic.Pointer[signal.Server]
|
|
|
|
mu sync.Mutex
|
|
closing bool
|
|
startupRequested bool
|
|
// startupDone is closed when listen settles, which is what shutdown awaits
|
|
// so the listener stays owned until an in-flight startup finishes.
|
|
startupDone chan struct{}
|
|
serveErr error
|
|
done chan error
|
|
|
|
shutdownOnce sync.Once
|
|
shutdownErr error
|
|
}
|
|
|
|
// New composes the service without binding sockets or opening the room database.
|
|
func New(options Options) (*Server, error) {
|
|
configuration := options.Config
|
|
now := options.Now
|
|
if now == nil {
|
|
now = func() int64 { return time.Now().UnixMilli() }
|
|
}
|
|
logger := options.Logger
|
|
if logger == nil {
|
|
logger = slog.Default()
|
|
}
|
|
|
|
store, err := newRoomStore(options)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
siteAccess, err := newSiteAccess(siteAccessOptions{
|
|
Password: configuration.SiteAccessPassword,
|
|
Secure: configuration.Env == config.EnvironmentProduction &&
|
|
configuration.PublicBaseURL.Scheme == "https",
|
|
Now: now,
|
|
TTLSeconds: options.SiteAccessTTLSeconds,
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
server := &Server{
|
|
config: configuration,
|
|
store: store,
|
|
siteAccess: siteAccess,
|
|
logger: logger,
|
|
startupDone: make(chan struct{}),
|
|
done: make(chan error, 1),
|
|
}
|
|
server.listeners = append([]net.Listener(nil), options.Listeners...)
|
|
if options.Assets != nil {
|
|
server.frontend = staticHandler(options.Assets, http.HandlerFunc(notFoundJSON))
|
|
}
|
|
server.signalOptions = signal.Options{
|
|
Store: store,
|
|
EndpointMediaCopyCapacity: configuration.EndpointMediaCopyCapacity,
|
|
SfuOnly: configuration.SFU != nil && configuration.SFU.Only,
|
|
Ice: config.IceConfig(configuration),
|
|
// The prediction capability is separate from the wire-shaped ICE settings.
|
|
NATPredictionEnabled: configuration.NATPredictionEnabled,
|
|
AllowedOrigins: configuration.AllowedOrigins,
|
|
SiteAccessAtUpgrade: func(request *http.Request) bool {
|
|
return server.siteAccessForRequest(request).isAuthenticated(cookieHeader(request))
|
|
},
|
|
PublicBaseURL: configuration.PublicBaseURL,
|
|
Now: now,
|
|
AuthenticationTimeoutMs: options.AuthenticationTimeoutMs,
|
|
ViewerDisconnectGraceMs: options.ViewerDisconnectGraceMs,
|
|
HeartbeatIntervalMs: options.HeartbeatIntervalMs,
|
|
RoomEmptyTimeoutMs: int64(configuration.RoomEmptyTimeoutSeconds) * 1_000,
|
|
MaxConnections: options.MaxSignalConnections,
|
|
MaxUnauthenticatedConnections: options.MaxUnauthenticatedSignalConnections,
|
|
AfterFunc: options.AfterFunc,
|
|
Logger: logger,
|
|
}
|
|
server.httpServer = &http.Server{
|
|
Handler: server,
|
|
ErrorLog: slog.NewLogLogger(logger.Handler(), slog.LevelDebug),
|
|
ReadHeaderTimeout: headersTimeout,
|
|
ReadTimeout: requestTimeout,
|
|
IdleTimeout: keepAliveTimeout,
|
|
// No WriteTimeout: a fixed deadline would cut long asset downloads.
|
|
}
|
|
return server, nil
|
|
}
|
|
|
|
// newRoomStore uses the injected store or creates one from configuration.
|
|
// An empty RoomDatabasePath selects memory-only authority.
|
|
func newRoomStore(options Options) (*room.Store, error) {
|
|
if options.RoomStore != nil {
|
|
return options.RoomStore, nil
|
|
}
|
|
var database *room.Database
|
|
if options.Config.RoomDatabasePath != "" {
|
|
// The file is opened by store.Initialize, not here: a failed bind must
|
|
// leave no database behind.
|
|
opened, err := room.NewDatabase(options.Config.RoomDatabasePath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
database = opened
|
|
}
|
|
return room.New(room.Options{
|
|
MaxRooms: room.Capacity,
|
|
MaxViewersPerRoom: options.Config.MaxViewersPerRoom,
|
|
Database: database,
|
|
Now: options.Now,
|
|
})
|
|
}
|
|
|
|
// Done reports the first unexpected HTTP listener failure. Normal Close/End
|
|
// leave it silent; owners also observe their own cancellation/lifetime signal.
|
|
func (s *Server) Done() <-chan error { return s.done }
|
|
|
|
// Listen binds application sockets before recovering room authority and accepting traffic.
|
|
func (s *Server) Listen(ctx context.Context) (int, error) {
|
|
s.mu.Lock()
|
|
if s.startupRequested {
|
|
s.mu.Unlock()
|
|
return 0, errors.New("Piik server startup was already requested")
|
|
}
|
|
if s.closing {
|
|
s.mu.Unlock()
|
|
return 0, errors.New("Piik server is closing")
|
|
}
|
|
s.startupRequested = true
|
|
s.mu.Unlock()
|
|
|
|
// Release the startup latch even when start panics, so a later Close
|
|
// cannot wait forever for startup to finish.
|
|
defer close(s.startupDone)
|
|
return s.start(ctx)
|
|
}
|
|
|
|
func (s *Server) start(ctx context.Context) (int, error) {
|
|
var publicIP string
|
|
if s.config.SFU != nil {
|
|
var err error
|
|
publicIP, err = resolveSFUPublicIP(ctx, s.config.SFU.PublicIP)
|
|
if err != nil {
|
|
_ = s.stopServing(ctx)
|
|
return 0, err
|
|
}
|
|
}
|
|
// Bind first. A listener owned by another process must fail before
|
|
// the room database is opened.
|
|
var err error
|
|
if len(s.listeners) == 0 {
|
|
address := net.JoinHostPort(s.config.ListenHost, strconv.Itoa(s.config.Port))
|
|
listener, err := net.Listen("tcp", address)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if s.config.TLS != nil {
|
|
listener = tls.NewListener(listener, s.config.TLS)
|
|
}
|
|
s.listeners = []net.Listener{listener}
|
|
}
|
|
if len(s.config.STUNListenAddresses) > 0 {
|
|
s.stunServer, err = stun.Listen(ctx, s.config.STUNListenAddresses)
|
|
if err != nil {
|
|
for _, listener := range s.listeners {
|
|
_ = listener.Close()
|
|
}
|
|
return 0, fmt.Errorf("Piik STUN listener failed: %w", err)
|
|
}
|
|
}
|
|
if configuration := s.config.SFU; configuration != nil {
|
|
connection, listenErr := net.ListenPacket("udp4", net.JoinHostPort(configuration.ListenHost, strconv.Itoa(configuration.Port)))
|
|
if listenErr != nil {
|
|
_ = s.stopServing(ctx)
|
|
return 0, fmt.Errorf("Piik SFU listener failed: %w", listenErr)
|
|
}
|
|
factory := diagnostics.PionLoggerFactory()
|
|
s.mediaMux = forwarding.NewUDPMux(ice.UDPMuxParams{UDPConn: connection, Logger: factory.NewLogger("sfu-udp")})
|
|
settings := webrtc.SettingEngine{LoggerFactory: factory}
|
|
settings.SetNetworkTypes([]webrtc.NetworkType{webrtc.NetworkTypeUDP4})
|
|
settings.SetICEUDPMux(s.mediaMux)
|
|
settings.SetIncludeLoopbackCandidate(net.ParseIP(configuration.ListenHost).IsLoopback())
|
|
if publicIP != "" {
|
|
settings.SetNAT1To1IPs([]string{publicIP}, webrtc.ICECandidateTypeHost)
|
|
}
|
|
s.media = sfu.NewMedia(sfu.MediaOptions{Settings: settings, Events: func(event sfu.MediaEvent) {
|
|
if signaling := s.signaling.Load(); signaling != nil {
|
|
signaling.HandleSfuMediaEvent(event)
|
|
}
|
|
}})
|
|
s.signalOptions.SfuFallback = &signal.SfuFallback{Media: s.media, Admission: sfu.NewAdmission(sfu.AdmissionOptions{
|
|
IngressCapacity: room.Capacity, EgressCapacity: room.Capacity * s.config.MaxViewersPerRoom,
|
|
})}
|
|
}
|
|
for _, listener := range s.listeners {
|
|
go func() {
|
|
// Report permanent accept failures so an unexpectedly stopped HTTP
|
|
// listener is visible to the operator.
|
|
if err := s.httpServer.Serve(listener); !errors.Is(err, http.ErrServerClosed) {
|
|
s.mu.Lock()
|
|
if !s.closing && s.serveErr == nil {
|
|
s.serveErr = fmt.Errorf("Piik HTTP listener stopped unexpectedly: %w", err)
|
|
s.acceptingTraffic.Store(false)
|
|
s.done <- s.serveErr
|
|
}
|
|
s.mu.Unlock()
|
|
s.logger.Error("Piik HTTP server stopped unexpectedly", "errorType", fmt.Sprintf("%T", err))
|
|
s.logger.Debug("http-listener-failed", diagnostics.Error(err))
|
|
}
|
|
}()
|
|
}
|
|
port := s.listeners[0].Addr().(*net.TCPAddr).Port
|
|
|
|
if err := s.reconcile(); err != nil {
|
|
// Give the database and the listener back before reporting.
|
|
var cleanup []error
|
|
if closeErr := s.store.Close(); closeErr != nil {
|
|
cleanup = append(cleanup, closeErr)
|
|
}
|
|
if closeErr := s.stopServing(ctx); closeErr != nil {
|
|
cleanup = append(cleanup, closeErr)
|
|
}
|
|
if len(cleanup) > 0 {
|
|
return 0, fmt.Errorf("Piik startup reconciliation failed: %w",
|
|
errors.Join(append([]error{err}, cleanup...)...))
|
|
}
|
|
return 0, err
|
|
}
|
|
return port, nil
|
|
}
|
|
|
|
// stopServing releases the application-owned HTTP and STUN sockets. Shutdown
|
|
// stops accepting HTTP and drains, but it can lose the race against the Serve
|
|
// goroutine registering the listener, in
|
|
// which case it returns without having closed the bound socket; closing the
|
|
// listener afterwards makes the port release synchronous. A second close of an
|
|
// already closed HTTP listener is harmless.
|
|
func (s *Server) stopServing(ctx context.Context) error {
|
|
err := s.httpServer.Shutdown(ctx)
|
|
for _, listener := range s.listeners {
|
|
_ = listener.Close()
|
|
}
|
|
if s.stunServer != nil {
|
|
err = errors.Join(err, s.stunServer.Close())
|
|
s.stunServer = nil
|
|
}
|
|
if s.media != nil {
|
|
err = errors.Join(err, s.media.Close())
|
|
s.media = nil
|
|
}
|
|
if s.mediaMux != nil {
|
|
err = errors.Join(err, s.mediaMux.Close())
|
|
s.mediaMux = nil
|
|
}
|
|
return err
|
|
}
|
|
|
|
// reconcile restores room authority and enables traffic unless shutdown has begun.
|
|
func (s *Server) reconcile() error {
|
|
if err := s.store.Initialize(); err != nil {
|
|
return err
|
|
}
|
|
// Serialize publication with shutdown; once closing is set, startup must
|
|
// never re-enable traffic.
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.closing {
|
|
return nil
|
|
}
|
|
if s.serveErr != nil {
|
|
return s.serveErr
|
|
}
|
|
signaling, err := signal.New(s.signalOptions)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
s.signaling.Store(signaling)
|
|
s.acceptingTraffic.Store(true)
|
|
return nil
|
|
}
|
|
|
|
// Close stops accepting traffic, closes signaling, the HTTP/STUN listeners and
|
|
// the room store, and leaves the rooms in place. Hosted restarts use it.
|
|
func (s *Server) Close(ctx context.Context) error {
|
|
return s.shutdown(ctx, false)
|
|
}
|
|
|
|
// End is Close preceded by ending every room. The Local App uses it, because its
|
|
// authority dies with the process.
|
|
func (s *Server) End(ctx context.Context) error {
|
|
return s.shutdown(ctx, true)
|
|
}
|
|
|
|
// Every shutdown caller joins the first operation and receives the same result.
|
|
func (s *Server) shutdown(ctx context.Context, endRooms bool) error {
|
|
s.shutdownOnce.Do(func() { s.shutdownErr = s.runShutdown(ctx, endRooms) })
|
|
return s.shutdownErr
|
|
}
|
|
|
|
func (s *Server) runShutdown(ctx context.Context, endRooms bool) error {
|
|
// Stop traffic, mark closing, then wait for an in-flight startup.
|
|
s.mu.Lock()
|
|
s.acceptingTraffic.Store(false)
|
|
s.closing = true
|
|
awaitStartup := s.startupRequested
|
|
s.mu.Unlock()
|
|
if awaitStartup {
|
|
// The listen caller owns the startup error; shutdown only waits.
|
|
<-s.startupDone
|
|
}
|
|
|
|
var failures []error
|
|
signaling := s.signaling.Load()
|
|
if endRooms {
|
|
failures = append(failures, s.endAllRooms(signaling))
|
|
}
|
|
if signaling != nil {
|
|
failures = append(failures, signaling.Close(ctx))
|
|
}
|
|
// The signaling server must be closed before the listener: its connections
|
|
// live on it.
|
|
failures = append(failures, s.stopServing(ctx))
|
|
if signaling != nil {
|
|
failures = append(failures, signaling.CloseStorage())
|
|
} else {
|
|
failures = append(failures, s.store.Close())
|
|
}
|
|
if joined := errors.Join(failures...); joined != nil {
|
|
return fmt.Errorf("Piik server shutdown failed: %w", joined)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Without signaling no participant is connected, so room authority can be
|
|
// retired directly; otherwise signaling owns participant and media teardown.
|
|
func (s *Server) endAllRooms(signaling *signal.Server) error {
|
|
if signaling != nil {
|
|
return signaling.EndAllRooms()
|
|
}
|
|
_, err := s.store.AbandonAllRooms()
|
|
return err
|
|
}
|