Пример #1
0
        public void TestTakeItemTimeout()
        {
            using (var cache = new DisposableCache <IDisposable>(1))
            {
                var item = new Mock <IDisposable>().Object;
                cache.CacheItem(item);

                using (var handle1 = cache.TakeItem())
                {
                    var timeout = TimeSpan.FromMilliseconds(250);

                    var stopwatch = Stopwatch.StartNew();
                    try
                    {
                        using (var handle2 = cache.TakeItem(timeout))
                        { }
                        Assert.Fail();
                    }
                    catch (TimeoutException) { /*expected*/ }
                    stopwatch.Stop();

                    // verify the timout period was respected before the exception was thrown
                    Assert.IsTrue(stopwatch.Elapsed >= timeout);
                }
            }
        }
Пример #2
0
        public EsentBlockStorage(string baseDirectory)
        {
            this.jetDirectory = Path.Combine(baseDirectory, "Blocks");
            this.jetDatabase  = Path.Combine(this.jetDirectory, "Blocks.edb");

            this.cursorCache = new DisposableCache <EsentBlockCursor>(1024,
                                                                      createFunc: () => new EsentBlockCursor(this.jetDatabase, this.jetInstance));

            this.jetInstance = new Instance(Guid.NewGuid().ToString());
            var success = false;

            try
            {
                EsentStorageManager.InitInstanceParameters(jetInstance, jetDirectory);
                this.jetInstance.Init();
                this.CreateOrOpenDatabase();
                success = true;
            }
            finally
            {
                if (!success)
                {
                    this.jetInstance.Dispose();
                }
            }
        }
Пример #3
0
        internal MemoryStorageManager(ChainedHeader chainTip = null, int?unspentTxCount = null, int?unspentOutputCount = null, int?totalTxCount = null, int?totalInputCount = null, int?totalOutputCount = null, ImmutableSortedDictionary <UInt256, ChainedHeader> headers = null, ImmutableSortedDictionary <UInt256, UnspentTx> unspentTransactions = null, ImmutableDictionary <int, BlockSpentTxes> spentTransactions = null)
        {
            blockStorage           = new MemoryBlockStorage();
            blockTxesStorage       = new MemoryBlockTxesStorage();
            chainStateStorage      = new MemoryChainStateStorage(chainTip, unspentTxCount, unspentOutputCount, totalTxCount, totalInputCount, totalOutputCount, headers, unspentTransactions, spentTransactions);
            unconfirmedTxesStorage = new MemoryUnconfirmedTxesStorage();

            chainStateCursorCache = new DisposableCache <IChainStateCursor>(1024,
                                                                            createFunc: () => new MemoryChainStateCursor(chainStateStorage),
                                                                            prepareAction: cursor =>
            {
                // rollback any open transaction before returning the cursor to the cache
                if (cursor.InTransaction)
                {
                    cursor.RollbackTransaction();
                }
            });

            unconfirmedTxesCursorCache = new DisposableCache <IUnconfirmedTxesCursor>(1024,
                                                                                      createFunc: () => new MemoryUnconfirmedTxesCursor(unconfirmedTxesStorage),
                                                                                      prepareAction: cursor =>
            {
                // rollback any open transaction before returning the cursor to the cache
                if (cursor.InTransaction)
                {
                    cursor.RollbackTransaction();
                }
            });
        }
        public LevelDbChainStateManager(string baseDirectory, ulong?cacheSize, ulong?writeCacheSize)
        {
            this.baseDirectory = baseDirectory;
            dbDirectory        = Path.Combine(baseDirectory, "ChainState");

            db = DB.Open(dbDirectory, cacheSize ?? 0, writeCacheSize ?? 0);

            cursorCache = new DisposableCache <IChainStateCursor>(1024,
                                                                  createFunc: () => new LevelDbChainStateCursor(db, isDeferred: false),
                                                                  prepareAction: cursor =>
            {
                // rollback any open transaction before returning the cursor to the cache
                if (cursor.InTransaction)
                {
                    cursor.RollbackTransaction();
                }
            });

            deferredCursorCache = new DisposableCache <IDeferredChainStateCursor>(1,
                                                                                  createFunc: () => new LevelDbChainStateCursor(db, isDeferred: true),
                                                                                  prepareAction: cursor =>
            {
                // rollback any open transaction before returning the cursor to the cache
                if (cursor.InTransaction)
                {
                    cursor.RollbackTransaction();
                }
            });
        }
Пример #5
0
        public void TestTakeItemTimeoutFreed()
        {
            using (var cache = new DisposableCache <IDisposable>(1))
            {
                var item = new Mock <IDisposable>().Object;
                cache.CacheItem(item);

                var delay   = TimeSpan.FromMilliseconds(50);
                var timeout = TimeSpan.FromMilliseconds(5000);

                // return the first item after a delay
                var handle1 = cache.TakeItem();
                Task.Run(() =>
                {
                    using (handle1)
                    {
                        Task.Delay(delay).Wait();
                    }
                });

                // take a second item and verify it succeeds after the delay has passed
                var stopwatch = Stopwatch.StartNew();
                using (var handle2 = cache.TakeItem(timeout))
                {
                    stopwatch.Stop();

                    Assert.IsTrue(stopwatch.Elapsed >= delay);
                }
            }
        }
Пример #6
0
        public EsentChainStateManager(string baseDirectory)
        {
            this.baseDirectory = baseDirectory;
            this.jetDirectory = Path.Combine(baseDirectory, "ChainState");
            this.jetDatabase = Path.Combine(this.jetDirectory, "ChainState.edb");

            this.jetInstance = new Instance(Guid.NewGuid().ToString());
            var success = false;
            try
            {
                EsentStorageManager.InitInstanceParameters(jetInstance, jetDirectory);
                this.jetInstance.Init();

                this.CreateOrOpenDatabase();

                this.cursorCache = new DisposableCache<IChainStateCursor>(1024,
                    createFunc: () => new EsentChainStateCursor(this.jetDatabase, this.jetInstance),
                    prepareAction: cursor =>
                    {
                        // rollback any open transaction before returning the cursor to the cache
                        if (cursor.InTransaction)
                            cursor.RollbackTransaction();
                    });

                success = true;
            }
            finally
            {
                if (!success)
                {
                    this.cursorCache?.Dispose();
                    this.jetInstance.Dispose();
                }
            }
        }
Пример #7
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }
            disposed = true;

            if (disposing)
            {
                // free managed resources
                selection.Changed                      -= HandlePointerChanged;
                selection.Collection.Changed           -= HandleCollectionChanged;
                selection.Collection.ItemsChanged      -= HandleCollectionItemsChanged;
                ThumbnailLoader.Default.OnPixbufLoaded -= HandlePixbufLoaded;
                if (background_pixbuf != null)
                {
                    background_pixbuf.Dispose();
                    background_pixbuf = null;
                }
                if (background_tile != null)
                {
                    background_tile.Dispose();
                    background_tile = null;
                }
                if (thumb_cache != null)
                {
                    thumb_cache.Dispose();
                    thumb_cache = null;
                }
            }
            // free unmanaged resources
        }
Пример #8
0
        internal MemoryStorageManager(ChainedHeader chainTip = null, int? unspentTxCount = null, int? unspentOutputCount = null, int? totalTxCount = null, int? totalInputCount = null, int? totalOutputCount = null, ImmutableSortedDictionary<UInt256, ChainedHeader> headers = null, ImmutableSortedDictionary<UInt256, UnspentTx> unspentTransactions = null, ImmutableDictionary<int, BlockSpentTxes> spentTransactions = null)
        {
            blockStorage = new MemoryBlockStorage();
            blockTxesStorage = new MemoryBlockTxesStorage();
            chainStateStorage = new MemoryChainStateStorage(chainTip, unspentTxCount, unspentOutputCount, totalTxCount, totalInputCount, totalOutputCount, headers, unspentTransactions, spentTransactions);
            unconfirmedTxesStorage = new MemoryUnconfirmedTxesStorage();

            chainStateCursorCache = new DisposableCache<IChainStateCursor>(1024,
                createFunc: () => new MemoryChainStateCursor(chainStateStorage),
                prepareAction: cursor =>
                {
                    // rollback any open transaction before returning the cursor to the cache
                    if (cursor.InTransaction)
                        cursor.RollbackTransaction();
                });

            unconfirmedTxesCursorCache = new DisposableCache<IUnconfirmedTxesCursor>(1024,
                createFunc: () => new MemoryUnconfirmedTxesCursor(unconfirmedTxesStorage),
                prepareAction: cursor =>
                {
                    // rollback any open transaction before returning the cursor to the cache
                    if (cursor.InTransaction)
                        cursor.RollbackTransaction();
                });
        }
        public LmdbChainStateManager(string baseDirectory, long chainStateSize)
        {
            this.baseDirectory = baseDirectory;
            this.jetDirectory = Path.Combine(baseDirectory, "ChainState");
            this.jetDatabase = Path.Combine(this.jetDirectory, "ChainState.edb");

            LmdbStorageManager.PrepareSparseDatabase(this.jetDirectory);
            this.jetInstance = new LightningEnvironment(this.jetDirectory, EnvironmentOpenFlags.NoThreadLocalStorage | EnvironmentOpenFlags.NoSync)
            {
                MaxDatabases = 10,
                MapSize = chainStateSize
            };
            this.jetInstance.Open();

            using (var txn = this.jetInstance.BeginTransaction())
            {
                globalsTableId = txn.OpenDatabase("Globals", new DatabaseOptions { Flags = DatabaseOpenFlags.Create });
                headersTableId = txn.OpenDatabase("Headers", new DatabaseOptions { Flags = DatabaseOpenFlags.Create });
                unspentTxTableId = txn.OpenDatabase("UnspentTx", new DatabaseOptions { Flags = DatabaseOpenFlags.Create });
                blockSpentTxesTableId = txn.OpenDatabase("BlockSpentTxes", new DatabaseOptions { Flags = DatabaseOpenFlags.Create });
                blockUnmintedTxesTableId = txn.OpenDatabase("BlockUnmintedTxes", new DatabaseOptions { Flags = DatabaseOpenFlags.Create });

                txn.Commit();
            }

            this.cursorCache = new DisposableCache<IChainStateCursor>(1024,
                createFunc: () => new LmdbChainStateCursor(this.jetDatabase, this.jetInstance, globalsTableId, headersTableId, unspentTxTableId, blockSpentTxesTableId, blockUnmintedTxesTableId),
                prepareAction: cursor =>
                {
                    // rollback any open transaction before returning the cursor to the cache
                    if (cursor.InTransaction)
                        cursor.RollbackTransaction();
                });
        }
Пример #10
0
        public EsentBlockTxesStorage(string baseDirectory, int? index = null)
        {
            this.jetDirectory = Path.Combine(baseDirectory, "BlockTxes");
            if (index.HasValue)
                this.jetDirectory = Path.Combine(jetDirectory, index.Value.ToString());
            this.jetDatabase = Path.Combine(this.jetDirectory, "BlockTxes.edb");

            this.cursorCache = new DisposableCache<EsentBlockTxesCursor>(1024,
                createFunc: () => new EsentBlockTxesCursor(this.jetDatabase, this.jetInstance));

            this.jetInstance = new Instance(Guid.NewGuid().ToString());
            var success = false;
            try
            {
                EsentStorageManager.InitInstanceParameters(jetInstance, jetDirectory);
                this.jetInstance.Init();
                this.CreateOrOpenDatabase();
                success = true;
            }
            finally
            {
                if (!success)
                    this.jetInstance.Dispose();
            }
        }
Пример #11
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }
            disposed = true;

            if (disposing)
            {
                // free managed resources
                selection.Changed -= HandlePointerChanged;
                // FIXME, observable collections
                //selection.Collection.Changed -= HandleCollectionChanged;
                //selection.Collection.ItemsChanged -= HandleCollectionItemsChanged;
                App.Instance.Container.Resolve <IThumbnailLoader> ().OnPixbufLoaded -= HandlePixbufLoaded;
                if (background_pixbuf != null)
                {
                    background_pixbuf.Dispose();
                    background_pixbuf = null;
                }
                if (background_tile != null)
                {
                    background_tile.Dispose();
                    background_tile = null;
                }
                if (thumb_cache != null)
                {
                    thumb_cache.Dispose();
                    thumb_cache = null;
                }
            }
            // free unmanaged resources
        }
Пример #12
0
        public LevelDbChainStateManager(string baseDirectory, ulong? cacheSize, ulong? writeCacheSize)
        {
            this.baseDirectory = baseDirectory;
            dbDirectory = Path.Combine(baseDirectory, "ChainState");

            db = DB.Open(dbDirectory, cacheSize ?? 0, writeCacheSize ?? 0);

            cursorCache = new DisposableCache<IChainStateCursor>(1024,
                createFunc: () => new LevelDbChainStateCursor(db, isDeferred: false),
                prepareAction: cursor =>
                {
                    // rollback any open transaction before returning the cursor to the cache
                    if (cursor.InTransaction)
                        cursor.RollbackTransaction();
                });

            deferredCursorCache = new DisposableCache<IDeferredChainStateCursor>(1,
                createFunc: () => new LevelDbChainStateCursor(db, isDeferred: true),
                prepareAction: cursor =>
                {
                    // rollback any open transaction before returning the cursor to the cache
                    if (cursor.InTransaction)
                        cursor.RollbackTransaction();
                });
        }
Пример #13
0
        public void TestTakeItem()
        {
            var openCount = 0;
            var disposeCount = 0;

            Func<IDisposable> createFunc =
                () =>
                {
                    var disposable = new Mock<IDisposable>();

                    disposable.Setup(x => x.Dispose())
                        .Callback(() => disposeCount++);

                    openCount++;
                    return disposable.Object;
                };

            // create a cache with a capacity of 2
            using (var cache = new DisposableCache<IDisposable>(2, createFunc))
            {
                Assert.AreEqual(0, openCount);
                Assert.AreEqual(0, disposeCount);

                // take 3 items, 1 should be disposed when it is returned
                using (var handle1 = cache.TakeItem())
                {
                    Assert.AreEqual(1, openCount);
                    Assert.AreEqual(0, disposeCount);

                    using (var handle2 = cache.TakeItem())
                    {
                        Assert.AreEqual(2, openCount);
                        Assert.AreEqual(0, disposeCount);

                        using (var handle3 = cache.TakeItem())
                        {
                            Assert.AreEqual(3, openCount);
                            Assert.AreEqual(0, disposeCount);
                        }

                        Assert.AreEqual(3, openCount);
                        Assert.AreEqual(0, disposeCount);
                    }

                    Assert.AreEqual(3, openCount);
                    Assert.AreEqual(0, disposeCount);
                }

                // verify final item was disposed as the cache was full
                Assert.AreEqual(3, openCount);
                Assert.AreEqual(1, disposeCount);
            }

            // now that cache is disposed, remaining two items should have been disposed
            Assert.AreEqual(3, openCount);
            Assert.AreEqual(3, disposeCount);
        }
Пример #14
0
        public void TestTakeItem()
        {
            var openCount    = 0;
            var disposeCount = 0;

            Func <IDisposable> createFunc =
                () =>
            {
                var disposable = new Mock <IDisposable>();

                disposable.Setup(x => x.Dispose())
                .Callback(() => disposeCount++);

                openCount++;
                return(disposable.Object);
            };

            // create a cache with a capacity of 2
            using (var cache = new DisposableCache <IDisposable>(2, createFunc))
            {
                Assert.AreEqual(0, openCount);
                Assert.AreEqual(0, disposeCount);

                // take 3 items, 1 should be disposed when it is returned
                using (var handle1 = cache.TakeItem())
                {
                    Assert.AreEqual(1, openCount);
                    Assert.AreEqual(0, disposeCount);

                    using (var handle2 = cache.TakeItem())
                    {
                        Assert.AreEqual(2, openCount);
                        Assert.AreEqual(0, disposeCount);

                        using (var handle3 = cache.TakeItem())
                        {
                            Assert.AreEqual(3, openCount);
                            Assert.AreEqual(0, disposeCount);
                        }

                        Assert.AreEqual(3, openCount);
                        Assert.AreEqual(0, disposeCount);
                    }

                    Assert.AreEqual(3, openCount);
                    Assert.AreEqual(0, disposeCount);
                }

                // verify final item was disposed as the cache was full
                Assert.AreEqual(3, openCount);
                Assert.AreEqual(1, disposeCount);
            }

            // now that cache is disposed, remaining two items should have been disposed
            Assert.AreEqual(3, openCount);
            Assert.AreEqual(3, disposeCount);
        }
Пример #15
0
 public Filmstrip(FSpot.BrowsablePointer selection, bool squared_thumbs) : base()
 {
     CanFocus                                   = true;
     this.selection                             = selection;
     this.selection.Changed                    += HandlePointerChanged;
     this.selection.Collection.Changed         += HandleCollectionChanged;
     this.selection.Collection.ItemsChanged    += HandleCollectionItemsChanged;
     this.squared_thumbs                        = squared_thumbs;
     thumb_cache                                = new DisposableCache <string, Pixbuf> (30);
     ThumbnailGenerator.Default.OnPixbufLoaded += HandlePixbufLoaded;
 }
Пример #16
0
        public void AircraftOnlineLookupManager_Dispose_Does_Not_Dispose_Of_Unmanaged_Caches()
        {
            var manager         = Factory.Singleton.Resolve <IAircraftOnlineLookupManager>();
            var disposableCache = new DisposableCache();

            manager.RegisterCache(disposableCache, 1, letManagerControlLifetime: false);

            manager.Dispose();

            Assert.AreEqual(0, disposableCache.DisposeCallCount);
        }
        public void AircraftOnlineLookupManager_Dispose_Disposes_Of_Managed_Caches()
        {
            var manager         = Factory.Singleton.ResolveNewInstance <IAircraftOnlineLookupManager>();
            var disposableCache = new DisposableCache();

            manager.RegisterCache(disposableCache, 1, letManagerControlLifetime: true);

            manager.Dispose();

            Assert.AreEqual(1, disposableCache.DisposeCallCount);
        }
Пример #18
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         // free managed resources
         if (preview_cache != null)
         {
             preview_cache.Dispose();
             preview_cache = null;
         }
     }
     // free unmanaged resources
 }
Пример #19
0
        public void CacheSetDisposesCorrectly()
        {
            var disposableCache = new DisposableCache();

            var client = new KerberosClient()
            {
                Cache = disposableCache
            };

            client.Cache = new DisposableCache();

            Assert.IsTrue(disposableCache.Disposed);
        }
Пример #20
0
        public Filmstrip(BrowsablePointer selection, bool squaredThumbs)
        {
            CanFocus                                = true;
            this.selection                          = selection;
            this.selection.Changed                 += HandlePointerChanged;
            this.selection.Collection.Changed      += HandleCollectionChanged;
            this.selection.Collection.ItemsChanged += HandleCollectionItemsChanged;
            SquaredThumbs                           = squaredThumbs;
            thumb_cache                             = new DisposableCache <SafeUri, Pixbuf> (30);
            ThumbnailLoader.Default.OnPixbufLoaded += HandlePixbufLoaded;

            animation = new DoubleAnimation(0, 0, TimeSpan.FromSeconds(1.5), SetPositionCore, new CubicEase(EasingMode.EaseOut));
        }
Пример #21
0
            public void ShouldDisposeUnderlyingCache()
            {
                // Arrange
                var actual = new DisposableCache();
                var sut    = Create(actual);

                Expect(actual.Disposed)
                .To.Be.False();
                // Act
                sut.Dispose();
                // Assert
                Expect(actual.Disposed)
                .To.Be.True();
            }
Пример #22
0
        public Filmstrip(BrowsablePointer selection, bool squaredThumbs)
        {
            CanFocus                = true;
            this.selection          = selection;
            this.selection.Changed += HandlePointerChanged;
            // FIXME, ObservableCollection
            //this.selection.Collection.Changed += HandleCollectionChanged;
            //this.selection.Collection.ItemsChanged += HandleCollectionItemsChanged;
            SquaredThumbs = squaredThumbs;
            thumb_cache   = new DisposableCache <Uri, Pixbuf> (30);
            App.Instance.Container.Resolve <IThumbnailLoader> ().OnPixbufLoaded += HandlePixbufLoaded;

            animation = new DoubleAnimation(0, 0, TimeSpan.FromSeconds(1.5), SetPositionCore, new CubicEase(EasingMode.EaseOut));
        }
Пример #23
0
        public void TestTakeItemExhausted()
        {
            using (var cache = new DisposableCache <IDisposable>(1))
            {
                var item = new Mock <IDisposable>().Object;
                cache.CacheItem(item);

                using (var handle1 = cache.TakeItem())
                {
                    using (var handle2 = cache.TakeItem())
                    {
                    }
                }
            }
        }
Пример #24
0
        public void TestTakeItemExhausted()
        {
            using (var cache = new DisposableCache<IDisposable>(1))
            using (var taker1Taken = new AutoResetEvent(false))
            using (var taker1Finish = new AutoResetEvent(false))
            using (var taker2Started = new AutoResetEvent(false))
            using (var taker2Taken = new AutoResetEvent(false))
            {
                var item = new Mock<IDisposable>().Object;
                cache.CacheItem(item);

                var taker1 = Task.Run(() =>
                    {
                        using (var handle1 = cache.TakeItem())
                        {
                            taker1Taken.Set();
                            taker1Finish.WaitOne();
                        }
                    });

                // wait for taker 1 to retrieve a cached item
                taker1Taken.WaitOne();

                var taker2 = Task.Run(() =>
                    {
                        taker2Started.Set();
                        using (var handle2 = cache.TakeItem())
                        {
                            taker2Taken.Set();
                        }
                    });

                // wait for taker 2 to start
                Assert.IsTrue(taker2Started.WaitOne(2000));

                // verify taker 2 hasn't been able to retrieve a cached item
                Assert.IsFalse(taker2Taken.WaitOne(500));

                // allow taker 1 to return its cached item
                taker1Finish.Set();
                Assert.IsTrue(taker1.Wait(2000));

                // verify taker 2 then retrieves a cached item
                Assert.IsTrue(taker2Taken.WaitOne(2000));
                Assert.IsTrue(taker2.Wait(2000));
            }
        }
Пример #25
0
        public void TestTakeItemExhausted()
        {
            using (var cache = new DisposableCache <IDisposable>(1))
                using (var taker1Taken = new AutoResetEvent(false))
                    using (var taker1Finish = new AutoResetEvent(false))
                        using (var taker2Started = new AutoResetEvent(false))
                            using (var taker2Taken = new AutoResetEvent(false))
                            {
                                var item = new Mock <IDisposable>().Object;
                                cache.CacheItem(item);

                                var taker1 = Task.Run(() =>
                                {
                                    using (var handle1 = cache.TakeItem())
                                    {
                                        taker1Taken.Set();
                                        taker1Finish.WaitOne();
                                    }
                                });

                                // wait for taker 1 to retrieve a cached item
                                taker1Taken.WaitOne();

                                var taker2 = Task.Run(() =>
                                {
                                    taker2Started.Set();
                                    using (var handle2 = cache.TakeItem())
                                    {
                                        taker2Taken.Set();
                                    }
                                });

                                // wait for taker 2 to start
                                Assert.IsTrue(taker2Started.WaitOne(2000));

                                // verify taker 2 hasn't been able to retrieve a cached item
                                Assert.IsFalse(taker2Taken.WaitOne(500));

                                // allow taker 1 to return its cached item
                                taker1Finish.Set();
                                Assert.IsTrue(taker1.Wait(2000));

                                // verify taker 2 then retrieves a cached item
                                Assert.IsTrue(taker2Taken.WaitOne(2000));
                                Assert.IsTrue(taker2.Wait(2000));
                            }
        }
Пример #26
0
        public ChainState(Chain chain, IStorageManager storageManager)
        {
            CursorCount = Environment.ProcessorCount;
            Chain       = chain;

            // create a cache of cursors that are in an open snapshot transaction with the current chain state
            var success = false;

            this.cursorCache = new DisposableCache <DisposeHandle <IChainStateCursor> >(CursorCount);
            try
            {
                for (var i = 0; i < this.cursorCache.Capacity; i++)
                {
                    // open the cursor
                    var handle = storageManager.OpenChainStateCursor();
                    var cursor = handle.Item;

                    // cache the cursor
                    // this must be done before beginning the transaction as caching will rollback any transactions
                    this.cursorCache.CacheItem(handle);

                    // begin transaction to take the snapshot
                    cursor.BeginTransaction(readOnly: true);

                    // verify the chain state matches the expected chain
                    var chainTip = cursor.ChainTip;
                    if (chainTip?.Hash != chain.LastBlock?.Hash)
                    {
                        throw new ChainStateOutOfSyncException(chain.LastBlock, chainTip);
                    }
                }

                success = true;
            }
            finally
            {
                // ensure any opened cursors are cleaned up on an error
                if (!success)
                {
                    this.cursorCache.Dispose();
                }
            }
        }
Пример #27
0
        public BlockTxesStorage(string baseDirectory, Logger logger)
        {
            this.logger       = logger;
            this.jetDirectory = Path.Combine(baseDirectory, "BlockTxes");
            this.jetDatabase  = Path.Combine(this.jetDirectory, "BlockTxes.edb");

            this.cursorCache = new DisposableCache <BlockTxesCursor>(64,
                                                                     createFunc: () => new BlockTxesCursor(this.jetDatabase, this.jetInstance));

            this.jetInstance = CreateInstance(this.jetDirectory);
            try
            {
                this.jetInstance.Init();
                this.CreateOrOpenDatabase();
            }
            catch (Exception)
            {
                this.jetInstance.Dispose();
                throw;
            }
        }
Пример #28
0
        public EsentChainStateManager(string baseDirectory)
        {
            this.baseDirectory = baseDirectory;
            this.jetDirectory  = Path.Combine(baseDirectory, "ChainState");
            this.jetDatabase   = Path.Combine(this.jetDirectory, "ChainState.edb");

            this.jetInstance = new Instance(Guid.NewGuid().ToString());
            var success = false;

            try
            {
                EsentStorageManager.InitInstanceParameters(jetInstance, jetDirectory);
                this.jetInstance.Init();

                this.CreateOrOpenDatabase();

                this.cursorCache = new DisposableCache <IChainStateCursor>(1024,
                                                                           createFunc: () => new EsentChainStateCursor(this.jetDatabase, this.jetInstance),
                                                                           prepareAction: cursor =>
                {
                    // rollback any open transaction before returning the cursor to the cache
                    if (cursor.InTransaction)
                    {
                        cursor.RollbackTransaction();
                    }
                });

                success = true;
            }
            finally
            {
                if (!success)
                {
                    this.cursorCache?.Dispose();
                    this.jetInstance.Dispose();
                }
            }
        }
Пример #29
0
        public ChainState(Chain chain, IStorageManager storageManager)
        {
            CursorCount = Environment.ProcessorCount;
            Chain = chain;

            // create a cache of cursors that are in an open snapshot transaction with the current chain state
            var success = false;
            this.cursorCache = new DisposableCache<DisposeHandle<IChainStateCursor>>(CursorCount);
            try
            {
                for (var i = 0; i < this.cursorCache.Capacity; i++)
                {
                    // open the cursor
                    var handle = storageManager.OpenChainStateCursor();
                    var cursor = handle.Item;

                    // cache the cursor
                    // this must be done before beginning the transaction as caching will rollback any transactions
                    this.cursorCache.CacheItem(handle);

                    // begin transaction to take the snapshot
                    cursor.BeginTransaction(readOnly: true);

                    // verify the chain state matches the expected chain
                    var chainTip = cursor.ChainTip;
                    if (chainTip?.Hash != chain.LastBlock?.Hash)
                        throw new ChainStateOutOfSyncException(chain.LastBlock, chainTip);
                }

                success = true;
            }
            finally
            {
                // ensure any opened cursors are cleaned up on an error
                if (!success)
                    this.cursorCache.Dispose();
            }
        }
Пример #30
0
        public EsentChainStateManager(string baseDirectory, Logger logger)
        {
            this.logger        = logger;
            this.baseDirectory = baseDirectory;
            this.jetDirectory  = Path.Combine(baseDirectory, "ChainState");
            this.jetDatabase   = Path.Combine(this.jetDirectory, "ChainState.edb");

            this.jetInstance = CreateInstance(this.jetDirectory);
            this.jetInstance.Init();

            this.CreateOrOpenDatabase();

            this.cursorCache = new DisposableCache <IChainStateCursor>(64,
                                                                       createFunc: () => new ChainStateCursor(this.jetDatabase, this.jetInstance, this.logger),
                                                                       prepareAction: cursor =>
            {
                // rollback any open transaction before returning the cursor to the cache
                if (cursor.InTransaction)
                {
                    cursor.RollbackTransaction();
                }
            });
        }
Пример #31
0
        public ChainState(Chain chain, IStorageManager storageManager)
        {
            this.chain = chain;

            // create a cache of cursors that are in an open snapshot transaction with the current chain state
            this.cursorCache = new DisposableCache <DisposeHandle <IChainStateCursor> >(16);
            try
            {
                for (var i = 0; i < this.cursorCache.Capacity; i++)
                {
                    // open the cursor
                    var handle = storageManager.OpenChainStateCursor();
                    var cursor = handle.Item;

                    // cache the cursor
                    // this must be done before beginning the transaction as caching will rollback any transactions
                    this.cursorCache.CacheItem(handle);

                    // begin transaction to take the snapshot
                    cursor.BeginTransaction();

                    // verify the chain state matches the expected chain
                    var chainTip = cursor.GetChainTip();
                    if (chainTip != chain.LastBlock)
                    {
                        throw new InvalidOperationException();
                    }
                }
            }
            catch (Exception)
            {
                // ensure any opened cursors are cleaned up on an error
                this.cursorCache.Dispose();
                throw;
            }
        }
Пример #32
0
        private async Task PruneTxIndexAsync(PruningMode mode, Chain chain, ChainedHeader pruneBlock, BlockSpentTxes spentTxes)
        {
            if (!mode.HasFlag(PruningMode.TxIndex))
            {
                return;
            }

            var maxParallelism = Environment.ProcessorCount;

            // prepare a cache of cursors to be used by the pruning action block, allowing a pool of transactions
            var openedCursors = new ConcurrentBag <IChainStateCursor>();

            using (var cursorHandles = new DisposableCache <DisposeHandle <IChainStateCursor> >(maxParallelism,
                                                                                                () =>
            {
                // retrieve a new cursor and start its transaction, keeping track of any cursors opened
                var cursorHandle = this.storageManager.OpenChainStateCursor();
                cursorHandle.Item.BeginTransaction();
                openedCursors.Add(cursorHandle.Item);

                return(cursorHandle);
            }))
            {
                var pruneTxIndex = new ActionBlock <SpentTx>(
                    spentTx =>
                {
                    using (var handle = cursorHandles.TakeItem())
                    {
                        var chainStateCursor = handle.Item.Item;

                        chainStateCursor.RemoveUnspentTx(spentTx.TxHash);
                        for (var outputIndex = 0; outputIndex < spentTx.OutputCount; outputIndex++)
                        {
                            chainStateCursor.RemoveUnspentTxOutput(new TxOutputKey(spentTx.TxHash, (uint)outputIndex));
                        }
                    }
                },
                    new ExecutionDataflowBlockOptions {
                    MaxDegreeOfParallelism = maxParallelism
                });

                var spentTxesQueue = new BufferBlock <SpentTx>();
                spentTxesQueue.LinkTo(pruneTxIndex, new DataflowLinkOptions {
                    PropagateCompletion = true
                });

                await spentTxesQueue.SendAndCompleteAsync(spentTxes);

                await pruneTxIndex.Completion;

                // commit all opened cursors on success
                var commitTasks = new Task[openedCursors.Count];
                var i           = 0;
                foreach (var cursor in openedCursors)
                {
                    commitTasks[i++] = cursor.CommitTransactionAsync();
                }

                await Task.WhenAll(commitTasks);
            }
        }
Пример #33
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing) {
         // free managed resources
         if (preview_cache != null) {
             preview_cache.Dispose ();
             preview_cache = null;
         }
     }
     // free unmanaged resources
 }
Пример #34
0
        public Filmstrip(BrowsablePointer selection, bool squaredThumbs)
        {
            CanFocus = true;
            this.selection = selection;
            this.selection.Changed += HandlePointerChanged;
            this.selection.Collection.Changed += HandleCollectionChanged;
            this.selection.Collection.ItemsChanged += HandleCollectionItemsChanged;
            SquaredThumbs = squaredThumbs;
            thumb_cache = new DisposableCache<SafeUri, Pixbuf> (30);
            ThumbnailLoader.Default.OnPixbufLoaded += HandlePixbufLoaded;

            animation = new DoubleAnimation (0, 0, TimeSpan.FromSeconds (1.5), SetPositionCore, new CubicEase (EasingMode.EaseOut));
        }
Пример #35
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
                return;
            disposed = true;

            if (disposing) {
                // free managed resources
                selection.Changed -= HandlePointerChanged;
                selection.Collection.Changed -= HandleCollectionChanged;
                selection.Collection.ItemsChanged -= HandleCollectionItemsChanged;
                ThumbnailLoader.Default.OnPixbufLoaded -= HandlePixbufLoaded;
                if (background_pixbuf != null) {
                    background_pixbuf.Dispose ();
                    background_pixbuf = null;
                }
                if (background_tile != null) {
                    background_tile.Dispose ();
                    background_tile = null;
                }
                if (thumb_cache != null) {
                    thumb_cache.Dispose ();
                    thumb_cache = null;
                }
            }
            // free unmanaged resources
        }
Пример #36
0
        private async Task PruneTxIndexAsync(PruningMode mode, Chain chain, ChainedHeader pruneBlock, BlockSpentTxes spentTxes)
        {
            if (!mode.HasFlag(PruningMode.TxIndex))
                return;

            var maxParallelism = Environment.ProcessorCount;

            // prepare a cache of cursors to be used by the pruning action block, allowing a pool of transactions
            var openedCursors = new ConcurrentBag<IChainStateCursor>();
            using (var cursorHandles = new DisposableCache<DisposeHandle<IChainStateCursor>>(maxParallelism,
                () =>
                {
                    // retrieve a new cursor and start its transaction, keeping track of any cursors opened
                    var cursorHandle = this.storageManager.OpenChainStateCursor();
                    cursorHandle.Item.BeginTransaction(pruneOnly: true);
                    openedCursors.Add(cursorHandle.Item);

                    return cursorHandle;
                }))
            {
                var pruneTxIndex = new ActionBlock<SpentTx>(
                    spentTx =>
                    {
                        using (var handle = cursorHandles.TakeItem())
                        {
                            var chainStateCursor = handle.Item.Item;

                            chainStateCursor.TryRemoveUnspentTx(spentTx.TxHash);
                        }
                    },
                    new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = maxParallelism });

                var spentTxesQueue = new BufferBlock<SpentTx>();
                spentTxesQueue.LinkTo(pruneTxIndex, new DataflowLinkOptions { PropagateCompletion = true });

                await spentTxesQueue.SendAndCompleteAsync(spentTxes);
                await pruneTxIndex.Completion;

                // commit all opened cursors on success
                Parallel.ForEach(openedCursors, cursor =>
                    cursor.CommitTransaction());
            }
        }
Пример #37
0
        public void TestTakeItemTimeout()
        {
            using (var cache = new DisposableCache<IDisposable>(1))
            {
                var item = new Mock<IDisposable>().Object;
                cache.CacheItem(item);

                using (var handle1 = cache.TakeItem())
                {
                    var timeout = TimeSpan.FromMilliseconds(250);

                    var stopwatch = Stopwatch.StartNew();
                    try
                    {
                        using (var handle2 = cache.TakeItem(timeout))
                        { }
                        Assert.Fail();
                    }
                    catch (TimeoutException) { /*expected*/ }
                    stopwatch.Stop();

                    // verify the timout period was respected before the exception was thrown
                    Assert.IsTrue(stopwatch.Elapsed >= timeout);
                }
            }
        }
Пример #38
0
		public Filmstrip (FSpot.BrowsablePointer selection, bool squared_thumbs) : base ()
		{
			CanFocus = true;
			this.selection = selection;
			this.selection.Changed += HandlePointerChanged;
			this.selection.Collection.Changed += HandleCollectionChanged;
			this.selection.Collection.ItemsChanged += HandleCollectionItemsChanged;
			this.squared_thumbs = squared_thumbs;
			thumb_cache = new DisposableCache<string, Pixbuf> (30);
			ThumbnailGenerator.Default.OnPixbufLoaded += HandlePixbufLoaded;
		}
Пример #39
0
        public void TestTakeItemTimeoutFreed()
        {
            using (var cache = new DisposableCache<IDisposable>(1))
            {
                var item = new Mock<IDisposable>().Object;
                cache.CacheItem(item);

                var delay = TimeSpan.FromMilliseconds(50);
                var timeout = TimeSpan.FromMilliseconds(5000);

                // return the first item after a delay
                var handle1 = cache.TakeItem();
                Task.Run(() =>
                {
                    using (handle1)
                    {
                        Task.Delay(delay).Wait();
                    }
                });

                // take a second item and verify it succeeds after the delay has passed
                var stopwatch = Stopwatch.StartNew();
                using (var handle2 = cache.TakeItem(timeout))
                {
                    stopwatch.Stop();

                    Assert.IsTrue(stopwatch.Elapsed >= delay);
                }
            }
        }