askrobots / dbbasic-scroll
Public
Scroll: the Flutter operator console for the DBBASIC Object Server, for people building alongside AI agents.
realtime.dart · 5.0 KB · 164 lines
| 1 | import 'dart:async'; |
| 2 | import 'dart:convert'; |
| 3 | import 'dart:io'; |
| 4 | import 'package:flutter/foundation.dart'; |
| 5 | |
| 6 | import 'api.dart'; |
| 7 | |
| 8 | /// Live record-change signals over the object server's `/ws` websocket. |
| 9 | /// |
| 10 | /// Signal-not-data: each event carries only {collection, record_id, action} |
| 11 | /// — never the record body — and delivery is permission-filtered server-side |
| 12 | /// (you only receive events for records your row filters would show). |
| 13 | /// Listeners refetch through the normal enforced API when notified. |
| 14 | /// |
| 15 | /// One shared connection for the whole app. Screens register interest in a |
| 16 | /// collection via [bind]; the manager ref-counts subscriptions, sends |
| 17 | /// subscribe frames, and reconnects with backoff. Over-subscription is |
| 18 | /// harmless (signals are tiny and permission-gated), so removal keeps the |
| 19 | /// server-side subscription — only local listeners are dropped. |
| 20 | class ScrollRealtime { |
| 21 | static final ScrollRealtime _instance = ScrollRealtime._(); |
| 22 | factory ScrollRealtime() => _instance; |
| 23 | ScrollRealtime._(); |
| 24 | |
| 25 | WebSocket? _socket; |
| 26 | StreamSubscription<dynamic>? _sub; |
| 27 | final Set<String> _subscriptions = {}; |
| 28 | final Map<String, int> _refCounts = {}; |
| 29 | final Map<String, ValueNotifier<int>> _tickers = {}; |
| 30 | |
| 31 | bool _connecting = false; |
| 32 | bool _wantConnected = false; |
| 33 | int _backoffMs = 1000; |
| 34 | Timer? _reconnectTimer; |
| 35 | |
| 36 | /// True while the websocket is open — drives a "live" indicator. |
| 37 | final ValueNotifier<bool> connected = ValueNotifier(false); |
| 38 | |
| 39 | /// Per-collection counter bumped on each record event, so a widget can |
| 40 | /// listen cheaply without threading callbacks. |
| 41 | ValueListenable<int> ticker(String collection) => |
| 42 | _tickers.putIfAbsent(collection, () => ValueNotifier(0)); |
| 43 | |
| 44 | /// Subscribe [collection] and invoke [onEvent] whenever one of its |
| 45 | /// records changes. Returns a disposer to call in State.dispose(). |
| 46 | VoidCallback bind(String collection, VoidCallback onEvent) { |
| 47 | _addSubscription(collection); |
| 48 | final tick = _tickers.putIfAbsent(collection, () => ValueNotifier(0)); |
| 49 | tick.addListener(onEvent); |
| 50 | return () { |
| 51 | tick.removeListener(onEvent); |
| 52 | _removeSubscription(collection); |
| 53 | }; |
| 54 | } |
| 55 | |
| 56 | void _addSubscription(String collection) { |
| 57 | final isNew = !_subscriptions.contains(collection); |
| 58 | _refCounts[collection] = (_refCounts[collection] ?? 0) + 1; |
| 59 | _subscriptions.add(collection); |
| 60 | _ensureConnected(); |
| 61 | if (isNew && connected.value) { |
| 62 | _sendSubscribe([collection]); |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | void _removeSubscription(String collection) { |
| 67 | final remaining = (_refCounts[collection] ?? 1) - 1; |
| 68 | if (remaining <= 0) { |
| 69 | _refCounts.remove(collection); |
| 70 | // Keep the server subscription (signal-only, permission-filtered); |
| 71 | // with no local listeners its ticks are simply ignored. |
| 72 | } else { |
| 73 | _refCounts[collection] = remaining; |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | void _ensureConnected() { |
| 78 | _wantConnected = true; |
| 79 | if (_socket == null && !_connecting) _connect(); |
| 80 | } |
| 81 | |
| 82 | Future<void> _connect() async { |
| 83 | if (_connecting || !_wantConnected) return; |
| 84 | final url = ScrollAPI().realtimeUrl; |
| 85 | if (url == null) return; |
| 86 | _connecting = true; |
| 87 | try { |
| 88 | final socket = await WebSocket.connect( |
| 89 | url, |
| 90 | headers: ScrollAPI().realtimeHeaders, |
| 91 | ); |
| 92 | _socket = socket; |
| 93 | _connecting = false; |
| 94 | _backoffMs = 1000; |
| 95 | connected.value = true; |
| 96 | if (_subscriptions.isNotEmpty) { |
| 97 | _sendSubscribe(_subscriptions.toList()); |
| 98 | } |
| 99 | _sub = socket.listen( |
| 100 | _onMessage, |
| 101 | onDone: _onDisconnect, |
| 102 | onError: (_) => _onDisconnect(), |
| 103 | cancelOnError: true, |
| 104 | ); |
| 105 | } catch (_) { |
| 106 | _connecting = false; |
| 107 | connected.value = false; |
| 108 | _scheduleReconnect(); |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | void _onMessage(dynamic data) { |
| 113 | if (data is! String) return; |
| 114 | dynamic message; |
| 115 | try { |
| 116 | message = jsonDecode(data); |
| 117 | } catch (_) { |
| 118 | return; |
| 119 | } |
| 120 | if (message is! Map) return; |
| 121 | if (message['type'] == 'record') { |
| 122 | final collection = message['collection']?.toString(); |
| 123 | if (collection != null) { |
| 124 | _tickers[collection]?.value++; |
| 125 | } |
| 126 | } |
| 127 | // {welcome} and any other frames are informational — ignored. |
| 128 | } |
| 129 | |
| 130 | void _onDisconnect() { |
| 131 | _sub?.cancel(); |
| 132 | _sub = null; |
| 133 | _socket = null; |
| 134 | connected.value = false; |
| 135 | if (_wantConnected) _scheduleReconnect(); |
| 136 | } |
| 137 | |
| 138 | void _scheduleReconnect() { |
| 139 | _reconnectTimer?.cancel(); |
| 140 | _reconnectTimer = Timer(Duration(milliseconds: _backoffMs), _connect); |
| 141 | _backoffMs = (_backoffMs * 2).clamp(1000, 30000); |
| 142 | } |
| 143 | |
| 144 | void _sendSubscribe(List<String> collections) { |
| 145 | if (collections.isEmpty) return; |
| 146 | _socket?.add( |
| 147 | jsonEncode({'action': 'subscribe', 'collections': collections}), |
| 148 | ); |
| 149 | } |
| 150 | |
| 151 | /// Tear down on disconnect / sign-out. Subscriptions are cleared; a |
| 152 | /// later bind() reconnects fresh with the new session. |
| 153 | void shutdown() { |
| 154 | _wantConnected = false; |
| 155 | _reconnectTimer?.cancel(); |
| 156 | _sub?.cancel(); |
| 157 | _sub = null; |
| 158 | _socket?.close(); |
| 159 | _socket = null; |
| 160 | _subscriptions.clear(); |
| 161 | _refCounts.clear(); |
| 162 | connected.value = false; |
| 163 | } |
| 164 | } |