Compare commits

...
1 Commits
  • fix(rooms): reclaim empty rooms on public sites (#456)
    Public sites can exhaust the four-digit room-code pool because retained room authority has no default expiry. Add an opt-in empty-room timeout and reclaim the oldest eligible empty room when capacity is exhausted. Connected Hosts and Viewers retain their rooms through sharing, pause and idle chat; the existing reconnect grace protects early reclamation.
    
    The default remains disabled, including App Local and the internal deployment. The public Demo will use `ROOM_EMPTY_TIMEOUT_SECONDS=3600`. Retirement reuses the storage-first deletion and signaling cleanup owners; no protocol or SQLite schema changes are required.
    
    Validation: Web type-check, 81 test files / 1372 tests and production build; Go core tests, formatting, vet and target builds; documentation/project hygiene; access-privacy gate; live server expiry/occupied-room check. Regression coverage includes all 9000 codes, restart, stale credentials, reconnects, revocation and atomic storage failure. Native device behavior is unchanged; physical macOS/Linux acceptance retains its documented limits.
    
    ## Release notes
    
    ### 中文
    
    这是一次面向公共站点的维护更新,解决长期保留的空房间占满房间号的问题。
    
    - 管理员可配置空房间回收时长;号码用满时,优先回收过期空房间,再按创建顺序回收符合条件的空房间。在线分享、暂停和聊天均会保留。
    - 房间号确实已用满时,界面会显示更明确的提示。
    - 自动回收默认关闭。公共站点可设置 `ROOM_EMPTY_TIMEOUT_SECONDS=3600`,在房间连续无人在线一小时后回收;未配置的站点保持原有行为。
    
    ### English
    
    This maintenance release helps public sites avoid exhausting room codes through indefinitely retained empty rooms.
    
    - Operators can configure an empty-room timeout. When all codes are in use, allocation reclaims expired empty rooms first, then the oldest eligible empty room. Connected sharing, paused sessions and chat remain protected.
    - Capacity errors now provide clearer guidance when no room code is available.
    - Automatic reclamation is disabled by default. Public sites can set `ROOM_EMPTY_TIMEOUT_SECONDS=3600` to retire rooms after one continuous hour with no connected participants. Unconfigured sites retain their existing behavior.
30 changed files with 678 additions and 77 deletions

No files matched your search

+4
View File
@@ -16,6 +16,10 @@ SITE_ACCESS_PASSWORD=
# should use an access-restricted absolute path outside the release directory,
# preserving the existing database and its writable parent across updates.
ROOM_DATABASE_PATH=
# Optional empty-room recycling. 0 keeps rooms indefinitely (default).
# 3600 expires rooms after an hour with no authenticated participants; when
# all codes are used, the oldest empty room may be reclaimed earlier.
ROOM_EMPTY_TIMEOUT_SECONDS=0
# Viewers per room, excluding the Host. Valid range: 1..20; default: 20.
MAX_VIEWERS_PER_ROOM=20
# Bounded standard-WebRTC relay/SFU controller is active for every room.
+3
View File
@@ -4,6 +4,9 @@ STUN_URLS=stun:share.example.com:3478
MAX_VIEWERS_PER_ROOM=20
# Empty means the site opens without a site password. Room access is separate.
SITE_ACCESS_PASSWORD=
# Optional for public sites: reclaim empty rooms after an hour, or earlier
# under room-code pressure. Unset/0 preserves room authority indefinitely.
# ROOM_EMPTY_TIMEOUT_SECONDS=3600
# Optional automatic media fallback: set BOTH values and allow UDP 7882.
# SFU_UDP_PORT=7882
@@ -28,11 +28,15 @@ Every room owns:
- a monotonically increasing Viewer authorization generation;
- `open | private` code entry and optional salted scrypt password material.
Room authority has no time limit. Stop, disconnect and inactivity do not change
it. Explicit replacement or deletion invalidates its credentials and releases
the code; grant rotation or revocation retires the invitation independently.
There is no lease, renewal, expiry timer or replacement garbage collector.
The existing 9,000-code bound remains; a full store rejects new rooms.
Room authority has no time limit by default. Explicit replacement or deletion
invalidates its credentials and releases the code; grant rotation or revocation
retires the invitation independently. Public sites may opt into the
[empty-room retention policy](../standards/rooms-access.md#optional-empty-room-retention)
to keep abandoned allocations from exhausting the 9,000-code space. Occupancy,
including idle chat, protects a room; the existing signaling heartbeat owns
expiry and normal retirement owns cleanup. There is no client lease or renewal.
The allocation bound remains; a full store rejects creation when no empty room
is reclaimable.
Site-access cookies retain their separate 24-hour rolling idle lifetime.
### Lightweight And Stable Storage
@@ -126,8 +130,10 @@ returns `ROOM_ACCESS_DENIED`.
- Both modes pass the same creation, ownership, admission, password,
rotate/revoke, replacement and 9,000-code-capacity behavior.
- Inactivity cannot invalidate room authority. Stable restart preserves it
exactly and restores no participant or media authority.
- Default inactivity cannot invalidate room authority. Opt-in retention only
retires empty rooms, commits storage first and cleans up all transient effects.
Stable restart preserves authority, restarts the empty interval and restores
no participant or media authority.
- A surviving Host and Viewer can reauthenticate after restart, receive fresh
sessions/routes, and recommit media; an old revoked grant stays revoked.
- Replacement never returns the old code, never partially retires the old room,
@@ -142,4 +148,5 @@ returns `ROOM_ACCESS_DENIED`.
- [`modernc.org/sqlite` driver](https://pkg.go.dev/modernc.org/sqlite)
- [SQLite transactional guarantees](https://www.sqlite.org/transactional.html)
- [SQLite locking mode](https://sqlite.org/pragma.html#pragma_locking_mode)
- [LiveKit room lifecycle timeouts](https://docs.livekit.io/reference/other/roomservice-api/)
- [LiveKit reconnect behavior](https://docs.livekit.io/intro/basics/connect/#network-changes-and-reconnection)
+2 -1
View File
@@ -12,8 +12,9 @@ collect a diagnostic report if the problem persists.
| App startup fails, or no page opens automatically | Read the reason on the page and in the terminal. If the App is still running, copy its address into your browser. See [App diagnostics](../../cmd/piik-app/README.md#diagnostics) to collect a report; if Local mode lists several addresses, choose an adapter and IP on the launch page. |
| Public invitation fails to start, or a link shows 1033 | Check the host's App and current link using [public invitation troubleshooting](#public-invitation-fails-or-shows-1033). |
| Local invitation will not open | Check that both devices are on the same network and can reach each other. Guest Wi-Fi or firewall rules can block local access. |
| Room code says the room does not exist | Codes work only on the site where the room was created. Open the host's full invitation link; see [joining a room](./getting-started.md#join-a-friends-room). |
| Room code says the room does not exist | Open the host's current full invitation link. Codes work only on their original site; a site with empty-room recycling may also have reclaimed it. The host can create a new room; see [joining a room](./getting-started.md#join-a-friends-room). |
| Cannot create a room (403) | On a self-hosted site, ask the administrator to check the [allowed site address](#room-creation-returns-403). |
| All room codes are in use | Retry later or use another Piik site. Administrators can enable [empty-room retention](../operations/self-hosting.md#1-configure-and-start-piik) to reclaim unused codes. This is separate from the per-room Viewer limit. |
| No screen picker | Allow the browser or App to record the screen when the OS asks. Browser capture needs HTTPS or `localhost`; try sharing from a desktop computer. |
| No App windows or screens listed | Check the message in the source picker, then follow [App source troubleshooting](#app-windows-or-screens-are-missing). **Browser** → **Choose what to share** opens the browser's screen, window or tab chooser. |
| Sharing fails after selecting a source | Click the error icon below the TV for details and guidance, then follow [sharing startup checks](#sharing-does-not-start-after-source-selection). |
+2 -1
View File
@@ -12,8 +12,9 @@
| App 启动失败,或没有自动打开网页 | 查看页面和终端中的原因;App 仍在运行时可复制终端中的地址打开。按 [App 运行与诊断说明](../../cmd/piik-app/README.zh-CN.md#诊断)收集报告;本地模式提示多个地址时,在启动页选择网卡和 IP。 |
| 公网邀请创建失败,或打开链接出现 1033 | 按[公网邀请排查](#公网邀请创建失败或出现-1033)检查房主 App 和当前链接。 |
| 本地邀请打不开 | 确认两台设备在同一网络且可以互相访问。访客 Wi-Fi 或防火墙规则可能阻止本地连接。 |
| 输入房间号后提示房间不存在 | 房间号只在创建它的站点有效。优先打开房主发送的完整邀请链接,参阅[加入房间](./getting-started.zh-CN.md#加入朋友的房间)。 |
| 输入房间号后提示房间不存在 | 先打开房主最新的完整邀请链接。房间号只在原站点有效;站点开启空房间回收时,旧房间也可能已被回收,由房主重新创建即可。参阅[加入房间](./getting-started.zh-CN.md#加入朋友的房间)。 |
| 无法创建房间 (403) | 自建站点请联系管理员检查[允许访问的站点地址](#创建房间返回-403)。 |
| 站点房间号已用满 | 稍后重试或使用其他 Piik 站点;管理员可配置[空房间回收](../operations/self-hosting.zh-CN.md#1-配置并启动-piik)。这与单个房间的观众人数上限不同。 |
| 没有屏幕选择弹窗 | 按系统提示允许浏览器或 App 录制屏幕。浏览器采集需要 HTTPS 或 `localhost`,请在电脑上尝试分享。 |
| App 的窗口或屏幕列表为空 | 先查看选源器中的提示,再按 [App 来源排查](#app-找不到窗口或屏幕) 操作;也可以选 **浏览器** → **选择画面**,在浏览器弹窗中选择屏幕、窗口或标签页。 |
| 选源后提示分享失败 | 点击电视下方的错误图标查看原因和排查入口,按[分享启动排查](#选源后无法开始分享)逐步对照。 |
+6
View File
@@ -100,6 +100,12 @@ cause [403 when creating a room](../guide/troubleshooting.md#room-creation-retur
resources. See [room capacity](../standards/configuration.md#room-capacity)
for defaults and the difference from App rooms.
For a public site, optionally set `ROOM_EMPTY_TIMEOUT_SECONDS=3600` and restart.
Rooms with nobody connected are reclaimed after an hour; if all room codes are
used, the oldest empty room can be reclaimed earlier. Occupied rooms keep working.
Reclaimed rooms need new invitations. Unset or `0` keeps the default indefinite
retention; see [room retention](../standards/configuration.md#room-retention).
### 2. Enable HTTPS
Use your existing HTTPS reverse proxy to forward to `127.0.0.1:8787` with
+5
View File
@@ -92,6 +92,11 @@ SITE_ACCESS_PASSWORD=
人数越多,对网络和转发资源的需求也可能增加。默认值及 App 房间的区别见
[人数限制](../standards/configuration.md#room-capacity)。
公开站点可选设 `ROOM_EMPTY_TIMEOUT_SECONDS=3600`,重启后,无人在线的房间会在空置一小时后
回收;房间号用满时,会提前回收最早创建的空房间,仍有人在线的房间不受影响。
被回收的房间需要重新创建并发送邀请。不设置或设为 `0` 则保持默认的长期保留行为,
详见[房间保留策略](../standards/configuration.md#room-retention)。
### 2. 配置 HTTPS
如果已有 HTTPS 反向代理,将请求转发到 `127.0.0.1:8787`,并启用 WebSocket 支持。
+5 -4
View File
@@ -1,6 +1,6 @@
# Project Memory
Last updated: 2026-10-01
Last updated: 2026-10-06
Piik is private, low-latency screen sharing for one Host and up to 20
authenticated friends. The current product surface is Web Host, Web Viewer, and
@@ -60,9 +60,10 @@ implementation and routine UI detail.
- Rooms use random four-digit codes, exact Host ownership, room-scoped Viewer
invitations and independent `open | private` code entry. Room authority ends
through explicit replacement/deletion, with separate invitation rotation or
revocation. Hosted defaults to SQLite, with explicit process-memory opt-out;
App Local remains process-only. Site access has a separate 24-hour idle
through replacement/deletion, with separate invitation rotation or revocation.
Hosted operators may opt into empty-room expiry and capacity reclamation;
the default retains rooms indefinitely. Hosted defaults to SQLite, with explicit
process-memory opt-out; App Local remains process-only. Site access has a separate 24-hour idle
cookie lifetime within one service run. Production persists SQLite room
authority; live participants, routes, and media remain process-only.
- Media is automatic and distributed. Ordinary peers are STUN-only and prefer
+5 -2
View File
@@ -13,7 +13,9 @@ code-entry policy and password verifier. It is not a generic
store for future features.
Hosted defaults to SQLite over the same RoomStore contract. Process-only mode
remains an explicit composition; neither mode needs time-based room expiry.
remains an explicit composition. Persistence is independent of the optional
[empty-room retention policy](../standards/rooms-access.md#optional-empty-room-retention):
the default keeps authority indefinitely; public sites may reclaim abandoned codes.
## Stored Authority
@@ -92,7 +94,8 @@ compatibility path. The completed cutover is retained in Git; current
2. Stable restart preserves code, token/grant validation, password, policy,
generation while restoring zero participants or media state.
3. A grant revoked before restart remains revoked afterward.
4. Presence and elapsed time do not mutate durable authority.
4. Default presence and elapsed time do not mutate durable authority; opt-in
retention retires only empty rooms and resets the empty interval on restart.
5. Explicit deletion/replacement releases codes; the allocation bound is unchanged.
6. Corrupt/mismatched/multiply owned state fails before accepting traffic.
7. Surviving Host/Viewer tabs reauthenticate and rebuild a fresh route; no test
+12 -2
View File
@@ -27,6 +27,7 @@ service secret store or an untracked access-restricted environment file.
| `ALLOWED_ORIGINS` | Unset or empty follows `PUBLIC_BASE_URL`. A non-empty comma-separated list replaces that default; include every trusted browser origin (scheme, host and port). Wildcard is invalid. |
| `SITE_ACCESS_PASSWORD` | Optional in every environment. Unset or empty allows entry without a site password. A configured value is matched exactly, including spaces and Unicode; there are no password length or character rules. General HTTP request limits still apply. Room ownership and Viewer admission remain independent. |
| `ROOM_DATABASE_PATH` | Hosted defaults to `rooms.sqlite` in its working directory when unset or blank. An explicit absolute file path selects another SQLite file; `:memory:` opts into process-memory room authority. App Local remains in memory. |
| `ROOM_EMPTY_TIMEOUT_SECONDS` | Integer `0..31536000`, default `0` (disabled). Positive values enable empty-room expiry and oldest-empty reclamation under allocation pressure. Apply at Server startup; App Local retains its process-only lifecycle. |
| `MAX_VIEWERS_PER_ROOM` | `1..20`, default `20`; excludes the Host. |
| `ENDPOINT_MEDIA_COPY_CAPACITY` | Shared endpoint steady-copy cap `1..3`, default `2`. |
| `STUN_URLS` | Comma-separated advertised `stun:` discovery URLs; at least one is required in production. These are not local bind addresses and may use an unproxied DNS name separate from the Web origin. |
@@ -47,6 +48,15 @@ so increasing it in source requires a compatibility and capacity review. More
Viewers can add relay hops, routing wait and total media load. The setting does
not increase the per-endpoint copy cap or guarantee available bandwidth.
### Room retention
Public sites can use `ROOM_EMPTY_TIMEOUT_SECONDS=3600` to release unused codes.
Only rooms without authenticated participants expire; watching, paused sharing
and idle chat are protected. When all codes are used, the oldest empty room may
be reclaimed before the hour. Expired rooms and invitations must be recreated.
The default `0` preserves existing indefinite-room behavior. The complete
lifecycle and restart semantics belong to [rooms/access](./rooms-access.md#optional-empty-room-retention).
### Media fallback
Automatic SFU fallback runs inside the Hosted process when `SFU_UDP_PORT` is set:
@@ -79,9 +89,9 @@ The SQLite parent directory must exist and be writable. The systemd template
sets `/var/lib/piik/rooms.sqlite` under its managed state directory; the
container image sets `/home/nonroot/rooms.sqlite` under its writable data
directory. Keep the existing database path and data across application updates.
Room authority has no idle expiry; the separate site-access cookie keeps its
Room authority has no idle expiry by default; the separate site-access cookie keeps its
24-hour idle lifetime within one service run. Restarting the App or Server
requires site-password entry again; saved rooms and invitation grants are unaffected.
requires site-password entry again; saved rooms and invitation grants are restored.
Removed access, room TTL/lease, endpoint-tier, room-rollout, and TURN variables fail
startup even when blank. A present `NODE_ENV` fails the same way, so a stale
+33 -5
View File
@@ -20,17 +20,45 @@ the storage decision; implementation detail belongs in code and tests.
but duplicated-tab exclusion is not guaranteed. Closing the tab releases its
claim; losing Host authority clears that tab without erasing another tab's
resume hint.
- Room identity and credentials do not expire with inactivity. The exact Host
token resumes the room until explicit replacement or deletion. Grant rotation
or revocation ends an invitation without changing the room code. No presence
event renews or shortens room authority.
- Room identity and credentials have no inactivity expiry by default. The exact
Host token resumes the room until explicit replacement or deletion, including
the optional empty-room policy below. Grant rotation or revocation ends an
invitation without changing the room code.
- The Host may replace its room code. Replacement atomically creates a different
room and invalidates the old ownership, invitations, password, sessions,
routes, and media resources. It ends an active share and stops its capture
tracks; it does not migrate or automatically restart capture.
- A locally remembered preferred code is only a request. The server remains the
authority and allocates another code when that code is unavailable. The store
remains bounded by 9,000 codes; it rejects new rooms when full.
remains bounded by 9,000 codes; full allocation rejects new rooms when no
empty room may be reclaimed under the deployment's retention policy.
### Optional empty-room retention
Hosted operators may enable `ROOM_EMPTY_TIMEOUT_SECONDS`; `0` (default) preserves
indefinite authority. A positive value retires a room after that many seconds
continuously without any authenticated Host or Viewer. Never-joined rooms start
empty at creation. Sharing, pausing and idle chat do not change this rule; failed
authentication and HTTP access do not renew it. The existing heartbeat performs
expiry checks, normally every 30 seconds.
With retention enabled, allocation first reclaims expired empty rooms; if none
are available, it may retire the earliest-created empty room before the timeout,
including when replacing a room code. Early reclamation observes the existing
20-second reconnect grace after creation, restore or the last departure. Occupied rooms
are never candidates; a replacement cannot reclaim its own old room before the
replacement commits. If all rooms are occupied, creation still returns capacity
exhaustion. Expiry and pressure retirement use the same storage-first deletion
and signaling cleanup as explicit abandonment; recycled codes never retain old
credentials, share generations or reconnect timers.
The empty interval is process-local. Restored rooms receive a fresh interval so
surviving pages can reconnect; allocation pressure can still reclaim them while
empty. SQLite restores the insertion order of retained rows. This policy adds
no room lease, client renewal, wire field or persisted presence. Deletion ends
both ownership and invitations; ordinary missing-room/invalid-credential handling
applies. [Configuration](./configuration.md#room-retention) owns deployment values.
Disabling retention stops future reclamation; it cannot restore retired authority.
## Admission Paths
+7 -7
View File
@@ -12,7 +12,7 @@ and Git/PRs own completed history.
[Versioning](./standards/versioning.md#public-compatibility-promise) owns
compatibility between published Web/App/Server versions.
- Hosted Server defaults to SQLite schema 2. Room authority has no inactivity
expiry; explicit replacement/deletion or grant rotation/revocation ends the
expiry by default; replacement/deletion or grant rotation/revocation ends the
corresponding authority. Explicit memory mode and App Local end rooms at
process exit. Site access retains its separate 24-hour idle lifetime within
one service run; service restart requires site-password entry again.
@@ -54,12 +54,12 @@ Release artifacts and operator deployment records own delivery completion;
## Current Work
The public baseline retains Browser/server v23, Native control v9, capture v7
and the 1440p ceiling. The compatible maintenance phase combines sharing-failure
guidance and bilingual troubleshooting with source-list, codec admission,
minimized-capture and gateway-mapping repairs. Live audio-exclusion controls
reuse the source/mixer owner; website controls retain shared motion and cache
identity. 4K and resolution/capability expansion are not planned for this phase.
The public baseline retains Browser/server v23, Native control v9, capture v7,
SQLite schema 2 and the 1440p ceiling. Hosted empty-room retention and capacity
guidance preserve indefinite retention by default. The accepted Demo policy is
one hour without authenticated participants; the private deployment retains the
default. Operator records own activation, database and postflight evidence.
4K and resolution/capability expansion are not planned for this phase.
Native Magicsock remains a separate experiment, outside product integration.
Immutable release artifacts own delivery completion; [TODO](./todo.md#now) owns
remaining work.
+2
View File
@@ -169,6 +169,7 @@ func New(options Options) (*Server, error) {
AuthenticationTimeoutMs: options.AuthenticationTimeoutMs,
ViewerDisconnectGraceMs: options.ViewerDisconnectGraceMs,
HeartbeatIntervalMs: options.HeartbeatIntervalMs,
RoomEmptyTimeoutMs: int64(configuration.RoomEmptyTimeoutSeconds) * 1_000,
MaxConnections: options.MaxSignalConnections,
MaxUnauthenticatedConnections: options.MaxUnauthenticatedSignalConnections,
AfterFunc: options.AfterFunc,
@@ -204,6 +205,7 @@ func newRoomStore(options Options) (*room.Store, error) {
MaxRooms: room.Capacity,
MaxViewersPerRoom: options.Config.MaxViewersPerRoom,
Database: database,
Now: options.Now,
})
}
+25
View File
@@ -1265,6 +1265,31 @@ func TestRoomCreationReturnsServiceUnavailableAtTheGlobalRoomBound(t *testing.T)
expect(http.StatusServiceUnavailable, `{"error":"Room capacity reached"}`)
}
func TestConfiguredEmptyRoomExpiryRunsFromTheOwnedHeartbeat(t *testing.T) {
var now atomic.Int64
configuration := testConfig(t)
configuration.SiteAccessPassword = ""
configuration.RoomEmptyTimeoutSeconds = 3600
ticks := make(chan func(), 2)
server := start(t, Options{
Config: configuration, Now: now.Load,
AfterFunc: func(_ time.Duration, callback func()) func() bool {
ticks <- callback
return func() bool { return true }
},
})
created := server.createRoom(roomRequest{}).expectStatus(http.StatusCreated).room()
now.Store(3_599_999)
(<-ticks)()
request := accessRequest{roomID: created.RoomID, hostToken: created.HostToken,
body: `{"action":"set-code-entry-policy","policy":"private"}`}
server.updateRoomAccess(request).expectStatus(http.StatusOK)
now.Store(3_600_000)
(<-ticks)()
server.updateRoomAccess(request).expectStatus(http.StatusNotFound)
server.createRoom(roomRequest{}).expectStatus(http.StatusCreated)
}
// --- server HTTP listener and health --------------------------------------
func TestServesAnExplicitStaticFrontendIndependentlyOfTheEnvironment(t *testing.T) {
+11 -2
View File
@@ -57,8 +57,8 @@ var removedEnvironmentVariables = []struct{ name, reason string }{
{"PEER_ASSISTED_MEDIA", "peer-assisted media is always enabled"},
{"HOST_ADMISSION_PASSWORD", "use SITE_ACCESS_PASSWORD"},
{"MAX_PEER_RELAY_DOWNSTREAM_EDGES", "use ENDPOINT_MEDIA_COPY_CAPACITY"},
{"ROOM_TTL_SECONDS", "rooms do not expire"},
{"ROOM_LEASE_SECONDS", "rooms do not expire"},
{"ROOM_TTL_SECONDS", "use ROOM_EMPTY_TIMEOUT_SECONDS for empty-room retention"},
{"ROOM_LEASE_SECONDS", "use ROOM_EMPTY_TIMEOUT_SECONDS for empty-room retention"},
{"ACCESS_PASSWORD", "use SITE_ACCESS_PASSWORD"},
{"NODE_ENV", "use PIIK_ENV"},
}
@@ -82,6 +82,7 @@ type Config struct {
AllowedOrigins map[string]struct{}
SiteAccessPassword string
RoomDatabasePath string
RoomEmptyTimeoutSeconds int
MaxViewersPerRoom int
EndpointMediaCopyCapacity int
SFU *SFUConfig
@@ -144,6 +145,13 @@ func Load(env map[string]string) (Config, error) {
if err != nil {
return Config{}, err
}
roomEmptyTimeout := 0
if value := strings.TrimSpace(env["ROOM_EMPTY_TIMEOUT_SECONDS"]); value != "" {
roomEmptyTimeout, err = strconv.Atoi(value)
if err != nil || roomEmptyTimeout < 0 || roomEmptyTimeout > 31_536_000 {
return Config{}, errors.New("ROOM_EMPTY_TIMEOUT_SECONDS must be an integer between 0 and 31536000")
}
}
stunURLs, err := parseStunURLList(env["STUN_URLS"], "STUN_URLS")
if err != nil {
return Config{}, err
@@ -201,6 +209,7 @@ func Load(env map[string]string) (Config, error) {
AllowedOrigins: allowedOrigins,
SiteAccessPassword: siteAccessPassword,
RoomDatabasePath: roomDatabasePath,
RoomEmptyTimeoutSeconds: roomEmptyTimeout,
MaxViewersPerRoom: int(maxViewersPerRoom),
EndpointMediaCopyCapacity: int(endpointMediaCopyCapacity),
SFU: sfu,
+3 -3
View File
@@ -496,11 +496,11 @@ func TestLoadRejects(t *testing.T) {
{"removed peer-assisted toggle", map[string]string{"PEER_ASSISTED_MEDIA": "true"},
"PEER_ASSISTED_MEDIA is no longer supported; peer-assisted media is always enabled"},
{"removed room TTL", map[string]string{"ROOM_TTL_SECONDS": ""},
"ROOM_TTL_SECONDS is no longer supported; rooms do not expire"},
"ROOM_TTL_SECONDS is no longer supported; use ROOM_EMPTY_TIMEOUT_SECONDS for empty-room retention"},
{"removed room lease", map[string]string{"ROOM_LEASE_SECONDS": "86400"},
"ROOM_LEASE_SECONDS is no longer supported; rooms do not expire"},
"ROOM_LEASE_SECONDS is no longer supported; use ROOM_EMPTY_TIMEOUT_SECONDS for empty-room retention"},
{"blank removed room lease", map[string]string{"ROOM_LEASE_SECONDS": ""},
"ROOM_LEASE_SECONDS is no longer supported; rooms do not expire"},
"ROOM_LEASE_SECONDS is no longer supported; use ROOM_EMPTY_TIMEOUT_SECONDS for empty-room retention"},
{"removed access password", map[string]string{"ACCESS_PASSWORD": "legacy-password"},
"ACCESS_PASSWORD is no longer supported; use SITE_ACCESS_PASSWORD"},
{"blank access password", map[string]string{"ACCESS_PASSWORD": ""},
+21
View File
@@ -0,0 +1,21 @@
package config
import "testing"
func TestRoomEmptyTimeoutConfiguration(t *testing.T) {
for _, value := range []string{"", "0", "3600", "31536000"} {
cfg, err := Load(map[string]string{"ROOM_EMPTY_TIMEOUT_SECONDS": value})
if err != nil {
t.Fatalf("value %q: %v", value, err)
}
if value == "3600" && cfg.RoomEmptyTimeoutSeconds != 3600 ||
(value == "" || value == "0") && cfg.RoomEmptyTimeoutSeconds != 0 {
t.Fatalf("value %q: timeout=%d", value, cfg.RoomEmptyTimeoutSeconds)
}
}
for _, value := range []string{"-1", "1.5", "31536001", "NaN", "Infinity"} {
if _, err := Load(map[string]string{"ROOM_EMPTY_TIMEOUT_SECONDS": value}); err == nil {
t.Fatalf("accepted invalid timeout %q", value)
}
}
}
+19 -10
View File
@@ -48,6 +48,9 @@ const roomSchema = `
PRAGMA user_version = 2;
`
// The current schema only inserts/deletes rooms; updates retain rowid. Reading
// its insertion order keeps oldest-empty allocation stable across restarts,
// without persisting presence or adding a creation-time schema migration.
const selectStoredRooms = `SELECT
room_id,
host_token_digest,
@@ -56,7 +59,7 @@ const selectStoredRooms = `SELECT
code_entry_policy,
viewer_password_material
FROM rooms
ORDER BY room_id`
ORDER BY rowid`
const insertStoredRoom = `INSERT INTO rooms (
room_id,
@@ -264,17 +267,23 @@ func (d *Database) SetViewerGrant(
})
}
// DeleteRoom is deleteRoom.
func (d *Database) DeleteRoom(roomID string, hostTokenDigest []byte) error {
if err := assertRoomIdentity(roomID, hostTokenDigest); err != nil {
return err
}
return d.transaction(func() error {
changes, err := d.exec(deleteRoomStatement, roomID, hostTokenDigest)
if err != nil {
func (d *Database) deleteRooms(rooms []StoredRoomAuthority) error {
for _, room := range rooms {
if err := assertRoomIdentity(room.RoomID, room.HostTokenDigest); err != nil {
return err
}
return assertSingleChange(changes, "delete")
}
return d.transaction(func() error {
for _, room := range rooms {
changes, err := d.exec(deleteRoomStatement, room.RoomID, room.HostTokenDigest)
if err != nil {
return err
}
if err := assertSingleChange(changes, "delete"); err != nil {
return err
}
}
return nil
})
}
+1 -1
View File
@@ -531,7 +531,7 @@ func TestRejectsInvalidAuthorityArguments(t *testing.T) {
return d.InsertRoom(room)
}, "Viewer password material must contain 48 bytes"},
{"identity", func(d *Database) error {
return d.DeleteRoom("123", make([]byte, 32))
return d.deleteRooms([]StoredRoomAuthority{{RoomID: "123", HostTokenDigest: make([]byte, 32)}})
}, "Room ID is invalid"},
{"update policy", func(d *Database) error {
return d.SetCodeEntryPolicy("1234", make([]byte, 32), "public")
+31
View File
@@ -0,0 +1,31 @@
package room
// ExpireEmptyRooms commits storage retirement before returning effect cleanup.
func (s *Store) ExpireEmptyRooms(beforeMs int64) ([]ClosedRoom, error) {
return s.abandonRooms(s.EmptyRoomIDs(beforeMs))
}
// EmptyRoomIDs returns empty rooms in creation order, including never-joined
// rooms. A connected Host or Viewer protects an idle chat room just like a share.
// Callers retire candidates synchronously under the same signaling lock.
func (s *Store) EmptyRoomIDs(beforeMs int64) []string {
var ids []string
for id, room := range s.rooms.All() {
if room.emptySinceMs <= beforeMs && !roomOccupied(room) {
ids = append(ids, id)
}
}
return ids
}
func roomOccupied(room *Room) bool {
if room.host != nil && room.host.sessionID != "" {
return true
}
for _, viewer := range room.viewers.All() {
if viewer.sessionID != "" {
return true
}
}
return false
}
+129
View File
@@ -0,0 +1,129 @@
package room
import (
"reflect"
"testing"
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
)
func TestEmptyRoomRetentionUsesAuthenticatedPresence(t *testing.T) {
var now int64
store := newStore(t, Options{Now: func() int64 { return now }})
created := createRoom(t, store, protocol.CodeEntryOpen, "", "4321")
if ids := store.EmptyRoomIDs(0); !reflect.DeepEqual(ids, []string{created.RoomID}) {
t.Fatalf("never-joined room = %v", ids)
}
host := mustConnect(t, store, hostInput(created.RoomID, created.HostToken))
viewer := mustConnect(t, store, viewerInput(created.RoomID, "viewer-session", created.ViewerGrant))
now = 3_600_000
if closed, err := store.ExpireEmptyRooms(now); err != nil || len(closed) != 0 {
t.Fatalf("occupied room retired: %v %v", closed, err)
}
_, _ = store.DisconnectParticipant(created.RoomID, host.PeerID, "host-session")
if len(store.EmptyRoomIDs(now)) != 0 {
t.Fatal("a Viewer without a Host must protect the room")
}
_, _ = store.DisconnectParticipant(created.RoomID, viewer.PeerID, "viewer-session")
if len(store.EmptyRoomIDs(now-1)) != 0 {
t.Fatal("empty interval began before the last departure")
}
// Reconnect/replacement and a late old-session close must not retire the
// current participant, or let failed admission renew an empty room.
now += 10
mustConnect(t, store, hostInput(created.RoomID, created.HostToken, "new-session"))
_, _ = store.DisconnectParticipant(created.RoomID, host.PeerID, "host-session")
if len(store.EmptyRoomIDs(now)) != 0 {
t.Fatal("stale disconnect made the new session empty")
}
_, _ = store.DisconnectParticipant(created.RoomID, host.PeerID, "new-session")
lastDeparture := now
now += 100
_, err := store.ConnectParticipant(hostInput(created.RoomID, "wrong-token"))
expectCode(t, err, CodeInvalidToken)
store.RemoveDisconnectedViewer(created.RoomID, viewer.PeerID)
closed, err := store.ExpireEmptyRooms(lastDeparture)
if err != nil || len(closed) != 1 || len(closed[0].SessionIDs) != 0 || store.Size() != 0 {
t.Fatalf("empty retirement = %v %v, size=%d", closed, err, store.Size())
}
reused := createRoom(t, store, protocol.CodeEntryOpen, "", created.RoomID)
_, err = store.ConnectParticipant(viewerInput(reused.RoomID, "old-invite", created.ViewerGrant))
expectCode(t, err, CodeInvalidToken)
}
func TestRevokingLastConnectedViewerStartsEmptyInterval(t *testing.T) {
var now int64
store := newStore(t, Options{Now: func() int64 { return now }})
created := createRoom(t, store, protocol.CodeEntryOpen, "", "4321")
mustConnect(t, store, viewerInput(created.RoomID, "viewer-session", created.ViewerGrant))
now = 100
if _, err := store.SetViewerGrant(created.RoomID, "revoke", created.HostToken); err != nil {
t.Fatal(err)
}
if len(store.EmptyRoomIDs(99)) != 0 || len(store.EmptyRoomIDs(100)) != 1 {
t.Fatal("revocation did not start the empty interval")
}
now = 200
if _, err := store.SetViewerGrant(created.RoomID, "rotate", created.HostToken); err != nil {
t.Fatal(err)
}
if len(store.EmptyRoomIDs(100)) != 1 {
t.Fatal("changing credentials on an already empty room renewed it")
}
}
func TestRestorePreservesCreationOrderAndRestartsEmptyInterval(t *testing.T) {
path := databasePath(t)
var now int64
options := Options{Now: func() int64 { return now }}
first := stableStore(t, path, options)
older := createRoom(t, first, protocol.CodeEntryOpen, "", "9000")
now++
createRoom(t, first, protocol.CodeEntryOpen, "", "1000")
_, err := first.SetCodeEntryPolicy(older.RoomID, protocol.CodeEntryPrivate, older.HostToken)
if err != nil {
t.Fatal(err)
}
if err := first.Close(); err != nil {
t.Fatal(err)
}
now = 7_200_000
restored := stableStore(t, path, options)
if len(restored.EmptyRoomIDs(now-1)) != 0 {
t.Fatal("restart must allow participants to reconnect")
}
if ids := restored.EmptyRoomIDs(now); !reflect.DeepEqual(ids, []string{"9000", "1000"}) {
t.Fatalf("restored creation order = %v", ids)
}
closed, err := restored.ExpireEmptyRooms(now)
if err != nil || len(closed) != 2 {
t.Fatalf("expire = %v %v", closed, err)
}
if err := restored.Close(); err != nil {
t.Fatal(err)
}
if next := stableStore(t, path, options); next.Size() != 0 {
t.Fatal("expired authority survived restart")
}
}
func TestExpiryStorageFailureDoesNotPartiallyRetireRooms(t *testing.T) {
store := stableStore(t, databasePath(t), Options{Now: func() int64 { return 0 }})
createRoom(t, store, protocol.CodeEntryOpen, "", "9000")
createRoom(t, store, protocol.CodeEntryOpen, "", "1000")
// Fail the second deletion, after the first executed inside the transaction.
_, err := store.database.exec(`CREATE TEMP TRIGGER fail_retirement BEFORE DELETE ON rooms
WHEN OLD.room_id = '1000' BEGIN SELECT RAISE(ABORT, 'injected write failure'); END`)
if err != nil {
t.Fatal(err)
}
free := len(store.freeRoomCodes)
if closed, err := store.ExpireEmptyRooms(0); err == nil || len(closed) != 0 {
t.Fatalf("expiry unexpectedly succeeded: %v %v", closed, err)
}
rows, err := store.database.readStoredRooms()
if err != nil || len(rows) != 2 || store.Size() != 2 || len(store.freeRoomCodes) != free {
t.Fatalf("failed batch changed authority: rows=%d, rooms=%d, free=%d, error=%v", len(rows), store.Size(), len(store.freeRoomCodes), err)
}
}
+48 -21
View File
@@ -12,6 +12,7 @@ import (
"math"
"slices"
"strconv"
"time"
"github.com/TNTcraftHIM/Piik/internal/server/ordered"
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
@@ -77,6 +78,9 @@ type Room struct {
viewerAuthorizationGeneration string
codeEntryPolicy protocol.CodeEntryPolicy
host *participant
// Process-local: restored rooms receive a fresh reconnect window. Only the
// last authenticated departure updates this; failed admission cannot renew it.
emptySinceMs int64
// ordering: JS Map insertion order decides viewer presence order, the
// closed-session list and the router's participant order.
viewers ordered.Map[string, *participant]
@@ -175,6 +179,7 @@ type Options struct {
MaxViewersPerRoom int
Database *Database
Random func(size int) []byte
Now func() int64
}
// Store is RoomStore. See the package comment for the locking contract.
@@ -183,6 +188,7 @@ type Store struct {
rooms ordered.Map[string, *Room]
freeRoomCodes []string
random func(size int) []byte
now func() int64
database *Database
initialized bool
maxRooms int
@@ -207,6 +213,7 @@ func New(options Options) (*Store, error) {
store := &Store{
freeRoomCodes: make([]string, Capacity),
random: options.Random,
now: options.Now,
database: options.Database,
initialized: options.Database == nil,
maxRooms: options.MaxRooms,
@@ -219,6 +226,9 @@ func New(options Options) (*Store, error) {
if store.random == nil {
store.random = cryptoRandom
}
if store.now == nil {
store.now = func() int64 { return time.Now().UnixMilli() }
}
return store, nil
}
@@ -284,6 +294,7 @@ func (s *Store) restore() error {
viewerPasswordMaterial: bytes.Clone(stored.ViewerPasswordMaterial),
viewerAuthorizationGeneration: stored.ViewerAuthorizationGeneration,
codeEntryPolicy: stored.CodeEntryPolicy,
emptySinceMs: s.now(),
})
}
available := s.freeRoomCodes[:0]
@@ -538,12 +549,16 @@ func (s *Store) SetViewerGrant(
}
room.viewerGrantDigest = viewerGrantDigest
room.viewerAuthorizationGeneration = generation
wasOccupied := roomOccupied(room)
// ordering: delete during iteration, which a JS Map allows.
for clientID, viewer := range room.viewers.All() {
if viewer.admittedBy == admittedByGrant {
room.viewers.Delete(clientID)
}
}
if wasOccupied && !roomOccupied(room) {
room.emptySinceMs = s.now()
}
return ViewerGrantUpdate{
ViewerGrant: viewerGrant,
ViewerAuthorizationGeneration: room.viewerAuthorizationGeneration,
@@ -681,6 +696,9 @@ func (s *Store) DisconnectParticipant(
return nil, nil
}
room.host.sessionID = ""
if !roomOccupied(room) {
room.emptySinceMs = s.now()
}
return &DisconnectedParticipant{
RoomID: roomID, Role: protocol.RoleHost, PeerID: peerID}, nil
}
@@ -690,6 +708,9 @@ func (s *Store) DisconnectParticipant(
return nil, nil
}
viewer.sessionID = ""
if !roomOccupied(room) {
room.emptySinceMs = s.now()
}
return &DisconnectedParticipant{
RoomID: roomID, Role: protocol.RoleViewer, PeerID: peerID}, nil
}
@@ -761,41 +782,46 @@ func (s *Store) GetConnectedViewers(roomID string) []ConnectedPeer {
// AbandonRoom is abandonRoom; it returns nil where the TypeScript returned
// undefined.
func (s *Store) AbandonRoom(roomID string) (*ClosedRoom, error) {
closed, err := s.abandonRooms([]string{roomID})
if err != nil || len(closed) == 0 {
return nil, err
}
return &closed[0], nil
}
// Retire a batch atomically before releasing codes. One SQLite transaction
// avoids thousands of fsyncs under the signaling lock after a restart.
func (s *Store) abandonRooms(roomIDs []string) ([]ClosedRoom, error) {
if err := s.ensureInitialized(); err != nil {
return nil, err
}
room, ok := s.rooms.Get(roomID)
if !ok {
var authorities []StoredRoomAuthority
var closed []ClosedRoom
for _, roomID := range roomIDs {
if room, ok := s.rooms.Get(roomID); ok {
authorities = append(authorities, StoredRoomAuthority{RoomID: roomID, HostTokenDigest: room.hostTokenDigest})
closed = append(closed, ClosedRoom{RoomID: roomID, SessionIDs: connectedSessionIDs(room)})
}
}
if len(closed) == 0 {
return nil, nil
}
sessionIDs := connectedSessionIDs(room)
err := s.writeDatabase(func() error {
return s.database.DeleteRoom(roomID, room.hostTokenDigest)
return s.database.deleteRooms(authorities)
})
if err != nil {
return nil, err
}
s.rooms.Delete(roomID)
s.releaseRoomCode(roomID)
return &ClosedRoom{RoomID: roomID, SessionIDs: sessionIDs}, nil
for _, room := range closed {
s.rooms.Delete(room.RoomID)
s.releaseRoomCode(room.RoomID)
}
return closed, nil
}
// AbandonAllRooms is abandonAllRooms, in room insertion order.
func (s *Store) AbandonAllRooms() ([]ClosedRoom, error) {
if err := s.ensureInitialized(); err != nil {
return nil, err
}
var closedRooms []ClosedRoom
for _, roomID := range s.rooms.Keys() {
closed, err := s.AbandonRoom(roomID)
if err != nil {
return nil, err
}
if closed != nil {
closedRooms = append(closedRooms, *closed)
}
}
return closedRooms, nil
return s.abandonRooms(s.rooms.Keys())
}
func (s *Store) connectHost(
@@ -1004,6 +1030,7 @@ func (s *Store) newRoom(
viewerPasswordMaterial: material,
viewerAuthorizationGeneration: generation,
codeEntryPolicy: policy,
emptySinceMs: s.now(),
}
return room, CreatedRoom{
RoomID: roomID,
+45
View File
@@ -0,0 +1,45 @@
package signal
import (
"errors"
"fmt"
"github.com/TNTcraftHIM/Piik/internal/server/room"
)
// Capacity reclamation and scheduled expiry use the normal room retirement
// owner, so grace timers, route state and share generations cannot outlive a
// recycled code. All selection and retirement happen under Server.mu.
func (s *Server) roomCapacityCandidate(err error, exceptRoomID string) string {
var roomError *room.Error
if s.roomEmptyTimeoutMs <= 0 || !errors.As(err, &roomError) || roomError.Code != room.CodeRoomLimit {
return ""
}
now := s.now()
// A recently vacated old room should not be displaced while another empty
// room has already expired but is waiting for the next heartbeat sweep.
// Reuse the admission/reconnect window for early reclamation as well: a
// new room's HTTP response must reach its Host before its code can be reused.
for _, before := range []int64{now - s.roomEmptyTimeoutMs, now - int64(s.viewerDisconnectGraceMs)} {
for _, id := range s.store.EmptyRoomIDs(before) {
if id != exceptRoomID {
return id
}
}
}
return ""
}
func (s *Server) expireEmptyRooms() {
if s.roomEmptyTimeoutMs <= 0 {
return
}
closed, err := s.store.ExpireEmptyRooms(s.now() - s.roomEmptyTimeoutMs)
if err != nil {
s.logger.Error("Could not expire empty rooms", "errorType", fmt.Sprintf("%T", err))
return
}
for _, room := range closed {
s.closeRoom(room)
}
}
+188
View File
@@ -0,0 +1,188 @@
package signal
import (
"errors"
"testing"
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
"github.com/TNTcraftHIM/Piik/internal/server/room"
)
func TestRoomCapacityReclaimsOldestEmptyRoomOnlyWhenEnabled(t *testing.T) {
for _, enabled := range []bool{false, true} {
t.Run(map[bool]string{false: "default-retention", true: "empty-reclamation"}[enabled], func(t *testing.T) {
store, err := room.New(room.Options{MaxRooms: 2, MaxViewersPerRoom: 2, Now: func() int64 { return 0 }})
if err != nil {
t.Fatal(err)
}
timeout := int64(0)
if enabled {
timeout = 3_600_000
}
h := startHarness(t, harnessOptions{store: store, now: func() int64 { return 51 }, roomEmptyTimeoutMs: timeout})
second, err := h.server.CreateRoom(protocol.CodeEntryOpen, nil, "")
if err != nil {
t.Fatal(err)
}
created, err := h.server.CreateRoom(protocol.CodeEntryOpen, nil, h.room.RoomID)
if !enabled {
var limit *room.Error
if !errors.As(err, &limit) || limit.Code != room.CodeRoomLimit {
t.Fatalf("default capacity result = %v", err)
}
return
}
if err != nil || created.RoomID != h.room.RoomID || created.HostToken == h.room.HostToken {
t.Fatalf("reclaim oldest empty = %v %v", created.RoomID, err)
}
h.locked(func() {
if _, err := store.HostManagedRoom(second.RoomID, second.HostToken); err != nil {
t.Fatal("newer empty room was retired")
}
})
host := openClient(t, h)
authenticate(t, host, created, protocol.RoleHost, "idle-host", 1, "", presenceOptions{roomSession: true, roomOnly: true})
viewer := openClient(t, h)
authenticate(t, viewer, second, protocol.RoleViewer, "waiting-viewer", 1, "", presenceOptions{})
_, err = h.server.CreateRoom(protocol.CodeEntryOpen, nil, "")
var limit *room.Error
if !errors.As(err, &limit) || limit.Code != room.CodeRoomLimit {
t.Fatalf("occupied rooms must not be evicted: %v", err)
}
})
}
}
func TestEmptyExpiryCleansShareAndReconnectState(t *testing.T) {
clock := &clock{}
store, err := room.New(room.Options{MaxRooms: 2, MaxViewersPerRoom: 2, Now: clock.now})
if err != nil {
t.Fatal(err)
}
h := startHarness(t, harnessOptions{store: store, now: clock.now, roomEmptyTimeoutMs: 3_600_000, viewerDisconnectGraceMs: 20_000})
host := openClient(t, h)
authenticate(t, host, h.room, protocol.RoleHost, "retention-host", 1, "", presenceOptions{roomSession: true})
host.ignore("route-update")
viewer := openClient(t, h)
authenticate(t, viewer, h.room, protocol.RoleViewer, "retention-viewer", 1, "", presenceOptions{})
viewer.ignore("route-update")
clock.advance(7_200_000)
h.locked(func() {
h.server.expireEmptyRooms()
if store.Size() != 1 {
t.Fatal("connected room expired")
}
})
h.closeClient(viewer)
h.closeClient(host)
h.locked(func() {
if len(h.server.viewerGraceTimers) != 1 || len(h.server.shares) != 1 {
t.Fatal("test did not retain reconnect/share state")
}
})
clock.advance(3_599_999)
h.locked(func() {
h.server.expireEmptyRooms()
if store.Size() != 1 {
t.Fatal("room expired before an hour empty")
}
})
clock.advance(1)
h.locked(func() {
h.server.expireEmptyRooms()
if store.Size() != 0 || len(h.server.shares) != 0 || len(h.server.viewerGraceTimers) != 0 {
t.Fatal("expired room left authority or effects behind")
}
})
created, err := h.server.CreateRoom(protocol.CodeEntryOpen, nil, h.room.RoomID)
if err != nil {
t.Fatal(err)
}
newHost := openClient(t, h)
authenticate(t, newHost, created, protocol.RoleHost, "new-host", 1, "", presenceOptions{roomSession: true, roomOnly: true})
}
func TestRoomCapacityPrefersExpiredRoomOverRecentlyVacatedOlderRoom(t *testing.T) {
clock := &clock{}
store, err := room.New(room.Options{MaxRooms: 2, MaxViewersPerRoom: 2, Now: clock.now})
if err != nil {
t.Fatal(err)
}
h := startHarness(t, harnessOptions{store: store, now: clock.now, roomEmptyTimeoutMs: 3_600_000})
host := openClient(t, h)
authenticate(t, host, h.room, protocol.RoleHost, "retention-host", 1, "", presenceOptions{roomSession: true, roomOnly: true})
clock.advance(10)
newer := h.createRoom(protocol.CodeEntryOpen, "")
clock.advance(3_600_000)
h.closeClient(host)
clock.advance(100)
created, err := h.server.CreateRoom(protocol.CodeEntryOpen, nil, newer.RoomID)
if err != nil || created.RoomID != newer.RoomID {
t.Fatalf("expired room not reclaimed first: %s %v", created.RoomID, err)
}
h.locked(func() {
if _, err := store.HostManagedRoom(h.room.RoomID, h.room.HostToken); err != nil {
t.Fatal("recent departure lost its room before an already-expired room")
}
})
}
func TestRoomReplacementAtAll9000CodesReclaimsAnotherEmptyRoom(t *testing.T) {
store, err := room.New(room.Options{MaxRooms: room.Capacity, MaxViewersPerRoom: 2, Now: func() int64 { return 0 }})
if err != nil {
t.Fatal(err)
}
oldest := createStoreRoom(t, store, protocol.CodeEntryOpen, "")
second := createStoreRoom(t, store, protocol.CodeEntryOpen, "")
for store.Size() < room.Capacity {
createStoreRoom(t, store, protocol.CodeEntryOpen, "")
}
h := startHarness(t, harnessOptions{store: store, room: &oldest, now: func() int64 { return 51 }, roomEmptyTimeoutMs: 3_600_000})
if _, err := h.server.ReplaceRoom(oldest.RoomID, "wrong-token", protocol.CodeEntryOpen, nil); err == nil {
t.Fatal("invalid ownership replaced a room")
}
if h.storeSize() != room.Capacity {
t.Fatal("rejected replacement evicted another room")
}
replacement, err := h.server.ReplaceRoom(oldest.RoomID, oldest.HostToken, protocol.CodeEntryOpen, nil)
if err != nil || replacement.RoomID != second.RoomID || replacement.HostToken == second.HostToken {
t.Fatalf("replacement did not reclaim the next oldest empty room: %s %v", replacement.RoomID, err)
}
if h.storeSize() != room.Capacity-1 {
t.Fatal("replacement left incorrect room capacity")
}
h.locked(func() {
if _, err := store.HostManagedRoom(oldest.RoomID, oldest.HostToken); err == nil {
t.Fatal("old replacement authority survived")
}
})
}
func TestCapacityReclamationProtectsCreationAndReconnectWindow(t *testing.T) {
clock := &clock{}
store, err := room.New(room.Options{MaxRooms: 1, MaxViewersPerRoom: 1, Now: clock.now})
if err != nil {
t.Fatal(err)
}
h := startHarness(t, harnessOptions{store: store, now: clock.now, roomEmptyTimeoutMs: 3_600_000, viewerDisconnectGraceMs: 20_000})
assertProtected := func() {
t.Helper()
_, err := h.server.CreateRoom(protocol.CodeEntryOpen, nil, "")
var limit *room.Error
if !errors.As(err, &limit) || limit.Code != room.CodeRoomLimit {
t.Fatalf("creation/reconnect window lost its room: %v", err)
}
}
clock.advance(19_999)
assertProtected()
host := openClient(t, h)
authenticate(t, host, h.room, protocol.RoleHost, "retention-host", 1, "", presenceOptions{roomSession: true, roomOnly: true})
h.closeClient(host)
clock.advance(19_999)
assertProtected()
clock.advance(1)
if _, err := h.server.CreateRoom(protocol.CodeEntryOpen, nil, ""); err != nil {
t.Fatalf("reclamation after reconnect window: %v", err)
}
assertProtected()
}
+27 -6
View File
@@ -85,10 +85,13 @@ type Options struct {
SiteAccessAtUpgrade func(*http.Request) bool
PublicBaseURL *url.URL
// Now returns Unix milliseconds; nil uses the wall clock.
Now func() int64
AuthenticationTimeoutMs int
ViewerDisconnectGraceMs int
HeartbeatIntervalMs int
Now func() int64
AuthenticationTimeoutMs int
ViewerDisconnectGraceMs int
HeartbeatIntervalMs int
// Zero retains room authority indefinitely. Otherwise empty rooms expire
// and allocation pressure may reclaim the oldest empty room early.
RoomEmptyTimeoutMs int64
MaxConnections int
MaxUnauthenticatedConnections int
// AfterFunc is the timer factory; nil uses time.AfterFunc.
@@ -178,6 +181,7 @@ type Server struct {
authenticationTimeoutMs int
viewerDisconnectGraceMs int
heartbeatIntervalMs int
roomEmptyTimeoutMs int64
maxConnections int
maxUnauthenticatedConnections int
@@ -235,6 +239,7 @@ func New(options Options) (*Server, error) {
authenticationTimeoutMs: orDefault(options.AuthenticationTimeoutMs, defaultAuthenticationTimeoutMs),
viewerDisconnectGraceMs: orDefault(options.ViewerDisconnectGraceMs, defaultViewerDisconnectGraceMs),
heartbeatIntervalMs: orDefault(options.HeartbeatIntervalMs, defaultHeartbeatIntervalMs),
roomEmptyTimeoutMs: options.RoomEmptyTimeoutMs,
maxConnections: orDefault(options.MaxConnections, defaultMaxSignalConnections),
maxUnauthenticatedConnections: orDefault(options.MaxUnauthenticatedConnections, defaultMaxUnauthenticatedConnections),
sessionsByID: map[string]*session{},
@@ -599,6 +604,13 @@ func (s *Server) ReplaceRoom(
}
material, derived := s.deriveViewerPasswordMaterial(roomID, hostToken, roomPassword, current)
replacement, err := s.store.ReplaceRoom(roomID, hostToken, codeEntryPolicy, material, derived, current)
if derived == nil {
if candidate := s.roomCapacityCandidate(err, roomID); candidate != "" {
if err = s.abandonRoom(candidate); err == nil {
replacement, err = s.store.ReplaceRoom(roomID, hostToken, codeEntryPolicy, material, derived, current)
}
}
}
if err != nil {
return room.CreatedRoom{}, err
}
@@ -615,7 +627,7 @@ func (s *Server) CreateRoom(
) (room.CreatedRoom, error) {
s.mu.Lock()
defer s.mu.Unlock()
if err := s.store.BeginCreateRoom(); err != nil {
if err := s.store.BeginCreateRoom(); err != nil && s.roomCapacityCandidate(err, "") == "" {
return room.CreatedRoom{}, err
}
var material []byte
@@ -627,7 +639,15 @@ func (s *Server) CreateRoom(
material, derived = s.store.DeriveViewerPasswordMaterial(*roomPassword, nil)
}()
}
return s.store.CreateRoom(codeEntryPolicy, material, derived, preferredRoomID)
created, err := s.store.CreateRoom(codeEntryPolicy, material, derived, preferredRoomID)
if derived == nil {
if candidate := s.roomCapacityCandidate(err, ""); candidate != "" {
if err = s.abandonRoom(candidate); err == nil {
created, err = s.store.CreateRoom(codeEntryPolicy, material, derived, preferredRoomID)
}
}
}
return created, err
}
// armHeartbeat is the heartbeat setInterval: each tick re-arms the
@@ -641,6 +661,7 @@ func (s *Server) armHeartbeat() {
return
}
pings := s.heartbeat()
s.expireEmptyRooms()
s.armHeartbeat()
s.mu.Unlock()
for _, sess := range pings {
+2
View File
@@ -248,6 +248,7 @@ func TestPersistentRoomSessionReconnectStaysMediaIdle(t *testing.T) {
type harnessOptions struct {
authenticationTimeoutMs int
viewerDisconnectGraceMs int
roomEmptyTimeoutMs int64
maxViewersPerRoom int
maxSignalConnections int
maxUnauthenticatedSignalConnections int
@@ -353,6 +354,7 @@ func startHarness(t *testing.T, options harnessOptions) *harness {
AuthenticationTimeoutMs: orValue(options.authenticationTimeoutMs, 500),
ViewerDisconnectGraceMs: orValue(options.viewerDisconnectGraceMs, 50),
HeartbeatIntervalMs: 60_000,
RoomEmptyTimeoutMs: options.roomEmptyTimeoutMs,
MaxConnections: options.maxSignalConnections,
MaxUnauthenticatedConnections: options.maxUnauthenticatedSignalConnections,
AfterFunc: options.afterFunc,
+7 -5
View File
@@ -32,11 +32,13 @@ async function responseBody(response: Response): Promise<unknown> {
} catch {
throw new ApiError(say("host.err.serverError"), response.status);
}
if (
response.status === 403 && body && typeof body === "object" &&
"error" in body && body.error === "Origin not allowed"
) {
throw new ApiError(say("api.originNotAllowed"), response.status);
if (body && typeof body === "object" && "error" in body) {
if (response.status === 403 && body.error === "Origin not allowed") {
throw new ApiError(say("api.originNotAllowed"), response.status);
}
if (response.status === 503 && body.error === "Room capacity reached") {
throw new ApiError(say("host.err.roomCapacity"), response.status);
}
}
return body;
}
+1
View File
@@ -523,6 +523,7 @@ export const en: Record<CopyKey, string> = {
"host.err.forbidden": "Action unavailable",
"host.err.serverError": "Service temporarily unavailable; try again later",
"host.err.createRoomStatus": "Cannot create a room right now ({status})",
"host.err.roomCapacity": "All room codes are in use. Try again later or use another Piik site.",
"host.err.replaceRoomStatus": "Cannot change rooms right now ({status})",
"host.err.updateRoomStatus": "Cannot update room settings right now ({status})",
"host.capture.cancelled": "Screen selection cancelled or not permitted",
+1
View File
@@ -523,6 +523,7 @@ export const zh = {
"host.err.forbidden": "当前操作不可用",
"host.err.serverError": "服务暂时不可用,请稍后重试",
"host.err.createRoomStatus": "当前无法创建房间 ({status})",
"host.err.roomCapacity": "站点房间号已用满,请稍后重试或使用其他 Piik 站点。",
"host.err.replaceRoomStatus": "当前无法更换房间 ({status})",
"host.err.updateRoomStatus": "当前无法更新房间设置 ({status})",
"host.capture.cancelled": "屏幕选择已取消或没有共享权限",
+19
View File
@@ -740,6 +740,25 @@ describe("client session identity", () => {
});
describe("site access API", () => {
it.each(["zh", "en"] as const)("explains room capacity across creation and replacement in %s", async (lang) => {
setCopy({ lang, vis: false });
vi.stubGlobal("fetch", vi.fn<typeof fetch>().mockImplementation(async () =>
new Response(JSON.stringify({ error: "Room capacity reached" }), { status: 503 }),
));
for (const request of [
() => createRoom("open", null),
() => replaceOwnedRoom("4321", "host-token", "open", null),
]) {
await expect(request()).rejects.toMatchObject({ status: 503, message: say("host.err.roomCapacity") });
}
vi.stubGlobal("fetch", vi.fn<typeof fetch>().mockResolvedValue(
new Response(JSON.stringify({ error: "Room creation unavailable" }), { status: 503 }),
));
await expect(createRoom("open", null)).rejects.toMatchObject({
status: 503, message: say("host.err.createRoomStatus", { status: "503" }),
});
});
it.each(["zh", "en"] as const)("explains rejected origins across write APIs in %s", async (lang) => {
setCopy({ lang, vis: false });
vi.stubGlobal("fetch", vi.fn<typeof fetch>().mockImplementation(async () =>