File: LocalProjectSnapshot.cpp

package info (click to toggle)
audacity 3.7.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 125,252 kB
  • sloc: cpp: 358,238; ansic: 75,458; lisp: 7,761; sh: 3,410; python: 1,503; xml: 1,385; perl: 854; makefile: 122
file content (636 lines) | stat: -rw-r--r-- 18,357 bytes parent folder | download | duplicates (2)
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
/*  SPDX-License-Identifier: GPL-2.0-or-later */
/*!********************************************************************

  Audacity: A Digital Audio Editor

  CloudProjectSnapshot.cpp

  Dmitry Vedenko

**********************************************************************/
#include "LocalProjectSnapshot.h"

#include <algorithm>
#include <future>

#include "../OAuthService.h"
#include "../ServiceConfig.h"

#include "BasicUI.h"

#include "BlockHasher.h"
#include "CloudProjectsDatabase.h"
#include "DataUploader.h"
#include "MixdownUploader.h"
#include "NetworkUtils.h"
#include "ProjectCloudExtension.h"

#include "ExportUtils.h"
#include "MemoryX.h"
#include "Project.h"
#include "SampleBlock.h"
#include "Sequence.h"
#include "Track.h"
#include "WaveClip.h"
#include "WaveTrack.h"
#include "WaveTrackUtilities.h"

#include "IResponse.h"
#include "NetworkManager.h"
#include "Request.h"

#include "MissingBlocksUploader.h"

#include "StringUtils.h"

#include "crypto/SHA256.h"

namespace audacity::cloud::audiocom::sync
{
struct LocalProjectSnapshot::ProjectBlocksLock final : private BlockHashCache
{
   ProjectCloudExtension& Extension;

   SampleBlockIDSet BlockIds;

   std::vector<LockedBlock> Blocks;
   std::vector<BlockUploadTask> MissingBlocks;

   std::unordered_map<int64_t, size_t> BlockIdToIndex;
   std::unordered_map<std::string, size_t> BlockHashToIndex;

   std::unique_ptr<BlockHasher> Hasher;

   std::future<void> UpdateCacheFuture;
   std::vector<std::pair<int64_t, std::string>> NewHashes;

   std::function<void()> OnBlocksLocked;

   explicit ProjectBlocksLock(
      ProjectCloudExtension& extension, AudacityProject& project,
      std::function<void()> onBlocksLocked)
       : Extension { extension }
       , OnBlocksLocked { std::move(onBlocksLocked) }
   {
      VisitBlocks(TrackList::Get(project));

      if (Extension.IsCloudProject())
      {
         CloudProjectsDatabase::Get().UpdateProjectBlockList(
            Extension.GetCloudProjectId(), BlockIds);
      }

      Hasher = std::make_unique<BlockHasher>();

      Hasher->ComputeHashes(*this, Blocks, [this] { CollectHashes(); });
   }

   ~ProjectBlocksLock() override
   {
   }

   void VisitBlocks(TrackList& tracks)
   {
      const auto visitor = [this](const SampleBlockPtr &pBlock){
         const auto id = pBlock->GetBlockID();
         if(id >= 0)
         {
            Blocks.push_back({
               id, pBlock->GetSampleFormat(), pBlock });
            BlockIdToIndex[id] = Blocks.size() - 1;
         }
         //Do not compute hashes for negative id's, which describe
         //the length of a silenced sequence. Making an id record in
         //project blob is enough to restore block contents fully.
         //VS: Older versions of Audacity encoded them as a regular
         //blocks, but due to wrong sanity checks in `WavPackCompressor`
         //attempt to load them could fail. The check above will purge
         //such blocks if they are present in old project.
      };
      WaveTrackUtilities::VisitBlocks(tracks, visitor, &BlockIds);
   }

   void CollectHashes()
   {
      // TakeResult() will call UpdateHash() for each block
      // not found in the cache
      const auto result = Hasher->TakeResult();

      for (auto [id, hash] : result)
      {
         auto it = BlockIdToIndex.find(id);

         if (it == BlockIdToIndex.end())
         {
            assert(false);
            continue;
         }

         while (BlockHashToIndex.find(hash) != BlockHashToIndex.end())
         {
            // Hash is used by another block, rehash
            hash = crypto::sha256(hash);
         }

         BlockHashToIndex[hash]  = BlockIdToIndex[id];
         Blocks[it->second].Hash = std::move(hash);
      }

      // This will potentially block, if the cache is being updated
      // already
      UpdateProjectHashesInCache();

      if (OnBlocksLocked)
         OnBlocksLocked();
   }

   void UpdateProjectHashesInCache()
   {
      if (!Extension.IsCloudProject())
         return;

      UpdateCacheFuture = std::async(
         std::launch::async,
         [this, hashes = std::move(NewHashes)]
         {
            CloudProjectsDatabase::Get().UpdateBlockHashes(
               Extension.GetCloudProjectId(), hashes);
         });
   }

   bool GetHash(int64_t blockId, std::string& hash) const override
   {
      if (!Extension.IsCloudProject())
         return false;

      auto cachedResult = CloudProjectsDatabase::Get().GetBlockHash(
         Extension.GetCloudProjectId(), blockId);

      if (!cachedResult)
         return false;

      hash = std::move(*cachedResult);

      return true;
   }

   void UpdateHash(int64_t blockId, const std::string& hash) override
   {
      NewHashes.emplace_back(blockId, hash);
   }

   void FillMissingBlocks(const std::vector<UploadUrls>& missingBlockUrls)
   {
      for (const auto& urls : missingBlockUrls)
      {
         auto it = BlockHashToIndex.find(ToUpper(urls.Id));

         if (it == BlockHashToIndex.end())
         {
            assert(false);
            continue;
         }

         const auto index = it->second;

         MissingBlocks.push_back(BlockUploadTask { urls, Blocks[index] });
      }
   }
};

LocalProjectSnapshot::LocalProjectSnapshot(
   Tag, const ServiceConfig& config, const OAuthService& oauthService,
   ProjectCloudExtension& extension, std::string name, UploadMode mode,
   AudiocomTrace trace)
    : mProjectCloudExtension { extension }
    , mWeakProject { extension.GetProject() }
    , mServiceConfig { config }
    , mOAuthService { oauthService }
    , mAudiocomTrace { trace }
    , mProjectName { std::move(name) }
    , mUploadMode { mode }
    , mCancellationContext { concurrency::CancellationContext::Create() }
{
}

LocalProjectSnapshot::~LocalProjectSnapshot()
{
}

LocalProjectSnapshot::Future LocalProjectSnapshot::Create(
   const ServiceConfig& config, const OAuthService& oauthService,
   ProjectCloudExtension& extension, std::string name, UploadMode mode,
   AudiocomTrace trace)
{
   auto project = extension.GetProject().lock();

   if (!project)
      return {};

   auto snapshot = std::make_shared<LocalProjectSnapshot>(
      Tag {}, config, oauthService, extension, std::move(name), mode, trace);

   snapshot->mProjectCloudExtension.OnUploadOperationCreated(snapshot);

   snapshot->mProjectBlocksLock = std::make_unique<ProjectBlocksLock>(
      extension, *project,
      [weakSnapshot = std::weak_ptr(snapshot)]
      {
         auto snapshot = weakSnapshot.lock();

         if (snapshot == nullptr)
            return;

         auto project = snapshot->GetProject();

         if (project == nullptr)
            return;

         snapshot->mProjectCloudExtension.OnBlocksHashed(*snapshot);
      });

   return snapshot->mCreateSnapshotPromise.get_future();
}

bool LocalProjectSnapshot::IsCompleted() const
{
   return mCompleted.load(std::memory_order_acquire);
}

std::shared_ptr<AudacityProject> LocalProjectSnapshot::GetProject()
{
   return mWeakProject.lock();
}

void LocalProjectSnapshot::Start()
{
   UpdateProjectSnapshot();
}

void LocalProjectSnapshot::SetUploadData(const ProjectUploadData& data)
{
   mProjectDataReady.store(true);
   mProjectDataPromise.set_value(data);
}

void LocalProjectSnapshot::Cancel()
{
   mCancelled.store(true, std::memory_order_release);

   mCancellationContext->Cancel();

   if (!mProjectDataReady.load(std::memory_order_acquire))
      mProjectDataPromise.set_value({});

   UploadFailed({ CloudSyncError::Cancelled });
}

void LocalProjectSnapshot::Abort()
{
   mCancelled.store(true, std::memory_order_release);

   mCancellationContext->Cancel();

   if (!mProjectDataReady.load(std::memory_order_acquire))
      mProjectDataPromise.set_value({});

   UploadFailed({ CloudSyncError::Aborted });

   DeleteSnapshot();
}

void LocalProjectSnapshot::UploadFailed(CloudSyncError error)
{
   if (!mCompleted.exchange(true, std::memory_order_release))
      mProjectCloudExtension.OnSyncCompleted(
         this, std::make_optional(error), mAudiocomTrace);
}

void LocalProjectSnapshot::DataUploadFailed(const ResponseResult& uploadResult)
{
   UploadFailed({ DeduceError(uploadResult.Code), uploadResult.Content });
}

void LocalProjectSnapshot::DataUploadFailed(
   const MissingBlocksUploadProgress& uploadResult)
{
   CloudSyncError::ErrorType errorType = CloudSyncError::DataUploadFailed;

   for (const auto& uploadError : uploadResult.UploadErrors)
   {
      if (
         uploadError.Code == SyncResultCode::Success ||
         uploadError.Code == SyncResultCode::Conflict)
         continue;

      const auto deducedError = DeduceError(uploadError.Code);

      if (
         errorType == CloudSyncError::DataUploadFailed &&
         deducedError == CloudSyncError::Network)
      {
         errorType = deducedError;
      }
      else if (
         deducedError == CloudSyncError::ProjectStorageLimitReached ||
         deducedError == CloudSyncError::Cancelled)
      {
         errorType = deducedError;
         break;
      }
   }

   UploadFailed({ errorType, {} });
}

void LocalProjectSnapshot::UpdateProjectSnapshot()
{
   auto project = mWeakProject.lock();

   if (project == nullptr)
   {
      UploadFailed(MakeClientFailure(
         XO("Project was closed before snapshot was created")));
      return;
   }

   const bool isCloudProject = mProjectCloudExtension.IsCloudProject();
   const bool createNew =
      mUploadMode == UploadMode::CreateNew || !isCloudProject;

   ProjectForm projectForm;

   if (createNew)
      projectForm.Name = mProjectName;
   else
      projectForm.HeadSnapshotId = mProjectCloudExtension.GetSnapshotId();

   // For empty projects, mProjectBlocksLock will be nullptr at this point
   if (mProjectBlocksLock != nullptr)
   {
      projectForm.Hashes.reserve(mProjectBlocksLock->Blocks.size());
      std::transform(
         mProjectBlocksLock->Blocks.begin(), mProjectBlocksLock->Blocks.end(),
         std::back_inserter(projectForm.Hashes),
         [](const auto& block) { return block.Hash; });
   }

   using namespace audacity::network_manager;

   const auto url = createNew ? mServiceConfig.GetCreateProjectUrl() :
                                mServiceConfig.GetCreateSnapshotUrl(
                                   mProjectCloudExtension.GetCloudProjectId());

   projectForm.Force = !createNew && mUploadMode == UploadMode::ForceOverwrite;

   auto request = Request(url);

   request.setHeader(
      common_headers::ContentType, common_content_types::ApplicationJson);
   request.setHeader(
      common_headers::Accept, common_content_types::ApplicationJson);
   // request.setHeader(common_headers::ContentEncoding, "gzip");

   SetOptionalHeaders(request);

   const auto language = mServiceConfig.GetAcceptLanguageValue();

   if (!language.empty())
      request.setHeader(
         audacity::network_manager::common_headers::AcceptLanguage, language);

   request.setHeader(
      common_headers::Authorization, mOAuthService.GetAccessToken());

   auto serializedForm = Serialize(projectForm);

   auto response = NetworkManager::GetInstance().doPost(
      request, serializedForm.data(), serializedForm.size());

   response->setRequestFinishedCallback(
      [this, response, createNew, weakThis = weak_from_this()](auto)
      {
         auto strongThis = weakThis.lock();
         if (!strongThis)
            return;

         const auto error = response->getError();

         if (error != NetworkError::NoError)
         {
            UploadFailed(DeduceUploadError(*response));

            mCreateSnapshotPromise.set_value({});
            return;
         }

         const auto body = response->readAll<std::string>();
         auto result     = DeserializeCreateSnapshotResponse(body);

         if (!result)
         {
            UploadFailed(MakeClientFailure(
               XO("Invalid Response: %s").Format(body).Translation()));

            mCreateSnapshotPromise.set_value({});
            return;
         }

         OnSnapshotCreated(*result, createNew);
      });

   mCancellationContext->OnCancelled(response);
}

void LocalProjectSnapshot::OnSnapshotCreated(
   const CreateSnapshotResponse& response, bool newProject)
{
   auto project = mWeakProject.lock();

   if (project == nullptr)
   {
      UploadFailed(MakeClientFailure(
         XO("Project was closed before snapshot was created")));
      return;
   }

   if (newProject)
      mProjectBlocksLock->UpdateProjectHashesInCache();

   mProjectBlocksLock->FillMissingBlocks(response.SyncState.MissingBlocks);

   mProjectCloudExtension.OnSnapshotCreated(*this, response);

   {
      auto lock = std::lock_guard { mCreateSnapshotResponseMutex };
      mCreateSnapshotResponse = response;
   }

   mCreateSnapshotPromise.set_value({ response, shared_from_this() });

   auto projectData = mProjectDataPromise.get_future().get();

   if (mCancelled.load(std::memory_order_acquire))
      return;

   StorePendingSnapshot(response, projectData);

   DataUploader::Get().Upload(
      mCancellationContext, mServiceConfig, response.SyncState.FileUrls,
      projectData.ProjectSnapshot,
      [this, weakThis = weak_from_this()](ResponseResult result)
      {
         auto strongThis = weakThis.lock();
         if (!strongThis)
            return;

         auto& db = CloudProjectsDatabase::Get();

         const auto projectId  = mCreateSnapshotResponse->Project.Id;
         const auto snapshotId = mCreateSnapshotResponse->Snapshot.Id;

         if (result.Code != SyncResultCode::Success)
         {
            db.RemovePendingSnapshot(projectId, snapshotId);
            db.RemovePendingProjectBlob(projectId, snapshotId);
            db.RemovePendingProjectBlocks(projectId, snapshotId);

            DataUploadFailed(result);
            return;
         }

         mProjectCloudExtension.OnProjectDataUploaded(*this);
         db.RemovePendingProjectBlob(projectId, snapshotId);

         if (mProjectBlocksLock->MissingBlocks.empty())
         {
            MarkSnapshotSynced();
            return;
         }

         mMissingBlockUploader = MissingBlocksUploader::Create(
            mCancellationContext, mServiceConfig,
            mProjectBlocksLock->MissingBlocks,
            [this, weakThis = weak_from_this()](
               auto result, auto block, auto uploadResult)
            {
               auto strongThis = weakThis.lock();
               if (!strongThis)
                  return;

               if (!IsUploadRecoverable(uploadResult.Code))
                  CloudProjectsDatabase::Get().RemovePendingProjectBlock(
                     mCreateSnapshotResponse->Project.Id, block.Id);

               mProjectCloudExtension.OnBlockUploaded(
                  *this, block.Hash,
                  uploadResult.Code == SyncResultCode::Success);

               const auto completed =
                  result.UploadedBlocks == result.TotalBlocks ||
                  result.FailedBlocks != 0;
               const bool succeeded = completed && result.FailedBlocks == 0;

               if (!completed)
                  return;

               if (succeeded)
                  MarkSnapshotSynced();
               else
                  DataUploadFailed(result);
            });
      });
}

void LocalProjectSnapshot::StorePendingSnapshot(
   const CreateSnapshotResponse& response, const ProjectUploadData& projectData)
{
   CloudProjectsDatabase::Get().AddPendingSnapshot(
      { response.Project.Id, response.Snapshot.Id,
        mServiceConfig.GetSnapshotSyncUrl(
           response.Project.Id, response.Snapshot.Id) });

   CloudProjectsDatabase::Get().AddPendingProjectBlob(
      { response.Project.Id, response.Snapshot.Id,
        response.SyncState.FileUrls.UploadUrl,
        response.SyncState.FileUrls.SuccessUrl,
        response.SyncState.FileUrls.FailUrl, projectData.ProjectSnapshot });

   if (mProjectBlocksLock->MissingBlocks.empty())
      return;

   std::vector<PendingProjectBlockData> pendingBlocks;
   pendingBlocks.reserve(mProjectBlocksLock->MissingBlocks.size());

   for (const auto& block : mProjectBlocksLock->MissingBlocks)
   {
      pendingBlocks.push_back(PendingProjectBlockData {
         response.Project.Id, response.Snapshot.Id, block.BlockUrls.UploadUrl,
         block.BlockUrls.SuccessUrl, block.BlockUrls.FailUrl, block.Block.Id,
         static_cast<int>(block.Block.Format), block.Block.Hash });
   }

   CloudProjectsDatabase::Get().AddPendingProjectBlocks(pendingBlocks);
}

void LocalProjectSnapshot::MarkSnapshotSynced()
{
   using namespace network_manager;
   Request request(mServiceConfig.GetSnapshotSyncUrl(
      mCreateSnapshotResponse->Project.Id,
      mCreateSnapshotResponse->Snapshot.Id));

   SetCommonHeaders(request);
   SetOptionalHeaders(request);

   auto response = NetworkManager::GetInstance().doPost(request, nullptr, 0);

   response->setRequestFinishedCallback(
      [this, response, weakThis = weak_from_this()](auto)
      {
         auto strongThis = weakThis.lock();
         if (!strongThis)
            return;

         CloudProjectsDatabase::Get().RemovePendingSnapshot(
            mCreateSnapshotResponse->Project.Id,
            mCreateSnapshotResponse->Snapshot.Id);

         if (response->getError() != NetworkError::NoError)
         {
            UploadFailed(DeduceUploadError(*response));
            return;
         }

         mCompleted.store(true, std::memory_order_release);
         mProjectCloudExtension.OnSyncCompleted(this, {}, mAudiocomTrace);
      });

   mCancellationContext->OnCancelled(response);
}

void LocalProjectSnapshot::DeleteSnapshot()
{
   if (!mCreateSnapshotResponse)
      return;

   using namespace network_manager;

   Request request(mServiceConfig.GetDeleteSnapshotUrl(
      mCreateSnapshotResponse->Project.Id,
      mCreateSnapshotResponse->Snapshot.Id));

   SetCommonHeaders(request);

   auto response = NetworkManager::GetInstance().doDelete(request);

   response->setRequestFinishedCallback(
      [this, response, strongThis = shared_from_this()](auto)
      {
         CloudProjectsDatabase::Get().RemovePendingSnapshot(
            mCreateSnapshotResponse->Project.Id,
            mCreateSnapshotResponse->Snapshot.Id);
      });
}

} // namespace audacity::cloud::audiocom::sync