aboutsummaryrefslogtreecommitdiff
path: root/lib/VNLib.Plugins.Extensions.VNCache/src/DataModel/EntityResultCache.cs
blob: 56311f08e6028f4dfbbd10daaa9fa0af55994ad5 (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
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
/*
* Copyright (c) 2024 Vaughn Nugent
* 
* Library: VNLib
* Package: VNLib.Plugins.Extensions.VNCache
* File: EntityResultCache.cs 
*
* EntityResultCache.cs is part of VNLib.Plugins.Extensions.VNCache 
* which is part of the larger VNLib collection of libraries and utilities.
*
* VNLib.Plugins.Extensions.VNCache 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.Plugins.Extensions.VNCache 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.Threading;
using System.Threading.Tasks;

namespace VNLib.Plugins.Extensions.VNCache.DataModel
{
    /// <summary>
    /// Represents a cache that can store entities by their unique key
    /// using a user-provided backing store and custom request state.
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    /// <param name="cache">The cache backing store</param>
    /// <param name="taskPolicy">Specifies how background cache tasks are handled</param>
    /// <param name="expirationPolicy">The result expiration policy</param>
    public class EntityResultCache<TEntity>(
        IEntityCache<TEntity> cache, 
        ICacheTaskPolicy taskPolicy, 
        ICacheExpirationPolicy<TEntity> expirationPolicy
    )
        where TEntity : class
    {

        /// <summary>
        /// The backing entity cache store
        /// </summary>
        public IEntityCache<TEntity> Cache => cache;

        /// <summary>
        /// The task policy for which this result cache will 
        /// respect
        /// </summary>
        public ICacheTaskPolicy TaskPolicy => taskPolicy;

        /// <summary>
        /// The expiration policy for which this result cache will
        /// respect for entity expiration and refreshing
        /// </summary>
        public ICacheExpirationPolicy<TEntity> ExpirationPolicy => expirationPolicy;


        /// <summary>
        /// Fetchs a result by it's request entity
        /// </summary>
        /// <param name="request">The fetch request state object</param>
        /// <param name="cancellation">A token to canel the operation</param>
        /// <param name="resultFactory">A callback generator function</param>
        /// <returns>A task the returns the result of the requested entity, or null if it was not found or provided by the backing store</returns>
        public Task<TEntity?> FetchAsync<TRequest>(
            TRequest request, 
            Func<TRequest, CancellationToken, Task<TEntity?>> resultFactory, 
            CancellationToken cancellation = default
        ) where TRequest : IEntityCacheKey
        {
            ArgumentNullException.ThrowIfNull(request);
            ArgumentNullException.ThrowIfNull(resultFactory);

            return FetchAsync(
                key: request.GetKey(),
                state: (resultFactory, request), 
                resultFactory: static (rf, c) => rf.resultFactory(rf.request, c), 
                cancellation
            );
        }

        /// <summary>
        /// Fetchs a result by it's request entity
        /// </summary>
        /// <param name="key">The fetch request state object</param>
        /// <param name="cancellation">A token to canel the operation</param>
        /// <param name="resultFactory">A callback generator function</param>
        /// <returns>A task the returns the result of the requested entity, or null if it was not found or provided by the backing store</returns>
        public Task<TEntity?> FetchAsync(
            string key,
            Func<CancellationToken, Task<TEntity?>> resultFactory,
            CancellationToken cancellation = default
        )
        {
            ArgumentNullException.ThrowIfNull(resultFactory);

            return FetchAsync(
                key, 
                state: resultFactory, 
                resultFactory: static (rf, c) => rf(c), 
                cancellation
            );
        }

        private async Task<TEntity?> FetchAsync<TState>(
            string key,
            TState state,
            Func<TState, CancellationToken, Task<TEntity?>> resultFactory,
            CancellationToken cancellation = default
        )
        {
            ArgumentException.ThrowIfNullOrWhiteSpace(key);
            ArgumentNullException.ThrowIfNull(resultFactory);
            cancellation.ThrowIfCancellationRequested();

            //try to fetch from cache
            TEntity? entity = await cache.GetAsync(key, cancellation);

            if (entity is not null)
            {
                //Check if the entity is expired
                if (expirationPolicy.IsExpired(entity))
                {
                    //Setting to null will force a cache miss
                    entity = null;
                }
            }

            if (entity is null)
            {
                //Cache miss, load from factory
                entity = await resultFactory(state, cancellation);

                if (entity is not null)
                {
                    //Notify the expiration policy that the entity was refreshed before writing back to cache
                    expirationPolicy.OnRefreshed(entity);

                    //Fresh entity was fetched from the factory so write to cache
                    Task upsert = cache.UpsertAsync(key, entity, cancellation);

                    //Allow task policy to determine how completions are observed
                    await taskPolicy.ObserveOperationAsync(upsert);
                }
            }

            return entity;
        }

        /// <summary>
        /// Removes an entity from the cache by it's request entity
        /// </summary>
        /// <param name="request">The request entity to retrieve the entity key from</param>
        /// <param name="cancellation">A token to cancel the async operation</param>
        /// <returns>A task that completes when the key is removed, based on the task policy</returns>
        public Task RemoveAsync<TRequest>(TRequest request, CancellationToken cancellation = default) 
            where TRequest : IEntityCacheKey
        {
            ArgumentNullException.ThrowIfNull(request);

            string key = request.GetKey();

            return cache.RemoveAsync(key, cancellation);
        }

        /// <summary>
        /// Removes an entity from the cache by it's request entity
        /// </summary>
        /// <param name="key">The entities unique key</param>
        /// <param name="cancellation">A token to cancel the async operation</param>
        /// <returns>A task that completes when the key is removed, based on the task policy</returns>
        public Task RemoveAsync(string key, CancellationToken cancellation = default)
        {
            ArgumentException.ThrowIfNullOrWhiteSpace(key);

            Task remove = cache.RemoveAsync(key, cancellation);

            return taskPolicy.ObserveOperationAsync(remove);
        }

        /// <summary>
        /// Performs a cache replacement operation. That is substitutes an exiting
        /// value with a new one, or inserts a new value if the key does not exist.
        /// </summary>
        /// <param name="request">The operation request state object</param>
        /// <param name="entity">The entity object to store</param>
        /// <param name="action">A generic callback function to invoke in parallel with the upsert operation</param>
        /// <param name="cancellation">A token to cancel the async operation</param>
        /// <returns>
        /// A task that completes when the upsert operation has completed according to the 
        /// <see cref="TaskPolicy"/>
        /// </returns>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        public Task UpsertAsync<TRequest>(
            TRequest request,
            TEntity entity,
            Func<TRequest, TEntity, CancellationToken, Task> action,
            CancellationToken cancellation = default
        ) where TRequest : IEntityCacheKey
        {
            ArgumentNullException.ThrowIfNull(request);
            ArgumentNullException.ThrowIfNull(action);

            return UpsertAsync(
                key: request.GetKey(),
                entity: entity,
                state: (action, request),
                callback: static (cb, e, c) => cb.action.Invoke(cb.request, e, c),
                cancellation
            );
        }


        /// <summary>
        /// Performs a cache replacement operation. That is substitutes an exiting
        /// value with a new one, or inserts a new value if the key does not exist.
        /// </summary>
        /// <param name="key">The entity's unique id within the cache store</param>
        /// <param name="entity">The entity object to store</param>
        /// <param name="action">A generic callback function to invoke in parallel with the upsert operation</param>
        /// <param name="cancellation">A token to cancel the async operation</param>
        /// <returns>
        /// A task that completes when the upsert operation has completed according to the 
        /// <see cref="TaskPolicy"/>
        /// </returns>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        public Task UpsertAsync(
            string key,
            TEntity entity,
            Func<TEntity, CancellationToken, Task> action,
            CancellationToken cancellation = default
        )
        {
            ArgumentNullException.ThrowIfNull(action);

            return UpsertAsync(
                key, 
                entity, 
                state: action, 
                callback: static (cb, e, c) => cb.Invoke(e, c), 
                cancellation
            );
        }

        /// <summary>
        /// Performs a cache replacement operation. That is substitutes an exiting
        /// value with a new one, or inserts a new value if the key does not exist.
        /// </summary>
        /// <param name="key">The entity's unique id within the cache store</param>
        /// <param name="entity">The entity object to store</param>
        /// <param name="cancellation">A token to cancel the async operation</param>
        /// <returns>
        /// A task that completes when the upsert operation has completed according to the 
        /// <see cref="TaskPolicy"/>
        /// </returns>
        /// <exception cref="ArgumentNullException"></exception>
        public Task UpsertAsync(string key, TEntity entity, CancellationToken cancellation = default)
        {
            return UpsertAsync<object?>(
                key,
                entity,
                state: null,
                callback: static (_, _, _) => Task.CompletedTask,
                cancellation
            );
        }

        private Task UpsertAsync<TState>(
            string key, 
            TEntity entity, 
            TState state, 
            Func<TState, TEntity, CancellationToken, Task> callback,
            CancellationToken cancellation = default
        )
        {
            ArgumentException.ThrowIfNullOrWhiteSpace(key);
            ArgumentNullException.ThrowIfNull(callback);
            cancellation.ThrowIfCancellationRequested();

            //Call refresh before storing the entity incase any setup needs to be performed
            expirationPolicy.OnRefreshed(entity);

            //Cache task must be observed by the task policy
            Task upsert = taskPolicy.ObserveOperationAsync(
                 operation: cache.UpsertAsync(key, entity, cancellation)
            );

            Task cbResult = callback(state, entity, cancellation);

            //Combine the observed task and the callback function
            return Task.WhenAll(cbResult, upsert);
        }
    }
}