File: CacheManager.cpp

package info (click to toggle)
orthanc-webviewer 2.10%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 1,932 kB
  • sloc: javascript: 21,840; cpp: 7,296; python: 345; sh: 93; makefile: 60
file content (625 lines) | stat: -rw-r--r-- 16,388 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
/**
 * Orthanc - A Lightweight, RESTful DICOM Store
 * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
 * Department, University Hospital of Liege, Belgium
 * Copyright (C) 2017-2023 Osimis S.A., Belgium
 * Copyright (C) 2024-2025 Orthanc Team SRL, Belgium
 * Copyright (C) 2021-2025 Sebastien Jodogne, ICTEAM UCLouvain, Belgium
 *
 * This program is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 **/


#include "CacheManager.h"

#include <Compatibility.h>
#include <Toolbox.h>
#include <SQLite/Transaction.h>

#include <boost/lexical_cast.hpp>


namespace OrthancPlugins
{
  class CacheManager::Bundle
  {
  private:
    uint32_t  count_;
    uint64_t  space_;

  public:
    Bundle() : count_(0), space_(0)
    {
    }

    Bundle(uint32_t count,
           uint64_t space) : 
      count_(count), space_(space)
    {
    }

    uint32_t GetCount() const
    {
      return count_;
    }

    uint64_t GetSpace() const
    {
      return space_;
    }

    void Remove(uint64_t fileSize)
    {
      if (count_ == 0 ||
          space_ < fileSize)
      {
        throw std::runtime_error("Internal error");
      }

      count_ -= 1;
      space_ -= fileSize;
    }

    void Add(uint64_t fileSize)
    {
      count_ += 1;
      space_ += fileSize;
    }
  };


  class CacheManager::BundleQuota
  {
  private:   
    uint32_t maxCount_;
    uint64_t maxSpace_;

  public:
    BundleQuota(uint32_t maxCount,
                uint64_t maxSpace) : 
      maxCount_(maxCount), maxSpace_(maxSpace)
    {
    }

    BundleQuota()
    {
      // Default quota
      maxCount_ = 0;  // No limit on the number of files
      maxSpace_ = 100 * 1024 * 1024;  // Max 100MB per bundle
    }

    uint32_t GetMaxCount() const
    {
      return maxCount_;
    }

    uint64_t GetMaxSpace() const
    {
      return maxSpace_;
    }

    bool IsSatisfied(const Bundle& bundle) const
    {
      if (maxCount_ != 0 &&
          bundle.GetCount() > maxCount_)
      {
        return false;
      }

      if (maxSpace_ != 0 &&
          bundle.GetSpace() > maxSpace_)
      {
        return false;
      }

      return true;
    }
  };


  struct CacheManager::PImpl
  {
    OrthancPluginContext* context_;
    Orthanc::SQLite::Connection& db_;
    Orthanc::FilesystemStorage& storage_;

    bool sanityCheck_;
    Bundles  bundles_;
    BundleQuota  defaultQuota_;
    BundleQuotas  quotas_;

    PImpl(OrthancPluginContext* context,
          Orthanc::SQLite::Connection& db,
          Orthanc::FilesystemStorage& storage) :
      context_(context),
      db_(db), 
      storage_(storage), 
      sanityCheck_(false)
    {
    }
  };


  const CacheManager::BundleQuota& CacheManager::GetBundleQuota(int bundleIndex) const
  {
    BundleQuotas::const_iterator found = pimpl_->quotas_.find(bundleIndex);

    if (found == pimpl_->quotas_.end())
    {
      return pimpl_->defaultQuota_;
    }
    else
    {
      return found->second;
    }
  }


  CacheManager::Bundle CacheManager::GetBundle(int bundleIndex) const
  {
    Bundles::const_iterator it = pimpl_->bundles_.find(bundleIndex);
  
    if (it == pimpl_->bundles_.end())
    {
      return Bundle();
    }
    else
    {
      return it->second;
    }
  }


  void CacheManager::MakeRoom(Bundle& bundle,
                              std::list<std::string>& toRemove,
                              int bundleIndex,
                              const BundleQuota& quota)
  {
    toRemove.clear();

    // Make room in the bundle
    while (!quota.IsSatisfied(bundle))
    {
      Orthanc::SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "SELECT seq, fileUuid, fileSize FROM Cache WHERE bundle=? ORDER BY seq");
      s.BindInt(0, bundleIndex);

      if (s.Step())
      {
        Orthanc::SQLite::Statement t(pimpl_->db_, SQLITE_FROM_HERE, "DELETE FROM Cache WHERE seq=?");
        t.BindInt64(0, s.ColumnInt64(0));
        t.Run();

        toRemove.push_back(s.ColumnString(1));
        bundle.Remove(s.ColumnInt64(2));
      }
      else
      {
        // Should never happen
        throw std::runtime_error("Internal error");
      }
    }
  }



  void CacheManager::EnsureQuota(int bundleIndex,
                                 const BundleQuota& quota)
  {
    // Remove the cached files that exceed the quota
    std::unique_ptr<Orthanc::SQLite::Transaction> transaction(new Orthanc::SQLite::Transaction(pimpl_->db_));
    transaction->Begin();

    Bundle bundle = GetBundle(bundleIndex);

    std::list<std::string> toRemove;
    MakeRoom(bundle, toRemove, bundleIndex, quota);

    transaction->Commit();
    for (std::list<std::string>::const_iterator
           it = toRemove.begin(); it != toRemove.end(); ++it)
    {
      pimpl_->storage_.Remove(*it, Orthanc::FileContentType_Unknown);
    }

    pimpl_->bundles_[bundleIndex] = bundle;
  }



  void CacheManager::ReadBundleStatistics()
  {
    pimpl_->bundles_.clear();

    Orthanc::SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "SELECT bundle,COUNT(*),SUM(fileSize) FROM Cache GROUP BY bundle");
    while (s.Step())
    {
      int index = s.ColumnInt(0);
      Bundle bundle(static_cast<uint32_t>(s.ColumnInt(1)),
                    static_cast<uint64_t>(s.ColumnInt64(2)));
      pimpl_->bundles_[index] = bundle;
    }
  }



  void CacheManager::SanityCheck()
  {
    if (!pimpl_->sanityCheck_)
    {
      return;
    }

    Orthanc::SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "SELECT bundle,COUNT(*),SUM(fileSize) FROM Cache GROUP BY bundle");
    while (s.Step())
    {
      const Bundle& bundle = GetBundle(s.ColumnInt(0));
      if (bundle.GetCount() != static_cast<uint32_t>(s.ColumnInt(1)) ||
          bundle.GetSpace() != static_cast<uint64_t>(s.ColumnInt64(2)))
      {
        throw std::runtime_error("SANITY ERROR in cache: " + boost::lexical_cast<std::string>(bundle.GetCount()) 
                                 + "/" + boost::lexical_cast<std::string>(bundle.GetSpace())
                                 + " vs " + boost::lexical_cast<std::string>(s.ColumnInt(1)) + "/"
                                 + boost::lexical_cast<std::string>(s.ColumnInt64(2)));
      }
    }
  }



  CacheManager::CacheManager(OrthancPluginContext* context,
                             Orthanc::SQLite::Connection& db,
                             Orthanc::FilesystemStorage& storage) :
    pimpl_(new PImpl(context, db, storage))
  {
    Open();
    ReadBundleStatistics();
  }


  OrthancPluginContext* CacheManager::GetPluginContext() const
  {
    return pimpl_->context_;
  }


  void CacheManager::SetSanityCheckEnabled(bool enabled)
  {
    pimpl_->sanityCheck_ = enabled;
  }


  void CacheManager::Open()
  {
    if (!pimpl_->db_.DoesTableExist("Cache"))
    {
      pimpl_->db_.Execute("CREATE TABLE Cache(seq INTEGER PRIMARY KEY, bundle INTEGER, item TEXT, fileUuid TEXT, fileSize INT);");
      pimpl_->db_.Execute("CREATE INDEX CacheBundles ON Cache(bundle);");
      pimpl_->db_.Execute("CREATE INDEX CacheIndex ON Cache(bundle, item);");
    }

    if (!pimpl_->db_.DoesTableExist("CacheProperties"))
    {
      pimpl_->db_.Execute("CREATE TABLE CacheProperties(property INTEGER PRIMARY KEY, value TEXT);");
    }

    // Performance tuning of SQLite with PRAGMAs
    // http://www.sqlite.org/pragma.html
    pimpl_->db_.Execute("PRAGMA SYNCHRONOUS=OFF;");
    pimpl_->db_.Execute("PRAGMA JOURNAL_MODE=WAL;");
    pimpl_->db_.Execute("PRAGMA LOCKING_MODE=EXCLUSIVE;");
  }


  void CacheManager::Store(int bundleIndex,
                           const std::string& item,
                           const std::string& content)
  {
    SanityCheck();

    const BundleQuota quota = GetBundleQuota(bundleIndex);

    if (quota.GetMaxSpace() > 0 &&
        content.size() > quota.GetMaxSpace())
    {
      // Cannot store such a large instance into the cache, forget about it
      return;
    }

    std::unique_ptr<Orthanc::SQLite::Transaction> transaction(new Orthanc::SQLite::Transaction(pimpl_->db_));
    transaction->Begin();

    Bundle bundle = GetBundle(bundleIndex);

    std::list<std::string>  toRemove;
    bundle.Add(content.size());
    MakeRoom(bundle, toRemove, bundleIndex, quota);

    // Store the cached content on the disk
    const char* data = content.size() ? &content[0] : NULL;
    std::string uuid = Orthanc::Toolbox::GenerateUuid();
    pimpl_->storage_.Create(uuid, data, content.size(), Orthanc::FileContentType_Unknown);

    // Remove the previous cached value. This might happen if the same
    // item is accessed very quickly twice: Another factory could have
    // been cached a value before the check for existence in Access().
    {
      Orthanc::SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "SELECT seq, fileUuid, fileSize FROM Cache WHERE bundle=? AND item=?");
      s.BindInt(0, bundleIndex);
      s.BindString(1, item);
      if (s.Step())
      {
        Orthanc::SQLite::Statement t(pimpl_->db_, SQLITE_FROM_HERE, "DELETE FROM Cache WHERE seq=?");
        t.BindInt64(0, s.ColumnInt64(0));
        t.Run();

        toRemove.push_back(s.ColumnString(1));
        bundle.Remove(s.ColumnInt64(2));
      }
    }

    {
      Orthanc::SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "INSERT INTO Cache VALUES(NULL, ?, ?, ?, ?)");
      s.BindInt(0, bundleIndex);
      s.BindString(1, item);
      s.BindString(2, uuid);
      s.BindInt64(3, content.size());

      if (!s.Run())
      {
        // Error: Remove the stored file
        pimpl_->storage_.Remove(uuid, Orthanc::FileContentType_Unknown);
      }
      else
      {
        transaction->Commit();

        pimpl_->bundles_[bundleIndex] = bundle;
    
        for (std::list<std::string>::const_iterator
               it = toRemove.begin(); it != toRemove.end(); ++it)
        {
          pimpl_->storage_.Remove(*it, Orthanc::FileContentType_Unknown);
        }
      }
    }

    SanityCheck();
  }



  bool CacheManager::LocateInCache(std::string& uuid,
                                   uint64_t& size,
                                   int bundle,
                                   const std::string& item)
  {
    SanityCheck();

    std::unique_ptr<Orthanc::SQLite::Transaction> transaction(new Orthanc::SQLite::Transaction(pimpl_->db_));
    transaction->Begin();

    Orthanc::SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "SELECT seq, fileUuid, fileSize FROM Cache WHERE bundle=? AND item=?");
    s.BindInt(0, bundle);
    s.BindString(1, item);
    if (!s.Step())
    {
      return false;
    }

    int64_t seq = s.ColumnInt64(0);
    uuid = s.ColumnString(1);
    size = s.ColumnInt64(2);

    // Touch the cache to fulfill the LRU scheme.
    Orthanc::SQLite::Statement t(pimpl_->db_, SQLITE_FROM_HERE, "DELETE FROM Cache WHERE seq=?");
    t.BindInt64(0, seq);
    if (t.Run())
    {
      Orthanc::SQLite::Statement u(pimpl_->db_, SQLITE_FROM_HERE, "INSERT INTO Cache VALUES(NULL, ?, ?, ?, ?)");
      u.BindInt(0, bundle);
      u.BindString(1, item);
      u.BindString(2, uuid);
      u.BindInt64(3, size);
      if (u.Run())
      {
        // Everything was OK. Commit the changes to the cache.
        transaction->Commit();
        return true;
      }
    }

    return false;
  }


  bool CacheManager::IsCached(int bundle,
                              const std::string& item)
  {
    std::string uuid;
    uint64_t size;
    return LocateInCache(uuid, size, bundle, item);
  }


  bool CacheManager::Access(std::string& content,
                            int bundle,
                            const std::string& item)
  {
    std::string uuid;
    uint64_t size;
    if (!LocateInCache(uuid, size, bundle, item))
    {
      return false;
    }

    bool ok;
    try
    {
#if defined(ORTHANC_FRAMEWORK_VERSION_IS_ABOVE) && ORTHANC_FRAMEWORK_VERSION_IS_ABOVE(1, 9, 0) 
      std::unique_ptr<Orthanc::IMemoryBuffer> buffer(
        pimpl_->storage_.Read(uuid, Orthanc::FileContentType_Unknown));
      buffer->MoveToString(content);
#else
      pimpl_->storage_.Read(content, uuid, Orthanc::FileContentType_Unknown);
#endif
      
      ok = (content.size() == size);
    }
    catch (std::runtime_error&)
    {
      ok = false;
    }

    if (ok)
    {
      return true;
    }
    else
    {
      throw std::runtime_error("Error in the filesystem");
    }
  }


  void CacheManager::Invalidate(int bundleIndex,
                                const std::string& item)
  {
    SanityCheck();

    std::unique_ptr<Orthanc::SQLite::Transaction> transaction(new Orthanc::SQLite::Transaction(pimpl_->db_));
    transaction->Begin();

    Bundle bundle = GetBundle(bundleIndex);

    Orthanc::SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "SELECT seq, fileUuid, fileSize FROM Cache WHERE bundle=? AND item=?");
    s.BindInt(0, bundleIndex);
    s.BindString(1, item);
    if (s.Step())
    {
      int64_t seq = s.ColumnInt64(0);
      const std::string uuid = s.ColumnString(1);
      uint64_t expectedSize = s.ColumnInt64(2);
      bundle.Remove(expectedSize);

      Orthanc::SQLite::Statement t(pimpl_->db_, SQLITE_FROM_HERE, "DELETE FROM Cache WHERE seq=?");
      t.BindInt64(0, seq);
      if (t.Run())
      {
        transaction->Commit();
        pimpl_->bundles_[bundleIndex] = bundle;
        pimpl_->storage_.Remove(uuid, Orthanc::FileContentType_Unknown);
      }
    }
  }



  void CacheManager::SetBundleQuota(int bundle,
                                    uint32_t maxCount,
                                    uint64_t maxSpace)
  {
    SanityCheck();

    const BundleQuota quota(maxCount, maxSpace);
    EnsureQuota(bundle, quota);
    pimpl_->quotas_[bundle] = quota;

    SanityCheck();
  }

  void CacheManager::SetDefaultQuota(uint32_t maxCount,
                                     uint64_t maxSpace)
  {
    SanityCheck();

    pimpl_->defaultQuota_ = BundleQuota(maxCount, maxSpace);

    Orthanc::SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "SELECT DISTINCT bundle FROM Cache");
    while (s.Step())
    {
      EnsureQuota(s.ColumnInt(0), pimpl_->defaultQuota_);
    }

    SanityCheck();
  }


  void CacheManager::Clear()
  {
    SanityCheck();

    Orthanc::SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "SELECT fileUuid FROM Cache");
    while (s.Step())
    {
      pimpl_->storage_.Remove(s.ColumnString(0), Orthanc::FileContentType_Unknown);
    }  

    Orthanc::SQLite::Statement t(pimpl_->db_, SQLITE_FROM_HERE, "DELETE FROM Cache");
    t.Run();

    ReadBundleStatistics();
    SanityCheck();
  }



  void CacheManager::Clear(int bundle)
  {
    SanityCheck();

    Orthanc::SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "SELECT fileUuid FROM Cache WHERE bundle=?");
    s.BindInt(0, bundle);
    while (s.Step())
    {
      pimpl_->storage_.Remove(s.ColumnString(0), Orthanc::FileContentType_Unknown);
    }  

    Orthanc::SQLite::Statement t(pimpl_->db_, SQLITE_FROM_HERE, "DELETE FROM Cache WHERE bundle=?");
    t.BindInt(0, bundle);
    t.Run();

    ReadBundleStatistics();
    SanityCheck();
  }


  void CacheManager::SetProperty(CacheProperty property,
                                 const std::string& value)
  {
    Orthanc::SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE,
                                 "INSERT OR REPLACE INTO CacheProperties VALUES(?, ?)");
    s.BindInt(0, property);
    s.BindString(1, value);
    s.Run();
  }


  bool CacheManager::LookupProperty(std::string& target,
                                    CacheProperty property)
  {
    Orthanc::SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, 
                                 "SELECT value FROM CacheProperties WHERE property=?");
    s.BindInt(0, property);

    if (!s.Step())
    {
      return false;
    }
    else
    {
      target = s.ColumnString(0);
      return true;
    }
  }
}