-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage_module_plugin.cpp
More file actions
1127 lines (901 loc) · 39.7 KB
/
storage_module_plugin.cpp
File metadata and controls
1127 lines (901 loc) · 39.7 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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "storage_module_plugin.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QJsonArray>
#include <QList>
#include <QMutexLocker>
#include <QPointer>
#include <QTimer>
#include <QVariantList>
#include <variant>
// Storage Module C++ wrapper based on libstorage C bindings.
//
// Most of the C bindings functions are asynchronous: you call a function
// that sends the job to a worker and you receive the result in a callback.
//
// Based on that, the Storage Module defines different types of callbacks
// (like strategies) to handle data.
// The generic callback will receive the data and calls `handleResponse`
// that varies for each callback type.
// The types of callback are:
//
// 1- EventCallbackCtx: It is used for asynchronous functions in order to send
// an event to the caller on callback completion. This is typically used for
// start / stop methods for example.
// The caller has to subscribe to the event to receive the data.
//
// 2- ConnectCallbackCtx: Wrapper on top of EventCallbackCtx in order to free
// the peer addresses in the destructor.
//
// 3- SignalCallbackCtx: This is very easy to understand. Several APIs
// are sync-like, because they retrieve data. Example: peerId, debug, manifests...
// SignalCallbackCtx provides a mechanism that mimics the sync behaviour by defining
// a signal, and waiting that the callback fires this signal on data receive.
// A timeout is defined to not block too long.
// Because this pattern is widely used, syncCall is a shorthand that reduces the
// amount of code.
//
// 4- UploadFileCallbackCtx: When the callback receives RET_PROGRESS, it will
// notify the caller by sending the size of the data uploaded in order to reflect it
// with an indicator like a progress bar.
//
// 5- UploadChunkCallbackCtx: The callback notifies on success the caller by sending
// the size of the data uploaded.
//
// 6- DownloadStreamCallbackCtx: It is a bit complex because it can handle 2 cases:
// * Streaming into a file
// * Streaming by providing the chunks
// In the first case, the data is written into the provided filepath and the progress
// is notified by providing the number of bytes.
// In the second case, the data is not written but provided through the callback. Note
// that the chunk is COPIED because the Logos SDK uses Qt::QueuedConnection with remote objects.
StorageModulePlugin::StorageModulePlugin() : storageCtx(nullptr) {
// Track storage start/stop state
QObject::connect(this, &StorageModulePlugin::storageResponse, this,
[this](const StorageSignal& signal, int code, const QString&) {
if (signal == StorageSignal::Start) {
isStarted = (code == RET_OK);
} else if (signal == StorageSignal::Stop) {
isStarted = false;
}
});
}
// Destructor implementation
StorageModulePlugin::~StorageModulePlugin() {
qDebug() << "StorageModulePlugin: Destructor called";
// Clean up resources
if (logosAPI) {
delete logosAPI;
logosAPI = nullptr;
}
// Clean up Storage context if it exists
if (storageCtx) {
storageCtx = nullptr;
// The destroy should have been called before destructor
qWarning() << "StorageModulePlugin: Warning - Storage context was not "
"destroyed before plugin destruction";
}
}
// Bind the LogosApi instance
void StorageModulePlugin::initLogos(LogosAPI* logosAPIInstance) {
if (logosAPI) {
delete logosAPI;
}
logosAPI = logosAPIInstance;
}
// Define a generic callback ctx.
struct CallbackCtx {
// QPointer provides safe weak reference to the plugin.
// If the plugin is destroyed before the callback executes,
// the pointer becomes null automatically, preventing crashes.
// This is critical because callbacks are invoked asynchronously
// from the storage module thread.
QPointer<StorageModulePlugin> plugin;
CallbackCtx(QPointer<StorageModulePlugin> p) : plugin(p) {}
LogosAPIClient* client() const {
if (!plugin || !plugin->logosAPI) {
qWarning() << "CallbackCtx::handleResponse: Invalid plugin or logosAPI";
return nullptr;
}
LogosAPIClient* client = plugin->logosAPI->getClient("storage");
if (!client) {
qWarning() << "CallbackCtx::handleResponse: core_manager client is null";
return nullptr;
}
return client;
}
virtual ~CallbackCtx() = default;
virtual void handleResponse(int callerRet, const char* msg, size_t len) const = 0;
};
// Send an event to the caller on completion.
// The response values are:
// 1- ret: the return code of the command (0 for success, non-zero for failure)
// 2- msg: the return string message.
struct EventCallbackCtx : CallbackCtx {
StorageEvent event;
EventCallbackCtx(QPointer<StorageModulePlugin> p, StorageEvent e) : CallbackCtx(p), event(e) {}
void handleResponse(int ret, const char* msg, size_t len) const override {
LogosAPIClient* client = CallbackCtx::client();
if (client == nullptr) {
return;
}
// Get the message reponse from the callback
const QString message = (msg && len > 0) ? QString::fromUtf8(msg, len) : QString();
// Construct the response data to send to the UI.
const QVariantList eventData{ret == RET_OK, message};
client->onEventResponse(plugin.data(), eventName(event), eventData);
// Also emit storageResponse for Start/Stop events to allow using waitForSignal
if (event == StorageEvent::Start) {
emit plugin->storageResponse(StorageSignal::Start, ret, message);
} else if (event == StorageEvent::Stop) {
emit plugin->storageResponse(StorageSignal::Stop, ret, message);
}
}
};
// Connect callback context that holds the peerId and peerAddresses for the connect event.
// It frees the peer addresses when destroyed to avoid memory leaks.
// The response values are:
// 1- ret: the return code of the command (0 for success, non-zero for failure)
// 2- msg: the return string message.
struct ConnectCallbackCtx : EventCallbackCtx {
QByteArray peerId;
QVector<char*> addrs;
ConnectCallbackCtx(QPointer<StorageModulePlugin> p, QByteArray pid, QVector<char*> a)
: EventCallbackCtx(p, StorageEvent::Connect), peerId(pid), addrs(a) {}
~ConnectCallbackCtx() {
for (char* addr : addrs) {
if (addr) {
free(addr);
}
}
addrs.clear();
}
};
// Send an internal signal for sync calls.
// The response values are:
// 1- ret: the return code of the command (0 for success, non-zero for failure)
// 2- msg: the return string message.
struct SyncCallbackCtx : CallbackCtx {
StorageSignal signal;
// Extra data to ensure that args are still valid
// during the async call.
QByteArray lifetimeUtf8;
SyncCallbackCtx(QPointer<StorageModulePlugin> p, StorageSignal s, QByteArray l = QByteArray())
: CallbackCtx(p), signal(s), lifetimeUtf8(std::move(l)) {}
void handleResponse(int ret, const char* msg, size_t len) const override {
// Make sure that we have a valid environment
if (CallbackCtx::client() == nullptr) {
return;
}
// Making sure that plugin is alive
if (!plugin || !plugin->logosAPI) {
qWarning() << "SyncCallbackCtx::handleResponse: Invalid plugin or logosAPI";
return;
}
// Get the message reponse from the callback
const QString message = (msg && len > 0) ? QString::fromUtf8(msg, len) : QString();
emit plugin->storageResponse(signal, ret, message);
}
};
// Callback use for file upload.
//
// When it receives RET_PROGRESS, the response values are:
// 1- success: true if the operation was successful, false otherwise
// 2- sessionId: the upload sessionId.
// 3- size: the number of bytes uploaded.
//
// Progress events are throttled to at most one per percentage point (max 100
// events total) to avoid flooding the caller with events on every block.
// When totalBytes is 0 (unknown), every event is forwarded without throttling.
//
// When it receives RET_OK or RET_ERROR, the response values are:
// 1- success: true if the operation was successful, false otherwise
// 2- sessionId: the upload sessionId.
// 3- message: the CID on success, or the error message on error.
struct UploadFileCallbackCtx : CallbackCtx {
QByteArray sessionIdUtf8;
qint64 totalBytes;
mutable qint64 bytesUploaded = 0;
mutable qint64 pendingBytes = 0;
mutable int lastEmittedPercent = -1;
UploadFileCallbackCtx(QPointer<StorageModulePlugin> p, QByteArray s, qint64 total)
: CallbackCtx(p), sessionIdUtf8(std::move(s)), totalBytes(total) {}
void handleResponse(int ret, const char* msg, size_t len) const override {
LogosAPIClient* client = CallbackCtx::client();
if (client == nullptr) {
return;
}
const QString sessionId = QString::fromUtf8(sessionIdUtf8, sessionIdUtf8.size());
if (ret == RET_PROGRESS) {
bytesUploaded += static_cast<qint64>(len);
pendingBytes += static_cast<qint64>(len);
// Throttle to at most one event per percentage point (max 100 events).
// Skipped chunks keep accumulating in pendingBytes so the next emitted
// event carries all bytes processed since the last emission.
if (totalBytes > 0) {
const int percent = static_cast<int>((bytesUploaded * 100LL) / totalBytes);
if (percent <= lastEmittedPercent) {
return;
}
lastEmittedPercent = percent;
}
const int size = static_cast<int>(pendingBytes);
pendingBytes = 0;
QVariantList eventData{true, sessionId, size};
client->onEventResponse(plugin.data(), eventName(StorageEvent::UploadProgress), eventData);
return;
}
const QString message = (msg && len > 0) ? QString::fromUtf8(msg, len) : QString();
QVariantList eventData{ret == RET_OK, sessionId, message};
client->onEventResponse(plugin.data(), eventName(StorageEvent::UploadDone), eventData);
// Also emit storageResponse with sessionId and cid
emit plugin->storageResponse(StorageSignal::UploadDone, ret, sessionId + "," + message);
}
};
// Callback for a single chunk upload.
//
// When it receives RET_ERROR, the response values are:
// 1- ret: the return code of the command (0 for success, non-zero for failure)
// 2- sessionId: the upload sessionId.
// 3- message: the error message.
//
// When it receives RET_OK, the response values are:
// 1- ret: the return code of the command (0 for success, non-zero for failure)
// 2- sessionId: the upload sessionId.
// 3- size: the number of bytes uploaded.
struct UploadChunkCallbackCtx : CallbackCtx {
QByteArray sessionIdUtf8;
QByteArray chunk;
UploadChunkCallbackCtx(QPointer<StorageModulePlugin> p, QByteArray s, QByteArray c)
: CallbackCtx(p), sessionIdUtf8(std::move(s)), chunk(std::move(c)) {}
void handleResponse(int ret, const char* msg, size_t len) const override {
LogosAPIClient* client = CallbackCtx::client();
if (client == nullptr) {
return;
}
const QString sessionId = QString::fromUtf8(sessionIdUtf8);
if (ret != RET_OK) {
const QString message = (msg && len > 0) ? QString::fromUtf8(msg, len) : QString();
qWarning() << "UploadChunkCallbackCtx: Chunk upload failed, message=" << message;
QVariantList progressData{true, sessionId, message};
client->onEventResponse(plugin.data(), eventName(StorageEvent::UploadProgress), progressData);
// Note that we do not want to cancel the upload because the caller may handle the
// error properly.
return;
}
QVariantList progressData{true, sessionId, chunk.size()};
client->onEventResponse(plugin.data(), eventName(StorageEvent::UploadProgress), progressData);
}
};
// Callback for streaming download data.
//
// When the streaming is done in a file, the progress will be reported with those values:
// 1- success: true if the operation was successful, false otherwise
// 2- cid: CID used as the download session ID
// 3- size: the number of bytes downloaded.
//
// Progress events are throttled to at most one per percentage point (max 100
// events total) to avoid flooding the caller with events on every block.
// When totalBytes is 0 (unknown), every event is forwarded without throttling.
//
// When the streaming is not done in a file, the progress will be reported with those values:
// 1- success: true if the operation was successful, false otherwise
// 2- cid: CID used as the download session ID
// 3- chunk: the chunk of data downloaded.
//
// When the streaming is done, the response values are:
// 1- success: true if the operation was successful, false otherwise
// 2- cid: CID used as the download session ID
// 3- message: empty on success.
struct DownloadStreamCallbackCtx : CallbackCtx {
QByteArray cidUtf8;
QByteArray filepathUtf8;
qint64 totalBytes;
mutable qint64 bytesDownloaded = 0;
mutable qint64 pendingBytes = 0;
mutable int lastEmittedPercent = -1;
DownloadStreamCallbackCtx(QPointer<StorageModulePlugin> p, QByteArray c, QByteArray f, qint64 total = 0)
: CallbackCtx(p), cidUtf8(std::move(c)), filepathUtf8(std::move(f)), totalBytes(total) {}
void handleResponse(int ret, const char* msg, size_t len) const override {
LogosAPIClient* client = CallbackCtx::client();
if (client == nullptr) {
return;
}
const QString cid = QString::fromUtf8(cidUtf8, cidUtf8.size());
if (ret == RET_PROGRESS) {
if (filepathUtf8.isEmpty()) {
// Here we MUST make a copy of the chunk.
// LogosAPIClient::onEventResponse uses Qt::QueuedConnection,
// which queues the event instead of calling immediately. By the time the
// handler executes, `msg` (pointing to messageUtf8 in the callback lambda)
// will be freed. Using QByteArray::fromRawData() would be unsafe.
//
// No throttle here because the chunk is the actual data.
QByteArray chunk(msg, len);
QVariantList eventData{true, cid, chunk};
client->onEventResponse(plugin.data(), eventName(StorageEvent::DownloadProgress), eventData);
} else {
// Throttle to at most one event per percentage point (max 100 events).
// Skipped chunks keep accumulating in pendingBytes so the next emitted
// event carries all bytes processed since the last emission.
bytesDownloaded += static_cast<qint64>(len);
pendingBytes += static_cast<qint64>(len);
if (totalBytes > 0) {
const int percent = static_cast<int>((bytesDownloaded * 100LL) / totalBytes);
if (percent <= lastEmittedPercent) {
return;
}
lastEmittedPercent = percent;
}
const int size = static_cast<int>(pendingBytes);
pendingBytes = 0;
QVariantList eventData{true, cid, size};
client->onEventResponse(plugin.data(), eventName(StorageEvent::DownloadProgress), eventData);
}
return;
}
const QString message = (msg && len > 0) ? QString::fromUtf8(msg, len) : QString();
QVariantList eventData{ret == RET_OK, cid, message};
client->onEventResponse(plugin.data(), eventName(StorageEvent::DownloadDone), eventData);
}
};
// Generic callback to pass data back from libstorage.
// Ensure to NOT DELETE the ctx on RET_PROGRESS.
void StorageModulePlugin::callback(int ret, const char* msg, size_t len, void* userData) {
// Be careful when logging here.
// It can slow down the performance.
// qDebug() << "StorageModulePlugin::callback called with ret=" << ret << "and len=" << len;
// Build the context from userData
auto* ctx = static_cast<CallbackCtx*>(userData);
if (!ctx) {
qWarning() << "StorageModulePlugin::eventCallback: Invalid userData";
return;
}
// Make sure the plugin is still valid.
if (!ctx->plugin) {
// Delete the context to avoid memory leaks.
delete ctx;
return;
}
const QString message = (msg && len > 0) ? QString::fromUtf8(msg, len) : QString();
// Copy the message to a QByteArray to extend its lifetime.
const QByteArray messageUtf8 = message.toUtf8();
// Use invokeMethod to ensure thread-safety when emitting the event.
QMetaObject::invokeMethod(
ctx->plugin.data(),
[ctx, ret, messageUtf8, len]() {
// Call constData to satisfy the callback signature
ctx->handleResponse(ret, messageUtf8.constData(), len);
if (ret != RET_PROGRESS) {
delete ctx;
}
},
Qt::QueuedConnection);
}
// Helper method to wait for a specific signal with a timeout.
LogosResult StorageModulePlugin::waitForSignal(const StorageSignal& signal, int timeout) {
QEventLoop loop;
QString msg;
LogosResult result = {false, ""};
qDebug() << "StorageModulePlugin::waitForSignal: Waiting for signal with timeout" << timeout << "ms";
// Connect the signal to capture the message.
// Connection is used to disconnect after receiving the signal.
QMetaObject::Connection connection;
// Create a callback that will assign the result and
// quit the loop when the signal is received.
auto fn = [&](const StorageSignal& s, int code, const QString& m) {
if (s != signal) {
// We are looking for another signal, ignore this one.
return;
}
result.success = code == RET_OK;
result.value = m;
// Disconnect after receiving the signal to avoid multiple triggers.
QObject::disconnect(connection);
// Quit the loop to unblock the waiting function.
loop.quit();
};
connection = QObject::connect(this, &StorageModulePlugin::storageResponse, &loop, fn);
QTimer timer;
// Just make sure the timer is single shot
timer.setSingleShot(true);
// Connect the timer to quit the loop on timeout.
QObject::connect(&timer, &QTimer::timeout, &loop, [&]() {
result.success = false;
result.value = QString("Cannot get response before timeout.");
loop.quit();
});
timer.start(timeout);
// Wait for the signal or timeout
loop.exec();
return result;
}
// Generic helper that handles all sync call types with optional arguments.
// It is just a shorthand because the pattern is widely used in the code.
LogosResult StorageModulePlugin::syncCall(StorageSignal signal, StorageNoArgFunction fn, int timeout) {
if (!storageCtx) {
return {false, "", "Storage context is not initialized."};
}
auto* ctx = new SyncCallbackCtx{this, signal};
int ret = fn(storageCtx, callback, ctx);
if (ret != RET_OK) {
delete ctx;
return {false, "", "Failed to send command."};
}
return waitForSignal(signal, timeout);
}
LogosResult StorageModulePlugin::syncCall(StorageSignal signal, StorageStringArgFunction fn, const QString& arg1,
int timeout) {
if (!storageCtx) {
return {false, "", "Storage context is not initialized."};
}
auto* ctx = new SyncCallbackCtx{this, signal};
ctx->lifetimeUtf8 = arg1.toUtf8();
int ret = fn(storageCtx, ctx->lifetimeUtf8, callback, ctx);
if (ret != RET_OK) {
delete ctx;
return {false, "", "Failed to send command."};
}
return waitForSignal(signal, timeout);
}
LogosResult StorageModulePlugin::syncCall(StorageSignal signal, StorageStringArgAndIntArgFunction fn,
const QString& arg1, int arg2, int timeout) {
if (!storageCtx) {
return {false, "", "Storage context is not initialized."};
}
auto* ctx = new SyncCallbackCtx{this, signal};
ctx->lifetimeUtf8 = arg1.toUtf8();
int ret = fn(storageCtx, ctx->lifetimeUtf8, arg2, callback, ctx);
if (ret != RET_OK) {
delete ctx;
return {false, "", "Failed to send command."};
}
return waitForSignal(signal, timeout);
}
// Initialize the storage module with the given configuration.
// The method is synchronous.
bool StorageModulePlugin::init(const QString& cfg) {
qDebug() << "StorageModulePlugin::init called with cfg:" << cfg;
// Create a QByteArray to ensure that the data is valid during the async call.
const QByteArray cfgUtf8 = cfg.toUtf8();
storageCtx = storage_new(cfgUtf8.constData(), callback, new SyncCallbackCtx(this, StorageSignal::Init));
LogosResult result = waitForSignal(StorageSignal::Init, DEFAULT_SYNC_TIMEOUT);
if (!result.success) {
qWarning() << "StorageModulePlugin::init Failed to create context error=" << result.getError();
return false;
}
if (storageCtx) {
return true;
}
qWarning() << "StorageModulePlugin::init Failed to create context.";
return false;
}
// The method is asynchronous.
bool StorageModulePlugin::start() {
qDebug() << "StorageModulePlugin::start called";
if (!storageCtx) {
qWarning() << "StorageModulePlugin::start Storage context is not initialized.";
return false;
}
const int ret = storage_start(storageCtx, callback, new EventCallbackCtx{this, StorageEvent::Start});
if (ret != RET_OK) {
qWarning() << "StorageModulePlugin::start Failed to send start command.";
return false;
}
return true;
}
// The method is asynchronous.
LogosResult StorageModulePlugin::stop() {
qDebug() << "StorageModulePlugin::stop called";
if (!storageCtx) {
return {false, "", "Storage context is not initialized."};
}
const int ret = storage_stop(storageCtx, callback, new EventCallbackCtx{this, StorageEvent::Stop});
if (ret != RET_OK) {
return {false, "", "Failed to send stop command to Storage module."};
}
return {true, ""};
}
// The method is synchronous.
// It calls storage_close and storage_destroy internally.
LogosResult StorageModulePlugin::destroy() {
qDebug() << "StorageModulePlugin::destroy called";
LogosResult result = syncCall(StorageSignal::Close, storage_close);
if (!result.success) {
qWarning() << "StorageModulePlugin::destroy failed to close with error " << result.value
<< ". Let's try to destroy anyway.";
}
// callback is actually not called, it should be removed from the api.
const int destroyRet = storage_destroy(storageCtx);
if (destroyRet == RET_OK) {
storageCtx = nullptr;
return {true, ""};
}
return {false, "", "Failed to destroy Storage."};
}
// Connect to a peer by its peer id
// The method is asynchronous.
LogosResult StorageModulePlugin::connect(const QString& peerId, const QStringList& peerAddresses) {
qDebug() << "StorageModulePlugin::connect called with peerId=" << peerId << "and peerAddresses =" << peerAddresses;
if (!storageCtx) {
return {false, "", " Storage context is not initialized"};
}
// Copy the addresses to ensure validity in the callback.
QVector<char*> addrs;
addrs.reserve(peerAddresses.size());
for (const auto& addr : peerAddresses) {
// Use constData to satisfy libstorage C api.
addrs.append(strdup(addr.toUtf8().constData()));
}
// Create a QByteArray to ensure that the data is valid during the async call.
auto* ctx = new ConnectCallbackCtx(this, peerId.toUtf8(), addrs);
// Use constData to satisfy libstorage C api.
const int ret = storage_connect(storageCtx, ctx->peerId.constData(), const_cast<const char**>(ctx->addrs.data()),
static_cast<size_t>(ctx->addrs.size()), callback, ctx);
if (ret != RET_OK) {
// Delete the context because the callback won't be called it because it failed.
delete ctx;
return {false, "", "Failed to send the connect command."};
}
return {true, ""};
}
// The method is synchronous.
LogosResult StorageModulePlugin::version() {
qDebug() << "StorageModulePlugin::version called";
auto version = storage_version(storageCtx);
return {true, QString(version)};
}
// The method is synchronous.
LogosResult StorageModulePlugin::dataDir() {
qDebug() << "StorageModulePlugin::dataDir called";
return syncCall(StorageSignal::DataDir, storage_repo);
}
// The method is synchronous.
LogosResult StorageModulePlugin::peerId() {
qDebug() << "StorageModulePlugin::peerId called";
return syncCall(StorageSignal::PeerId, storage_peer_id);
}
// Get the node's Signed Peer Record (SPR)
// The method is synchronous.
LogosResult StorageModulePlugin::spr() {
qDebug() << "StorageModulePlugin::spr called";
return syncCall(StorageSignal::Spr, storage_spr);
}
// Get the debug info of the node
// The method is synchronous.
LogosResult StorageModulePlugin::debug() {
qDebug() << "StorageModulePlugin::debug called";
LogosResult result = syncCall(StorageSignal::Debug, storage_debug);
if (!result.success) {
return result;
}
QString jsonString = result.value.toString();
QJsonDocument doc = QJsonDocument::fromJson(jsonString.toUtf8());
// Return the whole JSON as QVariant structure
return {true, doc.toVariant()};
}
// The method is synchronous.
LogosResult StorageModulePlugin::updateLogLevel(const QString& logLevel) {
qDebug() << "StorageModulePlugin::updateLogLevel called";
return syncCall(StorageSignal::LogLevel, storage_log_level, logLevel);
}
// The method is synchronous.
LogosResult StorageModulePlugin::exists(const QString& cid) {
qDebug() << "StorageModulePlugin::exists called";
LogosResult result = syncCall(StorageSignal::Exists, storage_exists, cid);
if (result.success) {
return {true, result.getString() == "true"};
}
return {false, false, result.getError()};
}
// The method is synchronous.
LogosResult StorageModulePlugin::fetch(const QString& cid) {
qDebug() << "StorageModulePlugin::fetch called";
int timeout = 3000;
return syncCall(StorageSignal::Fetch, storage_fetch, cid, timeout);
}
// The method is synchronous.
LogosResult StorageModulePlugin::remove(const QString& cid) {
qDebug() << "StorageModulePlugin::remove called";
int timeout = 3000;
return syncCall(StorageSignal::Remove, storage_delete, cid, timeout);
}
// The method is synchronous.
LogosResult StorageModulePlugin::space() {
qDebug() << "StorageModulePlugin::space called";
LogosResult result = syncCall(StorageSignal::Space, storage_space);
if (!result.success) {
return {false, QVariant(), result.getError()};
}
QString jsonString = result.value.toString();
QJsonDocument doc = QJsonDocument::fromJson(jsonString.toUtf8());
if (doc.isNull()) {
return {false, QVariant(), "Failed to parse the JSON document."};
}
return {true, doc.toVariant()};
}
// The method is synchronous.
LogosResult StorageModulePlugin::manifests() {
qDebug() << "StorageModulePlugin::manifests called";
LogosResult result = syncCall(StorageSignal::Manifests, storage_list);
if (!result.success) {
return {false, QVariantList(), result.getError()};
}
QString jsonString = result.value.toString();
QJsonDocument doc = QJsonDocument::fromJson(jsonString.toUtf8());
if (!doc.isArray()) {
return {false, QVariantList(), "Failed to parse json array."};
}
QJsonArray arr = doc.array();
QVariantList manifestsList;
// The manifest structure comes like this:
// {
// "cid": "..",
// "manifest": {
// }
// So ww will just flat everything.
for (const QJsonValue& val : arr) {
QJsonObject item = val.toObject();
QJsonObject manifestObj = item["manifest"].toObject();
QVariantMap manifest;
manifest["cid"] = item["cid"].toString();
manifest["treeCid"] = manifestObj["treeCid"].toString();
manifest["datasetSize"] = manifestObj["datasetSize"].toVariant();
manifest["blockSize"] = manifestObj["blockSize"].toVariant();
manifest["filename"] = manifestObj["filename"].toString();
manifest["mimetype"] = manifestObj["mimetype"].toVariant();
manifestsList.append(manifest);
}
return {true, manifestsList};
}
// The method is synchronous.
LogosResult StorageModulePlugin::downloadManifest(const QString& cid) {
qDebug() << "StorageModulePlugin::downloadManifest called";
int timeout = 3000;
LogosResult result = syncCall(StorageSignal::DownloadManifest, storage_download_manifest, cid, timeout);
if (!result.success) {
return {false, QVariant(), result.getError()};
}
QString jsonString = result.value.toString();
QJsonDocument doc = QJsonDocument::fromJson(jsonString.toUtf8());
if (!doc.isObject()) {
return {false, QVariant(), "Failed to parse JSON object."};
}
return {true, doc.toVariant()};
}
// The method is asynchronous.
LogosResult StorageModulePlugin::uploadUrl(const QUrl& url, const int chunkSize) {
qDebug() << "StorageModulePlugin::uploadUrl called with url=" << url << " and chunkSize=" << chunkSize;
if (!storageCtx) {
return {false, "", "Storage context is not initialized;"};
}
if (!url.isValid()) {
return {false, "", "The URL is not valid."};
}
if (!url.isLocalFile()) {
// TODO: we should handle case like
// - qrc:/resources/file.txt (ressources Qt)
// - data:text/plain;base64,SGVsbG8= (data URLs)
// - content:// (Android content providers)
// We should retrive the stream and use uploadStream
return {false, "", "Non local file is not supported yet."};
}
if (chunkSize <= 0) {
return {false, "", "Chunk size cannot be 0 or less."};
}
QString path = url.toLocalFile();
QFileInfo info(path);
if (!info.exists()) {
return {false, "", "The file does not exist."};
}
if (!info.isFile()) {
return {false, "", "The file is not a regular file (folder ?)."};
}
if (!info.isReadable()) {
return {false, "", "The file is not readable"};
}
// QString filename = info.fileName();
LogosResult result = syncCall(StorageSignal::UploadInit, storage_upload_init, path, chunkSize);
if (!result.success) {
// No need to delete the context, it was deleted in the callback.
return result;
}
QString sessionId = result.getValue<QString>();
// Create a QByteArray to ensure that the data is valid during the async call.
// Pass the file size so progress events can be throttled to one per percent.
auto* uploadFileCtx = new UploadFileCallbackCtx{
this,
sessionId.toUtf8(),
info.size(),
};
const int uploadFileRet =
storage_upload_file(storageCtx, uploadFileCtx->sessionIdUtf8.constData(), callback, uploadFileCtx);
if (uploadFileRet != RET_OK) {
result = uploadCancel(sessionId);
if (!result.success) {
qWarning() << "StorageModulePlugin:: uploadUrl Failed to cancel the session.";
// Continue on fails to cleanup the context
}
// Delete the context because the callback won't be called it.
delete uploadFileCtx;
return {false, "", "Failed to send the upload file command"};
}
return {true, sessionId};
}
// The method is synchronous.
LogosResult StorageModulePlugin::uploadInit(const QString& filename, const int chunkSize) {
qDebug() << "StorageModulePlugin::uploadInit called with filename:" << filename;
return syncCall(StorageSignal::UploadInit, storage_upload_init, filename, chunkSize);
}
// The method is asynchronous.
LogosResult StorageModulePlugin::uploadChunk(const QString& sessionId, const QByteArray& chunk) {
qDebug() << "StorageModulePlugin::uploadChunk called with sessionId:" << sessionId;
auto* ctx = new UploadChunkCallbackCtx{this, sessionId.toUtf8(), chunk};
const uint8_t* chunkC = reinterpret_cast<const uint8_t*>(ctx->chunk.constData());
const size_t sizeC = static_cast<size_t>(ctx->chunk.size());
const int ret = storage_upload_chunk(storageCtx, ctx->sessionIdUtf8.constData(), chunkC, sizeC, callback, ctx);
if (ret != RET_OK) {
// Delete the context because the callback won't be called it because it failed.
// We do not cancel the upload on failure, it does not corrupt the upload session.
delete ctx;
return {false, "", "Failed to send command."};
}
return {true, ""};
}
// The method is synchronous.
LogosResult StorageModulePlugin::uploadFinalize(const QString& sessionId) {
qDebug() << "StorageModulePlugin::uploadFinalize called with sessionId:" << sessionId;
return syncCall(StorageSignal::UploadFinalize, storage_upload_finalize, sessionId);
}
// The method is synchronous.
LogosResult StorageModulePlugin::uploadCancel(const QString& sessionId) {
qDebug() << "StorageModulePlugin::uploadCancel called with sessionId:" << sessionId;
return syncCall(StorageSignal::UploadCancel, storage_upload_cancel, sessionId);
}
// The method is asynchronous.
LogosResult StorageModulePlugin::downloadToUrl(const QString& cid, const QUrl& url, const bool local,
const int chunkSize) {
qDebug() << "StorageModulePlugin::downloadToUrl called";
if (!url.isValid()) {
return {false, "", "The URL is not valid"};
}
if (!url.isLocalFile()) {
return {false, "", "Non local file is not supported yet"};
}
QString path = url.toLocalFile();
return downloadChunks(cid, local, chunkSize, path);
}
// The method is synchronous.
LogosResult StorageModulePlugin::downloadChunks(const QString& cid, const bool local, const int chunkSize,
const QString& filepath) {
qDebug() << "StorageModulePlugin::downloadChunks called";
if (!storageCtx) {
return {false, "", "Storage context is not initialized"};
}
if (chunkSize <= 0) {
return {false, "", "Chunk size cannot be zero or negative."};
}
// Fetch the manifest first to retrive the size
// of the data and provide a download throttle.
qint64 totalBytes = 0;
if (!filepath.isEmpty()) {
LogosResult result = downloadManifest(cid);
if (result.success) {
totalBytes = result.getValue<qlonglong>("datasetSize");
} else {
qWarning() << "StorageModulePlugin::downloadManifest failed, error=" << result.getError();
return {false, "", "Failed to download the manifest: " + result.getError()};
}
}
// Create a QByteArray to ensure that the data is valid during the async call.
auto* initCtx = new SyncCallbackCtx{this, StorageSignal::DownloadInit, cid.toUtf8()};
const size_t chunkSizeC = static_cast<size_t>(chunkSize);
const int initRet =
storage_download_init(storageCtx, initCtx->lifetimeUtf8.constData(), chunkSizeC, local, callback, initCtx);
if (initRet != RET_OK) {
// Delete the context because the callback won't be called it.
delete initCtx;
return {false, "", "Failed to send download init command"};
}