aboutsummaryrefslogtreecommitdiff
path: root/lib/VNLib.Data.Caching.ObjectCache/src/BlobCacheTable.cs
blob: 8270f2f5df68956229249e0e9e400f51ba625b52 (plain)
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
/*
* Copyright (c) 2023 Vaughn Nugent
* 
* Library: VNLib
* Package: VNLib.Data.Caching.ObjectCache
* File: BlobCacheTable.cs 
*
* BlobCacheTable.cs is part of VNLib.Data.Caching.ObjectCache which is part of the larger 
* VNLib collection of libraries and utilities.
*
* VNLib.Data.Caching.ObjectCache 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.
*
* VNLib.Data.Caching.ObjectCache 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 https://www.gnu.org/licenses/.
*/

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

using VNLib.Utils;

namespace VNLib.Data.Caching.ObjectCache
{

    /// <summary>
    /// A concrete implementation of a <see cref="IBlobCacheTable"/>
    /// </summary>
    public sealed class BlobCacheTable : VnDisposeable, IBlobCacheTable
    {
        private readonly uint _tableSize;
        private readonly BlobCacheBucket[] _buckets;
        private readonly IPersistantCacheStore? _persistant;


        /// <summary>
        /// Initializes a new <see cref="BlobCacheTable"/>
        /// </summary>
        /// <param name="bucketSize">The number of elements in each bucket</param>
        /// <param name="tableSize">The number of buckets within the table</param>
        /// <param name="manager">A single cache memory manger to share across all buckets</param>
        /// <param name="persistantCache">An optional <see cref="IPersistantCacheStore"/> for persistant cache implementations</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentException"></exception>
        public BlobCacheTable(uint tableSize, uint bucketSize, ICacheEntryMemoryManager manager, IPersistantCacheStore? persistantCache)
            :this(tableSize, bucketSize, new SharedMemManager(manager), persistantCache)
        { }

        /// <summary>
        /// Initializes a new <see cref="BlobCacheTable"/>
        /// </summary>
        /// <param name="bucketSize">The number of elements in each bucket</param>
        /// <param name="tableSize">The number of buckets within the table</param>
        /// <param name="factory">A factory that can generate bucket-local memory managers</param>
        /// <param name="persistantCache">An optional <see cref="IPersistantCacheStore"/> for persistant cache implementations</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentException"></exception>
        public BlobCacheTable(uint tableSize, uint bucketSize, ICacheMemoryManagerFactory factory, IPersistantCacheStore? persistantCache)
        {
            _ = factory ?? throw new ArgumentNullException(nameof(factory));

            if(tableSize == 0)
            {
                throw new ArgumentException("Cache table must have atleast 1 bucket");
            }

            //Init bucket table
            _tableSize = tableSize;
            _persistant = persistantCache;

            //Init buckets
            InitBuckets(tableSize, bucketSize, out _buckets, factory, persistantCache);
        }


        private static void InitBuckets(uint size, uint bucketSize, out BlobCacheBucket[] table, ICacheMemoryManagerFactory man, IPersistantCacheStore? persistantCache)
        {
            table = new BlobCacheBucket[size];

            for(uint i = 0; i < size; i++)
            {
                //Get the memory manager for the bucket
                ICacheEntryMemoryManager manager = man.CreateForBucket(i);

                table[i] = new BlobCacheBucket(i, (int)bucketSize, manager, persistantCache);
            }
        }

        /*
         * A very simple algorithm that captures unique values
         * from an object id and builds an unsigned 32bit integer
         * used to determine the bucked index within the table.
         * 
         * This method will alawys result in the same index for 
         * for a given object-id
         */

        private uint FastGetBucketIndexFromId(ReadOnlySpan<char> objectId)
        {
            if (objectId.Length < 4)
            {
                throw new ArgumentException("Object id must be larger than 3 characters");
            }

            Span<byte> buffer = stackalloc byte[4];

            //cast the characters 
            buffer[0] = (byte)objectId[0];
            buffer[1] = (byte)objectId[objectId.Length / 2];
            buffer[2] = (byte)objectId[1];
            buffer[3] = (byte)objectId[^1];

            //Read the buffer back to a uint and mod by the table size to get the bucket index
            return BitConverter.ToUInt32(buffer) % _tableSize;
        }
     

        ///<inheritdoc/>
        ///<exception cref="ObjectDisposedException"></exception>
        public IBlobCacheBucket GetBucket(ReadOnlySpan<char> objectId)
        {
            Check();

            //If tablesize is 1, skip lookup, otherwise perform bucket index lookup
            uint index = _tableSize == 1 ? 0 : FastGetBucketIndexFromId(objectId);

            return _buckets[index];
        }

        ///<inheritdoc/>
        protected sealed override void Free()
        {
            //Dispose persistance store
            using (_persistant)
            {
                //Dispose buckets
                Array.ForEach(_buckets, static b => b.Dispose());
            }
        }

        ///<inheritdoc/>
        public IEnumerator<IBlobCacheBucket> GetEnumerator()
        {
            Check();
            return _buckets.AsEnumerable().GetEnumerator();
        }

        ///<inheritdoc/>
        IEnumerator IEnumerable.GetEnumerator()
        {
            Check();
            return _buckets.AsEnumerable().GetEnumerator();
        }

        private sealed record class SharedMemManager(ICacheEntryMemoryManager Manager) : ICacheMemoryManagerFactory
        {
            ///<inheritdoc/>
            public ICacheEntryMemoryManager CreateForBucket(uint bucketId) => Manager;
          
        }
    }
}