/
PublishedSnapshotService.cs
1817 lines (1512 loc) · 80.8 KB
/
PublishedSnapshotService.cs
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
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using CSharpTest.Net.Collections;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Dtos;
using Umbraco.Core.Persistence.Repositories;
using Umbraco.Core.Persistence.Repositories.Implement;
using Umbraco.Core.Scoping;
using Umbraco.Core.Services;
using Umbraco.Core.Services.Changes;
using Umbraco.Core.Services.Implement;
using Umbraco.Core.Strings;
using Umbraco.Core.Sync;
using Umbraco.Web.Cache;
using Umbraco.Web.Install;
using Umbraco.Web.PublishedCache.NuCache.DataSource;
using Umbraco.Web.Routing;
using File = System.IO.File;
namespace Umbraco.Web.PublishedCache.NuCache
{
internal class PublishedSnapshotService : PublishedSnapshotServiceBase
{
private readonly PublishedSnapshotServiceOptions _options;
private readonly IMainDom _mainDom;
private readonly ServiceContext _serviceContext;
private readonly IPublishedContentTypeFactory _publishedContentTypeFactory;
private readonly IScopeProvider _scopeProvider;
private readonly IDataSource _dataSource;
private readonly IProfilingLogger _logger;
private readonly IDocumentRepository _documentRepository;
private readonly IMediaRepository _mediaRepository;
private readonly IMemberRepository _memberRepository;
private readonly IGlobalSettings _globalSettings;
private readonly IEntityXmlSerializer _entitySerializer;
private readonly IPublishedModelFactory _publishedModelFactory;
private readonly IDefaultCultureAccessor _defaultCultureAccessor;
private readonly UrlSegmentProviderCollection _urlSegmentProviders;
private readonly IContentCacheDataSerializerFactory _contentCacheDataSerializerFactory;
private readonly ContentDataSerializer _contentDataSerializer;
private bool _isReady;
private bool _isReadSet;
private object _isReadyLock;
private ContentStore _contentStore;
private ContentStore _mediaStore;
private SnapDictionary<int, Domain> _domainStore;
private readonly object _storesLock = new object();
private readonly object _elementsLock = new object();
private BPlusTree<int, ContentNodeKit> _localContentDb;
private BPlusTree<int, ContentNodeKit> _localMediaDb;
private bool _localContentDbExists;
private bool _localMediaDbExists;
private readonly ISyncBootStateAccessor _syncBootStateAccessor;
// define constant - determines whether to use cache when previewing
// to store eg routes, property converted values, anything - caching
// means faster execution, but uses memory - not sure if we want it
// so making it configurable.
public static readonly bool FullCacheWhenPreviewing = true;
#region Constructors
//private static int _singletonCheck;
public PublishedSnapshotService(PublishedSnapshotServiceOptions options, IMainDom mainDom, IRuntimeState runtime,
ServiceContext serviceContext, IPublishedContentTypeFactory publishedContentTypeFactory, IdkMap idkMap,
IPublishedSnapshotAccessor publishedSnapshotAccessor, IVariationContextAccessor variationContextAccessor, IProfilingLogger logger, IScopeProvider scopeProvider,
IDocumentRepository documentRepository, IMediaRepository mediaRepository, IMemberRepository memberRepository,
IDefaultCultureAccessor defaultCultureAccessor,
IDataSource dataSource, IGlobalSettings globalSettings,
IEntityXmlSerializer entitySerializer,
IPublishedModelFactory publishedModelFactory,
UrlSegmentProviderCollection urlSegmentProviders,
ISyncBootStateAccessor syncBootStateAccessor,
IContentCacheDataSerializerFactory contentCacheDataSerializerFactory,
ContentDataSerializer contentDataSerializer = null)
: base(publishedSnapshotAccessor, variationContextAccessor)
{
//if (Interlocked.Increment(ref _singletonCheck) > 1)
// throw new Exception("Singleton must be instantiated only once!");
_options = options;
_mainDom = mainDom;
_serviceContext = serviceContext;
_publishedContentTypeFactory = publishedContentTypeFactory;
_dataSource = dataSource;
_logger = logger;
_scopeProvider = scopeProvider;
_documentRepository = documentRepository;
_mediaRepository = mediaRepository;
_memberRepository = memberRepository;
_defaultCultureAccessor = defaultCultureAccessor;
_globalSettings = globalSettings;
_urlSegmentProviders = urlSegmentProviders;
_contentCacheDataSerializerFactory = contentCacheDataSerializerFactory;
_contentDataSerializer = contentDataSerializer;
_syncBootStateAccessor = syncBootStateAccessor;
_syncBootStateAccessor = syncBootStateAccessor;
// we need an Xml serializer here so that the member cache can support XPath,
// for members this is done by navigating the serialized-to-xml member
_entitySerializer = entitySerializer;
_publishedModelFactory = publishedModelFactory;
// we always want to handle repository events, configured or not
// assuming no repository event will trigger before the whole db is ready
// (ideally we'd have Upgrading.App vs Upgrading.Data application states...)
InitializeRepositoryEvents();
// however, the cache is NOT available until we are configured, because loading
// content (and content types) from database cannot be consistent (see notes in "Handle
// Notifications" region), so
// - notifications will be ignored
// - trying to obtain a published snapshot from the service will throw
if (runtime.Level != RuntimeLevel.Run)
return;
if (idkMap != null)
{
idkMap.SetMapper(UmbracoObjectTypes.Document, id => GetUid(_contentStore, id), uid => GetId(_contentStore, uid));
idkMap.SetMapper(UmbracoObjectTypes.Media, id => GetUid(_mediaStore, id), uid => GetId(_mediaStore, uid));
}
}
private int GetId(ContentStore store, Guid uid)
{
EnsureCaches();
return store.LiveSnapshot.Get(uid)?.Id ?? default;
}
private Guid GetUid(ContentStore store, int id)
{
EnsureCaches();
return store.LiveSnapshot.Get(id)?.Uid ?? default;
}
/// <summary>
/// Install phase of <see cref="IMainDom"/>
/// </summary>
/// <remarks>
/// This is inside of a lock in MainDom so this is guaranteed to run if MainDom was acquired and guaranteed
/// to not run if MainDom wasn't acquired.
/// If MainDom was not acquired, then _localContentDb and _localMediaDb will remain null which means this appdomain
/// will load in published content via the DB and in that case this appdomain will probably not exist long enough to
/// serve more than a page of content.
/// </remarks>
private void MainDomRegister()
{
var path = GetLocalFilesPath();
var localContentDbPath = Path.Combine(path, "NuCache.Content.db");
var localMediaDbPath = Path.Combine(path, "NuCache.Media.db");
_localContentDbExists = File.Exists(localContentDbPath);
_localMediaDbExists = File.Exists(localMediaDbPath);
// if both local databases exist then GetTree will open them, else new databases will be created
_localContentDb = BTree.GetTree(localContentDbPath, _localContentDbExists, _contentDataSerializer);
_localMediaDb = BTree.GetTree(localMediaDbPath, _localMediaDbExists, _contentDataSerializer);
_logger.Info<PublishedSnapshotService, bool, bool>("Registered with MainDom, localContentDbExists? {LocalContentDbExists}, localMediaDbExists? {LocalMediaDbExists}", _localContentDbExists, _localMediaDbExists);
}
/// <summary>
/// Release phase of MainDom
/// </summary>
/// <remarks>
/// This will execute on a threadpool thread
/// </remarks>
private void MainDomRelease()
{
_logger.Debug<PublishedSnapshotService>("Releasing from MainDom...");
lock (_storesLock)
{
_logger.Debug<PublishedSnapshotService>("Releasing content store...");
_contentStore?.ReleaseLocalDb(); //null check because we could shut down before being assigned
_localContentDb = null;
_logger.Debug<PublishedSnapshotService>("Releasing media store...");
_mediaStore?.ReleaseLocalDb(); //null check because we could shut down before being assigned
_localMediaDb = null;
_logger.Info<PublishedSnapshotService>("Released from MainDom");
}
}
/// <summary>
/// Lazily populates the stores only when they are first requested
/// </summary>
internal void EnsureCaches() => LazyInitializer.EnsureInitialized(
ref _isReady,
ref _isReadSet,
ref _isReadyLock,
() =>
{
// lock this entire call, we only want a single thread to be accessing the stores at once and within
// the call below to mainDom.Register, a callback may occur on a threadpool thread to MainDomRelease
// at the same time as we are trying to write to the stores. MainDomRelease also locks on _storesLock so
// it will not be able to close the stores until we are done populating (if the store is empty)
lock (_storesLock)
{
if (!_options.IgnoreLocalDb)
{
var registered = _mainDom.Register(MainDomRegister, MainDomRelease);
// stores are created with a db so they can write to it, but they do not read from it,
// stores need to be populated, happens in OnResolutionFrozen which uses _localDbExists to
// figure out whether it can read the databases or it should populate them from sql
_logger.Info<PublishedSnapshotService, bool>("Creating the content store, localContentDbExists? {LocalContentDbExists}", _localContentDbExists);
_contentStore = new ContentStore(PublishedSnapshotAccessor, VariationContextAccessor, _logger, _localContentDb);
_logger.Info<PublishedSnapshotService, bool>("Creating the media store, localMediaDbExists? {LocalMediaDbExists}", _localMediaDbExists);
_mediaStore = new ContentStore(PublishedSnapshotAccessor, VariationContextAccessor, _logger, _localMediaDb);
}
else
{
_logger.Info<PublishedSnapshotService>("Creating the content store (local db ignored)");
_contentStore = new ContentStore(PublishedSnapshotAccessor, VariationContextAccessor, _logger);
_logger.Info<PublishedSnapshotService>("Creating the media store (local db ignored)");
_mediaStore = new ContentStore(PublishedSnapshotAccessor, VariationContextAccessor, _logger);
}
_domainStore = new SnapDictionary<int, Domain>();
SyncBootState bootState = _syncBootStateAccessor.GetSyncBootState();
var okContent = false;
var okMedia = false;
try
{
if (bootState != SyncBootState.ColdBoot && _localContentDbExists)
{
okContent = LockAndLoadContent(scope => LoadContentFromLocalDbLocked(true));
if (!okContent)
_logger.Warn<PublishedSnapshotService>("Loading content from local db raised warnings, will reload from database.");
}
if (bootState != SyncBootState.ColdBoot && _localMediaDbExists)
{
okMedia = LockAndLoadMedia(scope => LoadMediaFromLocalDbLocked(true));
if (!okMedia)
_logger.Warn<PublishedSnapshotService>("Loading media from local db raised warnings, will reload from database.");
}
if (!okContent)
LockAndLoadContent(scope => LoadContentFromDatabaseLocked(scope, true));
if (!okMedia)
LockAndLoadMedia(scope => LoadMediaFromDatabaseLocked(scope, true));
LockAndLoadDomains();
}
catch (Exception ex)
{
_logger.Fatal<PublishedSnapshotService>(ex, "Panic, exception while loading cache data.");
throw;
}
// finally, cache is ready!
return true;
}
});
private void InitializeRepositoryEvents()
{
// TODO: The reason these events are in the repository is for legacy, the events should exist at the service
// level now since we can fire these events within the transaction... so move the events to service level
// plug repository event handlers
// these trigger within the transaction to ensure consistency
// and are used to maintain the central, database-level XML cache
DocumentRepository.ScopeEntityRemove += OnContentRemovingEntity;
//ContentRepository.RemovedVersion += OnContentRemovedVersion;
DocumentRepository.ScopedEntityRefresh += OnContentRefreshedEntity;
MediaRepository.ScopeEntityRemove += OnMediaRemovingEntity;
//MediaRepository.RemovedVersion += OnMediaRemovedVersion;
MediaRepository.ScopedEntityRefresh += OnMediaRefreshedEntity;
MemberRepository.ScopeEntityRemove += OnMemberRemovingEntity;
//MemberRepository.RemovedVersion += OnMemberRemovedVersion;
MemberRepository.ScopedEntityRefresh += OnMemberRefreshedEntity;
// plug
ContentTypeService.ScopedRefreshedEntity += OnContentTypeRefreshedEntity;
MediaTypeService.ScopedRefreshedEntity += OnMediaTypeRefreshedEntity;
MemberTypeService.ScopedRefreshedEntity += OnMemberTypeRefreshedEntity;
LocalizationService.SavedLanguage += OnLanguageSaved;
}
private void TearDownRepositoryEvents()
{
DocumentRepository.ScopeEntityRemove -= OnContentRemovingEntity;
//ContentRepository.RemovedVersion -= OnContentRemovedVersion;
DocumentRepository.ScopedEntityRefresh -= OnContentRefreshedEntity;
MediaRepository.ScopeEntityRemove -= OnMediaRemovingEntity;
//MediaRepository.RemovedVersion -= OnMediaRemovedVersion;
MediaRepository.ScopedEntityRefresh -= OnMediaRefreshedEntity;
MemberRepository.ScopeEntityRemove -= OnMemberRemovingEntity;
//MemberRepository.RemovedVersion -= OnMemberRemovedVersion;
MemberRepository.ScopedEntityRefresh -= OnMemberRefreshedEntity;
ContentTypeService.ScopedRefreshedEntity -= OnContentTypeRefreshedEntity;
MediaTypeService.ScopedRefreshedEntity -= OnMediaTypeRefreshedEntity;
MemberTypeService.ScopedRefreshedEntity -= OnMemberTypeRefreshedEntity;
LocalizationService.SavedLanguage -= OnLanguageSaved;
}
public override void Dispose()
{
TearDownRepositoryEvents();
base.Dispose();
}
#endregion
#region Local files
private string GetLocalFilesPath()
{
var path = Path.Combine(_globalSettings.LocalTempPath, "NuCache");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
return path;
}
#endregion
#region Environment
public override bool EnsureEnvironment(out IEnumerable<string> errors)
{
// must have app_data and be able to write files into it
var ok = FilePermissionHelper.TryCreateDirectory(GetLocalFilesPath());
errors = ok ? Enumerable.Empty<string>() : new[] { "NuCache local files." };
return ok;
}
#endregion
#region Populate Stores
// sudden panic... but in RepeatableRead can a content that I haven't already read, be removed
// before I read it? NO! because the WHOLE content tree is read-locked using WithReadLocked.
// don't panic.
private bool LockAndLoadContent(Func<IScope, bool> action)
{
// first get a writer, then a scope
// if there already is a scope, the writer will attach to it
// otherwise, it will only exist here - cheap
using (_contentStore.GetScopedWriteLock(_scopeProvider))
using (var scope = _scopeProvider.CreateScope())
{
scope.ReadLock(Constants.Locks.ContentTree);
var ok = action(scope);
scope.Complete();
return ok;
}
}
private bool LoadContentFromDatabaseLocked(IScope scope, bool onStartup)
{
// locks:
// contentStore is wlocked (1 thread)
// content (and types) are read-locked
var contentTypes = _serviceContext.ContentTypeService.GetAll().ToList();
_contentStore.SetAllContentTypesLocked(contentTypes.Select(x => _publishedContentTypeFactory.CreateContentType(x)));
using (_logger.TraceDuration<PublishedSnapshotService>("Loading content from database"))
{
// beware! at that point the cache is inconsistent,
// assuming we are going to SetAll content items!
_localContentDb?.Clear();
// IMPORTANT GetAllContentSources sorts kits by level + parentId + sortOrder
var kits = _dataSource.GetAllContentSources(scope);
return onStartup ? _contentStore.SetAllFastSortedLocked(kits, true) : _contentStore.SetAllLocked(kits);
}
}
private bool LoadContentFromLocalDbLocked(bool onStartup)
{
var contentTypes = _serviceContext.ContentTypeService.GetAll()
.Select(x => _publishedContentTypeFactory.CreateContentType(x));
_contentStore.SetAllContentTypesLocked(contentTypes);
using (_logger.TraceDuration<PublishedSnapshotService>("Loading content from local cache file"))
{
// beware! at that point the cache is inconsistent,
// assuming we are going to SetAll content items!
return LoadEntitiesFromLocalDbLocked(onStartup, _localContentDb, _contentStore, "content");
}
}
// keep these around - might be useful
//private void LoadContentBranch(IContent content)
//{
// LoadContent(content);
// foreach (var child in content.Children())
// LoadContentBranch(child);
//}
//private void LoadContent(IContent content)
//{
// var contentService = _serviceContext.ContentService as ContentService;
// var newest = content;
// var published = newest.Published
// ? newest
// : (newest.HasPublishedVersion ? contentService.GetByVersion(newest.PublishedVersionGuid) : null);
// var contentNode = CreateContentNode(newest, published);
// _contentStore.Set(contentNode);
//}
private bool LockAndLoadMedia(Func<IScope, bool> action)
{
// see note in LockAndLoadContent
using (_mediaStore.GetScopedWriteLock(_scopeProvider))
using (var scope = _scopeProvider.CreateScope())
{
scope.ReadLock(Constants.Locks.MediaTree);
var ok = action(scope);
scope.Complete();
return ok;
}
}
private bool LoadMediaFromDatabaseLocked(IScope scope, bool onStartup)
{
// locks & notes: see content
var mediaTypes = _serviceContext.MediaTypeService.GetAll()
.Select(x => _publishedContentTypeFactory.CreateContentType(x));
_mediaStore.SetAllContentTypesLocked(mediaTypes);
using (_logger.TraceDuration<PublishedSnapshotService>("Loading media from database"))
{
// beware! at that point the cache is inconsistent,
// assuming we are going to SetAll content items!
_localMediaDb?.Clear();
_logger.Debug<PublishedSnapshotService>("Loading media from database...");
// IMPORTANT GetAllMediaSources sorts kits by level + parentId + sortOrder
var kits = _dataSource.GetAllMediaSources(scope);
return onStartup ? _mediaStore.SetAllFastSortedLocked(kits, true) : _mediaStore.SetAllLocked(kits);
}
}
private bool LoadMediaFromLocalDbLocked(bool onStartup)
{
var mediaTypes = _serviceContext.MediaTypeService.GetAll()
.Select(x => _publishedContentTypeFactory.CreateContentType(x));
_mediaStore.SetAllContentTypesLocked(mediaTypes);
using (_logger.TraceDuration<PublishedSnapshotService>("Loading media from local cache file"))
{
// beware! at that point the cache is inconsistent,
// assuming we are going to SetAll content items!
return LoadEntitiesFromLocalDbLocked(onStartup, _localMediaDb, _mediaStore, "media");
}
}
private bool LoadEntitiesFromLocalDbLocked(bool onStartup, BPlusTree<int, ContentNodeKit> localDb, ContentStore store, string entityType)
{
var kits = localDb.Select(x => x.Value)
.OrderBy(x => x.Node.Level)
.ThenBy(x => x.Node.ParentContentId)
.ThenBy(x => x.Node.SortOrder) // IMPORTANT sort by level + parentId + sortOrder
.ToList();
if (kits.Count == 0)
{
// If there's nothing in the local cache file, we should return false? YES even though the site legitately might be empty.
// Is it possible that the cache file is empty but the database is not? YES... (well, it used to be possible)
// * A new file is created when one doesn't exist, this will only be done when MainDom is acquired
// * The new file will be populated as soon as LoadCachesOnStartup is called
// * If the appdomain is going down the moment after MainDom was acquired and we've created an empty cache file,
// then the MainDom release callback is triggered from on a different thread, which will close the file and
// set the cache file reference to null. At this moment, it is possible that the file is closed and the
// reference is set to null BEFORE LoadCachesOnStartup which would mean that the current appdomain would load
// in the in-mem cache via DB calls, BUT this now means that there is an empty cache file which will be
// loaded by the next appdomain and it won't check if it's empty, it just assumes that since the cache
// file is there, that is correct.
// Update: We will still return false here even though the above mentioned race condition has been fixed since we now
// lock the entire operation of creating/populating the cache file with the same lock as releasing/closing the cache file
_logger.Info<PublishedSnapshotService>($"Tried to load {entityType} from the local cache file but it was empty.");
return false;
}
return onStartup ? store.SetAllFastSortedLocked(kits, false) : store.SetAllLocked(kits);
}
// keep these around - might be useful
//private void LoadMediaBranch(IMedia media)
//{
// LoadMedia(media);
// foreach (var child in media.Children())
// LoadMediaBranch(child);
//}
//private void LoadMedia(IMedia media)
//{
// var mediaType = _contentTypeCache.Get(PublishedItemType.Media, media.ContentTypeId);
// var mediaData = new ContentData
// {
// Name = media.Name,
// Published = true,
// Version = media.Version,
// VersionDate = media.UpdateDate,
// WriterId = media.CreatorId, // what else?
// TemplateId = -1, // have none
// Properties = GetPropertyValues(media)
// };
// var mediaNode = new ContentNode(media.Id, mediaType,
// media.Level, media.Path, media.SortOrder,
// media.ParentId, media.CreateDate, media.CreatorId,
// null, mediaData);
// _mediaStore.Set(mediaNode);
//}
//private Dictionary<string, object> GetPropertyValues(IContentBase content)
//{
// var propertyEditorResolver = PropertyEditorResolver.Current; // should inject
// return content
// .Properties
// .Select(property =>
// {
// var e = propertyEditorResolver.GetByAlias(property.PropertyType.PropertyEditorAlias);
// var v = e == null
// ? property.Value
// : e.ValueEditor.ConvertDbToString(property, property.PropertyType, _serviceContext.DataTypeService);
// return new KeyValuePair<string, object>(property.Alias, v);
// })
// .ToDictionary(x => x.Key, x => x.Value);
//}
//private ContentData CreateContentData(IContent content)
//{
// return new ContentData
// {
// Name = content.Name,
// Published = content.Published,
// Version = content.Version,
// VersionDate = content.UpdateDate,
// WriterId = content.WriterId,
// TemplateId = content.Template == null ? -1 : content.Template.Id,
// Properties = GetPropertyValues(content)
// };
//}
//private ContentNode CreateContentNode(IContent newest, IContent published)
//{
// var contentType = _contentTypeCache.Get(PublishedItemType.Content, newest.ContentTypeId);
// var draftData = newest.Published
// ? null
// : CreateContentData(newest);
// var publishedData = newest.Published
// ? CreateContentData(newest)
// : (published == null ? null : CreateContentData(published));
// var contentNode = new ContentNode(newest.Id, contentType,
// newest.Level, newest.Path, newest.SortOrder,
// newest.ParentId, newest.CreateDate, newest.CreatorId,
// draftData, publishedData);
// return contentNode;
//}
private void LockAndLoadDomains()
{
// see note in LockAndLoadContent
using (_domainStore.GetScopedWriteLock(_scopeProvider))
using (var scope = _scopeProvider.CreateScope())
{
scope.ReadLock(Constants.Locks.Domains);
LoadDomainsLocked();
scope.Complete();
}
}
private void LoadDomainsLocked()
{
var domains = _serviceContext.DomainService.GetAll(true);
foreach (var domain in domains
.Where(x => x.RootContentId.HasValue && x.LanguageIsoCode.IsNullOrWhiteSpace() == false)
.Select(x => new Domain(x.Id, x.DomainName, x.RootContentId.Value, CultureInfo.GetCultureInfo(x.LanguageIsoCode), x.IsWildcard)))
{
_domainStore.SetLocked(domain.Id, domain);
}
}
#endregion
#region Handle Notifications
// note: notifications for content type and data type changes should be invoked with the
// pure live model factory, if any, locked and refreshed - see ContentTypeCacheRefresher and
// DataTypeCacheRefresher
public override void Notify(ContentCacheRefresher.JsonPayload[] payloads, out bool draftChanged, out bool publishedChanged)
{
EnsureCaches();
using (_contentStore.GetScopedWriteLock(_scopeProvider))
{
NotifyLocked(payloads, out bool draftChanged2, out bool publishedChanged2);
draftChanged = draftChanged2;
publishedChanged = publishedChanged2;
}
if (draftChanged || publishedChanged)
((PublishedSnapshot)CurrentPublishedSnapshot)?.Resync();
}
// Calling this method means we have a lock on the contentStore (i.e. GetScopedWriteLock)
private void NotifyLocked(IEnumerable<ContentCacheRefresher.JsonPayload> payloads, out bool draftChanged, out bool publishedChanged)
{
publishedChanged = false;
draftChanged = false;
// locks:
// content (and content types) are read-locked while reading content
// contentStore is wlocked (so readable, only no new views)
// and it can be wlocked by 1 thread only at a time
// contentStore is write-locked during changes - see note above, calls to this method are wrapped in contentStore.GetScopedWriteLock
foreach (var payload in payloads)
{
_logger.Debug<PublishedSnapshotService,TreeChangeTypes,int>("Notified {ChangeTypes} for content {ContentId}", payload.ChangeTypes, payload.Id);
if (payload.ChangeTypes.HasType(TreeChangeTypes.RefreshAll))
{
using (var scope = _scopeProvider.CreateScope())
{
scope.ReadLock(Constants.Locks.ContentTree);
LoadContentFromDatabaseLocked(scope, false);
scope.Complete();
}
draftChanged = publishedChanged = true;
continue;
}
if (payload.ChangeTypes.HasType(TreeChangeTypes.Remove))
{
if (_contentStore.ClearLocked(payload.Id))
draftChanged = publishedChanged = true;
continue;
}
if (payload.ChangeTypes.HasTypesNone(TreeChangeTypes.RefreshNode | TreeChangeTypes.RefreshBranch))
{
// ?!
continue;
}
// TODO: should we do some RV check here? (later)
var capture = payload;
using (var scope = _scopeProvider.CreateScope())
{
scope.ReadLock(Constants.Locks.ContentTree);
if (capture.ChangeTypes.HasType(TreeChangeTypes.RefreshBranch))
{
// ?? should we do some RV check here?
// IMPORTANT GetbranchContentSources sorts kits by level and by sort order
var kits = _dataSource.GetBranchContentSources(scope, capture.Id);
_contentStore.SetBranchLocked(capture.Id, kits);
}
else
{
// ?? should we do some RV check here?
var kit = _dataSource.GetContentSource(scope, capture.Id);
if (kit.IsEmpty)
{
_contentStore.ClearLocked(capture.Id);
}
else
{
_contentStore.SetLocked(kit);
}
}
scope.Complete();
}
// ?? cannot tell really because we're not doing RV checks
draftChanged = publishedChanged = true;
}
}
/// <inheritdoc />
public override void Notify(MediaCacheRefresher.JsonPayload[] payloads, out bool anythingChanged)
{
EnsureCaches();
using (_mediaStore.GetScopedWriteLock(_scopeProvider))
{
NotifyLocked(payloads, out bool anythingChanged2);
anythingChanged = anythingChanged2;
}
if (anythingChanged)
((PublishedSnapshot)CurrentPublishedSnapshot)?.Resync();
}
private void NotifyLocked(IEnumerable<MediaCacheRefresher.JsonPayload> payloads, out bool anythingChanged)
{
anythingChanged = false;
// locks:
// see notes for content cache refresher
foreach (var payload in payloads)
{
_logger.Debug<PublishedSnapshotService,TreeChangeTypes,int>("Notified {ChangeTypes} for media {MediaId}", payload.ChangeTypes, payload.Id);
if (payload.ChangeTypes.HasType(TreeChangeTypes.RefreshAll))
{
using (var scope = _scopeProvider.CreateScope())
{
scope.ReadLock(Constants.Locks.MediaTree);
LoadMediaFromDatabaseLocked(scope, false);
scope.Complete();
}
anythingChanged = true;
continue;
}
if (payload.ChangeTypes.HasType(TreeChangeTypes.Remove))
{
if (_mediaStore.ClearLocked(payload.Id))
anythingChanged = true;
continue;
}
if (payload.ChangeTypes.HasTypesNone(TreeChangeTypes.RefreshNode | TreeChangeTypes.RefreshBranch))
{
// ?!
continue;
}
// TODO: should we do some RV checks here? (later)
var capture = payload;
using (var scope = _scopeProvider.CreateScope())
{
scope.ReadLock(Constants.Locks.MediaTree);
if (capture.ChangeTypes.HasType(TreeChangeTypes.RefreshBranch))
{
// ?? should we do some RV check here?
// IMPORTANT GetbranchContentSources sorts kits by level and by sort order
var kits = _dataSource.GetBranchMediaSources(scope, capture.Id);
_mediaStore.SetBranchLocked(capture.Id, kits);
}
else
{
// ?? should we do some RV check here?
var kit = _dataSource.GetMediaSource(scope, capture.Id);
if (kit.IsEmpty)
{
_mediaStore.ClearLocked(capture.Id);
}
else
{
_mediaStore.SetLocked(kit);
}
}
scope.Complete();
}
// ?? cannot tell really because we're not doing RV checks
anythingChanged = true;
}
}
/// <inheritdoc />
public override void Notify(ContentTypeCacheRefresher.JsonPayload[] payloads)
{
EnsureCaches();
foreach (var payload in payloads)
_logger.Debug<PublishedSnapshotService, ContentTypeChangeTypes, string,int>("Notified {ChangeTypes} for {ItemType} {ItemId}", payload.ChangeTypes, payload.ItemType, payload.Id);
Notify<IContentType>(_contentStore, payloads, RefreshContentTypesLocked);
Notify<IMediaType>(_mediaStore, payloads, RefreshMediaTypesLocked);
if (_publishedModelFactory.IsLiveFactoryEnabled())
{
//In the case of Pure Live - we actually need to refresh all of the content and the media
//see https://github.com/umbraco/Umbraco-CMS/issues/5671
//The underlying issue is that in Pure Live the ILivePublishedModelFactory will re-compile all of the classes/models
//into a new DLL for the application which includes both content types and media types.
//Since the models in the cache are based on these actual classes, all of the objects in the cache need to be updated
//to use the newest version of the class.
// NOTE: Ideally this can be run on background threads here which would prevent blocking the UI
// as is the case when saving a content type. Intially one would think that it won't be any different
// between running this here or in another background thread immediately after with regards to how the
// UI will respond because we already know between calling `WithSafeLiveFactoryReset` to reset the PureLive models
// and this code here, that many front-end requests could be attempted to be processed. If that is the case, those pages are going to get a
// model binding error and our ModelBindingExceptionFilter is going to to its magic to reload those pages so the end user is none the wiser.
// So whether or not this executes 'here' or on a background thread immediately wouldn't seem to make any difference except that we can return
// execution to the UI sooner.
// BUT!... there is a difference IIRC. There is still execution logic that continues after this call on this thread with the cache refreshers
// and those cache refreshers need to have the up-to-date data since other user cache refreshers will be expecting the data to be 'live'. If
// we ran this on a background thread then those cache refreshers are going to not get 'live' data when they query the content cache which
// they require.
// These can be run side by side in parallel.
using (_contentStore.GetScopedWriteLock(_scopeProvider))
{
NotifyLocked(new[] { new ContentCacheRefresher.JsonPayload(0, null, TreeChangeTypes.RefreshAll) }, out _, out _);
}
using (_mediaStore.GetScopedWriteLock(_scopeProvider))
{
NotifyLocked(new[] { new MediaCacheRefresher.JsonPayload(0, null, TreeChangeTypes.RefreshAll) }, out _);
}
}
((PublishedSnapshot)CurrentPublishedSnapshot)?.Resync();
}
private void Notify<T>(ContentStore store, ContentTypeCacheRefresher.JsonPayload[] payloads, Action<List<int>, List<int>, List<int>, List<int>> action)
where T : IContentTypeComposition
{
if (payloads.Length == 0) return; //nothing to do
var nameOfT = typeof(T).Name;
List<int> removedIds = null, refreshedIds = null, otherIds = null, newIds = null;
foreach (var payload in payloads)
{
if (payload.ItemType != nameOfT) continue;
if (payload.ChangeTypes.HasType(ContentTypeChangeTypes.Remove))
AddToList(ref removedIds, payload.Id);
else if (payload.ChangeTypes.HasType(ContentTypeChangeTypes.RefreshMain))
AddToList(ref refreshedIds, payload.Id);
else if (payload.ChangeTypes.HasType(ContentTypeChangeTypes.RefreshOther))
AddToList(ref otherIds, payload.Id);
else if (payload.ChangeTypes.HasType(ContentTypeChangeTypes.Create))
AddToList(ref newIds, payload.Id);
}
if (removedIds.IsCollectionEmpty() && refreshedIds.IsCollectionEmpty() && otherIds.IsCollectionEmpty() && newIds.IsCollectionEmpty()) return;
using (store.GetScopedWriteLock(_scopeProvider))
{
// ReSharper disable AccessToModifiedClosure
action(removedIds, refreshedIds, otherIds, newIds);
// ReSharper restore AccessToModifiedClosure
}
}
public override void Notify(DataTypeCacheRefresher.JsonPayload[] payloads)
{
EnsureCaches();
var idsA = payloads.Select(x => x.Id).ToArray();
foreach (var payload in payloads)
_logger.Debug<PublishedSnapshotService, string,int>("Notified {RemovedStatus} for data type {DataTypeId}",
payload.Removed ? "Removed" : "Refreshed",
payload.Id);
using (_contentStore.GetScopedWriteLock(_scopeProvider))
using (_mediaStore.GetScopedWriteLock(_scopeProvider))
{
// TODO: need to add a datatype lock
// this is triggering datatypes reload in the factory, and right after we create some
// content types by loading them ... there's a race condition here, which would require
// some locking on datatypes
_publishedContentTypeFactory.NotifyDataTypeChanges(idsA);
using (var scope = _scopeProvider.CreateScope())
{
scope.ReadLock(Constants.Locks.ContentTree);
_contentStore.UpdateDataTypesLocked(idsA, id => CreateContentType(PublishedItemType.Content, id));
scope.Complete();
}
using (var scope = _scopeProvider.CreateScope())
{
scope.ReadLock(Constants.Locks.MediaTree);
_mediaStore.UpdateDataTypesLocked(idsA, id => CreateContentType(PublishedItemType.Media, id));
scope.Complete();
}
}
((PublishedSnapshot)CurrentPublishedSnapshot)?.Resync();
}
public override void Notify(DomainCacheRefresher.JsonPayload[] payloads)
{
EnsureCaches();
// see note in LockAndLoadContent
using (_domainStore.GetScopedWriteLock(_scopeProvider))
{
foreach (var payload in payloads)
{
switch (payload.ChangeType)
{
case DomainChangeTypes.RefreshAll:
using (var scope = _scopeProvider.CreateScope())
{
scope.ReadLock(Constants.Locks.Domains);
LoadDomainsLocked();
scope.Complete();
}
break;
case DomainChangeTypes.Remove:
_domainStore.ClearLocked(payload.Id);
break;
case DomainChangeTypes.Refresh:
var domain = _serviceContext.DomainService.GetById(payload.Id);
if (domain == null) continue;
if (domain.RootContentId.HasValue == false) continue; // anomaly
if (domain.LanguageIsoCode.IsNullOrWhiteSpace()) continue; // anomaly
var culture = CultureInfo.GetCultureInfo(domain.LanguageIsoCode);
_domainStore.SetLocked(domain.Id, new Domain(domain.Id, domain.DomainName, domain.RootContentId.Value, culture, domain.IsWildcard));
break;
}
}
}
}
//Methods used to prevent allocations of lists
private void AddToList(ref List<int> list, int val) => GetOrCreateList(ref list).Add(val);
private List<int> GetOrCreateList(ref List<int> list) => list ?? (list = new List<int>());
#endregion
#region Content Types
private IReadOnlyCollection<IPublishedContentType> CreateContentTypes(PublishedItemType itemType, int[] ids)
{
// XxxTypeService.GetAll(empty) returns everything!
if (ids.Length == 0)
return Array.Empty<IPublishedContentType>();
IEnumerable<IContentTypeComposition> contentTypes;
switch (itemType)
{
case PublishedItemType.Content:
contentTypes = _serviceContext.ContentTypeService.GetAll(ids);
break;
case PublishedItemType.Media:
contentTypes = _serviceContext.MediaTypeService.GetAll(ids);