Scroll: the Flutter operator console for the DBBASIC Object Server, for people building alongside AI agents.

0 downloads

dbbasic-scroll/lib/data.dart
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-scroll.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-scroll.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-scroll.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

quellhorst Extension fields + schema conflict field names e8a817f 4 months, 1 week ago History
data.dart · 19.0 KB · 634 lines
1import 'api.dart';
2
3/// Cached data from the object server and platform API.
4/// Loads once on connect, refreshes on demand.
5class ScrollData {
6 static final ScrollData _instance = ScrollData._();
7 factory ScrollData() => _instance;
8 ScrollData._();
9
10 // Object server
11 Map<String, dynamic>? adminStatus;
12 Map<String, dynamic>? daemonStatus;
13 Map<String, dynamic>? daemonSchedulerTasksResponse;
14 Map<String, dynamic>? daemonQueueMessagesResponse;
15 Map<String, dynamic>? eventDeliveriesResponse;
16 Map<String, dynamic>? adminChangesResponse;
17 Map<String, dynamic>? permissionsStatus;
18 Map<String, dynamic>? permissionsPolicy;
19 Map<String, dynamic>? health;
20 Map<String, dynamic>? cluster;
21 List<dynamic> objects = [];
22 bool clusterAvailable = false;
23 bool usingHealthFallback = false;
24
25 // Platform counts
26 int projectCount = 0;
27 int contactCount = 0;
28 int taskCount = 0;
29 int fileCount = 0;
30 int objectCount = 0;
31
32 // Station info
33 List<dynamic> stations = [];
34 String uptime = '';
35 int requests = 0;
36 int errors = 0;
37 double rps = 0;
38 double errorRate = 0;
39 String version = '';
40 Map<String, dynamic>? responseTime;
41
42 bool loaded = false;
43
44 /// Reset every cached value. Call on disconnect so a later connection
45 /// (possibly a different token/identity) never renders stale data.
46 void clear() {
47 adminStatus = null;
48 daemonStatus = null;
49 daemonSchedulerTasksResponse = null;
50 daemonQueueMessagesResponse = null;
51 eventDeliveriesResponse = null;
52 adminChangesResponse = null;
53 permissionsStatus = null;
54 permissionsPolicy = null;
55 health = null;
56 cluster = null;
57 objects = [];
58 stations = [];
59 clusterAvailable = false;
60 usingHealthFallback = false;
61 projectCount = 0;
62 contactCount = 0;
63 taskCount = 0;
64 fileCount = 0;
65 objectCount = 0;
66 uptime = '';
67 requests = 0;
68 errors = 0;
69 rps = 0;
70 errorRate = 0;
71 version = '';
72 responseTime = null;
73 loaded = false;
74 }
75
76 Future<void> loadAll() async {
77 final api = ScrollAPI();
78
79 // Fields are swapped in as responses arrive (never blanked first), so a
80 // widget rebuilding mid-load renders last-known data instead of zeros.
81 // Object server health — the stats live behind metrics=true (auth
82 // required); fall back to the public plain /health if that is denied.
83 health = await api.getHealth(metrics: true) ?? await api.getHealth();
84 adminStatus = await api.getAdminStatus();
85 daemonStatus = await api.getDaemonStatus();
86 daemonSchedulerTasksResponse = await api.getDaemonSchedulerTasks();
87 daemonQueueMessagesResponse = await api.getDaemonQueueMessages();
88 eventDeliveriesResponse = await api.getEventDeliveries();
89 adminChangesResponse = await api.listAdminChanges();
90 permissionsStatus = await api.getPermissionsStatus();
91 permissionsPolicy = await api.getPermissionsPolicy();
92 if (health != null) {
93 uptime = health!['uptime']?.toString() ?? '';
94 requests = health!['requests'] as int? ?? 0;
95 errors = health!['errors'] as int? ?? 0;
96 rps = (health!['rps'] as num?)?.toDouble() ?? 0;
97 errorRate = (health!['error_rate'] as num?)?.toDouble() ?? 0;
98 version = health!['version']?.toString() ?? '';
99 responseTime = health!['response_time_ms'] as Map<String, dynamic>?;
100 }
101
102 // Cluster stations are optional on the OSS object server. If unavailable,
103 // show the connected server as a single node based on /health.
104 List<dynamic> newStations = [];
105 var newClusterAvailable = false;
106 var newFallback = false;
107 final clusterData = await api.getClusterStations();
108 if (clusterData is Map<String, dynamic>) {
109 cluster = clusterData;
110 final clusterStations = clusterData['stations'];
111 if (clusterStations is List && clusterStations.isNotEmpty) {
112 newStations = clusterStations;
113 newClusterAvailable = true;
114 }
115 }
116 if (newStations.isEmpty && health != null) {
117 newStations = [_singleServerStation(api.objectServerUrl ?? '')];
118 newFallback = true;
119 }
120 stations = newStations;
121 clusterAvailable = newClusterAvailable;
122 usingHealthFallback = newFallback;
123
124 // Objects
125 objects = await api.listObjects();
126 objectCount = _inventoryInt('objects') ?? objects.length;
127
128 // Platform counts (if connected)
129 if (api.hasPlatform) {
130 projectCount = await api.platformCount('projects');
131 contactCount = await api.platformCount('contacts');
132 taskCount = await api.platformCount('tasks');
133 fileCount = await api.platformCount('files');
134 }
135
136 loaded = true;
137 }
138
139 int get activeStations =>
140 stations.where((s) => s['is_active'] == true).length;
141 String get stationSummary {
142 if (adminStatus != null) {
143 return adminHealthStatus == 'ok'
144 ? 'Admin status healthy'
145 : 'Admin status $adminHealthStatus';
146 }
147 if (usingHealthFallback) {
148 return health?['status'] == 'ok'
149 ? 'Single OSS server healthy'
150 : 'Single OSS server status unknown';
151 }
152 return '$activeStations stations healthy';
153 }
154
155 Map<String, dynamic> _singleServerStation(String serverUrl) {
156 final uri = Uri.tryParse(serverUrl);
157 final host = uri?.host.isNotEmpty == true ? uri!.host : 'object-server';
158 final status = health?['status']?.toString() ?? 'unknown';
159 // /health?metrics=true nests machine stats under system/objects.
160 final system = health?['system'] is Map
161 ? Map<String, dynamic>.from(health!['system'] as Map)
162 : const <String, dynamic>{};
163 final memory = system['memory'] is Map
164 ? Map<String, dynamic>.from(system['memory'] as Map)
165 : const <String, dynamic>{};
166 final disk = system['disk'] is Map
167 ? Map<String, dynamic>.from(system['disk'] as Map)
168 : const <String, dynamic>{};
169 final objects = health?['objects'] is Map
170 ? Map<String, dynamic>.from(health!['objects'] as Map)
171 : const <String, dynamic>{};
172 return {
173 'station_id': 'object-server',
174 'is_active': status == 'ok',
175 'version': health?['version']?.toString() ?? 'OSS',
176 'host': host,
177 'port': uri?.hasPort == true ? uri!.port : null,
178 'source': 'health',
179 'metrics': {
180 'status': status,
181 'cpu_percent': system['cpu_percent'] ?? health?['cpu_percent'],
182 'memory_percent': memory['used_percent'] ?? health?['memory_percent'],
183 'disk_percent': disk['used_percent'] ?? health?['disk_percent'],
184 'cpu_count': system['cpu_count'] ?? health?['cpu_count'],
185 'memory_total_mb': memory['total_mb'] ?? health?['memory_total_mb'],
186 'disk_used_gb': disk['used_gb'] ?? health?['disk_used_gb'],
187 'disk_total_gb': disk['total_gb'] ?? health?['disk_total_gb'],
188 'object_count': objects['count'] ?? health?['object_count'],
189 },
190 };
191 }
192
193 String get requestSummary {
194 if (requests > 1000000) {
195 return '${(requests / 1000000).toStringAsFixed(1)}M';
196 }
197 if (requests > 1000) return '${(requests / 1000).toStringAsFixed(1)}k';
198 return '$requests';
199 }
200
201 bool get hasAdminStatus => adminStatus != null;
202 bool get hasDaemonStatus => daemonStatus != null;
203
204 bool get hasDaemonSchedulerTasks => daemonSchedulerTasksResponse != null;
205 bool get hasDaemonQueueMessages => daemonQueueMessagesResponse != null;
206 bool get hasEventDeliveries => eventDeliveriesResponse != null;
207 bool get hasAdminChanges => adminChangesResponse != null;
208 bool get hasPermissionsStatus => effectivePermissionsStatus.isNotEmpty;
209 bool get hasPermissionsPolicy => effectivePermissionsPolicy.isNotEmpty;
210 bool get fileWritesEnabled =>
211 _boolFromDynamic(fileWritesCapability['enabled']) == true;
212 bool get sourceWritesEnabled =>
213 _boolFromDynamic(sourceWritesCapability['enabled']) == true;
214 bool get passwordLoginEnabled =>
215 _boolFromDynamic(identityCapability['password_login_enabled']) == true;
216 bool get sessionAdminGatesEnabled =>
217 _boolFromDynamic(identityCapability['session_admin_gates_enabled']) ==
218 true ||
219 _boolFromDynamic(identityCapability['admin_gates_enabled']) == true;
220 bool get backupApiExposed =>
221 _boolFromDynamic(backupCapability['enabled']) == true ||
222 _boolFromDynamic(backupCapability['available']) == true ||
223 _boolFromDynamic(backupCapability['api_exposed']) == true;
224
225 bool get backupCanCreate =>
226 _boolFromDynamic(backupCapability['can_create']) == true;
227 bool get backupCanDownload =>
228 _boolFromDynamic(backupCapability['can_download']) == true;
229 bool get backupCanRestore =>
230 _boolFromDynamic(backupCapability['can_restore']) == true;
231 bool get backupScheduled =>
232 _boolFromDynamic(backupCapability['scheduled']) == true;
233 String? get backupSchedule =>
234 backupCapability['schedule']?.toString().trim().isNotEmpty == true
235 ? backupCapability['schedule'].toString()
236 : null;
237
238 Map<String, dynamic> get fileWritesCapability {
239 return _mapAt(const [
240 ['capabilities', 'file_writes'],
241 ['capabilities', 'fileWrites'],
242 ['file_writes'],
243 ['fileWrites'],
244 ], root: adminStatus);
245 }
246
247 Map<String, dynamic> get sourceWritesCapability {
248 return _mapAt(const [
249 ['capabilities', 'source_writes'],
250 ['capabilities', 'sourceWrites'],
251 ['source_writes'],
252 ['sourceWrites'],
253 ], root: adminStatus);
254 }
255
256 Map<String, dynamic> get identityCapability {
257 return _mapAt(const [
258 ['capabilities', 'identity'],
259 ['identity'],
260 ], root: adminStatus);
261 }
262
263 Map<String, dynamic> get backupCapability {
264 return _mapAt(const [
265 ['capabilities', 'backups'],
266 ['capabilities', 'backup'],
267 ['backup'],
268 ['backups'],
269 ], root: adminStatus);
270 }
271
272 Map<String, dynamic> get packagesCapability {
273 return _mapAt(const [
274 ['capabilities', 'packages'],
275 ['packages'],
276 ], root: adminStatus);
277 }
278
279 bool get packagesCanInstall =>
280 _boolFromDynamic(packagesCapability['can_install']) == true;
281
282 int? get maxObjectFileBytes {
283 final value =
284 fileWritesCapability['max_bytes'] ??
285 fileWritesCapability['maxBytes'] ??
286 fileWritesCapability['limit'];
287 return _intFromDynamic(value);
288 }
289
290 String get adminHealthStatus {
291 return _stringAt(const [
292 ['status'],
293 ['health', 'status'],
294 ['metrics', 'status'],
295 ]) ??
296 health?['status']?.toString() ??
297 'unknown';
298 }
299
300 String get packageSummary {
301 final packages = adminPackages;
302 if (packages.isEmpty) return 'No package status';
303 final installed = packages.where((p) {
304 final status = (p['status'] ?? p['state'] ?? p['value'])
305 ?.toString()
306 .toLowerCase();
307 final installed = p['installed'];
308 return installed == true || status == 'installed';
309 }).length;
310 return '$installed/${packages.length} packages installed';
311 }
312
313 String get daemonHealthStatus {
314 return _stringAt(const [
315 ['status'],
316 ['daemon', 'status'],
317 ], root: daemonStatus) ??
318 'unknown';
319 }
320
321 Map<String, dynamic> daemonSection(String key) {
322 final status = daemonStatus;
323 if (status == null) return const {};
324 final direct = status[key];
325 if (direct is Map<String, dynamic>) return direct;
326 if (direct is Map) {
327 return direct.map((itemKey, itemValue) {
328 return MapEntry(itemKey.toString(), itemValue);
329 });
330 }
331 final snake = _snakeCase(key);
332 final snakeValue = status[snake];
333 if (snakeValue is Map<String, dynamic>) return snakeValue;
334 if (snakeValue is Map) {
335 return snakeValue.map((itemKey, itemValue) {
336 return MapEntry(itemKey.toString(), itemValue);
337 });
338 }
339 return const {};
340 }
341
342 Map<String, dynamic> get effectivePermissionsStatus {
343 final direct = _mapFromNullable(permissionsStatus);
344 if (direct.isNotEmpty) return direct;
345 return _mapAt(const [
346 ['permissions'],
347 ['permission_status'],
348 ['permissionStatus'],
349 ], root: adminStatus);
350 }
351
352 Map<String, dynamic> get effectivePermissionsPolicy {
353 final direct = _mapFromNullable(permissionsPolicy);
354 if (direct.isNotEmpty) return direct;
355 final fromStatus = _mapAt(const [
356 ['policy'],
357 ['permissions', 'policy'],
358 ['permission_policy'],
359 ['permissionPolicy'],
360 ], root: permissionsStatus);
361 if (fromStatus.isNotEmpty) return fromStatus;
362 return _mapAt(const [
363 ['permissions', 'policy'],
364 ['permission_policy'],
365 ['permissionPolicy'],
366 ], root: adminStatus);
367 }
368
369 List<Map<String, dynamic>> get daemonSchedulerTasks {
370 return _itemsFromResponse(daemonSchedulerTasksResponse, const [
371 'tasks',
372 'items',
373 'rows',
374 'records',
375 'results',
376 ]);
377 }
378
379 List<Map<String, dynamic>> get daemonQueueMessages {
380 return _itemsFromResponse(daemonQueueMessagesResponse, const [
381 'messages',
382 'items',
383 'rows',
384 'records',
385 'results',
386 ]);
387 }
388
389 List<Map<String, dynamic>> get eventDeliveries {
390 return _itemsFromResponse(eventDeliveriesResponse, const [
391 'deliveries',
392 'subscriptions',
393 'items',
394 'rows',
395 'records',
396 'results',
397 ]);
398 }
399
400 List<Map<String, dynamic>> get adminChanges {
401 return _itemsFromResponse(adminChangesResponse, const [
402 'changes',
403 'items',
404 'events',
405 'results',
406 'records',
407 'rows',
408 ]);
409 }
410
411 int? get daemonSchedulerTaskCount {
412 return _responseInt(daemonSchedulerTasksResponse, const [
413 'total',
414 'count',
415 'task_count',
416 ]);
417 }
418
419 int? get adminChangeCount {
420 return _responseInt(adminChangesResponse, const [
421 'total',
422 'count',
423 'change_count',
424 'changes_count',
425 ]);
426 }
427
428 int? get daemonQueueMessageCount {
429 return _responseInt(daemonQueueMessagesResponse, const [
430 'total',
431 'count',
432 'message_count',
433 ]);
434 }
435
436 int? get eventDeliveryCount {
437 return _responseInt(eventDeliveriesResponse, const [
438 'total',
439 'count',
440 'delivery_count',
441 'subscription_count',
442 ]);
443 }
444
445 List<Map<String, dynamic>> get adminPackages {
446 final raw = _valueAt(const [
447 ['packages'],
448 ['package_posture'],
449 ['packagePosture'],
450 ]);
451 if (raw is List) {
452 return raw.map(_mapFromDynamic).toList();
453 }
454 if (raw is Map) {
455 final items = raw['items'] ?? raw['packages'];
456 if (items is List) return items.map(_mapFromDynamic).toList();
457 return raw.entries.map((entry) {
458 final value = _mapFromDynamic(entry.value);
459 return {'name': entry.key.toString(), ...value};
460 }).toList();
461 }
462 return const [];
463 }
464
465 List<MapEntry<String, dynamic>> get inventoryEntries {
466 final inventory = _inventoryMap();
467 if (inventory.isEmpty) return const [];
468 return inventory.entries
469 .where((entry) => entry.value is num || entry.value is String)
470 .toList();
471 }
472
473 List<MapEntry<String, dynamic>> get capabilityEntries {
474 final raw = _valueAt(const [
475 ['capabilities'],
476 ['capability_flags'],
477 ['flags'],
478 ['config', 'flags'],
479 ]);
480 if (raw is Map) {
481 return raw.entries
482 .map((entry) => MapEntry(entry.key.toString(), entry.value))
483 .toList();
484 }
485 return const [];
486 }
487
488 int? inventoryCount(String key) => _inventoryInt(key);
489
490 Map<String, dynamic> _inventoryMap() {
491 final raw = _valueAt(const [
492 ['inventory'],
493 ['inventory_counts'],
494 ['counts'],
495 ]);
496 if (raw is Map<String, dynamic>) return raw;
497 if (raw is Map) {
498 return raw.map((key, value) => MapEntry(key.toString(), value));
499 }
500 return const {};
501 }
502
503 Map<String, dynamic> _mapAt(
504 List<List<String>> paths, {
505 Map<String, dynamic>? root,
506 }) {
507 final value = _valueAt(paths, root: root);
508 return _mapFromNullable(value);
509 }
510
511 Map<String, dynamic> _mapFromNullable(dynamic value) {
512 if (value is Map<String, dynamic>) return value;
513 if (value is Map) {
514 return value.map((key, item) => MapEntry(key.toString(), item));
515 }
516 return const {};
517 }
518
519 int? _inventoryInt(String key) {
520 final value = _inventoryMap()[key];
521 if (value is int) return value;
522 if (value is num) return value.toInt();
523 if (value is String) return int.tryParse(value);
524 return null;
525 }
526
527 List<Map<String, dynamic>> _itemsFromResponse(
528 Map<String, dynamic>? response,
529 List<String> keys,
530 ) {
531 if (response == null) return const [];
532 for (final key in keys) {
533 final value = response[key];
534 if (value is List) return value.map(_mapFromDynamic).toList();
535 }
536 final data = response['data'];
537 if (data is List) return data.map(_mapFromDynamic).toList();
538 if (data is Map) {
539 for (final key in keys) {
540 final value = data[key];
541 if (value is List) return value.map(_mapFromDynamic).toList();
542 }
543 }
544 return const [];
545 }
546
547 int? _responseInt(Map<String, dynamic>? response, List<String> keys) {
548 if (response == null) return null;
549 for (final key in keys) {
550 final parsed = _intFromDynamic(response[key]);
551 if (parsed != null) return parsed;
552 }
553 final data = response['data'];
554 if (data is Map) {
555 for (final key in keys) {
556 final parsed = _intFromDynamic(data[key]);
557 if (parsed != null) return parsed;
558 }
559 }
560 return null;
561 }
562
563 int? _intFromDynamic(dynamic value) {
564 if (value is int) return value;
565 if (value is num) return value.toInt();
566 if (value is String) return int.tryParse(value);
567 return null;
568 }
569
570 bool? _boolFromDynamic(dynamic value) {
571 if (value is bool) return value;
572 if (value is num) return value != 0;
573 if (value is String) {
574 final normalized = value.toLowerCase();
575 if (normalized == 'true' ||
576 normalized == 'yes' ||
577 normalized == '1' ||
578 normalized == 'enabled') {
579 return true;
580 }
581 if (normalized == 'false' ||
582 normalized == 'no' ||
583 normalized == '0' ||
584 normalized == 'disabled') {
585 return false;
586 }
587 }
588 return null;
589 }
590
591 String? _stringAt(List<List<String>> paths, {Map<String, dynamic>? root}) {
592 for (final path in paths) {
593 final value = _valueAt([path], root: root);
594 if (value != null) return value.toString();
595 }
596 return null;
597 }
598
599 dynamic _valueAt(List<List<String>> paths, {Map<String, dynamic>? root}) {
600 final resolvedRoot = root ?? adminStatus;
601 if (resolvedRoot == null) return null;
602 for (final path in paths) {
603 dynamic current = resolvedRoot;
604 for (final part in path) {
605 if (current is Map) {
606 current = current[part];
607 } else {
608 current = null;
609 break;
610 }
611 }
612 if (current != null) return current;
613 }
614 return null;
615 }
616
617 Map<String, dynamic> _mapFromDynamic(dynamic value) {
618 if (value is Map<String, dynamic>) return value;
619 if (value is Map) {
620 return value.map((key, item) => MapEntry(key.toString(), item));
621 }
622 return {'value': value};
623 }
624
625 String _snakeCase(String value) {
626 return value
627 .replaceAllMapped(
628 RegExp(r'([a-z0-9])([A-Z])'),
629 (match) => '${match.group(1)}_${match.group(2)}',
630 )
631 .replaceAll('-', '_')
632 .toLowerCase();
633 }
634}