|
| 1 | +// Copyright (c) 2013, Emergent Design Ltd. All rights reserved. Use of this source code |
| 2 | +// is governed by a BSD-style licence that can be found in the LICENSE file. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Linq; |
| 6 | +using System.Reflection; |
| 7 | +using System.Threading.Tasks; |
| 8 | +using System.Collections.Generic; |
| 9 | + |
| 10 | +using BookSleeve; |
| 11 | +using ServiceStack.Text; |
| 12 | + |
| 13 | + |
| 14 | +namespace BookStack |
| 15 | +{ |
| 16 | + public static class BookStackExtensions |
| 17 | + { |
| 18 | + /// <summary> |
| 19 | + /// Generates an incremental ID for a given type. Each type is assigned their own incrementor in redis using the key "id:typename". |
| 20 | + /// This is the only synchronous method in BookStack since it is assumed that a new ID is required for immediate assignment. |
| 21 | + /// </summary> |
| 22 | + /// <returns> the new ID</returns> |
| 23 | + public static long NextId<T>(this RedisConnection redis, int db) |
| 24 | + { |
| 25 | + return redis.Wait(redis.Strings.Increment(db, string.Format("id:{0}", typeof(T).Name.ToLower()))); |
| 26 | + } |
| 27 | + |
| 28 | + |
| 29 | + /// <summary> |
| 30 | + /// Stores the given entity to redis. It is assumed that the entity has a public property named "Id" which is used to form |
| 31 | + /// the redis key. An exception will occur if an ID property does not exist. |
| 32 | + /// The object will be stored under the key "urn:typename:id" and if the key already exists it will be overwritten with the new |
| 33 | + /// serialized object instance. |
| 34 | + /// The ID of the object is also added to a set under the key "ids:typename" and is used for the fast retrieval of all entities of |
| 35 | + /// a given type. |
| 36 | + /// </summary> |
| 37 | + /// <returns> the same entity instance that was passed in</returns> |
| 38 | + public static Task<T> Store<T>(this RedisConnection redis, int db, T entity) |
| 39 | + { |
| 40 | + object id = entity.GetType().GetProperty("Id").GetGetMethod().Invoke(entity, new object[0]); |
| 41 | + |
| 42 | + return redis.Store(db, id, entity); |
| 43 | + } |
| 44 | + |
| 45 | + |
| 46 | + /// <summary> |
| 47 | + /// Stores the given entity to redis. The ID must be specified as this is used to form the redis key. The object will be stored |
| 48 | + /// under the key "urn:typename:id" and if the key already exists it will be overwritten with the new serialized object instance. |
| 49 | + /// The ID of the object is also added to a set under the key "ids:typename" and is used for the fast retrieval of all entities of |
| 50 | + /// a given type. |
| 51 | + /// </summary> |
| 52 | + /// <returns> the same entity instance that was passed in</returns> |
| 53 | + public static Task<T> Store<T>(this RedisConnection redis, int db, object id, T entity) |
| 54 | + { |
| 55 | + string urn = string.Format("urn:{0}:{1}", typeof(T).Name.ToLower(), id); |
| 56 | + var tasks = new Task [] { |
| 57 | + redis.Strings.Set(db, urn, entity.ToJson()), |
| 58 | + redis.Sets.Add(db, string.Format("ids:{0}", typeof(T).Name.ToLower()), id.ToString()) |
| 59 | + }; |
| 60 | + |
| 61 | + return Task.Factory.ContinueWhenAll(tasks, t => entity); |
| 62 | + } |
| 63 | + |
| 64 | + |
| 65 | + /// <summary> |
| 66 | + /// Stores a collection of entities to redis. Each item must have a public property named "Id" which is used to form the redis keys, |
| 67 | + /// otherwise an exception will occur. Each entity is stored in the same way as the Store method (except that this is performed as a |
| 68 | + /// batch process). |
| 69 | + /// </summary> |
| 70 | + /// <returns> the number of new entries only, existing entries will simply be updated</returns> |
| 71 | + public static Task<long> StoreAll<T>(this RedisConnection redis, int db, IEnumerable<T> entities) |
| 72 | + { |
| 73 | + return redis.StoreAll(db, entities.ToDictionary(e => e.GetType().GetProperty("Id").GetGetMethod().Invoke(e, new object[0]), e => e)); |
| 74 | + } |
| 75 | + |
| 76 | + |
| 77 | + /// <summary> |
| 78 | + /// Stores a collection of entities to redis. The items are expected as a dictionary where each key is the ID for the corresponding |
| 79 | + /// entity instance. Each entity is stored in the same way as the Store method (except that this is performed as a batch process). |
| 80 | + /// </summary> |
| 81 | + /// <returns> the number of new entries only, existing entries will simply be updated</returns> |
| 82 | + public static Task<long> StoreAll<T>(this RedisConnection redis, int db, Dictionary<object, T> entities) |
| 83 | + { |
| 84 | + string urn = string.Format("urn:{0}", typeof(T).Name.ToLower()); |
| 85 | + var tasks = new Task [] { |
| 86 | + redis.Strings.Set(db, entities.ToDictionary(i => string.Format("{0}:{1}", urn, i.Key), i => i.Value.ToJson())), |
| 87 | + redis.Sets.Add(db, string.Format("ids:{0}", typeof(T).Name.ToLower()), entities.Keys.Select(k => k.ToString()).ToArray()) |
| 88 | + }; |
| 89 | + |
| 90 | + return Task.Factory.ContinueWhenAll(tasks, t => (tasks[1] as Task<long>).Result); |
| 91 | + } |
| 92 | + |
| 93 | + |
| 94 | + /// <summary> |
| 95 | + /// Retrieves an entity from redis by ID. If the ID does not exist then null is returned. |
| 96 | + /// </summary> |
| 97 | + /// <returns> the deserialized entity instance or null if the ID cannot be found</returns> |
| 98 | + public static Task<T> Get<T>(this RedisConnection redis, int db, object id) |
| 99 | + { |
| 100 | + string urn = string.Format("urn:{0}:{1}", typeof(T).Name.ToLower(), id); |
| 101 | + var task = redis.Strings.GetString(db, urn); |
| 102 | + |
| 103 | + return task.ContinueWith(t => JsonSerializer.DeserializeFromString<T>(t.Result)); |
| 104 | + } |
| 105 | + |
| 106 | + |
| 107 | + /// <summary> |
| 108 | + /// Gets all entities of the given type from redis. The returned collection will be empty |
| 109 | + /// if no entities of that type exist. |
| 110 | + /// </summary> |
| 111 | + /// <returns> a collection of entities</returns> |
| 112 | + public static Task<IEnumerable<T>> GetAll<T>(this RedisConnection redis, int db) |
| 113 | + { |
| 114 | + string urn = string.Format("urn:{0}", typeof(T).Name.ToLower()); |
| 115 | + var task = redis.Sets.GetAllString(db, string.Format("ids:{0}", typeof(T).Name.ToLower())); |
| 116 | + |
| 117 | + return task.ContinueWith(ids => { |
| 118 | + var items = ids.Result.Length > 0 |
| 119 | + ? redis.Wait(redis.Strings.GetString(db, ids.Result.Select(i => string.Format("{0}:{1}", urn, i)).ToArray())) |
| 120 | + : new string[0]; |
| 121 | + |
| 122 | + return items.Select(i => JsonSerializer.DeserializeFromString<T>(i)); |
| 123 | + }); |
| 124 | + } |
| 125 | + |
| 126 | + |
| 127 | + /// <summary> |
| 128 | + /// Deletes the specified entity from redis. |
| 129 | + /// </summary> |
| 130 | + /// <returns> true if successful or false if the entity cannot be found</returns> |
| 131 | + /// <param name="redis">Redis.</param> |
| 132 | + /// <param name="db">Db.</param> |
| 133 | + /// <param name="id">Identifier.</param> |
| 134 | + /// <typeparam name="T">The 1st type parameter.</typeparam> |
| 135 | + public static Task<bool> Delete<T>(this RedisConnection redis, int db, object id) |
| 136 | + { |
| 137 | + string urn = string.Format("urn:{0}:{1}", typeof(T).Name.ToLower(), id); |
| 138 | + var tasks = new Task<bool> [] { |
| 139 | + redis.Keys.Remove(db, urn), |
| 140 | + redis.Sets.Remove(db, string.Format("ids:{0}", typeof(T).Name.ToLower()), id.ToString()) |
| 141 | + }; |
| 142 | + |
| 143 | + return Task.Factory.ContinueWhenAll(tasks, t => tasks[0].Result && tasks[1].Result); |
| 144 | + } |
| 145 | + |
| 146 | + |
| 147 | + /// <summary> |
| 148 | + /// Deletes all entities of the given type from redis. |
| 149 | + /// </summary> |
| 150 | + /// <returns> the number of entities that were deleted</returns> |
| 151 | + public static Task<long> DeleteAll<T>(this RedisConnection redis, int db) |
| 152 | + { |
| 153 | + var task = redis.Sets.GetAllString(db, string.Format("ids:{0}", typeof(T).Name.ToLower())); |
| 154 | + |
| 155 | + return task.ContinueWith(ids => redis.Wait(redis.DeleteAll<T>(db, task.Result))); |
| 156 | + } |
| 157 | + |
| 158 | + |
| 159 | + /// <summary> |
| 160 | + /// Deletes a number of entities from redis at once. |
| 161 | + /// </summary> |
| 162 | + /// <returns> the number of entities that were deleted</returns> |
| 163 | + public static Task<long> DeleteAll<T>(this RedisConnection redis, int db, string [] ids) |
| 164 | + { |
| 165 | + string urn = string.Format("urn:{0}", typeof(T).Name.ToLower()); |
| 166 | + |
| 167 | + if (ids.Count() > 0) |
| 168 | + { |
| 169 | + var tasks = new Task [] { |
| 170 | + redis.Keys.Remove(db, ids.Select(i => string.Format("{0}:{1}", urn, i)).ToArray()), |
| 171 | + redis.Sets.Remove(db, string.Format("ids:{0}", typeof(T).Name.ToLower()), ids.Select(i => i.ToString()).ToArray()) |
| 172 | + }; |
| 173 | + |
| 174 | + return Task.Factory.ContinueWhenAll(tasks, t => (tasks[1] as Task<long>).Result); |
| 175 | + } |
| 176 | + |
| 177 | + // This bit can be replaced with Task.FromResult when using .NET 4.5 |
| 178 | + var result = new TaskCompletionSource<long>(); |
| 179 | + result.SetResult(0); |
| 180 | + |
| 181 | + return result.Task; |
| 182 | + } |
| 183 | + } |
| 184 | +} |
0 commit comments