Initial commit: watch-together phases 0-4 + presence hardening, internet-tested

This commit is contained in:
foxyz committed 2026-09-12 00:13:43 +03:00
commit 427d851a5b
101 files changed
+11326

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
export 'src/constants.dart';
export 'src/errors.dart';
export 'src/logging.dart';
export 'src/config.dart';
export 'src/protocol.dart';
export 'src/media_source.dart';
export 'src/sync_engine.dart';
+80
View File
@@ -0,0 +1,80 @@
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as p;
import 'package:yaml/yaml.dart';
import 'errors.dart';
class AppConfig {
final int port;
final String secret;
final String name;
final String mediaPath;
final String logLevel;
final String advertiseHost;
const AppConfig({
required this.port,
required this.secret,
required this.name,
this.mediaPath = '',
this.logLevel = 'INFO',
this.advertiseHost = '127.0.0.1',
});
factory AppConfig.defaults() =>
const AppConfig(port: 8080, secret: 'change-me', name: 'room');
factory AppConfig.fromMap(Map<String, Object?> map) {
try {
return AppConfig(
port: (map['port'] as num?)?.toInt() ?? 8080,
secret: (map['secret'] as String?) ?? 'change-me',
name: (map['name'] as String?) ?? 'room',
mediaPath: (map['mediaPath'] as String?) ?? '',
logLevel: (map['logLevel'] as String?) ?? 'INFO',
advertiseHost: (map['advertiseHost'] as String?) ?? '127.0.0.1',
);
} catch (e) {
throw ConfigException('invalid config map: $e');
}
}
Map<String, Object?> toMap() => {
'port': port,
'secret': secret,
'name': name,
'mediaPath': mediaPath,
'logLevel': logLevel,
'advertiseHost': advertiseHost,
};
static Future<AppConfig> loadFile(String path) async {
final file = File(path);
if (!await file.exists()) {
throw ConfigException('config file not found: $path');
}
final text = await file.readAsString();
try {
if (path.endsWith('.json')) {
final decoded = jsonDecode(text);
if (decoded is! Map) throw const ConfigException('root must be a map');
return AppConfig.fromMap(Map<String, Object?>.from(decoded));
}
final yamlMap = loadYaml(text);
if (yamlMap is! YamlMap) throw const ConfigException('root must be a map');
return AppConfig.fromMap(
Map<String, Object?>.from(yamlMap.map((k, v) => MapEntry('$k', v))));
} catch (e) {
if (e is ConfigException) rethrow;
throw ConfigException('failed to parse $path: $e');
}
}
static String defaultPath(String appName) {
final home =
Platform.environment['HOME'] ?? Platform.environment['USERPROFILE'] ?? '.';
return p.join(home, '.config', appName, 'config.yaml');
}
}
+21
View File
@@ -0,0 +1,21 @@
abstract class RelayConstants {
static const int protoVersion = 4;
static const int chunkBytes = 256 * 1024;
static const int creditWindowChunks = 8;
static const int maxConcurrentOpen = 16;
static const int seekDebounceMs = 300;
static const double driftSeekThresholdSecs = 5.0;
static const double slowDownThresholdSecs = 1.5;
static const double slowDownRate = 0.95;
static const double minBufferSecs = 4.0;
static const double resumeHysteresisSecs = 4.0;
static const int stateHeartbeatSecs = 1;
static const int pingIntervalSecs = 5;
static const int maxAvatarBytes = 64 * 1024;
static const int maxNameLength = 32;
static const int maxChatLength = 500;
}
+27
View File
@@ -0,0 +1,27 @@
abstract class SyncRelayException implements Exception {
final String message;
const SyncRelayException(this.message);
@override
String toString() => '$runtimeType: $message';
}
class ConfigException extends SyncRelayException {
const ConfigException(super.message);
}
class ProtocolException extends SyncRelayException {
const ProtocolException(super.message);
}
class AuthException extends SyncRelayException {
const AuthException(super.message);
}
class MediaException extends SyncRelayException {
const MediaException(super.message);
}
class TunnelException extends SyncRelayException {
const TunnelException(super.message);
}
+19
View File
@@ -0,0 +1,19 @@
import 'package:logging/logging.dart';
Logger createLogger(String name) => Logger(name);
void initLogging({Level level = Level.INFO}) {
Logger.root.level = level;
Logger.root.onRecord.listen((r) {
// ignore: avoid_print
print('${r.time.toIso8601String()} ${r.level.name} ${r.loggerName}: ${r.message}');
if (r.error != null) {
// ignore: avoid_print
print(' error: ${r.error}');
}
if (r.stackTrace != null) {
// ignore: avoid_print
print('${r.stackTrace}');
}
});
}
+92
View File
@@ -0,0 +1,92 @@
import 'dart:io';
import 'dart:typed_data';
abstract class MediaSource {
Future<int> get size;
String get displayName;
Future<Uint8List> read(int start, int length);
Future<void> close();
}
class FileMediaSource implements MediaSource { final File file;
RandomAccessFile? _handle;
FileMediaSource(this.file);
@override
String get displayName => file.path.split(Platform.pathSeparator).last;
@override
Future<int> get size async => file.length();
@override
Future<Uint8List> read(int start, int length) async {
_handle ??= await file.open();
await _handle!.setPosition(start);
return _handle!.read(length);
}
@override
Future<void> close() async {
await _handle?.close();
_handle = null;
}
}
class RangeRequest {
final int start;
final int? end;
final int size;
const RangeRequest({required this.start, required this.end, required this.size});
int get contentLength => (end ?? (size - 1)) - start + 1;
String get contentRange => 'bytes $start-${end ?? size - 1}/$size';
static RangeRequest? parse(String? header, int size) {
if (header == null || header.isEmpty) return null;
final value = header.trim();
if (!value.startsWith('bytes=')) return null;
final spec = value.substring(6);
if (spec.startsWith('-')) {
final suffix = int.tryParse(spec.substring(1));
if (suffix == null || suffix <= 0) return null;
final start = (size - suffix).clamp(0, size);
return RangeRequest(start: start, end: null, size: size);
}
final parts = spec.split('-');
if (parts.length != 2) return null;
final start = int.tryParse(parts[0].trim());
if (start == null || start < 0 || start >= size) return null;
if (parts[1].trim().isEmpty) return RangeRequest(start: start, end: null, size: size);
final end = int.tryParse(parts[1].trim());
if (end == null || end < start) return null;
return RangeRequest(start: start, end: end.clamp(0, size - 1), size: size);
}
}
String contentTypeForFile(String filename) {
final dot = filename.lastIndexOf('.');
final ext = dot < 0 ? '' : filename.substring(dot).toLowerCase();
switch (ext) {
case '.mkv':
return 'video/x-matroska';
case '.mp4':
case '.m4v':
return 'video/mp4';
case '.webm':
return 'video/webm';
case '.avi':
return 'video/x-msvideo';
case '.mov':
return 'video/quicktime';
case '.ts':
return 'video/mp2t';
case '.mp3':
return 'audio/mpeg';
case '.mka':
return 'audio/x-matroska';
default:
return 'application/octet-stream';
}
}
+390
View File
@@ -0,0 +1,390 @@
import 'constants.dart';
import 'errors.dart';
enum MessageKind {
hello,
welcome,
state,
event,
chat,
buffered,
kicked,
kick,
eof,
err,
open,
ack,
cancel,
}
class HelloUser {
final String name;
final String avatar;
const HelloUser({required this.name, this.avatar = ''});
Map<String, Object?> toJson() => {'name': name, 'avatar': avatar};
factory HelloUser.fromJson(Map<String, Object?> json) =>
HelloUser(name: (json['name'] as String?) ?? '', avatar: (json['avatar'] as String?) ?? '');
}
class HelloMedia {
final String name;
final int size;
final double duration;
final String? url;
const HelloMedia({required this.name, required this.size, required this.duration, this.url});
Map<String, Object?> toJson() => {'name': name, 'size': size, 'duration': duration, if (url != null) 'url': url};
factory HelloMedia.fromJson(Map<String, Object?> json) => HelloMedia(
name: (json['name'] as String?) ?? '',
size: (json['size'] as num?)?.toInt() ?? 0,
duration: (json['duration'] as num?)?.toDouble() ?? 0.0,
url: json['url'] as String?,
);
}
class HelloMessage {
final int proto;
final String secret;
final HelloUser user;
final HelloMedia media;
const HelloMessage({required this.proto, required this.secret, required this.user, required this.media});
Map<String, Object?> toJson() => {
't': 'hello',
'proto': proto,
'secret': secret,
'user': user.toJson(),
'media': media.toJson(),
};
factory HelloMessage.fromJson(Map<String, Object?> json) {
if (json['t'] != 'hello') throw const ProtocolException('not a hello message');
final user = json['user'];
final media = json['media'];
if (user is! Map || media is! Map) throw const ProtocolException('hello missing user/media');
return HelloMessage(
proto: (json['proto'] as num?)?.toInt() ?? RelayConstants.protoVersion,
secret: (json['secret'] as String?) ?? '',
user: HelloUser.fromJson(Map<String, Object?>.from(user)),
media: HelloMedia.fromJson(Map<String, Object?>.from(media)),
);
}
}
class RoomState {
final double position;
final bool paused;
final int mediaId;
final DateTime serverTime;
const RoomState({required this.position, required this.paused, required this.mediaId, required this.serverTime});
Map<String, Object?> toJson() => {
'position': position,
'paused': paused,
'mediaId': mediaId,
'serverTime': serverTime.toIso8601String(),
};
factory RoomState.fromJson(Map<String, Object?> json) => RoomState(
position: (json['position'] as num?)?.toDouble() ?? 0.0,
paused: (json['paused'] as bool?) ?? true,
mediaId: (json['mediaId'] as num?)?.toInt() ?? 0,
serverTime: DateTime.tryParse('${json['serverTime']}') ?? DateTime.now().toUtc(),
);
}
class WelcomeMessage {
final String token;
final String memberId;
final String? mediaUrl;
final Map<String, Object?>? state;
const WelcomeMessage({required this.token, this.memberId = '', this.mediaUrl, this.state});
Map<String, Object?> toJson() => {
't': 'welcome',
'token': token,
'memberId': memberId,
if (mediaUrl != null) 'mediaUrl': mediaUrl,
if (state != null) 'state': state,
};
factory WelcomeMessage.fromJson(Map<String, Object?> json) {
if (json['t'] != 'welcome') throw const ProtocolException('not a welcome message');
final state = json['state'];
return WelcomeMessage(
token: (json['token'] as String?) ?? '',
memberId: (json['memberId'] as String?) ?? '',
mediaUrl: json['mediaUrl'] as String?,
state: state is Map ? Map<String, Object?>.from(state) : null,
);
}
}
class KickedMessage {
final String reason;
const KickedMessage({this.reason = ''});
Map<String, Object?> toJson() => {'t': 'kicked', 'reason': reason};
factory KickedMessage.fromJson(Map<String, Object?> json) {
if (json['t'] != 'kicked') throw const ProtocolException('not a kicked message');
return KickedMessage(reason: (json['reason'] as String?) ?? '');
}
}
class KickRequest {
final String target;
final String reason;
const KickRequest({required this.target, this.reason = ''});
Map<String, Object?> toJson() => {'t': 'kick', 'target': target, 'reason': reason};
factory KickRequest.fromJson(Map<String, Object?> json) {
if (json['t'] != 'kick') throw const ProtocolException('not a kick request');
return KickRequest(
target: (json['target'] as String?) ?? '',
reason: (json['reason'] as String?) ?? '',
);
}
}
class ReadyIntent {
final bool ready;
final String source;
const ReadyIntent({required this.ready, this.source = 'manual'});
Map<String, Object?> toJson() => {'t': 'ready', 'ready': ready, 'source': source};
factory ReadyIntent.fromJson(Map<String, Object?> json) {
if (json['t'] != 'ready') throw const ProtocolException('not a ready intent');
return ReadyIntent(
ready: (json['ready'] as bool?) ?? false,
source: (json['source'] as String?) ?? 'manual',
);
}
}
class ForceIntent {
final String target;
final bool ready;
const ForceIntent({required this.target, required this.ready});
Map<String, Object?> toJson() => {'t': 'force', 'target': target, 'ready': ready};
factory ForceIntent.fromJson(Map<String, Object?> json) {
if (json['t'] != 'force') throw const ProtocolException('not a force intent');
return ForceIntent(
target: (json['target'] as String?) ?? '',
ready: (json['ready'] as bool?) ?? false,
);
}
}
class SeekIntent {
final double position;
const SeekIntent({required this.position});
Map<String, Object?> toJson() => {'t': 'seek', 'position': position};
factory SeekIntent.fromJson(Map<String, Object?> json) {
if (json['t'] != 'seek') throw const ProtocolException('not a seek intent');
return SeekIntent(position: (json['position'] as num?)?.toDouble() ?? 0.0);
}
}
class SwapIntent {
final HelloMedia media;
const SwapIntent({required this.media});
Map<String, Object?> toJson() => {'t': 'swap', 'media': media.toJson()};
factory SwapIntent.fromJson(Map<String, Object?> json) {
if (json['t'] != 'swap') throw const ProtocolException('not a swap intent');
final media = json['media'];
if (media is! Map) throw const ProtocolException('swap missing media');
return SwapIntent(media: HelloMedia.fromJson(Map<String, Object?>.from(media)));
}
}
class ReportMessage {
final double position;
final double buffered;
final int eventId;
const ReportMessage({required this.position, required this.buffered, required this.eventId});
Map<String, Object?> toJson() =>
{'t': 'report', 'position': position, 'buffered': buffered, 'eventId': eventId};
factory ReportMessage.fromJson(Map<String, Object?> json) {
if (json['t'] != 'report') throw const ProtocolException('not a report');
return ReportMessage(
position: (json['position'] as num?)?.toDouble() ?? 0.0,
buffered: (json['buffered'] as num?)?.toDouble() ?? 0.0,
eventId: (json['eventId'] as num?)?.toInt() ?? 0,
);
}
}
class ChatMessage {
final String text;
const ChatMessage({required this.text});
Map<String, Object?> toJson() => {'t': 'chat', 'text': text};
factory ChatMessage.fromJson(Map<String, Object?> json) {
if (json['t'] != 'chat') throw const ProtocolException('not a chat message');
return ChatMessage(text: (json['text'] as String?) ?? '');
}
}
class MemberView {
final String id;
final String name;
final String avatar;
final bool ready;
final bool inSet;
final double buffered;
final bool stale;
const MemberView({
required this.id,
required this.name,
this.avatar = '',
required this.ready,
required this.inSet,
required this.buffered,
required this.stale,
});
Map<String, Object?> toJson() => {
'id': id,
'name': name,
'avatar': avatar,
'ready': ready,
'inSet': inSet,
'buffered': buffered,
'stale': stale,
};
factory MemberView.fromJson(Map<String, Object?> json) => MemberView(
id: (json['id'] as String?) ?? '',
name: (json['name'] as String?) ?? '',
avatar: (json['avatar'] as String?) ?? '',
ready: (json['ready'] as bool?) ?? false,
inSet: (json['inSet'] as bool?) ?? false,
buffered: (json['buffered'] as num?)?.toDouble() ?? 0.0,
stale: (json['stale'] as bool?) ?? false,
);
}
class RoomBroadcast {
final int eventId;
final String transport;
final double position;
final DateTime serverTime;
final int mediaId;
final Map<String, Object?>? media;
final List<MemberView> members;
const RoomBroadcast({
required this.eventId,
required this.transport,
required this.position,
required this.serverTime,
required this.mediaId,
this.media,
required this.members,
});
Map<String, Object?> toJson() => {
't': 'room',
'eventId': eventId,
'transport': transport,
'position': position,
'serverTime': serverTime.toIso8601String(),
'mediaId': mediaId,
if (media != null) 'media': media,
'members': members.map((m) => m.toJson()).toList(),
};
factory RoomBroadcast.fromJson(Map<String, Object?> json) {
if (json['t'] != 'room') throw const ProtocolException('not a room broadcast');
final members = json['members'];
final media = json['media'];
return RoomBroadcast(
eventId: (json['eventId'] as num?)?.toInt() ?? 0,
transport: (json['transport'] as String?) ?? 'held',
position: (json['position'] as num?)?.toDouble() ?? 0.0,
serverTime: DateTime.tryParse('${json['serverTime']}') ?? DateTime.now().toUtc(),
mediaId: (json['mediaId'] as num?)?.toInt() ?? 0,
media: media is Map ? Map<String, Object?>.from(media) : null,
members: members is List
? members
.whereType<Map>()
.map((m) => MemberView.fromJson(Map<String, Object?>.from(m)))
.toList()
: const [],
);
}
}
class FeedMessage {
final String actor;
final String action;
final String? target;
final String reason;
final DateTime at;
const FeedMessage({
required this.actor,
required this.action,
this.target,
this.reason = '',
required this.at,
});
Map<String, Object?> toJson() => {
't': 'feed',
'actor': actor,
'action': action,
if (target != null) 'target': target,
'reason': reason,
'at': at.toIso8601String(),
};
factory FeedMessage.fromJson(Map<String, Object?> json) {
if (json['t'] != 'feed') throw const ProtocolException('not a feed message');
return FeedMessage(
actor: (json['actor'] as String?) ?? '',
action: (json['action'] as String?) ?? '',
target: json['target'] as String?,
reason: (json['reason'] as String?) ?? '',
at: DateTime.tryParse('${json['at']}') ?? DateTime.now().toUtc(),
);
}
}
class SyncEvent { final String kind;
final double position;
final bool doSeek;
final int ignoringOnTheFly;
const SyncEvent({required this.kind, required this.position, this.doSeek = false, this.ignoringOnTheFly = 0});
Map<String, Object?> toJson() => {
't': 'event',
'kind': kind,
'position': position,
'doSeek': doSeek,
'ignoringOnTheFly': ignoringOnTheFly,
};
factory SyncEvent.fromJson(Map<String, Object?> json) {
if (json['t'] != 'event') throw const ProtocolException('not an event message');
return SyncEvent(
kind: (json['kind'] as String?) ?? '',
position: (json['position'] as num?)?.toDouble() ?? 0.0,
doSeek: (json['doSeek'] as bool?) ?? false,
ignoringOnTheFly: (json['ignoringOnTheFly'] as num?)?.toInt() ?? 0,
);
}
}
+257
View File
@@ -0,0 +1,257 @@
import 'constants.dart';
import 'protocol.dart';
typedef RoomClock = DateTime Function();
enum Transport { playing, held }
enum Correction { none, slowDown, seek }
Correction correctionFor({required double ownPosition, required double roomPosition}) {
final drift = ownPosition - roomPosition;
if (drift.abs() > RelayConstants.driftSeekThresholdSecs) return Correction.seek;
if (drift > RelayConstants.slowDownThresholdSecs) return Correction.slowDown;
return Correction.none;
}
class EngineMember {
final String id;
final String token;
String name;
String avatar;
bool ready = false;
bool inSet = false;
double buffered = 0;
DateTime lastSeen;
EngineMember({
required this.id,
required this.token,
required this.name,
this.avatar = '',
required DateTime now,
}) : lastSeen = now;
MemberView view({required bool stale}) => MemberView(
id: id,
name: name,
avatar: avatar,
ready: ready,
inSet: inSet,
buffered: buffered,
stale: stale,
);
}
class EngineFeed {
final List<FeedMessage> pending = [];
void add(FeedMessage message) => pending.add(message);
List<FeedMessage> drain() {
final out = List<FeedMessage>.from(pending);
pending.clear();
return out;
}
}
class RoomEngine {
final RoomClock clock;
final Duration staleAfter;
final Duration dropAfter;
final EngineFeed feed = EngineFeed();
final Map<String, EngineMember> members = {};
int eventId = 0;
Transport transport = Transport.held;
double position = 0;
DateTime serverTime;
int mediaId = 1;
HelloMedia? media;
int _nextId = 1;
RoomEngine({RoomClock? clock, Duration? staleAfter, Duration? dropAfter})
: clock = clock ?? (() => DateTime.now().toUtc()),
staleAfter = staleAfter ?? const Duration(seconds: 15),
dropAfter = dropAfter ?? const Duration(seconds: 30),
serverTime = (clock ?? (() => DateTime.now().toUtc()))();
DateTime get now => clock();
double positionAt([DateTime? at]) {
final t = at ?? now;
if (transport != Transport.playing) return position;
return position + t.difference(serverTime).inMilliseconds / 1000.0;
}
bool isStale(EngineMember member, [DateTime? at]) =>
(at ?? now).difference(member.lastSeen) > staleAfter;
String applyJoin(String token, String name, String avatar) {
final id = 'm${_nextId++}';
members[token] =
EngineMember(id: id, token: token, name: name, avatar: avatar, now: now);
feed.add(FeedMessage(actor: name, action: 'join', at: now));
return id;
}
String? applyLeave(String token) {
final removed = members.remove(token);
if (removed == null) return null;
feed.add(FeedMessage(actor: removed.name, action: 'leave', at: now));
evaluate();
return removed.id;
}
EngineMember? byId(String id) {
for (final member in members.values) {
if (member.id == id) return member;
}
return null;
}
void applyReady(String token, bool ready, {String source = 'manual'}) {
final member = members[token];
if (member == null) return;
member.lastSeen = now;
if (member.ready == ready && member.inSet) {
evaluate();
return;
}
member.ready = ready;
if (ready) member.inSet = true;
feed.add(FeedMessage(
actor: member.name,
action: ready ? 'ready' : 'unready',
reason: source,
at: now));
evaluate();
}
void applyForce(String actorToken, String target, bool ready) {
final actor = members[actorToken];
final actorName = actor?.name ?? '?';
if (target == 'all') {
for (final member in members.values) {
member.ready = ready;
if (ready) member.inSet = true;
}
} else {
final member = byId(target);
if (member == null) return;
member.ready = ready;
if (ready) member.inSet = true;
feed.add(FeedMessage(
actor: actorName,
action: ready ? 'force-ready' : 'force-unready',
target: member.name,
at: now));
evaluate();
return;
}
feed.add(FeedMessage(
actor: actorName,
action: ready ? 'force-play' : 'force-hold',
at: now));
evaluate();
}
void applySeek(String token, double seekPosition) {
final member = members[token];
if (member == null) return;
if (seekPosition.isNaN || seekPosition < 0) return;
member.lastSeen = now;
position = seekPosition;
serverTime = now;
eventId++;
feed.add(FeedMessage(actor: member.name, action: 'seek', at: now));
}
void applySwap(String actorToken, HelloMedia next) {
final actor = members[actorToken];
mediaId++;
media = next;
position = 0;
serverTime = now;
eventId++;
transport = Transport.held;
for (final member in members.values) {
member.ready = false;
member.inSet = false;
member.buffered = 0;
}
feed.add(FeedMessage(actor: actor?.name ?? '?', action: 'swap', at: now));
}
void applyReport(String token, double reportPosition, double buffered, int reportEventId) {
final member = members[token];
if (member == null) return;
member.lastSeen = now;
member.buffered = buffered.isNaN || buffered < 0 ? 0 : buffered;
if (reportEventId < eventId) return;
evaluate();
}
void sweepStale() {
var changed = false;
for (final member in members.values) {
if (isStale(member) && member.inSet) {
member.inSet = false;
changed = true;
feed.add(FeedMessage(actor: member.name, action: 'stale', reason: 'no signal', at: now));
}
}
if (changed) evaluate();
}
List<String> sweepDropped() {
final t = now;
final dropped = <String>[];
for (final member in members.values.toList()) {
if (t.difference(member.lastSeen) > dropAfter) {
members.remove(member.token);
dropped.add(member.token);
feed.add(FeedMessage(actor: member.name, action: 'leave', reason: 'silent too long', at: t));
}
}
if (dropped.isNotEmpty) evaluate();
return dropped;
}
void evaluate() {
final t = now;
if (transport == Transport.playing) {
final blocked = members.values
.where((m) => m.inSet)
.any((m) => !m.ready || m.buffered < RelayConstants.minBufferSecs || isStale(m, t));
if (blocked) {
position = positionAt(t);
serverTime = t;
eventId++;
transport = Transport.held;
feed.add(FeedMessage(actor: 'server', action: 'pause', at: t));
}
return;
}
final inSet = members.values.where((m) => m.inSet).toList();
if (inSet.isEmpty) return;
final freshCount =
members.values.where((m) => !isStale(m, t)).length;
final quorum = inSet.length >= 2 || freshCount <= 1;
final allGood = inSet.every(
(m) => m.ready && m.buffered >= RelayConstants.minBufferSecs && !isStale(m, t));
if (allGood && quorum) {
serverTime = t;
eventId++;
transport = Transport.playing;
feed.add(FeedMessage(actor: 'server', action: 'resume', at: t));
}
}
RoomBroadcast broadcast() => RoomBroadcast(
eventId: eventId,
transport: transport == Transport.playing ? 'playing' : 'held',
position: position,
serverTime: serverTime,
mediaId: mediaId,
media: media?.toJson(),
members: members.values.map((m) => m.view(stale: isStale(m))).toList(),
);
}
+389
View File
@@ -0,0 +1,389 @@
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
_fe_analyzer_shared:
dependency: transitive
description:
name: _fe_analyzer_shared
sha256: fe18c7e37d5acb3b43224fa255281dec007970d6fd01f6d76fcd88ed3777a117
url: "https://pub.dev"
source: hosted
version: "107.0.0"
analyzer:
dependency: transitive
description:
name: analyzer
sha256: f2dde9e50c23fc95b846b4ef334e98c3ae8c0effd5d2453b02fc9fb3f8939791
url: "https://pub.dev"
source: hosted
version: "14.3.0"
args:
dependency: transitive
description:
name: args
sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04
url: "https://pub.dev"
source: hosted
version: "2.7.0"
async:
dependency: transitive
description:
name: async
sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37
url: "https://pub.dev"
source: hosted
version: "2.13.1"
boolean_selector:
dependency: transitive
description:
name: boolean_selector
sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea"
url: "https://pub.dev"
source: hosted
version: "2.1.2"
cli_config:
dependency: transitive
description:
name: cli_config
sha256: ac20a183a07002b700f0c25e61b7ee46b23c309d76ab7b7640a028f18e4d99ec
url: "https://pub.dev"
source: hosted
version: "0.2.0"
collection:
dependency: transitive
description:
name: collection
sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
url: "https://pub.dev"
source: hosted
version: "1.19.1"
convert:
dependency: transitive
description:
name: convert
sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68
url: "https://pub.dev"
source: hosted
version: "3.1.2"
coverage:
dependency: transitive
description:
name: coverage
sha256: "956a3de0725ca232ad353565a8290d3357592bf4250f6f298a185e2d949c5d3d"
url: "https://pub.dev"
source: hosted
version: "1.15.1"
crypto:
dependency: "direct main"
description:
name: crypto
sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
url: "https://pub.dev"
source: hosted
version: "3.0.7"
file:
dependency: transitive
description:
name: file
sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4
url: "https://pub.dev"
source: hosted
version: "7.0.1"
frontend_server_client:
dependency: transitive
description:
name: frontend_server_client
sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694
url: "https://pub.dev"
source: hosted
version: "4.0.0"
glob:
dependency: transitive
description:
name: glob
sha256: "218aeb56050c714f62a3182775320dfa04602b55074873e24e31bbd39bda96fb"
url: "https://pub.dev"
source: hosted
version: "2.2.0"
http_multi_server:
dependency: transitive
description:
name: http_multi_server
sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8
url: "https://pub.dev"
source: hosted
version: "3.2.2"
http_parser:
dependency: transitive
description:
name: http_parser
sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"
url: "https://pub.dev"
source: hosted
version: "4.1.2"
io:
dependency: transitive
description:
name: io
sha256: "2635216ca6a737e60de577ffa1a48a0bec76ca8a62917cfc1bb88c14c570646f"
url: "https://pub.dev"
source: hosted
version: "1.1.0"
lints:
dependency: "direct dev"
description:
name: lints
sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7
url: "https://pub.dev"
source: hosted
version: "5.1.1"
logging:
dependency: "direct main"
description:
name: logging
sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61
url: "https://pub.dev"
source: hosted
version: "1.3.0"
matcher:
dependency: transitive
description:
name: matcher
sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd"
url: "https://pub.dev"
source: hosted
version: "0.12.20"
meta:
dependency: transitive
description:
name: meta
sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
url: "https://pub.dev"
source: hosted
version: "1.19.0"
mime:
dependency: transitive
description:
name: mime
sha256: bd47de35f07e27267e69c8c8b22edf9473bfee170a60d60fcc93730c5144b7f6
url: "https://pub.dev"
source: hosted
version: "2.1.0"
node_preamble:
dependency: transitive
description:
name: node_preamble
sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db"
url: "https://pub.dev"
source: hosted
version: "2.0.2"
package_config:
dependency: transitive
description:
name: package_config
sha256: ffcf4cf3d6c0b74ac43708d9f56625506e8a68aa935abe9d267a7330f320eb5d
url: "https://pub.dev"
source: hosted
version: "3.0.0"
path:
dependency: "direct main"
description:
name: path
sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
url: "https://pub.dev"
source: hosted
version: "1.9.1"
pool:
dependency: transitive
description:
name: pool
sha256: "4177f68c237ea2128d1bee66ac17b2ce05ba3dbaafcbdd54c5d40a39d0b6b11c"
url: "https://pub.dev"
source: hosted
version: "1.5.3"
pub_semver:
dependency: transitive
description:
name: pub_semver
sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24"
url: "https://pub.dev"
source: hosted
version: "2.2.1"
shelf:
dependency: transitive
description:
name: shelf
sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12
url: "https://pub.dev"
source: hosted
version: "1.4.2"
shelf_packages_handler:
dependency: transitive
description:
name: shelf_packages_handler
sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e"
url: "https://pub.dev"
source: hosted
version: "3.0.2"
shelf_static:
dependency: transitive
description:
name: shelf_static
sha256: c87c3875f91262785dade62d135760c2c69cb217ac759485334c5857ad89f6e3
url: "https://pub.dev"
source: hosted
version: "1.1.3"
shelf_web_socket:
dependency: transitive
description:
name: shelf_web_socket
sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925"
url: "https://pub.dev"
source: hosted
version: "3.0.0"
source_map_stack_trace:
dependency: transitive
description:
name: source_map_stack_trace
sha256: c0713a43e323c3302c2abe2a1cc89aa057a387101ebd280371d6a6c9fa68516b
url: "https://pub.dev"
source: hosted
version: "2.1.2"
source_maps:
dependency: transitive
description:
name: source_maps
sha256: "14c2945847669b44089bb1222f66873d7ff7103c58911917f2a63c5a62327898"
url: "https://pub.dev"
source: hosted
version: "0.10.14"
source_span:
dependency: transitive
description:
name: source_span
sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab"
url: "https://pub.dev"
source: hosted
version: "1.10.2"
stack_trace:
dependency: transitive
description:
name: stack_trace
sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490"
url: "https://pub.dev"
source: hosted
version: "1.12.2"
stream_channel:
dependency: transitive
description:
name: stream_channel
sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"
url: "https://pub.dev"
source: hosted
version: "2.1.4"
string_scanner:
dependency: transitive
description:
name: string_scanner
sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43"
url: "https://pub.dev"
source: hosted
version: "1.4.1"
term_glyph:
dependency: transitive
description:
name: term_glyph
sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e"
url: "https://pub.dev"
source: hosted
version: "1.2.2"
test:
dependency: "direct dev"
description:
name: test
sha256: de5d145b0afff7921e5e788a880f52d7e5f3ae24068a202f6fd3b58e4ba26323
url: "https://pub.dev"
source: hosted
version: "1.32.0"
test_api:
dependency: transitive
description:
name: test_api
sha256: "0a10344e901e5b2e63819567951cb6a06673ed6b84f40462188ff5a0c41f371f"
url: "https://pub.dev"
source: hosted
version: "0.7.14"
test_core:
dependency: transitive
description:
name: test_core
sha256: "80f3fb49087454e07e7e07c67578cfdd156c8c3a5227d8b3f47c7b2d019c2e93"
url: "https://pub.dev"
source: hosted
version: "0.6.20"
typed_data:
dependency: transitive
description:
name: typed_data
sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006
url: "https://pub.dev"
source: hosted
version: "1.4.0"
vm_service:
dependency: transitive
description:
name: vm_service
sha256: "5f37239c4851efcef929cea7824e76df7f2f0970aef85d66bbc430afa40e72f0"
url: "https://pub.dev"
source: hosted
version: "15.3.0"
watcher:
dependency: transitive
description:
name: watcher
sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635"
url: "https://pub.dev"
source: hosted
version: "1.2.1"
web:
dependency: transitive
description:
name: web
sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
url: "https://pub.dev"
source: hosted
version: "1.1.1"
web_socket:
dependency: transitive
description:
name: web_socket
sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c"
url: "https://pub.dev"
source: hosted
version: "1.0.1"
web_socket_channel:
dependency: "direct main"
description:
name: web_socket_channel
sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8
url: "https://pub.dev"
source: hosted
version: "3.0.3"
webkit_inspection_protocol:
dependency: transitive
description:
name: webkit_inspection_protocol
sha256: "87d3f2333bb240704cd3f1c6b5b7acd8a10e7f0bc28c28dcf14e782014f4a572"
url: "https://pub.dev"
source: hosted
version: "1.2.1"
yaml:
dependency: "direct main"
description:
name: yaml
sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea
url: "https://pub.dev"
source: hosted
version: "3.1.4"
sdks:
dart: ">=3.11.0 <4.0.0"
+14
View File
@@ -0,0 +1,14 @@
name: sync_relay_core
description: Pure-Dart protocol, sync engine, media-source abstractions. No Flutter.
version: 0.1.0
environment:
sdk: ^3.0.0
dependencies:
logging: ^1.2.0
yaml: ^3.1.0
path: ^1.9.0
crypto: ^3.0.0
web_socket_channel: ^3.0.0
dev_dependencies:
lints: ^5.0.0
test: ^1.25.0
+94
View File
@@ -0,0 +1,94 @@
import 'package:sync_relay_core/core.dart';
import 'package:test/test.dart';
void main() {
group('AppConfig', () {
test('defaults are sane', () {
final c = AppConfig.defaults();
expect(c.port, 8080);
expect(c.secret, isNotEmpty);
});
test('fromMap tolerates missing keys', () {
final c = AppConfig.fromMap({});
expect(c.port, 8080);
expect(c.name, 'room');
});
test('round-trips through map', () {
const c = AppConfig(
port: 1234,
secret: 's',
name: 'n',
mediaPath: 'm',
advertiseHost: '1.2.3.4');
final back = AppConfig.fromMap(c.toMap());
expect(back.port, 1234);
expect(back.secret, 's');
expect(back.mediaPath, 'm');
expect(back.advertiseHost, '1.2.3.4');
});
});
group('protocol', () {
test('hello round-trips', () {
const msg = HelloMessage(
proto: 1,
secret: 'shh',
user: HelloUser(name: 'alice'),
media: HelloMedia(name: 'Ep01.mkv', size: 1500000000, duration: 1400.0),
);
final back = HelloMessage.fromJson(Map<String, Object?>.from(msg.toJson()));
expect(back.user.name, 'alice');
expect(back.media.size, 1500000000);
});
test('hello rejects wrong type', () {
expect(() => HelloMessage.fromJson({'t': 'bye'}), throwsA(isA<ProtocolException>()));
});
test('room state round-trips', () {
final s = RoomState(position: 12.5, paused: false, mediaId: 3, serverTime: DateTime.utc(2026, 1, 1));
final back = RoomState.fromJson(Map<String, Object?>.from(s.toJson()));
expect(back.position, 12.5);
expect(back.paused, isFalse);
expect(back.mediaId, 3);
});
test('sync event carries doSeek flag', () {
const e = SyncEvent(kind: 'seek', position: 42.0, doSeek: true, ignoringOnTheFly: 7);
final back = SyncEvent.fromJson(Map<String, Object?>.from(e.toJson()));
expect(back.doSeek, isTrue);
expect(back.ignoringOnTheFly, 7);
});
});
group('RangeRequest', () {
test('open-ended range', () {
final r = RangeRequest.parse('bytes=100-', 1000)!;
expect(r.start, 100);
expect(r.end, isNull);
expect(r.contentLength, 900);
});
test('closed range', () {
final r = RangeRequest.parse('bytes=0-99', 1000)!;
expect(r.contentLength, 100);
expect(r.contentRange, 'bytes 0-99/1000');
});
test('suffix range maps to tail (mkv cues probe)', () {
final r = RangeRequest.parse('bytes=-500', 1000)!;
expect(r.start, 500);
expect(r.contentLength, 500);
});
test('missing header returns null (full 200)', () {
expect(RangeRequest.parse(null, 1000), isNull);
});
test('out-of-range start rejected', () {
expect(RangeRequest.parse('bytes=5000-6000', 1000), isNull);
});
});
}
+20
View File
@@ -0,0 +1,20 @@
import 'dart:io';
import 'package:test/test.dart';
void main() {
test('core has zero flutter imports', () async {
final libDir = Directory('lib');
final offenders = <String>[];
await for (final entity in libDir.list(recursive: true)) {
if (entity is! File || !entity.path.endsWith('.dart')) continue;
final content = await entity.readAsString();
if (content.contains('package:flutter/') ||
content.contains('dart:ui') ||
content.contains('package:signals/signals_flutter')) {
offenders.add(entity.path);
}
}
expect(offenders, isEmpty, reason: 'Flutter imports in core: $offenders');
});
}
+385
View File
@@ -0,0 +1,385 @@
import 'package:sync_relay_core/core.dart';
import 'package:test/test.dart';
void main() {
late DateTime t;
late RoomEngine engine;
DateTime clock() => t;
setUp(() {
t = DateTime.utc(2026, 1, 1);
engine = RoomEngine(clock: clock);
});
String join(String token, String name) => engine.applyJoin(token, name, '');
void buffer(String token, double secs) =>
engine.applyReport(token, engine.positionAt(), secs, engine.eventId);
group('membership + gate', () {
test('join lands out-of-set, room stays held', () {
join('a', 'alice');
expect(engine.transport, Transport.held);
expect(engine.members['a']!.inSet, isFalse);
final room = engine.broadcast();
expect(room.members.single.inSet, isFalse);
});
test('single ready + buffered auto-plays', () {
join('a', 'alice');
engine.applyReady('a', true);
expect(engine.members['a']!.inSet, isTrue);
expect(engine.transport, Transport.held);
buffer('a', 4.0);
expect(engine.transport, Transport.playing);
});
test('late joiner does not halt a playing room', () {
join('a', 'alice');
engine.applyReady('a', true);
buffer('a', 4.0);
expect(engine.transport, Transport.playing);
join('b', 'bob');
expect(engine.transport, Transport.playing);
expect(engine.members['b']!.inSet, isFalse);
});
test('single unready in playing set pauses, stays in set', () {
join('a', 'alice');
join('b', 'bob');
engine.applyReady('a', true);
engine.applyReady('b', true);
buffer('a', 4.0);
buffer('b', 4.0);
expect(engine.transport, Transport.playing);
engine.applyReady('b', false);
expect(engine.transport, Transport.held);
expect(engine.members['b']!.inSet, isTrue);
});
test('disconnect removes from quorum, room resumes', () {
join('a', 'alice');
join('b', 'bob');
engine.applyReady('a', true);
engine.applyReady('b', true);
buffer('a', 4.0);
buffer('b', 4.0);
expect(engine.transport, Transport.playing);
engine.applyLeave('b');
expect(engine.transport, Transport.playing);
expect(engine.members.containsKey('b'), isFalse);
});
test('stale ghosts excluded from gate', () { join('a', 'alice');
join('b', 'bob');
engine.applyReady('a', true);
engine.applyReady('b', true);
buffer('a', 4.0);
buffer('b', 4.0);
expect(engine.transport, Transport.playing);
t = t.add(const Duration(seconds: 60));
engine.sweepStale();
expect(engine.transport, Transport.playing);
expect(engine.broadcast().members.firstWhere((m) => m.id == 'm2').stale, isTrue);
});
test('silent past drop window removed with leave feed', () {
join('a', 'alice');
join('b', 'bob');
engine.applyReady('a', true);
engine.applyReady('b', true);
buffer('a', 4.0);
buffer('b', 4.0);
expect(engine.transport, Transport.playing);
t = t.add(const Duration(seconds: 30));
expect(engine.sweepDropped(), isEmpty);
buffer('a', 4.0);
t = t.add(const Duration(seconds: 61));
buffer('a', 4.0);
final dropped = engine.sweepDropped();
expect(dropped, ['b']);
expect(engine.members.containsKey('b'), isFalse);
expect(engine.transport, Transport.playing);
final leaves = engine.feed.drain().where((f) => f.action == 'leave').toList();
expect(leaves.single.actor, 'bob');
expect(leaves.single.reason, 'silent too long');
});
});
group('quorum gate', () {
test('one ready of two fresh stays held', () {
join('a', 'alice');
join('b', 'bob');
engine.applyReady('a', true);
buffer('a', 6.0);
expect(engine.transport, Transport.held);
expect(engine.members['a']!.inSet, isTrue);
});
test('second ready opens the gate', () {
join('a', 'alice');
join('b', 'bob');
engine.applyReady('a', true);
buffer('a', 6.0);
expect(engine.transport, Transport.held);
engine.applyReady('b', true);
buffer('b', 6.0);
expect(engine.transport, Transport.playing);
});
test('stale other exempts the lone watcher', () {
join('a', 'alice');
join('b', 'bob');
t = t.add(const Duration(seconds: 16));
engine.applyReady('a', true);
buffer('a', 6.0);
expect(engine.transport, Transport.playing);
});
test('late joiner outside the set never blocks', () {
join('a', 'alice');
join('b', 'bob');
engine.applyReady('a', true);
engine.applyReady('b', true);
buffer('a', 6.0);
buffer('b', 6.0);
expect(engine.transport, Transport.playing);
join('c', 'cara');
expect(engine.transport, Transport.playing);
});
});
group('clock ownership', () {
test('clock advances only while playing', () {
expect(engine.positionAt(), 0);
t = t.add(const Duration(seconds: 10));
expect(engine.positionAt(), 0);
join('a', 'alice');
engine.applyReady('a', true);
buffer('a', 4.0);
t = t.add(const Duration(seconds: 10));
expect(engine.positionAt(), closeTo(10.0, 0.001));
});
test('lagging report cannot drag clock backward or forward', () {
join('a', 'alice');
engine.applyReady('a', true);
buffer('a', 4.0);
t = t.add(const Duration(seconds: 100));
expect(engine.positionAt(), closeTo(100.0, 0.01));
engine.applyReport('a', 5.0, 4.0, engine.eventId);
expect(engine.positionAt(), closeTo(100.0, 0.01));
engine.applyReport('a', 5000.0, 4.0, engine.eventId);
expect(engine.positionAt(), closeTo(100.0, 0.01));
});
test('stale eventId report position ignored, buffer kept', () {
join('a', 'alice');
engine.applyReady('a', true);
buffer('a', 4.0);
t = t.add(const Duration(seconds: 50));
engine.applySeek('a', 200.0);
final eid = engine.eventId;
engine.applyReport('a', 9999.0, 7.0, eid - 1);
expect(engine.positionAt(), closeTo(200.0, 0.01));
expect(engine.members['a']!.buffered, 7.0);
});
test('free seek while playing keeps transport, jumps edge', () {
join('a', 'alice');
engine.applyReady('a', true);
buffer('a', 4.0);
t = t.add(const Duration(seconds: 30));
final before = engine.eventId;
engine.applySeek('a', 600.0);
expect(engine.transport, Transport.playing);
expect(engine.positionAt(), closeTo(600.0, 0.01));
expect(engine.eventId, greaterThan(before));
expect(engine.members['a']!.ready, isTrue);
});
test('unpause uses room clock, laggards seek forward', () {
join('a', 'alice');
join('b', 'bob');
engine.applyReady('a', true);
engine.applyReady('b', true);
buffer('a', 4.0);
buffer('b', 4.0);
t = t.add(const Duration(seconds: 60));
engine.applyReady('b', false);
final frozen = engine.positionAt();
expect(frozen, closeTo(60.0, 0.01));
t = t.add(const Duration(seconds: 30));
expect(engine.positionAt(), closeTo(60.0, 0.01));
engine.applyReady('b', true);
buffer('a', 4.0);
buffer('b', 4.0);
expect(engine.transport, Transport.playing);
expect(engine.positionAt(), closeTo(60.0, 0.01));
});
});
group('starvation without flag churn', () {
test('zero buffer pauses, refill resumes, flags untouched', () {
join('a', 'alice');
engine.applyReady('a', true);
buffer('a', 4.0);
expect(engine.transport, Transport.playing);
engine.feed.drain();
engine.applyReport('a', engine.positionAt(), 0.0, engine.eventId);
expect(engine.transport, Transport.held);
expect(engine.members['a']!.ready, isTrue);
final feeds = engine.feed.drain().map((f) => f.action).toList();
expect(feeds, contains('pause'));
expect(feeds, isNot(contains('unready')));
buffer('a', 4.0);
expect(engine.transport, Transport.playing);
});
});
group('swap resets everything', () {
test('swap bumps mediaId, clears sets, holds', () {
join('a', 'alice');
engine.applyReady('a', true);
buffer('a', 4.0);
expect(engine.transport, Transport.playing);
engine.applySwap('a',
const HelloMedia(name: 'Ep02.mkv', size: 9, duration: 9.0));
expect(engine.mediaId, 2);
expect(engine.transport, Transport.held);
expect(engine.positionAt(), 0);
expect(engine.members['a']!.inSet, isFalse);
expect(engine.members['a']!.ready, isFalse);
});
});
group('force with actor feed', () {
test('force-play-all readies everyone, attributed', () {
join('a', 'alice');
join('b', 'bob');
engine.feed.drain();
engine.applyForce('a', 'all', true);
expect(engine.members['b']!.ready, isTrue);
expect(engine.members['b']!.inSet, isTrue);
final feeds = engine.feed.drain();
expect(
feeds.any((f) => f.action == 'force-play' && f.actor == 'alice'),
isTrue);
});
test('force single by member id', () {
join('a', 'alice');
final idB = join('b', 'bob');
engine.feed.drain();
engine.applyForce('a', idB, true);
expect(engine.members['b']!.ready, isTrue);
final feeds = engine.feed.drain();
expect(
feeds.any((f) =>
f.action == 'force-ready' &&
f.actor == 'alice' &&
f.target == 'bob'),
isTrue);
});
test('force unknown id is a no-op', () {
join('a', 'alice');
engine.feed.drain();
engine.applyForce('a', 'm99', true);
expect(engine.feed.drain(), isEmpty);
});
});
group('flap stability', () {
test('rapid unready/ready converges to playing, pairs stay balanced', () {
join('a', 'alice');
engine.applyReady('a', true);
buffer('a', 4.0);
expect(engine.transport, Transport.playing);
engine.feed.drain();
for (var i = 0; i < 10; i++) {
engine.applyReady('a', false);
engine.applyReady('a', true);
}
buffer('a', 4.0);
expect(engine.transport, Transport.playing);
expect(engine.members['a']!.ready, isTrue);
final actions = engine.feed.drain().map((f) => f.action).toList();
expect(actions.where((a) => a == 'pause').length,
actions.where((a) => a == 'resume').length);
});
});
group('input sanitizing', () {
test('NaN/negative seek ignored, edge + eventId untouched', () {
join('a', 'alice');
engine.applyReady('a', true);
buffer('a', 4.0);
t = t.add(const Duration(seconds: 20));
final eid = engine.eventId;
engine.applySeek('a', double.nan);
engine.applySeek('a', -5.0);
expect(engine.positionAt(), closeTo(20.0, 0.01));
expect(engine.eventId, eid);
expect(engine.feed.drain().where((f) => f.action == 'seek'), isEmpty);
});
test('NaN buffered counts as zero, gate holds', () {
join('a', 'alice');
engine.applyReady('a', true);
engine.applyReport('a', 0, double.nan, engine.eventId);
expect(engine.members['a']!.buffered, 0);
expect(engine.transport, Transport.held);
});
});
group('tiered correction', () {
test('big drift seeks either direction', () {
expect(correctionFor(ownPosition: 100, roomPosition: 0), Correction.seek);
expect(correctionFor(ownPosition: 0, roomPosition: 100), Correction.seek);
});
test('ahead beyond 1.5s slows to 0.95x', () {
expect(correctionFor(ownPosition: 3, roomPosition: 0), Correction.slowDown);
expect(correctionFor(ownPosition: 1.6, roomPosition: 0), Correction.slowDown);
});
test('deadzone does nothing', () {
expect(correctionFor(ownPosition: 1.0, roomPosition: 0), Correction.none);
expect(correctionFor(ownPosition: 0, roomPosition: 3.0), Correction.none);
expect(correctionFor(ownPosition: 5.1, roomPosition: 0), Correction.seek);
expect(correctionFor(ownPosition: 5.0, roomPosition: 0), Correction.slowDown);
});
});
group('broadcast shape', () {
test('room JSON round-trips with member views', () {
join('a', 'alice');
final room = engine.broadcast();
final back =
RoomBroadcast.fromJson(Map<String, Object?>.from(room.toJson()));
expect(back.transport, 'held');
expect(back.members.single.name, 'alice');
expect(back.members.single.id, 'm1');
});
test('intent schemas round-trip', () {
const r = ReadyIntent(ready: true, source: 'auto');
expect(
ReadyIntent.fromJson(Map<String, Object?>.from(r.toJson())).source,
'auto');
const s = SeekIntent(position: 42.5);
expect(
SeekIntent.fromJson(Map<String, Object?>.from(s.toJson())).position,
42.5);
const c = ChatMessage(text: 'hi');
expect(
ChatMessage.fromJson(Map<String, Object?>.from(c.toJson())).text,
'hi');
const rp = ReportMessage(position: 1, buffered: 2, eventId: 3);
final rpBack =
ReportMessage.fromJson(Map<String, Object?>.from(rp.toJson()));
expect(rpBack.eventId, 3);
});
});
}