public void AddOrUpdate(CacheKey key, TimedEntityTagHeaderValue eTag) { TimedEntityTagHeaderValue test; if (!TryGetValue(key, out test)) { var cacheKey = new PersistentCacheKey { Hash = key.Hash, RoutePattern = key.RoutePattern, CustomEtag = eTag.Tag, LastModified = eTag.LastModified, ResourceUri = key.ResourceUri }; _session.Store(cacheKey); } else { var cacheKey = _session.Query<PersistentCacheKey>() .Customize(x => x.WaitForNonStaleResults()) .FirstOrDefault(x => x.Hash == key.Hash); cacheKey.CustomEtag = eTag.Tag; cacheKey.LastModified = eTag.LastModified; cacheKey.ResourceUri = key.ResourceUri; cacheKey.RoutePattern = key.RoutePattern; _session.Store(cacheKey); } }
public void AddOrUpdate(CacheKey key, TimedEntityTagHeaderValue eTag) { TimedEntityTagHeaderValue test; if (!TryGetValue(key, out test)) { var cacheKey = new PersistentCacheKey { Hash = key.Hash, RoutePattern = key.RoutePattern, ETag = eTag.Tag, LastModified = eTag.LastModified }; using (var connection = new MongoEntiryStoreConnection(this.connectionString)) { connection.DocumentStore.Save(cacheKey); } } else { using (var connection = new MongoEntiryStoreConnection(this.connectionString)) { var cacheKey = connection.DocumentStore.AsQueryable().FirstOrDefault(x => x.Hash == key.Hash); if (cacheKey != null) { cacheKey.ETag = eTag.Tag; cacheKey.LastModified = eTag.LastModified; connection.DocumentStore.Save(cacheKey); } } } }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { string uri = request.RequestUri.ToString(); IEnumerable<string> varyHeaders; if(!VaryHeaderStore.TryGetValue(uri, out varyHeaders)) { varyHeaders = DefaultVaryHeaders; } var cacheKey = new CacheKey(uri, request.Headers.Where(x=> varyHeaders.Any(y=> y.Equals(x.Key, StringComparison.CurrentCultureIgnoreCase))) .SelectMany(z=>z.Value) ); HttpResponseMessage response; if(_cacheStore.TryGetValue(cacheKey, out response)) { response.RequestMessage = request; var taskCompletionSource = new TaskCompletionSource<HttpResponseMessage>(); taskCompletionSource.SetResult(response); return taskCompletionSource.Task; } // TODO: ..... REST) return base.SendAsync(request, cancellationToken); }
public void AddOrUpdate(CacheKey key, TimedEntityTagHeaderValue eTag) { TimedEntityTagHeaderValue test; if (!TryGetValue(key, out test)) { var cacheKey = new PersistentCacheKey() { Hash = key.Hash, RoutePattern = key.RoutePattern, ETag = eTag.Tag, LastModified = eTag.LastModified }; using (var session = _documentStore.OpenSession()) { session.Store(cacheKey); session.SaveChanges(); } } else { using (var session = _documentStore.OpenSession()) { var cacheKey = session.Query<PersistentCacheKey>() .Customize(x => x.WaitForNonStaleResults()) .FirstOrDefault(x => x.Hash == key.Hash); cacheKey.ETag = eTag.Tag; cacheKey.LastModified = eTag.LastModified; session.Store(cacheKey); session.SaveChanges(); } } }
public void AddTest() { var cacheKey = new CacheKey("/api/Cars", new[] { "1234", "abcdef" }); var documentStore = new EmbeddableDocumentStore() { RunInMemory = true }.Initialize(); new RavenDocumentsByEntityName().Execute(documentStore); var store = new RavenDbEntityTagStore(documentStore); var value = new TimedEntityTagHeaderValue("\"abcdef1234\"") { LastModified = DateTime.Now }; // first remove them store.RemoveAllByRoutePattern(cacheKey.RoutePattern); // add store.AddOrUpdate(cacheKey, value); // get TimedEntityTagHeaderValue dbValue; store.TryGetValue(cacheKey, out dbValue); Assert.AreEqual(value.Tag, dbValue.Tag); Assert.AreEqual(value.LastModified.ToString(), dbValue.LastModified.ToString()); }
public bool TryGetValue(CacheKey key, out TimedEntityTagHeaderValue eTag) { eTag = null; using (var connection = new SqlConnection(this._connectionString)) using (var command = new SqlCommand()) { connection.Open(); command.Connection = connection; command.CommandText = this.GetStoredProcedureName(StoredProcedureNames.GetCache); command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue(ColumnNames.CacheKeyHash, key.Hash); using (var reader = command.ExecuteReader( CommandBehavior.CloseConnection)) { if(!reader.HasRows) return false; reader.Read(); // there must be only one record eTag= new TimedEntityTagHeaderValue((string) reader[ColumnNames.ETag]) { LastModified = DateTime.SpecifyKind((DateTime)reader[ColumnNames.LastModified], DateTimeKind.Utc) }; return true; } } }
// TODO: !!! routePattern implementation needs to be changed to Cas public void AddOrUpdate(CacheKey key, TimedEntityTagHeaderValue eTag) { // add item _memcachedClient.ExecuteStore(StoreMode.Set, key.HashBase64, eTag.ToString()); // add route pattern if not there string keyForRoutePattern = GetKeyForRoutePattern(key.RoutePattern); string keyForResourceUri = GetKeyForResourceUri(key.ResourceUri); var routePatternEntries = GetRoutePatternEntries(key.RoutePattern); var resourceUriEntries = GetResourceUriEntries(key.ResourceUri); if (!routePatternEntries.Contains(key.HashBase64)) { var bytes = new List<byte>(); foreach (var routePatternEntry in routePatternEntries) { bytes.AddRange(new LengthedPrefixedString(routePatternEntry).ToByteArray()); } bytes.AddRange(new LengthedPrefixedString(key.HashBase64).ToByteArray()); _memcachedClient.ExecuteStore(StoreMode.Set, keyForRoutePattern, bytes.ToArray()); } if (!resourceUriEntries.Contains(key.HashBase64)) { var bytes = new List<byte>(); foreach (var routePatternEntry in resourceUriEntries) { bytes.AddRange(new LengthedPrefixedString(routePatternEntry).ToByteArray()); } bytes.AddRange(new LengthedPrefixedString(key.HashBase64).ToByteArray()); _memcachedClient.ExecuteStore(StoreMode.Set, keyForResourceUri, bytes.ToArray()); } }
public void AddOrUpdate(CacheKey key, HttpResponseMessage response) { // removing reference to request so that the request can get GCed response.RequestMessage = null; _responseCache.AddOrUpdate(key, response, (ky, resp) => resp); }
public void UpdateTest() { var cacheKey = new CacheKey("/api/Cars", new[] { "1234", "abcdef" }); var store = new SqlServerEntityTagStore(); var value = new TimedEntityTagHeaderValue("\"abcdef1234\"") { LastModified = DateTime.Now }; // first remove them store.RemoveAllByRoutePattern(cacheKey.RoutePattern); // add store.AddOrUpdate(cacheKey, value); // get TimedEntityTagHeaderValue dbValue; store.TryGetValue(cacheKey, out dbValue); value.LastModified = DateTime.Now.AddDays(-1); // update store.AddOrUpdate(cacheKey, value); // get TimedEntityTagHeaderValue dbValue2; store.TryGetValue(cacheKey, out dbValue2); Assert.AreEqual(dbValue.Tag, dbValue2.Tag); Assert.Greater(dbValue.LastModified, dbValue2.LastModified); Console.WriteLine(dbValue2.Tag); Console.WriteLine(dbValue2.LastModified); }
public static void TestCacheInvalidationForPost(string method) { const string relatedUrl = "http://api/SomeLocationUrl/"; // setup var locationUrl = new Uri(relatedUrl); var mocks = new MockRepository(); var request = new HttpRequestMessage(new HttpMethod(method), TestUrl); string routePattern = "http://myserver/api/stuffs/*"; var entityTagStore = mocks.StrictMock<IEntityTagStore>(); var cachingHandler = new CachingHandler(new HttpConfiguration(), entityTagStore) { }; var entityTagKey = new CacheKey(TestUrl, new string[0], routePattern); var response = new HttpResponseMessage(); response.Headers.Location = locationUrl; var invalidateCacheForPost = cachingHandler.PostInvalidationRule(entityTagKey, request, response); if(method == "POST") { entityTagStore.Expect(x => x.RemoveAllByRoutePattern("/SomeLocationUrl/")).Return(1); } mocks.ReplayAll(); // run invalidateCacheForPost(); // verify mocks.VerifyAll(); }
public static void AddCaching(string method, bool existsInStore, bool addVaryHeader, bool addLastModifiedHeader, bool alreadyHasLastModified, string[] varyByHeader) { // setup var mocks = new MockRepository(); var request = new HttpRequestMessage(new HttpMethod(method), TestUrl); request.Headers.Add(HttpHeaderNames.Accept, "text/xml"); request.Headers.Add(HttpHeaderNames.AcceptLanguage, "en-GB"); var entityTagStore = mocks.StrictMock<IEntityTagStore>(); var entityTagHeaderValue = new TimedEntityTagHeaderValue("\"12345678\""); var cachingHandler = new CachingHandler(entityTagStore, varyByHeader) { AddLastModifiedHeader = addLastModifiedHeader, AddVaryHeader = addVaryHeader, ETagValueGenerator = (x,y) => entityTagHeaderValue }; var entityTagKey = new CacheKey(TestUrl, new[] {"text/xml", "en-GB"}, TestUrl + "/*"); entityTagStore.Expect(x => x.TryGetValue(Arg<CacheKey>.Matches(etg => etg.ResourceUri == TestUrl), out Arg<TimedEntityTagHeaderValue>.Out(entityTagHeaderValue).Dummy)).Return(existsInStore); if (!existsInStore) { entityTagStore.Expect( x => x.AddOrUpdate(Arg<CacheKey>.Matches(etk => etk == entityTagKey), Arg<TimedEntityTagHeaderValue>.Matches(ethv => ethv.Tag == entityTagHeaderValue.Tag))); } var response = new HttpResponseMessage(); response.Content = new ByteArrayContent(new byte[0]); if (alreadyHasLastModified) response.Content.Headers.Add(HttpHeaderNames.LastModified, DateTimeOffset.Now.ToString("r")); var cachingContinuation = cachingHandler.AddCaching(entityTagKey, request, response, request.Headers); mocks.ReplayAll(); // run cachingContinuation(); // verify // test kast modified only if it is GET and PUT if (addLastModifiedHeader && method.IsIn("PUT", "GET")) { Assert.That(response.Content.Headers.Any(x => x.Key == HttpHeaderNames.LastModified), "LastModified does not exist"); } if (!addLastModifiedHeader && !alreadyHasLastModified) { Assert.That(!response.Content.Headers.Any(x => x.Key == HttpHeaderNames.LastModified), "LastModified exists"); } mocks.VerifyAll(); }
public void AddOrUpdate(CacheKey key, HttpResponseMessage response) { var memoryStream = new MemoryStream(); Task.Factory.StartNew(() => _serializer.SerializeAsync(response.ToTask(), memoryStream).Wait()).Wait(); // offloading memoryStream.Position = 0; var data = memoryStream.ToArray(); _database.StringSet(key.HashBase64, data); }
public void AddOrUpdate(CacheKey key, TimedEntityTagHeaderValue eTag) { cache.Put(key.HashBase64, eTag.ToString(), new[] { new DataCacheTag(key.ResourceUri), new DataCacheTag(key.RoutePattern), }, CacheRegion); }
public void AddOrUpdate(CacheKey key, HttpResponseMessage response) { var ms = new MemoryStream(); this.serializer.SerializeAsync(TaskHelpers.FromResult(response), ms) .Wait(); this.cache.Add(key.HashBase64, ms.ToArray(), CacheRegion); }
public void AddOrUpdate(CacheKey key, HttpResponseMessage response) { var ms = new MemoryStream(); _serializer.SerializeAsync(TaskHelpers.FromResult(response), ms) .Wait(); _memcachedClient.ExecuteStore(StoreMode.Set, key.HashBase64, ms.ToArray()); }
public bool TryGetValue(CacheKey key, out TimedEntityTagHeaderValue eTag) { var cacheObject = _cache.Get(key.HashBase64, _regionName) as string; if (!TimedEntityTagHeaderValue.TryParse(cacheObject, out eTag)) return false; return true; }
public void AddOrUpdate(CacheKey key, HttpResponseMessage response) { // removing reference to request so that the request can get GCed var req = response.RequestMessage; response.RequestMessage = null; var memoryStream = new MemoryStream(); _messageSerializer.SerializeAsync(TaskHelpers.FromResult(response), memoryStream).Wait(); response.RequestMessage = req; _responseCache.AddOrUpdate(key, memoryStream.ToArray(), (ky, old) => memoryStream.ToArray()); }
public void AddOrUpdate(CacheKey key, TimedEntityTagHeaderValue eTag) { _eTagCache.AddOrUpdate(key, eTag, (theKey, oldValue) => eTag); _routePatternCache.AddOrUpdate(key.RoutePattern, new HashSet<CacheKey>() { key }, (routePattern, hashSet) => { hashSet.Add(key); return hashSet; }); }
public bool TryGetValue(CacheKey key, out HttpResponseMessage response) { response = null; var result = _responseCache.Get(key.HashBase64); if (result!=null) { response = _messageSerializer.DeserializeToResponseAsync(new MemoryStream((byte[])result)).Result; } return result!=null; }
public void AddOrUpdate(CacheKey key, HttpResponseMessage response) { // removing reference to request so that the request can get GCed var req = response.RequestMessage; response.RequestMessage = null; var memoryStream = new MemoryStream(); Task.Factory.StartNew(() => _messageSerializer.SerializeAsync(TaskHelpers.FromResult(response), memoryStream)).Wait(); response.RequestMessage = req; _responseCache.Set(key.HashBase64, memoryStream.ToArray(), GetExpiry(response)); }
public bool TryGetValue(CacheKey key, out HttpResponseMessage response) { byte[] buffer; response = null; var result = _responseCache.TryGetValue(key, out buffer); if (result) { response = _messageSerializer.DeserializeToResponseAsync(new MemoryStream(buffer)).Result; } return result; }
public bool TryGetValue(CacheKey key, out TimedEntityTagHeaderValue eTag) { eTag = null; string value = _database.StringGet(key.HashBase64); if (!string.IsNullOrEmpty(value)) { return TimedEntityTagHeaderValue.TryParse(value, out eTag); } return false; }
public bool TryGetValue(CacheKey key, out HttpResponseMessage response) { response = null; var result = _responseCache.Get(key.HashBase64); if (result!=null) { Func<HttpResponseMessage> funky = () => _messageSerializer.DeserializeToResponseAsync(new MemoryStream((byte[]) result)).Result; response = Task.Factory.StartNew(funky).Result; } return result!=null; }
public bool TryGetValue(CacheKey key, out HttpResponseMessage response) { response = null; var operationResult = _memcachedClient.ExecuteGet<byte[]>(key.HashBase64); if (operationResult.HasValue) { var ms = new MemoryStream(operationResult.Value); response = _serializer.DeserializeToResponseAsync(ms).Result; } return operationResult.HasValue; }
public void AddOrUpdate(CacheKey key, HttpResponseMessage response) { var ms = new MemoryStream(); this.serializer.SerializeAsync(TaskHelpers.FromResult(response), ms) .Wait(); if (string.IsNullOrEmpty(_cacheRegion)) this._cache.Put(key.HashBase64, ms.ToArray()); else this._cache.Put(key.HashBase64, ms.ToArray(), _cacheRegion); }
public void AddOrUpdate(CacheKey key, HttpResponseMessage response) { try { cacheLock.EnterWriteLock(); var path = GetBaseFilePath(key.ResourceUri); WriteHeaders(path + HeadersSuffix, response); WriteContent(path + ContentSuffix, response); } finally { if (cacheLock.IsWriteLockHeld) cacheLock.ExitWriteLock(); } }
public void AddGetTest() { using (var store = new InMemoryEntityTagStore()) { var cacheKey = new CacheKey(Url, new[] { "Accept" }); var headerValue = new TimedEntityTagHeaderValue("\"abcdefghijkl\""); store.AddOrUpdate(cacheKey, headerValue); TimedEntityTagHeaderValue storedHeader; Assert.True(store.TryGetValue(cacheKey, out storedHeader)); Assert.AreEqual(headerValue.ToString(), storedHeader.ToString()); } }
public void AddRemoveTest() { using (var store = new InMemoryEntityTagStore()) { var cacheKey = new CacheKey(Url, new[] { "Accept" }); var headerValue = new TimedEntityTagHeaderValue("\"abcdefghijkl\""); store.AddOrUpdate(cacheKey, headerValue); store.TryRemove(cacheKey); TimedEntityTagHeaderValue storedHeader; Assert.False(store.TryGetValue(cacheKey, out storedHeader)); Assert.IsNull(storedHeader); } }
public void Test() { var store = new FileStore(_rootPath); List<Task> tasks = new List<Task>(); HttpResponseMessage responseMessage = null; for (int i = 0; i < ConcurrencyLevel; i++) { var message = GetMessage(i % ConcurrencyLevel); var cacheKey = new CacheKey(message.RequestUri.ToString(), new string[0]); tasks.Add(new Task( () => store.AddOrUpdate(cacheKey, _responseBuilder.Send(message)))); tasks.Add(new Task( () => store.TryGetValue(cacheKey, out responseMessage))); tasks.Add(new Task( () => store.TryRemove(cacheKey))); } var randomisedList = new List<Task>(); //while (tasks.Count>0) //{ // var i = _random.Next(tasks.Count); // randomisedList.Add(tasks[i]); // tasks.RemoveAt(i); //} //tasks = randomisedList; foreach (var task in tasks) { task.ContinueWith(t => { if (t.IsFaulted) Assert.Fail(t.Exception.ToString()); }); task. Start(); } DateTime tt = DateTime.Now; var waited = Task.WaitAll(tasks.ToArray(), WaitTimeOut); // Console.WriteLine("Total milliseconds " + (DateTime.Now - tt).TotalMilliseconds); if(!waited) Assert.Fail("Timed out"); }
/// <summary> /// Gets the value if exists /// ------------------------------------------ /// /// Steps: /// /// 1) Get the value /// 2) Update domain-based earliest access /// 3) Update global earliest access /// </summary> /// <param name="key"></param> /// <param name="response"></param> /// <returns></returns> public bool TryGetValue(CacheKey key, out HttpResponseMessage response) { HttpResponseMessage result = null; response = null; string entryKey = key.Hash.ToBase64(); if (!_database.KeyExists(entryKey)) return false; byte[] value = _database.StringGet(entryKey); var memoryStream = new MemoryStream(value); response = Task.Factory.StartNew(() => _serializer.DeserializeToResponseAsync(memoryStream).Result).Result; // offloading return true; }