-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCliApi.java
More file actions
795 lines (751 loc) · 33.9 KB
/
Copy pathCliApi.java
File metadata and controls
795 lines (751 loc) · 33.9 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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
package io.aether.cli;
import com.google.gson.GsonBuilder;
import io.aether.StandardUUIDs;
import io.aether.api.common.AccessGroup;
import io.aether.api.common.CryptoLib;
import io.aether.cloud.client.*;
import io.aether.common.AccessGroupI;
import io.aether.logger.Log;
import io.aether.utils.AString;
import io.aether.utils.Destroyer;
import io.aether.utils.RU;
import io.aether.utils.ToString;
import io.aether.utils.consoleCanonical.ConsoleMgrCanonical.*;
import io.aether.utils.flow.Flow;
import io.aether.utils.futures.AFuture;
import io.aether.utils.futures.ARFuture;
import io.aether.utils.slots.EventConsumer;
import io.aether.utils.slots.EventConsumerWithQueue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
/**
* Command Line Interface API for Aether Cloud Client operations.
*/
@Doc("Command Line Interface API for Aether Cloud Client operations.")
public class CliApi {
private static final Executor CLI_EXECUTOR = Executors.newSingleThreadExecutor(r -> {
var t = new Thread(r, "CLI-Async-Worker");
t.setDaemon(true);
return t;
});
private static final Executor DESTROY_EXECUTOR = Executors.newSingleThreadExecutor(r -> new Thread(r, "CLI-Destroy-Worker"));
public final Destroyer destroyer = new Destroyer("CliApi");
private final CliState cliState;
/**
* Known static UUID aliases and format details for documentation.
*/
private final String UUID_ALIASES_DOC = "Known static aliases: \n" +
" TEST\u00A0(3ac93165-3d37-4970-87a6-fa4ee27744e4)\n" +
" ROOT\u00A0(ed307ca7-8369-4342-91ee-60c8fc6f9b6b)\n" +
" ANONYMOUS\u00A0(237e2dc0-21a4-4e83-8184-c43052f93b79)\n" +
" (Also supports user aliases. Use 'show aliases' to list them)";
public CreateApi createApi;
public ShowApi showApi;
public SetApi setApi;
/**
* Constructor receiving the persistent state
*
* @param cliState The loaded CLI state
*/
public CliApi(CliState cliState) {
this.cliState = cliState;
}
/**
* Resolves UUID aliases (user-defined first, then static) or raw UUID strings.
* This method is used by ConsoleMgrCanonical as a type converter.
*
* @param uuidOrAlias The string to resolve.
* @return The resolved UUID.
* @throws IllegalArgumentException if the string is neither a valid alias nor a UUID.
*/
public UUID resolveUuid(String uuidOrAlias) {
if (uuidOrAlias == null) {
return null;
}
// 1. Check user-defined aliases (case-sensitive and then uppercase)
if (cliState.hasAlias(uuidOrAlias)) {
return UUID.fromString(cliState.getUuidForAlias(uuidOrAlias));
}
String upper = uuidOrAlias.toUpperCase();
if (cliState.hasAlias(upper)) {
return UUID.fromString(cliState.getUuidForAlias(upper));
}
// 2. Check static aliases
switch (upper) {
case "TEST":
return StandardUUIDs.TEST_UID;
case "ROOT":
return StandardUUIDs.ROOT_UID;
case "ANONYMOUS":
return StandardUUIDs.ANONYMOUS_UID;
}
// 3. Try to parse as a raw UUID
try {
return UUID.fromString(uuidOrAlias);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid UUID or alias: '" + uuidOrAlias + "'", e);
}
}
/**
* Safely destroys resources via an executor
*/
@Doc("Safely destroys CLI resources")
public AFuture safeDestroy() {
AFuture destroyFuture = AFuture.make();
DESTROY_EXECUTOR.execute(() -> {
try {
Log.info("Starting safe destroy of CLI resources");
destroyer.destroy(true).timeout(10, () -> {
Log.warn("Timeout during safe destroy");
}).to(destroyFuture);
} catch (Exception e) {
Log.error("Error during safe destroy", e);
destroyFuture.error(e);
}
});
return destroyFuture;
}
@Doc("Show version of cli instrument")
@Example("$exCmd version")
public String version() {
Log.info("Executing command: version");
try (var is = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/aether-cli-version.txt")))) {
return is.readLine();
} catch (Exception e) {
RU.error(e);
return null;
}
}
@Api
@Doc("Create a client or group")
public CreateApi create(
@Doc("Specify a time limit for the object creation")
@Optional("10")
int timeout) {
Log.info("Executing command: create", "timeout", timeout);
createApi = new CreateApi();
return createApi;
}
@Api
@Doc("Change properties of a client or group")
public ChangeApi change(
@Doc("Previously saved client state file")
@Optional(value = "state.bin")
File state) {
Log.info("Executing command: change", "stateFile", state);
ClientStateInMemory loadedState = ClientStateInMemory.load(state);
if (loadedState == null) {
throw new IllegalStateException("Command requires a valid state file, but it was not found or was corrupted. " +
"Default path is '" + state.getName() + "'. " +
"Please run 'create client' first, or specify a valid state file with --state.");
}
// Create client locally
var client = new AetherCloudClient(loadedState);
destroyer.add(client);
return new ChangeApi(client);
}
@Doc("Check the possibility of sending messages between two clients")
@Example("$exCmd check-access --uid1 TEST --uid2 my-friend-alias")
public ARFuture<Boolean> checkAccess(
@Doc("Previously saved client state file")
@Optional(value = "state.bin")
File state,
@Doc("Client 1 UUID or alias. \n" + UUID_ALIASES_DOC)
UUID uid1,
@Doc("Client 2 UUID or alias. \n" + UUID_ALIASES_DOC)
UUID uid2) {
Log.info("Executing command: checkAccess", "stateFile", state, "uid1", uid1, "uid2", uid2);
ClientStateInMemory loadedState = ClientStateInMemory.load(state);
if (loadedState == null) {
return ARFuture.doThrow(new IllegalStateException("Command requires a valid state file, but it was not found or was corrupted. " +
"Default path is '" + state.getName() + "'. " +
"Please run 'create client' first, or specify a valid state file with --state."));
}
// Create client locally
var client = new AetherCloudClient(loadedState);
destroyer.add(client);
// Capture client for use in lambda expression
AetherCloudClient finalClient = client;
// Explicitly specify the generic type for ARFuture.run to avoid error
return ARFuture.<Boolean>run2(CLI_EXECUTOR, () -> finalClient.checkAccess(uid1, uid2))
.apply(() -> {
destroyer.remove(finalClient);
finalClient.destroy(true);
});
}
@Api
@Doc("Send a message to an address")
public SendApi send(
@Doc("Previously saved client state file")
@Optional(value = "state.bin")
File state,
@Doc("Destination UUID address or alias. \n" + UUID_ALIASES_DOC)
UUID address) {
Log.info("Executing command: send", "stateFile", state, "address", address);
ClientStateInMemory loadedState = ClientStateInMemory.load(state);
if (loadedState == null) {
throw new IllegalStateException("Command requires a valid state file, but it was not found or was corrupted. " +
"Default path is '" + state.getName() + "'. " +
"Please run 'create client' first, or specify a valid state file with --state.");
}
// Create client locally
var client = new AetherCloudClient(loadedState);
destroyer.add(client);
// Wait for client to be fully connected before allowing message sending
ARFuture<AetherCloudClient> readyClient = client.connect().mapRFuture(() -> client);
var st = client.getMessageNode(address, MessageEventListener.DEFAULT);
return new SendApi(st, client, readyClient);
}
@Api
@Doc("Show client state, groups, aliases, and incoming messages")
public ShowApi show(/* --- state parameter removed --- */) {
Log.info("Executing command: show");
showApi = new ShowApi(this.cliState);
return showApi;
}
@Api
@Doc("Set properties, like user-defined aliases")
public SetApi set() {
Log.info("Executing command: set");
setApi = new SetApi(this.cliState);
return setApi;
}
static {
// Устанавливаем глобальный контекст для всех логов CLI
io.aether.logger.Log.of(io.aether.logger.Log.SYSTEM_COMPONENT, "CLI").context();
}
/**
* Message container class.
*/
@Doc("A container for a received message, holding the sender's address and data.")
public static class Msg implements ToString {
public final UUID address;
public final byte[] data;
public Msg(UUID address, byte[] data) {
this.address = address;
this.data = data;
}
@Override
public String toString() {
return toString2();
}
@Override
public AString toAString(AString sb) {
sb.add(address).add(":").add(data);
return sb;
}
}
/**
* API for changing resources (e.g., groups).
*/
@Doc("API for changing resources (e.g., groups).")
public class ChangeApi {
private final AetherCloudClient client;
public ChangeApi(AetherCloudClient client) {
this.client = client;
}
@Api
@Doc("Change an access group")
public ChangeGroupApi group(
@Doc("Access group ID")
UUID id) {
return new ChangeGroupApi(id, client);
}
/**
* API for changing an access group.
*/
@Doc("API for changing a specific access group.")
public class ChangeGroupApi {
private final UUID id;
private final AetherCloudClient client;
public ChangeGroupApi(UUID id, AetherCloudClient client) {
this.id = id;
this.client = client;
}
@Doc("Add clients to an access group")
@Example("$exCmd change group 123456 add TEST,my-friend-alias")
public AFuture add(
@Doc("Set of client UUIDs or aliases to add. \n" + UUID_ALIASES_DOC)
@StdIn Set<UUID> uid) {
Log.info("ChangeGroupApi: add started", "groupId", id);
AFuture res = AFuture.make();
// CAPTURE: Capture the reference to the Destroyer in the outer (safe) scope
Destroyer apiDestroyer = CliApi.this.destroyer;
AFuture.run(CLI_EXECUTOR, () -> {
client.getAuthApi(a -> {
Log.info("ChangeGroupApi: got AuthApi, starting add op");
AFuture.all(Flow.flow(uid).map(u -> a.addToAccessGroup(id, u)).map(ARFuture::toFuture).toList()).to(res);
});
});
return res.apply(() -> {
apiDestroyer.remove(client);
client.destroy(true);
});
}
@Doc("Remove clients from an access group")
@Example("$exCmd change group 123456 remove my-friend-alias")
public AFuture remove(
@Doc("Set of client UUIDs or aliases to remove. \n" + UUID_ALIASES_DOC)
Set<UUID> uid) {
Log.info("ChangeGroupApi: remove started", "groupId", id);
AFuture res = AFuture.make();
// CAPTURE: Capture the reference to the Destroyer in the outer (safe) scope
Destroyer apiDestroyer = CliApi.this.destroyer;
AFuture.run(CLI_EXECUTOR, () -> {
client.getAuthApi(a -> {
Log.info("ChangeGroupApi: got AuthApi, starting remove op");
AFuture.all(Flow.flow(uid).map(u -> a.removeFromAccessGroup(id, u)).map(ARFuture::toFuture).toList()).to(res);
});
});
return res.apply(() -> {
Log.info("ChangeGroupApi: remove finished.");
apiDestroyer.remove(client);
client.destroy(true);
});
}
}
}
/**
* API for showing resources.
*/
@Doc("API for showing resources.")
public class ShowApi {
private final CliState cliState; // ALWAYS NOT NULL
public EventConsumer<Msg> messages = new EventConsumerWithQueue<>();
/**
* @param cliState The loaded CLI state (aliases)
*/
public ShowApi(CliState cliState) {
this.cliState = cliState;
}
/**
* Internal helper that loads and checks if state.bin exists.
*
* @param stateFile The state file to load.
* @return The loaded ClientStateInMemory
* @throws IllegalStateException if state.bin was not found or corrupted.
*/
private ClientStateInMemory loadRequiredState(File stateFile) {
ClientStateInMemory state = ClientStateInMemory.load(stateFile);
if (state == null) {
throw new IllegalStateException("Command requires a valid state file, but it was not found or was corrupted. " +
"Default path is '" + stateFile.getName() + "'. " +
"Please run 'create client' first, or specify a valid state file with --state.");
}
return state;
}
@Doc("Show all user-defined aliases from ~/.aether-cli-state.json")
@Example("$exCmd show aliases")
public String aliases() {
// This command depends ONLY on cliState, so it will ALWAYS work.
return new GsonBuilder().setPrettyPrinting().create().toJson(cliState.getAliases());
}
@Doc("Show client state. Use --console json for JSON output.")
@Example("$exCmd show state")
public ClientStateInMemory state(
@Doc("Previously saved client state file")
@Optional(value = "state.bin")
File state) {
// This command REQUIRES state.bin
return loadRequiredState(state);
}
@Doc("Show all access groups for a client")
@Example("$exCmd show groups -c TEST")
@Alias("g")
public ARFuture<Set<UUID>> groups(
@Doc("Previously saved client state file")
@Optional(value = "state.bin")
File state,
@Doc("Specified client UID or alias. Defaults to client's UID from state file.\n" + UUID_ALIASES_DOC)
@Optional
@Alias("c")
UUID targetClient) {
// --- LOAD AND CHECK HERE ---
ClientStateInMemory requiredState;
try {
requiredState = loadRequiredState(state); // Check if state.bin is loaded
} catch (Exception e) {
return ARFuture.doThrow(e); // Return error if state.bin is missing
}
// -------------------------
// Create client locally
var client = AetherCloudClient.of(requiredState); // Use the checked state
CliApi.this.destroyer.add(client); // Add to the root destroyer
UUID targetUuid = targetClient;
if (targetUuid == null) {
targetUuid = client.getUid();
}
UUID finalTargetClient = targetUuid;
ARFuture<Set<UUID>> res = ARFuture.make();
CLI_EXECUTOR.execute(() -> {
client.getClientGroups(finalTargetClient).to(res);
});
return res.apply(() -> {
CliApi.this.destroyer.remove(client);
client.destroy(true);
});
}
@Doc("Show the contents (details) of the access groups for the specified IDs")
@Alias("gd")
@Example("$exCmd show groups-details 123456,789012")
public ARFuture<List<AccessGroup>> groupsDetails(
@Doc("Previously saved client state file")
@Optional(value = "state.bin")
File state,
@Doc("IDs of access groups, separated by comma")
Set<UUID> ids) {
// --- LOAD AND CHECK HERE ---
ClientStateInMemory requiredState;
try {
requiredState = loadRequiredState(state);
} catch (Exception e) {
return ARFuture.doThrow(e);
}
// -------------------------
// Create client locally
var client = AetherCloudClient.of(requiredState);
CliApi.this.destroyer.add(client); // Add to the root destroyer
ARFuture<List<AccessGroup>> res = ARFuture.make();
CLI_EXECUTOR.execute(() -> {
ARFuture.all(Flow.flow(ids)
.map(groupId -> client.getGroup(groupId).map(v -> v))
.toList()).to(res);
});
return res.apply(() -> {
CliApi.this.destroyer.remove(client);
client.destroy(true);
});
}
@Doc("Show all clients that the current client can access. This function does not work for public clients.")
@Alias("aac")
@Example("$exCmd show all-accessed-clients")
public ARFuture<Set<UUID>> allAccessedClients(
@Doc("Previously saved client file")
@Optional(value = "state.bin")
File state,
@Doc("Specified client UID or alias. Defaults to client's UID from state file.\n" + UUID_ALIASES_DOC)
@Optional @Alias("c") UUID targetClient) {
// --- LOAD AND CHECK HERE ---
ClientStateInMemory requiredState;
try {
requiredState = loadRequiredState(state);
} catch (Exception e) {
return ARFuture.doThrow(e);
}
// -------------------------
// Create client locally
var client = AetherCloudClient.of(requiredState);
CliApi.this.destroyer.add(client); // Add to the root destroyer
UUID targetUuid = targetClient;
if (targetUuid == null) {
targetUuid = client.getUid();
}
UUID finalTargetClient = targetUuid;
ARFuture<Set<UUID>> res = ARFuture.make();
CLI_EXECUTOR.execute(() -> {
client.getAllAccessedClients(finalTargetClient).to(res);
});
return res.apply(() -> {
CliApi.this.destroyer.remove(client);
client.destroy(true);
});
}
@Doc("Wait for and show incoming messages")
@Example("$exCmd show messages --wait-time 10000 --filter my-friend-alias")
public EventConsumer<Msg> messages(
@Doc("Previously saved client state file")
@Optional(value = "state.bin")
File state,
@Doc("Filter messages by sender UUIDs or aliases. \n" + UUID_ALIASES_DOC)
@Optional Set<UUID> filter,
@Doc("Exclude messages from these sender UUIDs or aliases. \n" + UUID_ALIASES_DOC)
@Optional Set<UUID> not,
@Optional("7500")
@Doc("The time in milliseconds to wait for new messages. After timeout, the client session is closed.")
long waitTime,
@Optional("bin")
@Doc("Output format for messages (e.g., bin, json, human)")
String fileOutFormat,
@Optional("message")
@Doc("Specify the file name template for output")
File fileOut,
@Optional("utf8")
@Doc("Console output encoding/format (e.g., utf8, json, bin)")
String console,
@Optional("true")
@Doc("Set true if you want to append data to the file, false to overwrite")
boolean fileAppend
) {
// --- LOAD AND CHECK HERE ---
// (This command does not return an AFuture, so it throws an exception directly)
ClientStateInMemory requiredState = loadRequiredState(state);
// -------------------------
Log.info("ShowApi: messages command started", "waitTimeMs", waitTime, "filterUids", filter, "notUids", not);
// Create client locally
var client = new AetherCloudClient(requiredState); // Use the checked state
CliApi.this.destroyer.add(client);
Log.info("ShowApi: Client instance created", "clientUid", client.getUid());
// CAPTURE: Capture the reference to the Destroyer in the outer (safe) scope
Destroyer apiDestroyer = CliApi.this.destroyer;
client.onClientStream(m -> {
UUID consumerUid = m.getConsumerUUID();
Log.info("ShowApi: received new MessageNode stream", "consumerUid", consumerUid);
m.toConsumer(d -> {
Log.info("ShowApi: Message data received from stream", "from", consumerUid, "dataLength", d.length);
boolean isFiltered = false;
if (filter != null && !filter.contains(consumerUid)) {
Log.info("ShowApi: Message SKIPPED (Filter check failed)", "from", consumerUid);
isFiltered = true;
}
if (!isFiltered && not != null && not.contains(consumerUid)) {
Log.info("ShowApi: Message SKIPPBLED (Exclude check failed)", "from", consumerUid);
isFiltered = true;
}
if (!isFiltered) {
var msg = new Msg(consumerUid, d);
messages.fire(msg);
Log.info("ShowApi: Message PROCESSED and fired to console", "from", consumerUid, "dataLength", d.length);
}
});
});
// Start connection in CLI_EXECUTOR
AFuture.run(CLI_EXECUTOR, client::connect)
.to(() -> {
Log.info("ShowApi: Client connect successful. Scheduling timeout.", "clientUid", client.getUid());
// Schedule forced termination after waitTime.
RU.schedule(waitTime, () -> {
Log.info("ShowApi: Timeout triggered after %s ms. Starting client destroy.", waitTime);
apiDestroyer.destroy(true);
});
Log.info("ShowApi: Timeout scheduled", "waitTimeMs", waitTime);
}).onError(e -> {
Log.info("ShowApi: Client connect FAILED. Scheduling exit.", "error", e.getMessage());
RU.schedule(10, () -> {
Log.info("ShowApi: Client connect failed, completing session.");
apiDestroyer.destroy(true);
});
});
return messages;
}
}
/**
* API for creating resources (client, group).
*/
@Doc("API for creating resources (client, group).")
public class CreateApi {
@Doc("Create a new client")
@Example("$exCmd create client --parent TEST --alias my-new-client")
public ARFuture<ClientState> client(
@Optional("TEST")
@Doc("Parent client UUID or alias. Defaults to TEST.\n" + UUID_ALIASES_DOC)
UUID parent,
@Optional("tcp://registration.aethernet.io:9010")
@Doc("Registration URI")
URI regUri,
@Optional("SODIUM")
@Doc("Cryptographic library to use")
CryptoLib cryptoLib,
@Optional("false")
@Doc("Use development registration URI")
boolean dev,
@Optional("bin")
@Doc("Output format for client state file (e.g., bin)")
String fileOutFormat,
@Optional("state.bin")
@Doc("File path for saving the client state")
File fileOut,
@Optional
@Doc("A custom alias to save for the new client's UUID in ~/.aether-cli-state.json")
String alias
) {
Log.info("CreateApi: client creation started", "parent", parent, "alias", alias);
if (dev) {
regUri = URI.create("tcp://reg-dev.aethernet.io:9010");
}
var state = new ClientStateInMemory(parent, List.of(regUri), null, cryptoLib);
var client = new AetherCloudClient(state);
CliApi.this.destroyer.add(client);
ARFuture<ClientState> result = ARFuture.make();
Log.debug("Wait start client");
client.startFuture.to(() -> {
client.forceUpdateStateFromCache()
.to(() -> {
// Закрываем регистрационное соединение после успеха
CliApi.this.destroyer.remove(client);
client.destroy(true);
result.done(state);
})
.onError(result);
}).onError(e -> {
Log.error("create client exception", e);
// Очистка при ошибке
CliApi.this.destroyer.remove(client);
client.destroy(true);
result.error(e);
});
return result;
}
@Doc("Create a new access group")
@Example("$exCmd create group --owner TEST TEST,ROOT,my-friend-alias")
public ARFuture<UUID> group(
@Optional(value = "state.bin")
@Doc("Client state file used for operation")
File state,
@Optional
@Doc("Owner UUID or alias of the new group. Defaults to client's UID from state file.\n" + UUID_ALIASES_DOC)
UUID owner,
@Doc("Set of client UUIDs or aliases to initially include in the group. \n" + UUID_ALIASES_DOC)
@Optional Set<UUID> uids) {
Log.info("CreateApi: group creation started");
ClientStateInMemory loadedState = ClientStateInMemory.load(state);
if (loadedState == null) {
return ARFuture.doThrow(new IllegalStateException("Command requires a valid state file, but it was not found or was corrupted. " +
"Default path is '" + state.getName() + "'. " +
"Please run 'create client' first, or specify a valid state file with --state."));
}
// Create client locally
var client = new AetherCloudClient(loadedState); // Use the loaded state
CliApi.this.destroyer.add(client);
UUID ownerUuid = owner;
if (ownerUuid == null) {
ownerUuid = client.getUid();
}
if (uids == null) {
uids = Set.of();
}
UUID finalOwner = ownerUuid;
Set<UUID> finalUids = uids;
// CAPTURE: Capture the reference to the Destroyer in the outer (safe) scope
Destroyer apiDestroyer = CliApi.this.destroyer;
return ARFuture.<AccessGroupI>run(CLI_EXECUTOR, () ->
client.createAccessGroupWithOwner(finalOwner, finalUids.toArray(new UUID[0])).get()
).apply(() -> {
Log.info("CreateApi: group creation finished.");
apiDestroyer.remove(client);
client.destroy(true);
}).map(AccessGroupI::getId);
}
}
/**
* API for sending messages.
*/
@Doc("API for sending messages.")
public class SendApi {
private final MessageNode st;
private final AetherCloudClient client; // Store the client passed from the send method
private final ARFuture<AetherCloudClient> readyClient; // Future that completes when client is ready
public SendApi(MessageNode st, AetherCloudClient client, ARFuture<AetherCloudClient> readyClient) {
this.st = st;
this.client = client;
this.readyClient = readyClient;
}
@Doc("Send a text message")
@Example("$exCmd send TEST text \"Hello, world!\"")
public AFuture text(
@Doc("Text content to send")
String text) {
Log.info("SendApi: sending text message", "textLength", text.length());
AFuture res = AFuture.make();
// Wait for client to be ready before sending
readyClient.to2(CLI_EXECUTOR, ready -> {
st.send(text.getBytes(StandardCharsets.UTF_8)).to(res);
});
// CAPTURE: Ссылка на Destroyer для очистки после отправки
Destroyer apiDestroyer = CliApi.this.destroyer;
return res.apply(() -> {
Log.info("SendApi: send text finished.");
apiDestroyer.remove(client);
client.destroy(true);
});
}
@Doc("Send file content")
@Example("$exCmd send TEST file my_document.pdf")
public AFuture file(
@Doc("File to send")
File file) {
Log.info("SendApi: sending file", "fileName", file.getName());
AFuture res = AFuture.make();
// Wait for client to be ready before sending
readyClient.to2(CLI_EXECUTOR, ready -> {
// Execute send via executor
try (var is = new FileInputStream(file)) {
var data = is.readAllBytes();
st.send(data).to(res);
} catch (Exception e) {
RU.error(e);
res.error(e);
}
}).onError(res::error);
// CAPTURE: Capture the reference to the Destroyer in the outer (safe) scope
Destroyer apiDestroyer = CliApi.this.destroyer;
return res.apply(() -> {
Log.info("SendApi: send file finished.");
apiDestroyer.remove(client);
client.destroy(true);
});
}
@Doc("Send data from standard input")
@Example("echo \"data\" | $exCmd send TEST stdin")
public AFuture stdIn(
@Doc("Data read from standard input")
@StdIn byte[] data) {
Log.info("SendApi: sending stdin data", "dataLength", data.length);
AFuture res = AFuture.make();
// Wait for client to be ready before sending
readyClient.to2(CLI_EXECUTOR, ready -> {
// Execute send via executor
st.send(data).to(res);
}).onError(res::error);
// CAPTURE: Capture the reference to the Destroyer in the outer (safe) scope
Destroyer apiDestroyer = CliApi.this.destroyer;
return res.apply(() -> {
Log.info("SendApi: send (stdin) finished.");
apiDestroyer.remove(client);
client.destroy(true);
});
}
}
/**
* API for setting properties.
*/
@Doc("API for setting properties.")
public class SetApi {
private final CliState cliState;
public SetApi(CliState cliState) {
this.cliState = cliState;
}
@Doc("Set or update a user-defined alias for a UUID")
@Example("$exCmd set alias my-friend 3ac93165-3d37-4970-87a6-fa4ee27744e4")
@Example("$exCmd set alias my-server TEST")
public void alias(
@Doc("The name for the alias")
String aliasName,
@Doc("The UUID or an existing alias (static or user-defined) to associate with the new alias name. \n" + UUID_ALIASES_DOC)
UUID uuid
) {
if (aliasName == null || aliasName.isBlank()) {
throw new IllegalArgumentException("Alias name cannot be empty.");
}
if (uuid == null) {
throw new IllegalArgumentException("UUID cannot be null.");
}
// Check if the name conflicts with static aliases
String upperName = aliasName.toUpperCase();
if (upperName.equals("TEST") || upperName.equals("ROOT") || upperName.equals("ANONYMOUS")) {
throw new IllegalArgumentException("Alias name '" + aliasName + "' conflicts with a built-in static alias and cannot be used.");
}
cliState.addAlias(aliasName, uuid.toString());
Log.info("SetApi: Saved alias '" + aliasName + "' for UUID " + uuid);
// Returns void, as the operation is synchronous
}
}
}