forked from ontola/atomic-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathatomic_client.dart
More file actions
429 lines (341 loc) · 16.2 KB
/
Copy pathatomic_client.dart
File metadata and controls
429 lines (341 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
import 'dart:convert';
import 'package:flutter/foundation.dart';
import '../src/rust/api/simple.dart' as ffi;
import '../src/rust/api/simple/types.dart'
show AgentInfo, CanvasListItem, VersionMetadata;
export '../src/rust/api/simple/types.dart'
show AgentInfo, CanvasListItem, VersionMetadata;
/// Atomic Data SDK — local-first with optional sync.
///
/// Groups:
/// 1. Database — openDb()
/// 2. Agent — setup(), loadAgent(), getActiveAgent(), clearAgent()
/// 3. Drive — createDrive(), listDrives(), getActiveDrive(), setActiveDrive()
/// 4. Resource — getProperty(), setProperty()
/// 5. Canvas — createCanvas(), save/load/list/delete/rename
/// 6. History — warmResourceHistory(), getResourceHistory(), getResourceAtVersion()
/// 7. Peer — startPeer(), getPeerId(), peerAnnounce(), peerSync(), peerDiscoverSync()
///
/// Networking (group 7) is explicit. Nothing in groups 1-6 touches the network.
class AtomicClient {
// ── 1. Database ──────────────────────────────────────────────────────────
static Future<void> openDb(String path) => ffi.openDb(path: path);
// ── 2. Agent ─────────────────────────────────────────────────────────────
/// Create an agent + personal drive. Pure local.
static Future<
({String agentSecret, String agentSubject, String driveSubject})>
setup(String name) async {
final r = await ffi.setup(name: name);
return (
agentSecret: r.agentSecret,
agentSubject: r.agentSubject,
driveSubject: r.driveSubject,
);
}
/// Load an agent from a secret. Pure local.
static Future<String> loadAgent(String secret) =>
ffi.loadAgent(secret: secret);
static Future<AgentInfo?> getActiveAgent() => ffi.getActiveAgent();
static AgentInfo createAgent(String name) => ffi.createAgent(name: name);
static AgentInfo agentFromSecret(String secret) =>
ffi.agentFromSecret(secret: secret);
// ── 3. Drive ─────────────────────────────────────────────────────────────
static Future<String> createDrive(String name) => ffi.createDrive(name: name);
static Future<List<String>> listDrives() => ffi.listDrives();
static String? getActiveDrive() => ffi.getActiveDrive();
static Future<void> setActiveDrive(String subject) async =>
ffi.setActiveDrive(subject: subject);
// ── 4. Resource ──────────────────────────────────────────────────────────
static Future<String> getProperty(String subject, String property) =>
ffi.getProperty(subject: subject, property: property);
static Future<void> setProperty(
String subject, String property, String value) =>
ffi.setProperty(subject: subject, property: property, value: value);
// ── 5. Canvas CRUD ───────────────────────────────────────────────────────
static Future<String> createCanvas(String name, {String? folderId}) =>
ffi.createCanvasWithFolder(name: name, folderId: folderId);
static Future<String> loadCanvasStrokes(String subject) =>
ffi.loadCanvasStrokes(subject: subject);
static Future<List<CanvasListItem>> listCanvases() => ffi.listCanvases();
static Future<Map<String, String>> listCanvasFolderIds() async {
final json = await ffi.listCanvasesJson();
final list = jsonDecode(json) as List;
return {
for (final e in list)
if ((e['folder_id'] as String?)?.isNotEmpty ?? false)
e['subject'] as String: e['folder_id'] as String,
};
}
static Future<void> deleteCanvas(String subject) =>
ffi.deleteCanvas(subject: subject);
static Future<void> renameCanvas(String subject, String name) =>
ffi.renameCanvas(subject: subject, name: name);
/// Rename a gallery folder (same signed commit path as [renameCanvas]).
static Future<void> renameFolder(String subject, String name) =>
renameCanvas(subject, name);
// ── 6. History ───────────────────────────────────────────────────────────
static Future<void> warmResourceHistory(String subject) =>
ffi.warmResourceHistory(subject: subject);
static Future<List<VersionMetadata>> getResourceHistory(String subject) =>
ffi.getResourceHistory(subject: subject);
static Future<String> getResourceAtVersion(
String subject, List<int> versionId) =>
ffi.getResourceAtVersion(
subject: subject,
versionId: versionId is Uint8List
? versionId
: Uint8List.fromList(versionId));
// ── 7. Peer / Sync (explicit, opt-in) ────────────────────────────────────
/// Start the Iroh peer. Returns the NodeID. Call before any sync operations.
static Future<String> startPeer() => ffi.startPeer();
/// Get this device's NodeID, or null if peer not started.
static Future<String?> getPeerId() async => ffi.getPeerId();
/// Announce a drive on DHT so other devices can find us.
static Future<void> peerAnnounce(String driveSubject) =>
ffi.peerAnnounce(driveSubject: driveSubject);
/// Sync the active drive with a peer by NodeID.
static Future<PeerSyncResult> peerSync(String nodeId) async =>
PeerSyncResult.fromJson(
jsonDecode(await ffi.peerSync(nodeId: nodeId)) as Map<String, dynamic>,
);
/// Discover a peer via DHT and sync. Combines lookup + sync.
static Future<int> peerDiscoverSync(String driveSubject) =>
ffi.peerDiscoverSync(driveSubject: driveSubject);
/// Start Iroh, sync known peers + pkarr. Use on app open and Settings → Retry.
static Future<SyncConnectivityReport> syncConnectivityNow() async {
final json = await ffi.syncConnectivityNow();
final m = jsonDecode(json) as Map<String, dynamic>;
return SyncConnectivityReport(
imported: (m['imported'] as num?)?.toInt() ?? 0,
livePeers: (m['live_peers'] as num?)?.toInt() ?? 0,
message: m['message'] as String? ?? '',
);
}
// ── 8. Known peers ──────────────────────────────────────────────────────
/// Get all known peers (persisted in DB).
/// Returns list of {node_id: String, name: String, last_synced: String}.
/// `last_synced` is unix millis as a string, or '' if never synced.
static Future<List<Map<String, String>>> getKnownPeers() async {
final json = ffi.getKnownPeersJson();
try {
return (jsonDecode(json) as List)
.map((e) => {
'node_id': (e['node_id'] ?? '') as String,
'name': (e['name'] ?? '') as String,
'last_synced': e['last_synced'] == null
? ''
: '${e['last_synced']}',
})
.toList();
} catch (_) {
return [];
}
}
/// Add a peer with optional device name.
static Future<void> addKnownPeer(String nodeId, [String name = '']) async =>
ffi.addKnownPeer(nodeId: nodeId, name: name);
/// Remove a peer by NodeID.
static Future<void> removeKnownPeer(String nodeId) async =>
ffi.removeKnownPeer(nodeId: nodeId);
// ── 10. WebSocket sync (server-backed) ───────────────────────────────────
/// Optional LAN hub (e.g. `http://192.168.x.x:9883`). Empty = device-to-device only.
static const defaultServerUrl = '';
/// Connect to Atomic Server over WebSocket; SUB active drive; apply remote updates.
static Future<void> openWsSync(String serverUrl) =>
ffi.openWsSync(serverUrl: serverUrl);
static Future<void> closeWsSync() => ffi.closeWsSync();
/// Push the active drive to `serverUrl`, so it is hosted there too.
/// Returns the number of resources pushed.
///
/// [openWsSync] fetches a drive this device lacks and pushes commits made
/// from now on; a drive made here before any server was connected has never
/// been offered to one. This offers it — and it is the only way a workspace
/// made here reaches a browser, which is not a peer and cannot be paired
/// with.
static Future<int> syncDriveToServer(String serverUrl) =>
ffi.syncDriveToServer(serverUrl: serverUrl);
/// Boot / auto-login: load agent, WS sync, fetch drive, optional Iroh discover.
/// Returns `ok` or `needs_sync`.
static Future<String> resumeSession({
required String serverUrl,
required String secret,
String? drive,
}) {
return ffi.resumeAppSession(
serverUrl: serverUrl,
secret: secret,
driveHint: drive,
);
}
static Future<void> wsSubscribeCanvas(String subject) =>
ffi.wsSubscribeCanvas(subject: subject);
static Future<String> createFolder(String name) =>
ffi.createFolder(name: name);
static Future<List<({String subject, String name})>> listFolders() async {
final list = await ffi.listFolders();
return list
.map((e) => (
subject: e.subject,
name: e.name,
))
.toList();
}
static Future<void> setCanvasFolder(String subject, String? folderId) =>
ffi.setCanvasFolder(subject: subject, folderId: folderId);
/// Block until a DB event (changed / destroyed / query membership). Null on timeout.
static Future<Map<String, dynamic>?> pollDbEvent(
{int timeoutMs = 60000}) async {
final json = await ffi.pollDbEvent(timeoutMs: timeoutMs);
if (json == null || json == 'null') return null;
try {
return Map<String, dynamic>.from(jsonDecode(json));
} catch (_) {
return null;
}
}
// ── 11. Live queries ────────────────────────────────────────────────────
/// Get persisted device name.
static Future<String> getDeviceName() async => ffi.getDeviceName();
/// Set device name (persisted in DB).
static Future<void> setDeviceName(String name) async =>
ffi.setDeviceName(name: name);
/// Push a single stroke to a canvas (CRDT-friendly append).
static Future<void> pushStroke(String subject, String strokeJson) =>
ffi.pushStroke(subject: subject, strokeJson: strokeJson);
/// Undo the last stroke edit. Persists and syncs. Returns new stroke count.
static Future<int> undoCanvas(String subject) =>
ffi.undoCanvas(subject: subject);
/// Redo the last undone stroke edit. Persists and syncs. Returns new stroke count.
static Future<int> redoCanvas(String subject) =>
ffi.redoCanvas(subject: subject);
static Future<bool> canUndoCanvas(String subject) =>
ffi.canUndoCanvas(subject: subject);
static Future<bool> canRedoCanvas(String subject) =>
ffi.canRedoCanvas(subject: subject);
/// Replace all strokes (used after undo/scrub). Clears and re-sets the full list.
static Future<void> setStrokes(String subject, String strokesJson) =>
ffi.setStrokes(subject: subject, strokesJson: strokesJson);
/// Move canvas to a synced Loro history version and persist (history scrub).
static Future<void> checkoutCanvasVersion(
String subject, List<int> versionId) {
return setStrokes(
subject,
jsonEncode({'checkout_version_id': versionId}),
);
}
/// Get the number of currently connected live peers.
static Future<int> livePeerCount() async => ffi.livePeerCount();
/// Get the node IDs of currently connected live peers.
static Set<String> livePeerIds() => ffi.livePeerIds().toSet();
/// Fired when Iroh live-peer count changes (`connected` / `disconnected` events).
static final ValueNotifier<int> livePeersRevision = ValueNotifier(0);
static void notifyLivePeersChanged() {
livePeersRevision.value++;
}
/// Canonical 64-char hex NodeID (matches Rust `normalize_node_id`).
static String normalizeNodeId(String id) {
var s = id.trim();
const prefix = 'did:ad:node:';
if (s.startsWith(prefix)) {
s = s.substring(prefix.length);
if (s.length > 64 && s[64] == ':') {
s = s.substring(0, 64);
}
}
if (s.startsWith('iroh:')) s = s.substring(5);
return s.toLowerCase();
}
static bool isLivePeer(String knownNodeId, Set<String> liveIds) {
final n = normalizeNodeId(knownNodeId);
return liveIds.any((l) => normalizeNodeId(l) == n);
}
/// Block until the next sync event arrives. Reactive — no polling.
static Future<Map<String, dynamic>?> waitForSyncEvent() async {
final json = await ffi.waitForSyncEvent();
if (json == 'null') return null;
try {
return Map<String, dynamic>.from(jsonDecode(json));
} catch (_) {
return null;
}
}
/// Block until the live peer count changes from [current]. Reactive.
static Future<int> waitForPeerCountChange(int current) =>
ffi.waitForPeerCountChange(current: current);
/// Block until a specific resource changes. Returns the subject or "timeout".
static Future<String> watchResource(String subject) =>
ffi.watchResource(subject: subject);
/// Block until a child of [parent] changes. Returns the changed subject.
/// Times out after 60s and returns "timeout".
static Future<String> watchChildren(String parent) =>
ffi.watchChildren(parent: parent);
// ── 9. Sync events ─────────────────────────────────────────────────────
/// Poll for incoming sync events (peer connected and synced).
/// Returns a list of {remoteNodeId, resourcesImported, timestamp}.
static Future<List<Map<String, dynamic>>> pollSyncEvents() async {
final json = await ffi.pollSyncEvents();
try {
return List<Map<String, dynamic>>.from(
(jsonDecode(json) as List).map((e) => Map<String, dynamic>.from(e)),
);
} catch (_) {
return [];
}
}
}
/// Result of [`AtomicClient.syncConnectivityNow`].
class SyncConnectivityReport {
final int imported;
final int livePeers;
final String message;
const SyncConnectivityReport({
required this.imported,
required this.livePeers,
required this.message,
});
}
/// What a sync did, in both directions.
///
/// A count of imports alone says "0" for the two things that most often
/// happen — sending a workspace somewhere that has none, and both sides
/// already holding the same thing — and "0" reads as failure.
class PeerSyncResult {
const PeerSyncResult({
required this.imported,
required this.pushed,
required this.inSync,
this.peerName,
});
/// Resources taken from the other device.
final int imported;
/// Resources handed to it.
final int pushed;
/// Both sides already held the same thing. Nothing moved, nothing needed to.
final bool inSync;
/// What the other device calls itself, if it said.
final String? peerName;
factory PeerSyncResult.fromJson(Map<String, dynamic> json) => PeerSyncResult(
imported: (json['imported'] as num?)?.toInt() ?? 0,
pushed: (json['pushed'] as num?)?.toInt() ?? 0,
inSync: json['in_sync'] == true,
peerName: json['peer_name'] as String?,
);
/// What happened, as a person would say it.
String describe([String? fallbackName]) {
final name = peerName?.isNotEmpty == true ? peerName : fallbackName;
final withWhom = name == null ? '' : ' with $name';
if (imported > 0 && pushed > 0) {
return 'Synced$withWhom — sent $pushed, received $imported';
}
if (pushed > 0) {
return 'Sent $pushed ${pushed == 1 ? 'resource' : 'resources'}$withWhom';
}
if (imported > 0) {
return 'Received $imported ${imported == 1 ? 'resource' : 'resources'}$withWhom';
}
if (inSync) {
return 'Already in sync$withWhom';
}
return 'Nothing to sync$withWhom';
}
}