Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Membase client now lives at https://github.com/couchbase/couchbase-ne…

  • Loading branch information...
commit b993e333f24a26a9cf9a668aafe42fcbd12f35ea 1 parent 0c6fe75
@enyim enyim authored
Showing with 10 additions and 4,501 deletions.
  1. +0 −4 DemoApp/DemoApp.csproj
  2. +2 −7 DemoApp/Program.cs
  3. +0 −11 Enyim.Caching.sln
  4. +0 −45 Membase/BasicMembaseOperationFactory.cs
  5. +0 −276 Membase/BucketConfigListener.cs
  6. +0 −32 Membase/Changes.mdown
  7. +0 −28 Membase/Config.transform
  8. +0 −92 Membase/ConfigHelper.cs
  9. +0 −40 Membase/Configuration/BucketPortType.cs
  10. +0 −44 Membase/Configuration/DefaultPerformanceMonitorFactory.cs
  11. +0 −75 Membase/Configuration/IMembaseClientConfiguration.cs
  12. +0 −33 Membase/Configuration/IMembasePerformanceMonitorFactory.cs
  13. +0 −293 Membase/Configuration/MembaseClientConfiguration.cs
  14. +0 −169 Membase/Configuration/MembaseClientSection.cs
  15. +0 −119 Membase/Configuration/ServersElement.cs
  16. +0 −42 Membase/Configuration/UriElement.cs
  17. +0 −68 Membase/Configuration/UriElementCollection.cs
  18. +0 −85 Membase/Configuration/UriValidator.cs
  19. +0 −28 Membase/Demo.config
  20. +0 −218 Membase/Deserialization.cs
  21. +0 −15 Membase/IMembaseOperationFactory.cs
  22. +0 −13 Membase/IMembaseServerPool.cs
  23. +0 −91 Membase/Membase.csproj
  24. +0 −19 Membase/Membase.nuspec
  25. +0 −464 Membase/MembaseClient.cs
  26. +0 −577 Membase/MembasePool.cs
  27. +0 −564 Membase/MessageStreamListener.cs
  28. +0 −11 Membase/OperationInterfaces.cs
  29. +0 −88 Membase/Operations/GetAndTouchOperation.cs
  30. +0 −240 Membase/Operations/SyncOperation.cs
  31. +0 −65 Membase/Operations/TouchOperation.cs
  32. +0 −35 Membase/Properties/AssemblyInfo.cs
  33. +0 −359 Membase/VBucketAwareOperationFactory.cs
  34. +0 −116 Membase/WebClientWithTimeout.cs
  35. +2 −27 MemcachedTest/ConfigTest.cs
  36. +0 −47 MemcachedTest/MembaseClientTest.cs
  37. +0 −41 MemcachedTest/MembaseMemcachedBucketTest.cs
  38. +0 −6 MemcachedTest/MemcachedTest.csproj
  39. +4 −8 TestApp/Program.cs
  40. +0 −4 TestApp/TestApp.csproj
  41. +2 −2 build/properties.ps1
View
4 DemoApp/DemoApp.csproj
@@ -39,10 +39,6 @@
<Project>{D438C0B3-A168-40B8-BDDD-61F0939DFF35}</Project>
<Name>Enyim.Caching</Name>
</ProjectReference>
- <ProjectReference Include="..\Membase\Membase.csproj">
- <Project>{708A2350-A26C-444D-B975-8164263951A7}</Project>
- <Name>Membase</Name>
- </ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>
View
9 DemoApp/Program.cs
@@ -1,13 +1,8 @@
using System;
-using System.Collections.Generic;
-using System.Text;
-using Enyim.Caching;
-using Enyim.Caching.Memcached;
using System.Net;
+using Enyim.Caching;
using Enyim.Caching.Configuration;
-using Membase;
-using Membase.Configuration;
-using System.Threading;
+using Enyim.Caching.Memcached;
namespace DemoApp
{
View
11 Enyim.Caching.sln
@@ -13,10 +13,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MemcachedTest", "MemcachedT
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DemoApp", "DemoApp\DemoApp.csproj", "{7225B6E0-A1FB-4F64-A5C5-1F640E21C90B}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Membase", "Membase\Membase.csproj", "{708A2350-A26C-444D-B975-8164263951A7}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestApp", "TestApp\TestApp.csproj", "{607B1927-A964-48B2-AEA3-6810D10A6831}"
-EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Enyim.Caching.Log4NetAdapter", "Enyim.Caching.Log4NetAdapter\Enyim.Caching.Log4NetAdapter.csproj", "{9D3F12E6-6BDD-4DED-8B25-D877780640B4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Enyim.Caching.NLogAdapter", "Enyim.Caching.NLogAdapter\Enyim.Caching.NLogAdapter.csproj", "{C96760B1-7CAD-4983-9FAD-EB00CD7A9FC6}"
@@ -37,13 +33,6 @@ Global
{7225B6E0-A1FB-4F64-A5C5-1F640E21C90B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7225B6E0-A1FB-4F64-A5C5-1F640E21C90B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7225B6E0-A1FB-4F64-A5C5-1F640E21C90B}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {708A2350-A26C-444D-B975-8164263951A7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {708A2350-A26C-444D-B975-8164263951A7}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {708A2350-A26C-444D-B975-8164263951A7}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {708A2350-A26C-444D-B975-8164263951A7}.Release|Any CPU.Build.0 = Release|Any CPU
- {607B1927-A964-48B2-AEA3-6810D10A6831}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {607B1927-A964-48B2-AEA3-6810D10A6831}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {607B1927-A964-48B2-AEA3-6810D10A6831}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9D3F12E6-6BDD-4DED-8B25-D877780640B4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9D3F12E6-6BDD-4DED-8B25-D877780640B4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9D3F12E6-6BDD-4DED-8B25-D877780640B4}.Release|Any CPU.ActiveCfg = Release|Any CPU
View
45 Membase/BasicMembaseOperationFactory.cs
@@ -1,45 +0,0 @@
-using System;
-using System.Collections.Generic;
-
-namespace Membase
-{
- internal class BasicMembaseOperationFactory : Enyim.Caching.Memcached.Protocol.Binary.BinaryOperationFactory, IMembaseOperationFactory
- {
- internal static readonly BasicMembaseOperationFactory Instance = new BasicMembaseOperationFactory();
-
- ITouchOperation IMembaseOperationFactory.Touch(string key, uint newExpiration)
- {
- return new TouchOperation(null, key, newExpiration);
- }
-
- IGetAndTouchOperation IMembaseOperationFactory.GetAndTouch(string key, uint newExpiration)
- {
- return new GetAndTouchOperation(null, key, newExpiration);
- }
-
- ISyncOperation IMembaseOperationFactory.Sync(SyncMode mode, IList<KeyValuePair<string, ulong>> keys, int replicationCount)
- {
- throw new NotSupportedException("Sync is not supported on memcached buckets.");
- }
- }
-}
-
-#region [ License information ]
-/* ************************************************************
- *
- * Copyright (c) 2010 Attila Kiskó, enyim.com
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * ************************************************************/
-#endregion
View
276 Membase/BucketConfigListener.cs
@@ -1,276 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Web.Script.Serialization;
-using System.Threading;
-using System.Net;
-using Enyim;
-using Membase.Configuration;
-
-namespace Membase
-{
- internal class BucketConfigListener
- {
- private static readonly Enyim.Caching.ILog log = Enyim.Caching.LogManager.GetLogger(typeof(BucketConfigListener));
-
- private Uri[] poolUrls;
- private string bucketName;
- private NetworkCredential credential;
- private int? lastHash;
- private ManualResetEvent mre;
- private MessageStreamListener listener;
-
- public BucketConfigListener(Uri[] poolUrls, string bucketName, string bucketPassword)
- {
- this.poolUrls = poolUrls;
- this.bucketName = String.IsNullOrEmpty(bucketName)
- ? "default"
- : bucketName;
-
- this.credential = bucketName == "default" || String.IsNullOrEmpty(bucketPassword)
- ? null
- : new NetworkCredential(bucketName, bucketPassword);
-
- this.Timeout = 10000;
- this.DeadTimeout = 10000;
-
- this.RetryCount = 0;
- this.RetryTimeout = new TimeSpan(0, 0, 0, 0, 500);
- }
-
- /// <summary>
- /// Connection timeout in milliseconds for connecting the pool.
- /// </summary>
- public int Timeout { get; set; }
-
- public int RetryCount { get; set; }
- public TimeSpan RetryTimeout { get; set; }
-
- /// <summary>
- /// Time to wait in milliseconds to reconnect to the pool when all nodes are down.
- /// </summary>
- public int DeadTimeout { get; set; }
-
- /// <summary>
- /// Raised when the pool's configuration changes.
- /// </summary>
- public event Action<ClusterConfig> ClusterConfigChanged;
-
- /// <summary>
- /// Starts listening for configuration data. This method blocks until the initial configuration is received. (Or until all pool urls fail.)
- /// </summary>
- public void Start()
- {
- var reset = this.mre = new ManualResetEvent(false);
-
- // subscribe to the config url
- this.listener = this.GetPooledListener();
-
- // this will be signaled by the config changed event handler
- reset.WaitOne();
-
- // set to null, then dispose, so RaiseConfigChanged will not
- // fail at Set when the config changes while we're cleaning up here
- this.mre = null;
- ((IDisposable)reset).Dispose();
- }
-
- public void Stop()
- {
- this.ReleaseListener(this.listener);
- this.listener = null;
- }
-
- private static readonly JavaScriptConverter[] KnownConverters = { ClusterNode.ConverterInstance };
-
- private void HandleMessage(string message)
- {
- // everything failed
- if (String.IsNullOrEmpty(message))
- {
- this.lastHash = null;
- this.RaiseConfigChanged(null);
- return;
- }
-
- // deserialize the buckets
- var jss = new JavaScriptSerializer();
- jss.RegisterConverters(KnownConverters);
-
- var config = jss.Deserialize<ClusterConfig>(message);
-
- // check if the config is the same as the previous
- // we cannot compare the messages because they have more information than we deserialize from them
- var configHash = config.GetHashCode();
-
- if (lastHash != configHash)
- {
- lastHash = configHash;
- this.RaiseConfigChanged(config);
- }
- else if (log.IsDebugEnabled)
- log.Debug("Last message was the same as current, ignoring.");
- }
-
- private void RaiseConfigChanged(ClusterConfig config)
- {
- var ccc = this.ClusterConfigChanged;
-
- // we got a new config, notify the pool to reload itself
- if (ccc != null)
- ccc(config);
-
- // trigger the event so Start stops blocking
- if (this.mre != null)
- this.mre.Set();
- }
-
- #region [ message listener pooling ]
- private static readonly object ListenerSync = new Object();
-
- // we pool and refcount the listeners here so we can safely dispose them when all clients are destroyed
- private static Dictionary<int, MessageStreamListener> listeners = new Dictionary<int, MessageStreamListener>();
- private static Dictionary<MessageStreamListener, ListenerInfo> listenerRefs = new Dictionary<MessageStreamListener, ListenerInfo>();
-
- private class ListenerInfo
- {
- public int RefCount;
- public int HashKey;
- }
-
- /// <summary>
- /// Unsubscibes from a pooled listener, and destrpys it if no additionals subscribers are present.
- /// </summary>
- /// <param name="listener"></param>
- private void ReleaseListener(MessageStreamListener listener)
- {
- lock (ListenerSync)
- {
- listener.Unsubscribe(this.HandleMessage);
-
- var info = listenerRefs[listener];
- if (info.RefCount == 1)
- {
- listenerRefs.Remove(listener);
- listeners.Remove(info.HashKey);
-
- try { using (listener) listener.Stop(); }
- catch { }
- }
- else
- {
- info.RefCount--;
- }
- }
- }
-
- /// <summary>
- /// Returns a MessageStreamListener instance based on this instance's configuratino (timeout, bucket name etc.)
- ///
- /// When multiple listeners are requested with the exact same parameters (usually when multiple clients are instantiated from the same configuration),
- /// the same listener will be returned each time.
- /// </summary>
- /// <returns></returns>
- private MessageStreamListener GetPooledListener()
- {
- // create a unique key based on the parameters
- // to find out if we already have a listener attached to this pool
- var hcc = new HashCodeCombiner();
-
- hcc.Add(this.Timeout);
- hcc.Add(this.DeadTimeout);
- hcc.Add(this.RetryCount);
- hcc.Add(this.RetryTimeout.GetHashCode());
- hcc.Add(this.bucketName.GetHashCode());
-
- if (credential != null)
- {
- hcc.Add((this.credential.UserName ?? String.Empty).GetHashCode());
- hcc.Add((this.credential.Password ?? String.Empty).GetHashCode());
- hcc.Add((this.credential.Domain ?? String.Empty).GetHashCode());
- }
-
- for (var i = 0; i < this.poolUrls.Length; i++)
- hcc.Add(this.poolUrls[i].GetHashCode());
-
- var hash = hcc.CurrentHash;
-
- MessageStreamListener retval;
-
- lock (ListenerSync)
- if (listeners.TryGetValue(hash, out retval))
- {
- listenerRefs[retval].RefCount++;
- retval.Subscribe(this.HandleMessage);
- }
- else
- {
- var name = this.bucketName;
-
- // create a new listener for the pool urls
- retval = new MessageStreamListener(poolUrls, (client, root) => ResolveBucketUri(client, root, name));
-
- retval.ConnectionTimeout = this.Timeout;
- retval.DeadTimeout = this.DeadTimeout;
- retval.Credentials = this.credential;
- retval.RetryCount = this.RetryCount;
- retval.RetryTimeout = this.RetryTimeout;
-
- retval.Subscribe(this.HandleMessage);
-
- listeners[hash] = retval;
- listenerRefs[retval] = new ListenerInfo { RefCount = 1, HashKey = hash };
-
- retval.Start();
- }
-
- return retval;
- }
-
- private static Uri ResolveBucketUri(WebClientWithTimeout client, Uri root, string bucketName)
- {
- try
- {
- var bucket = ConfigHelper.ResolveBucket(client, root, bucketName);
- if (bucket == null)
- return null;
-
- if (String.IsNullOrEmpty(bucket.streamingUri))
- {
- log.ErrorFormat("Url {0} for bucket {1} returned a config with no streamingUri", root, bucketName);
- return null;
- }
-
- return new Uri(root, bucket.streamingUri);
- }
- catch (Exception e)
- {
- log.Error("Error resolving streaming uri: " + root, e);
-
- return null;
- }
- }
-
- #endregion
- }
-}
-
-#region [ License information ]
-/* ************************************************************
- *
- * Copyright (c) 2010 Attila Kiskó, enyim.com
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * ************************************************************/
-#endregion
View
32 Membase/Changes.mdown
@@ -1,32 +0,0 @@
-# Membase Client Version History
-
-## Version 2.14
-
- * Fixed [Issue #69](https://github.com/enyim/EnyimMemcached/issues#issue/69) - Handle hist names in the cluster config
- * Fixed [Issue #71](https://github.com/enyim/EnyimMemcached/issues#issue/71) - Increasing number of vbucket errors
- * Fixed the CAS handling of Append and Prepend
- * Multigets now honor the receive timeout
-
-## Version 2.13
-
- * Fixed [Issue #65](https://github.com/enyim/EnyimMemcached/issues#issue/65) - Getting multiple keys twice in a row fails.
-
-## Version 2.12
-
- * Includes all the changes from Enyim.Caching 2.9
- * Fixed [Issue #60](https://github.com/enyim/EnyimMemcached/issues#issue/60) - Bucket and BucketPassword not picked up from config
- * Membase 1.7 support:
- * Get&Touch allows you to extend the expiration of an item without retrieving it.
- * Sync allows you to wait for an item to be replicated, changed, persisted, etc. _Please note: the maximum time to wait is ~2.5 sec and this limit is enforced by the Membase server (by closing the connection) so use it only for short waits._
-
-## Version 2.11
-
- * Includes all the changes from Enyim.Caching 2.8 (perfmon, bugfixes)
- * Cleaned up the credentials handling: only BucketName and BucketPasswords will be used, Credentials is obsolete. This way you do not have to specify your Membase cluster admin password in config files. See the wiki for more information.
-
-## Version 2.10
-
- * Changed the namespace to Membase and the client's name to MembaseClient to follow the name change of the product (& the company).
- * Includes all the changes from Enyim.Caching 2.7
-
-Make sure you update your configuration files accordingly!
View
28 Membase/Config.transform
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8" ?>
-<configuration>
- <configSections>
- <section name="membase" type="Membase.Configuration.MembaseClientSection, Membase" />
- </configSections>
-
- <membase>
- <!--
- Please read the documentation first:
- http://github.com/enyim/EnyimMemcached/wiki/MembaseClient-configuration
-
- Use this section as a template if you're connecting to Membase Servers.
- Note: you must have the top-level membase section if you're using the parameterless constructor of MembaseClient.
- -->
- <servers bucket="enyim" bucketPassword="password" retryCount="2" retryTimeout="00:00:02">
- <!--
- Provide at least 2-3 urls from your cluster.
- Usually you only need to change the host, except when connecting to older versions.
- Membase uses port 8091, while the NorthScale Memcached Server (1.0.3) uses 8080
- -->
- <add uri="http://192.168.2.202:8091/pools/default" />
- <add uri="http://192.168.2.200:8091/pools/default" />
- </servers>
- <!-- the client waits deadTmimeout time to reconnect to the pool when all the specified urls are down -->
- <socketPool connectionTimeout="00:00:10" deadTimeout="00:00:10" />
- </membase>
-
-</configuration>
View
92 Membase/ConfigHelper.cs
@@ -1,92 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Net;
-using System.Text;
-using System.Web.Script.Serialization;
-using System.IO;
-using System.Text.RegularExpressions;
-using Membase.Configuration;
-
-namespace Membase
-{
- internal static class ConfigHelper
- {
- private static readonly Enyim.Caching.ILog log = Enyim.Caching.LogManager.GetLogger(typeof(ConfigHelper));
-
- /// <summary>
- /// Deserializes the content of an url as a json object
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="uri"></param>
- /// <returns></returns>
- private static T DeserializeUri<T>(WebClient client, Uri uri, IEnumerable<JavaScriptConverter> converters)
- {
- var info = client.DownloadString(uri);
- var jss = new JavaScriptSerializer();
-
- if (converters != null)
- jss.RegisterConverters(converters);
-
- return jss.Deserialize<T>(info);
- }
-
- private static readonly JavaScriptConverter[] JSC = { ClusterNode.ConverterInstance };
-
- private static ClusterInfo GetClusterInfo(WebClient client, Uri clusterUrl)
- {
- var info = DeserializeUri<ClusterInfo>(client, clusterUrl, JSC);
-
- if (info == null)
- throw new ArgumentException("invalid pool url: " + clusterUrl);
-
- if (info.buckets == null || String.IsNullOrEmpty(info.buckets.uri))
- throw new ArgumentException("got an invalid response, missing { buckets : { uri : '' } }");
-
- return info;
- }
-
- /// <summary>
- /// Asks the cluster for the specified bucket's configuration.
- /// </summary>
- /// <param name="poolUri"></param>
- /// <param name="name"></param>
- /// <returns></returns>
- public static ClusterConfig ResolveBucket(WebClient client, Uri poolUri, string name)
- {
- var info = ConfigHelper.GetClusterInfo(client, poolUri);
- var root = new Uri(poolUri, info.buckets.uri);
-
- var allBuckets = ConfigHelper.DeserializeUri<ClusterConfig[]>(client, root, JSC);
- var retval = allBuckets.FirstOrDefault(b => b.name == name);
-
- if (retval == null)
- {
- if (log.IsWarnEnabled) log.WarnFormat("Could not find the pool '{0}' at {1}", name, poolUri);
- }
- else if (log.IsDebugEnabled) log.DebugFormat("Found config for bucket {0}.", name);
-
- return retval;
- }
- }
-}
-
-#region [ License information ]
-/* ************************************************************
- *
- * Copyright (c) 2010 Attila Kiskó, enyim.com
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * ************************************************************/
-#endregion
View
40 Membase/Configuration/BucketPortType.cs
@@ -1,40 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace Membase.Configuration
-{
- public enum BucketPortType
- {
- /// <summary>
- /// Connect to the nodes using moxy
- /// </summary>
- Proxy,
-
- /// <summary>
- /// Connect to the nodes directly using the Memcached port
- /// </summary>
- Direct
- }
-}
-
-#region [ License information ]
-/* ************************************************************
- *
- * Copyright (c) 2010 Attila Kiskó, enyim.com
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * ************************************************************/
-#endregion
View
44 Membase/Configuration/DefaultPerformanceMonitorFactory.cs
@@ -1,44 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Net;
-using Enyim.Caching.Configuration;
-using Enyim.Caching.Memcached;
-
-namespace Membase.Configuration
-{
- public class DefaultPerformanceMonitorFactory : IMembasePerformanceMonitorFactory
- {
- private string prefix;
-
- IPerformanceMonitor IMembasePerformanceMonitorFactory.Create(string bucket)
- {
- return new DefaultPerformanceMonitor(this.prefix + (String.IsNullOrEmpty(bucket) ? "default" : bucket));
- }
-
- void IProvider.Initialize(Dictionary<string, string> parameters)
- {
- if (parameters != null)
- parameters.TryGetValue("prefix", out this.prefix);
- }
- }
-}
-
-#region [ License information ]
-/* ************************************************************
- *
- * Copyright (c) 2010 Attila Kiskó, enyim.com
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * ************************************************************/
-#endregion
View
75 Membase/Configuration/IMembaseClientConfiguration.cs
@@ -1,75 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Net;
-using Enyim.Caching.Configuration;
-using Enyim.Caching.Memcached;
-
-namespace Membase.Configuration
-{
- public interface IMembaseClientConfiguration
- {
- /// <summary>
- /// Gets the name of the bucket to be used. If not specified the "default" bucket will be used.
- /// </summary>
- string Bucket { get; }
-
- /// <summary>
- /// Gets the pasword used to connect to the bucket.
- /// </summary>
- /// <remarks> If null, the bucket name will be used. Set to String.Empty to use an empty password.</remarks>
- string BucketPassword { get; }
-
- /// <summary>
- /// Gets a list of <see cref="T:IPEndPoint"/> each representing a Memcached server in the pool.
- /// </summary>
- IList<Uri> Urls { get; }
-
- /// <summary>
- /// Gets the configuration of the socket pool.
- /// </summary>
- ISocketPoolConfiguration SocketPool { get; }
-
- /// <summary>
- /// Creates an <see cref="T:Enyim.Caching.Memcached.IMemcachedKeyTransformer"/> instance which will be used to convert item keys for Memcached.
- /// </summary>
- IMemcachedKeyTransformer CreateKeyTransformer();
-
- /// <summary>
- /// Creates an <see cref="T:Enyim.Caching.Memcached.IMemcachedNodeLocator"/> instance which will be used to assign items to Memcached nodes.
- /// </summary>
- IMemcachedNodeLocator CreateNodeLocator();
-
- /// <summary>
- /// Creates an <see cref="T:Enyim.Caching.Memcached.ITranscoder"/> instance which will be used to serialize or deserialize items.
- /// </summary>
- ITranscoder CreateTranscoder();
-
- /// <summary>
- /// Creates an <see cref="T:Enyim.Caching.Memcached.IPerformanceMonitor"/> instance which will be used to monitor the performance of the client.
- /// </summary>
- IPerformanceMonitor CreatePerformanceMonitor();
-
- TimeSpan RetryTimeout { get; }
- int RetryCount { get; }
- }
-}
-
-#region [ License information ]
-/* ************************************************************
- *
- * Copyright (c) 2010 Attila Kiskó, enyim.com
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * ************************************************************/
-#endregion
View
33 Membase/Configuration/IMembasePerformanceMonitorFactory.cs
@@ -1,33 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Net;
-using Enyim.Caching.Configuration;
-using Enyim.Caching.Memcached;
-
-namespace Membase.Configuration
-{
- public interface IMembasePerformanceMonitorFactory: IProvider
- {
- IPerformanceMonitor Create(string bucket);
- }
-}
-
-#region [ License information ]
-/* ************************************************************
- *
- * Copyright (c) 2010 Attila Kiskó, enyim.com
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * ************************************************************/
-#endregion
View
293 Membase/Configuration/MembaseClientConfiguration.cs
@@ -1,293 +0,0 @@
-using System;
-using System.Linq;
-using System.Collections.Generic;
-using System.Net;
-using Enyim.Caching.Configuration;
-using Enyim.Caching.Memcached;
-using Enyim.Reflection;
-
-namespace Membase.Configuration
-{
- /// <summary>
- /// Configuration class
- /// </summary>
- public class MembaseClientConfiguration : IMembaseClientConfiguration
- {
- private Type nodeLocator;
- private ITranscoder transcoder;
- private IMemcachedKeyTransformer keyTransformer;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="T:MemcachedClientConfiguration"/> class.
- /// </summary>
- public MembaseClientConfiguration()
- {
- this.Urls = new List<Uri>();
-
- this.SocketPool = new SocketPoolConfiguration();
- }
-
- /// <summary>
- /// Gets or sets the name of the bucket to be used. Can be overriden at the pool's constructor, and if not specified the "default" bucket will be used.
- /// </summary>
- public string Bucket { get; set; }
-
- /// <summary>
- /// Gets or sets the pasword used to connect to the bucket.
- /// </summary>
- /// <remarks> If null, the bucket name will be used. Set to String.Empty to use an empty password.</remarks>
- public string BucketPassword { get; set; }
-
- /// <summary>
- /// Gets a list of <see cref="T:IPEndPoint"/> each representing a Memcached server in the pool.
- /// </summary>
- public IList<Uri> Urls { get; private set; }
-
- [Obsolete("Please use the bucket name&password for specifying credentials. This property has no use now, and will be completely removed in the next version.", true)]
- public NetworkCredential Credentials { get; set; }
-
- /// <summary>
- /// Gets the configuration of the socket pool.
- /// </summary>
- public ISocketPoolConfiguration SocketPool { get; private set; }
-
- /// <summary>
- /// Gets or sets the <see cref="T:Enyim.Caching.Memcached.IMemcachedKeyTransformer"/> which will be used to convert item keys for Memcached.
- /// </summary>
- public IMemcachedKeyTransformer KeyTransformer
- {
- get { return this.keyTransformer ?? (this.keyTransformer = new DefaultKeyTransformer()); }
- set { this.keyTransformer = value; }
- }
-
- /// <summary>
- /// Gets or sets the Type of the <see cref="T:Enyim.Caching.Memcached.IMemcachedNodeLocator"/> which will be used to assign items to Memcached nodes.
- /// </summary>
- /// <remarks>If both <see cref="M:NodeLocator"/> and <see cref="M:NodeLocatorFactory"/> are assigned then the latter takes precedence.</remarks>
- public Type NodeLocator
- {
- get { return this.nodeLocator; }
- set
- {
- ConfigurationHelper.CheckForInterface(value, typeof(IMemcachedNodeLocator));
- this.nodeLocator = value;
- }
- }
-
- /// <summary>
- /// Gets or sets the NodeLocatorFactory instance which will be used to create a new IMemcachedNodeLocator instances.
- /// </summary>
- /// <remarks>If both <see cref="M:NodeLocator"/> and <see cref="M:NodeLocatorFactory"/> are assigned then the latter takes precedence.</remarks>
- public IProviderFactory<IMemcachedNodeLocator> NodeLocatorFactory { get; set; }
-
- /// <summary>
- /// Gets or sets the <see cref="T:Enyim.Caching.Memcached.ITranscoder"/> which will be used serialzie or deserialize items.
- /// </summary>
- public ITranscoder Transcoder
- {
- get { return this.transcoder ?? (this.transcoder = new DefaultTranscoder()); }
- set { this.transcoder = value; }
- }
-
- /// <summary>
- /// Gets or sets the <see cref="T:Enyim.Caching.Memcached.IPerformanceMonitor"/> instance which will be used monitor the performance of the client.
- /// </summary>
- public IMembasePerformanceMonitorFactory PerformanceMonitorFactory { get; set; }
-
- public int RetryCount { get; set; }
- public TimeSpan RetryTimeout { get; set; }
-
- #region [ interface ]
-
- IList<Uri> IMembaseClientConfiguration.Urls
- {
- get { return this.Urls; }
- }
-
- ISocketPoolConfiguration IMembaseClientConfiguration.SocketPool
- {
- get { return this.SocketPool; }
- }
-
- IMemcachedKeyTransformer IMembaseClientConfiguration.CreateKeyTransformer()
- {
- return this.KeyTransformer;
- }
-
- IMemcachedNodeLocator IMembaseClientConfiguration.CreateNodeLocator()
- {
- var f = this.NodeLocatorFactory;
- if (f != null) return f.Create();
-
- return this.NodeLocator == null
- ? new KetamaNodeLocator()
- : (IMemcachedNodeLocator)FastActivator.Create(this.NodeLocator);
- }
-
- ITranscoder IMembaseClientConfiguration.CreateTranscoder()
- {
- return this.Transcoder;
- }
-
- string IMembaseClientConfiguration.Bucket
- {
- get { return this.Bucket; }
- }
-
- int IMembaseClientConfiguration.RetryCount
- {
- get { return this.RetryCount; }
- }
-
- TimeSpan IMembaseClientConfiguration.RetryTimeout
- {
- get { return this.RetryTimeout; }
- }
-
- string IMembaseClientConfiguration.BucketPassword
- {
- get { return this.BucketPassword; }
- }
-
- IPerformanceMonitor IMembaseClientConfiguration.CreatePerformanceMonitor()
- {
- return this.PerformanceMonitorFactory == null
- ? null
- : this.PerformanceMonitorFactory.Create(this.Bucket);
- }
-
- #endregion
- }
-
- internal class ReadOnlyConfig : IMembaseClientConfiguration
- {
- private string bucket;
- private string bucketPassword;
- private Uri[] urls;
- private TimeSpan retryTimeout;
- private int retryCount;
- private ISocketPoolConfiguration spc;
-
- private IMembaseClientConfiguration original;
-
- public ReadOnlyConfig(IMembaseClientConfiguration original)
- {
- this.bucket = original.Bucket;
- this.bucketPassword = original.BucketPassword;
- this.urls = original.Urls.ToArray();
-
- this.retryCount = original.RetryCount;
- this.retryTimeout = original.RetryTimeout;
-
- this.spc = new SPC(original.SocketPool);
-
- this.original = original;
- }
-
- public void OverrideBucket(string bucketName, string bucketPassword)
- {
- this.bucket = bucketName;
- this.bucketPassword = bucketPassword;
- }
-
- string IMembaseClientConfiguration.Bucket
- {
- get { return this.bucket; }
- }
-
- string IMembaseClientConfiguration.BucketPassword
- {
- get { return this.bucketPassword; }
- }
-
- IList<Uri> IMembaseClientConfiguration.Urls
- {
- get { return this.urls; }
- }
-
- ISocketPoolConfiguration IMembaseClientConfiguration.SocketPool
- {
- get { return this.spc; }
- }
-
- IMemcachedKeyTransformer IMembaseClientConfiguration.CreateKeyTransformer()
- {
- return this.original.CreateKeyTransformer();
- }
-
- IMemcachedNodeLocator IMembaseClientConfiguration.CreateNodeLocator()
- {
- return this.original.CreateNodeLocator();
- }
-
- ITranscoder IMembaseClientConfiguration.CreateTranscoder()
- {
- return this.original.CreateTranscoder();
- }
-
- IPerformanceMonitor IMembaseClientConfiguration.CreatePerformanceMonitor()
- {
- return this.original.CreatePerformanceMonitor();
- }
-
- TimeSpan IMembaseClientConfiguration.RetryTimeout
- {
- get { return this.retryTimeout; }
- }
-
- int IMembaseClientConfiguration.RetryCount
- {
- get { return this.retryCount; }
- }
-
- private class SPC : ISocketPoolConfiguration
- {
- private TimeSpan connectionTimeout;
- private TimeSpan deadTimeout;
- private int maxPoolSize;
- private int minPoolSize;
- private TimeSpan queueTimeout;
- private TimeSpan receiveTimeout;
- private INodeFailurePolicyFactory fpf;
-
- public SPC(ISocketPoolConfiguration original)
- {
- this.connectionTimeout = original.ConnectionTimeout;
- this.deadTimeout = original.DeadTimeout;
- this.maxPoolSize = original.MaxPoolSize;
- this.minPoolSize = original.MinPoolSize;
- this.queueTimeout = original.QueueTimeout;
- this.receiveTimeout = original.ReceiveTimeout;
- this.fpf = original.FailurePolicyFactory;
- }
-
- int ISocketPoolConfiguration.MinPoolSize { get { return this.minPoolSize; } set { } }
- int ISocketPoolConfiguration.MaxPoolSize { get { return this.maxPoolSize; } set { } }
- TimeSpan ISocketPoolConfiguration.ConnectionTimeout { get { return this.connectionTimeout; } set { } }
- TimeSpan ISocketPoolConfiguration.QueueTimeout { get { return this.queueTimeout; } set { } }
- TimeSpan ISocketPoolConfiguration.ReceiveTimeout { get { return this.receiveTimeout; } set { } }
- TimeSpan ISocketPoolConfiguration.DeadTimeout { get { return this.deadTimeout; } set { } }
- INodeFailurePolicyFactory ISocketPoolConfiguration.FailurePolicyFactory { get { return this.fpf; } set { } }
- }
- }
-}
-
-#region [ License information ]
-/* ************************************************************
- *
- * Copyright (c) 2010 Attila Kiskó, enyim.com
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * ************************************************************/
-#endregion
View
169 Membase/Configuration/MembaseClientSection.cs
@@ -1,169 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Configuration;
-using System.Net;
-using System.Web.Configuration;
-using Enyim.Caching.Configuration;
-using Enyim.Caching.Memcached;
-
-namespace Membase.Configuration
-{
- /// <summary>
- /// Configures the <see cref="T:MembaseClient"/>. This class cannot be inherited.
- /// </summary>
- public class MembaseClientSection : ConfigurationSection, IMembaseClientConfiguration
- {
- [ConfigurationProperty("servers", IsRequired = true)]
- public ServersElement Servers
- {
- get { return (ServersElement)base["servers"]; }
- set { base["servers"] = value; }
- }
-
- /// <summary>
- /// Gets or sets the configuration of the socket pool.
- /// </summary>
- [ConfigurationProperty("socketPool", IsRequired = false)]
- public SocketPoolElement SocketPool
- {
- get { return (SocketPoolElement)base["socketPool"]; }
- set { base["socketPool"] = value; }
- }
-
- /// <summary>
- /// Gets or sets the <see cref="T:Enyim.Caching.Memcached.IMemcachedNodeLocator"/> which will be used to assign items to Memcached nodes.
- /// </summary>
- [ConfigurationProperty("locator", IsRequired = false)]
- public ProviderElement<IMemcachedNodeLocator> NodeLocator
- {
- get { return (ProviderElement<IMemcachedNodeLocator>)base["locator"]; }
- set { base["locator"] = value; }
- }
-
- /// <summary>
- /// Gets or sets the <see cref="T:Enyim.Caching.Memcached.IMemcachedKeyTransformer"/> which will be used to convert item keys for Memcached.
- /// </summary>
- [ConfigurationProperty("keyTransformer", IsRequired = false)]
- public ProviderElement<IMemcachedKeyTransformer> KeyTransformer
- {
- get { return (ProviderElement<IMemcachedKeyTransformer>)base["keyTransformer"]; }
- set { base["keyTransformer"] = value; }
- }
-
- /// <summary>
- /// Gets or sets the <see cref="T:Enyim.Caching.Memcached.ITranscoder"/> which will be used serialize or deserialize items.
- /// </summary>
- [ConfigurationProperty("transcoder", IsRequired = false)]
- public ProviderElement<ITranscoder> Transcoder
- {
- get { return (ProviderElement<ITranscoder>)base["transcoder"]; }
- set { base["transcoder"] = value; }
- }
-
- /// <summary>
- /// Gets or sets the <see cref="T:Enyim.Caching.Memcached.IPerformanceMonitor"/> which will be used monitor the performance of the client.
- /// </summary>
- [ConfigurationProperty("performanceMonitor", IsRequired = false)]
- public FactoryElement<IMembasePerformanceMonitorFactory> PerformanceMonitorFactory
- {
- get { return (FactoryElement<IMembasePerformanceMonitorFactory>)base["performanceMonitor"]; }
- set { base["performanceMonitor"] = value; }
- }
-
- /// <summary>
- /// Called after deserialization.
- /// </summary>
- protected override void PostDeserialize()
- {
- WebContext hostingContext = base.EvaluationContext.HostingContext as WebContext;
-
- if (hostingContext != null && hostingContext.ApplicationLevel == WebApplicationLevel.BelowApplication)
- {
- throw new InvalidOperationException("The " + this.SectionInformation.SectionName + " section cannot be defined below the application level.");
- }
- }
-
- #region [ interface ]
-
- IList<Uri> IMembaseClientConfiguration.Urls
- {
- get { return this.Servers.Urls.ToUriCollection(); }
- }
-
- ISocketPoolConfiguration IMembaseClientConfiguration.SocketPool
- {
- get { return this.SocketPool; }
- }
-
- IMemcachedKeyTransformer IMembaseClientConfiguration.CreateKeyTransformer()
- {
- return this.KeyTransformer.CreateInstance() ?? new DefaultKeyTransformer();
- }
-
- IMemcachedNodeLocator IMembaseClientConfiguration.CreateNodeLocator()
- {
- return this.NodeLocator.CreateInstance() ?? new KetamaNodeLocator();
- }
-
- ITranscoder IMembaseClientConfiguration.CreateTranscoder()
- {
- return this.Transcoder.CreateInstance() ?? new DefaultTranscoder();
- }
-
- IPerformanceMonitor IMembaseClientConfiguration.CreatePerformanceMonitor()
- {
- var pmf = this.PerformanceMonitorFactory;
- if (pmf.ElementInformation.IsPresent)
- {
- var f = pmf.CreateInstance();
- if (f != null)
- return f.Create(this.Servers.Bucket);
- }
-
- return null;
- }
-
- string IMembaseClientConfiguration.Bucket
- {
- get { return this.Servers.Bucket; }
- }
-
- string IMembaseClientConfiguration.BucketPassword
- {
- get { return this.Servers.BucketPassword; }
- }
-
- int IMembaseClientConfiguration.RetryCount
- {
- get { return this.Servers.RetryCount; }
- }
-
- TimeSpan IMembaseClientConfiguration.RetryTimeout
- {
- get { return this.Servers.RetryTimeout; }
- }
-
- #endregion
- }
-}
-
-#region [ License information ]
-/* ************************************************************
- *
- * Copyright (c) 2010 Attila Kiskó, enyim.com
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * ************************************************************/
-#endregion
View
119 Membase/Configuration/ServersElement.cs
@@ -1,119 +0,0 @@
-using System;
-using System.ComponentModel;
-using System.Configuration;
-
-namespace Membase.Configuration
-{
- /// <summary>
- /// Configures the <see cref="T:MemcachedClient"/>. This class cannot be inherited.
- /// </summary>
- public sealed class ServersElement : ConfigurationElement
- {
- private static readonly object NullObject = new object();
-
- protected override void Init()
- {
- base.Init();
-
- base["bucketPassword"] = NullObject;
- }
-
- /// <summary>
- /// Gets or sets the name of the bucket to be used. Can be overriden at the pool's constructor, and if not specified the "default" bucket will be used.
- /// </summary>
- [ConfigurationProperty("bucket", IsRequired = false)]
- public string Bucket
- {
- get { return (string)base["bucket"]; }
- set { base["bucket"] = value; }
- }
-
- /// <summary>
- /// Gets or sets the pasword used to connect to the bucket.
- /// </summary>
- /// <remarks> If null, the bucket name will be used. Set to String.Empty to use an empty password.</remarks>
- [ConfigurationProperty("bucketPassword", IsRequired = false)]
- public string BucketPassword
- {
- get { var v = base["bucketPassword"]; return v == NullObject ? null : v as string; }
- set { base["bucketPassword"] = value; }
- }
-
- /// <summary>
- /// (Obsolete) Gets or sets the user name used to connect to a secured cluster
- /// </summary>
- [ConfigurationProperty("userName", IsRequired = false)]
- [Obsolete("Please use the bucket name&password for specifying credentials. This property has no use now, and will be completely removed in the next version.", true)]
- public string UserName
- {
- get { return (string)base["userName"]; }
- set { base["userName"] = value; }
- }
-
- /// <summary>
- /// (Obsolete) Gets or sets the password used to connect to a secured cluster
- /// </summary>
- [ConfigurationProperty("password", IsRequired = false)]
- [Obsolete("Please use the bucket name&password for specifying credentials. This property has no use now, and will be completely removed in the next version.", true)]
- public string Password
- {
- get { return (string)base["password"]; }
- set { base["password"] = value; }
- }
-
- /// <summary>
- /// Returns a collection of nodes in the cluster the client should use to retrieve the Memcached nodes.
- /// </summary>
- [ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
- public UriElementCollection Urls
- {
- get { return (UriElementCollection)base[""]; }
- }
-
- /// <summary>
- /// Determines which port the client should use to connect to the nodes
- /// </summary>
- [ConfigurationProperty("port", IsRequired = false, DefaultValue = BucketPortType.Direct)]
- [Obsolete]
- public BucketPortType Port
- {
- get { return (BucketPortType)base["port"]; }
- set { base["port"] = value; }
- }
-
- [ConfigurationProperty("retryCount", IsRequired = false, DefaultValue = 0)]
- public int RetryCount
- {
- get { return (int)base["retryCount"]; }
- set { base["retryCount"] = value; }
- }
-
- [ConfigurationProperty("retryTimeout", IsRequired = false, DefaultValue = "00:00:02"), PositiveTimeSpanValidator]
- [TypeConverter(typeof(TimeSpanConverter))]
- public TimeSpan RetryTimeout
- {
- get { return (TimeSpan)base["retryTimeout"]; }
- set { base["retryTimeout"] = value; }
- }
- }
-}
-
-#region [ License information ]
-/* ************************************************************
- *
- * Copyright (c) 2010 Attila Kiskó, enyim.com
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * ************************************************************/
-#endregion
View
42 Membase/Configuration/UriElement.cs
@@ -1,42 +0,0 @@
-using System;
-using System.ComponentModel;
-using System.Configuration;
-
-namespace Membase.Configuration
-{
- /// <summary>
- /// Represents a configuration element that contains a Memcached node address. This class cannot be inherited.
- /// </summary>
- public sealed class UriElement : ConfigurationElement
- {
- /// <summary>
- /// Gets or sets the ip address of the node.
- /// </summary>
- [ConfigurationProperty("uri", IsRequired = true, IsKey = true), UriValidator, TypeConverter(typeof(UriConverter))]
- public Uri Uri
- {
- get { return (Uri)base["uri"]; }
- set { base["uri"] = value; }
- }
- }
-}
-
-#region [ License information ]
-/* ************************************************************
- *
- * Copyright (c) 2010 Attila Kiskó, enyim.com
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * ************************************************************/
-#endregion
View
68 Membase/Configuration/UriElementCollection.cs
@@ -1,68 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Configuration;
-
-namespace Membase.Configuration
-{
- /// <summary>
- /// Represents a collection of <see cref="T:EndPointElement"/> instances. This class cannot be inherited.
- /// </summary>
- public sealed class UriElementCollection : ConfigurationElementCollection
- {
- /// <summary>
- /// Creates a new <see cref="T:ConfigurationElement"/>.
- /// </summary>
- /// <returns>A new <see cref="T:ConfigurationElement"/>.</returns>
- protected override ConfigurationElement CreateNewElement()
- {
- return new UriElement();
- }
-
- /// <summary>
- /// Gets the element key for a specified configuration element when overridden in a derived class.
- /// </summary>
- /// <param name="element">The <see cref="T:ConfigurationElement"/> to return the key for. </param>
- /// <returns>An <see cref="T:Object"/> that acts as the key for the specified <see cref="T:ConfigurationElement"/>.</returns>
- protected override object GetElementKey(ConfigurationElement element)
- {
- UriElement e = (UriElement)element;
-
- return e.Uri;
- }
-
- /// <summary>
- /// Helper method; converts the collection into an <see cref="T:IPEndPoint"/> collection for the interface implementation.
- /// </summary>
- /// <returns></returns>
- public IList<Uri> ToUriCollection()
- {
- List<Uri> retval = new List<Uri>(this.Count);
- foreach (UriElement e in this)
- {
- retval.Add(e.Uri);
- }
-
- return retval.AsReadOnly();
- }
- }
-}
-
-#region [ License information ]
-/* ************************************************************
- *
- * Copyright (c) 2010 Attila Kiskó, enyim.com
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * ************************************************************/
-#endregion
View
85 Membase/Configuration/UriValidator.cs
@@ -1,85 +0,0 @@
-using System;
-using System.Configuration;
-
-namespace Membase.Configuration
-{
- public sealed class UriValidatorAttribute : ConfigurationValidatorAttribute
- {
- public UriValidatorAttribute() { }
-
- public override ConfigurationValidatorBase ValidatorInstance
- {
- get { return new UriValidator(); }
- }
-
- #region [ UriValidator ]
- private class UriValidator : ConfigurationValidatorBase
- {
- public UriValidator() { }
-
- public override bool CanValidate(Type type)
- {
- return (type.TypeHandle.Equals(typeof(Uri).TypeHandle) || base.CanValidate(type));
- }
-
- public override void Validate(object value)
- {
- if (value != null && (value is string))
- {
- Uri tmp;
-
- if (!Uri.TryCreate((string)value, UriKind.Absolute, out tmp))
- throw new ConfigurationErrorsException(value + " must be an absolute url");
-
- if (tmp.Scheme != Uri.UriSchemeHttp)
- throw new ConfigurationErrorsException("only http is supported for now");
- }
- }
- }
- #endregion
- }
-
- public class UriConverter : ConfigurationConverterBase
- {
- public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
- {
- Uri tmp;
-
- if (Uri.TryCreate((string)value, UriKind.Absolute, out tmp))
- return tmp;
-
- return base.ConvertFrom(context, culture, value);
- }
-
- public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
- {
- if (value == null) return null;
-
- if (!(value is Uri))
- throw new InvalidOperationException("Unsupported type: " + value.GetType());
-
- return ((Uri)value).ToString();
- }
-
- }
-}
-
-#region [ License information ]
-/* ************************************************************
- *
- * Copyright (c) 2010 Attila Kiskó, enyim.com
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * ************************************************************/
-#endregion
View
28 Membase/Demo.config
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8" ?>
-<configuration>
- <configSections>
- <section name="membase" type="Membase.Configuration.MembaseClientSection, Membase" />
- </configSections>
-
- <membase>
- <!--
- Please read the documentation first:
- http://github.com/enyim/EnyimMemcached/wiki/MembaseClient-configuration
-
- Use this section as a template if you're connecting to Membase Servers.
- Note: you must have the top-level membase section if you're using the parameterless constructor of MembaseClient.
- -->
- <servers bucket="enyim" bucketPassword="password" retryCount="2" retryTimeout="00:00:02">
- <!--
- Provide at least 2-3 urls from your cluster.
- Usually you only need to change the host, except when connecting to older versions.
- Membase uses port 8091, while the NorthScale Memcached Server (1.0.3) uses 8080
- -->
- <add uri="http://192.168.2.202:8091/pools/default" />
- <add uri="http://192.168.2.200:8091/pools/default" />
- </servers>
- <!-- the client waits deadTmimeout time to reconnect to the pool when all the specified urls are down -->
- <socketPool connectionTimeout="00:00:10" deadTimeout="00:00:10" />
- </membase>
-
-</configuration>
View
218 Membase/Deserialization.cs
@@ -1,218 +0,0 @@
-using System;
-using System.Linq;
-using System.Collections.Generic;
-using System.Net;
-
-namespace Membase.Configuration
-{
-#pragma warning disable 649
- internal class ClusterInfo
- {
- public string name;
- public ClusterNode[] nodes;
- public ClusterBucketInfo buckets;
- }
-
- internal class ClusterBucketInfo
- {
- public string uri;
- }
-
- internal class ClusterConfig
- {
- public string name;
-
- public string uri;
- public string streamingUri;
-
- public ClusterNode[] nodes;
-
- public VBucketConfig vBucketServerMap;
- public VBucketConfig vBucketForwardServerMap;
-
- // mecached|membase
- public string bucketType;
- // sasl
- public string authType;
- // password for the bucket
- public string saslPassword;
-
- public override int GetHashCode()
- {
- var cnehc = new Enyim.HashCodeCombiner();
-
- for (var i = 0; i < nodes.Length; i++)
- cnehc.Add(nodes[i].GetHashCode());
-
- if (vBucketForwardServerMap != null)
- cnehc.Add(vBucketForwardServerMap.GetHashCode());
-
- if (vBucketServerMap != null)
- cnehc.Add(vBucketServerMap.GetHashCode());
-
- cnehc.Add(this.name.GetHashCode());
- cnehc.Add(this.streamingUri.GetHashCode());
-
- return cnehc.CurrentHash;
- }
- }
-
- internal class VBucketConfig
- {
- public string hashAlgorithm;
- public int numReplicas;
- public string[] serverList;
- public int[][] vBucketMap;
-
- public override int GetHashCode()
- {
- var ehc = new Enyim.HashCodeCombiner(this.hashAlgorithm.GetHashCode());
- ehc.Add(this.numReplicas);
-
- for (var i = 0; i < this.serverList.Length; i++)
- ehc.Add(this.serverList[i].GetHashCode());
-
- for (var i = 0; i < vBucketMap.Length; i++)
- {
- var ehc2 = new Enyim.HashCodeCombiner();
- var tmp = vBucketMap[i];
-
- for (var j = 0; j < tmp.Length; j++)
- ehc2.Add(tmp[j]);
-
- ehc.Add(ehc2.CurrentHash);
- }
-
- return ehc.CurrentHash;
- }
- }
-
- internal class ClusterNode
- {
- private static readonly Type[] SupportedTypes = { typeof(ClusterNode) };
-
- internal static readonly System.Web.Script.Serialization.JavaScriptConverter ConverterInstance = new Converter();
- internal static readonly IEqualityComparer<ClusterNode> ComparerInstance = new Comparer();
-
- private string hostNname;
-
- public ClusterNode()
- {
- }
-
- public string HostName
- {
- get { return this.hostNname; }
- set
- {
- var tmp = value;
-
- // strip the management port (mc server 1.0.3> & membase 1.6>)
- if (!String.IsNullOrEmpty(tmp))
- {
- var index = tmp.IndexOf(':');
- if (index > 0)
- tmp = tmp.Substring(0, index);
- }
-
- this.hostNname = tmp;
- }
- }
-
- public int Port { get; private set; }
- public string Status { get; private set; }
- public string Version { get; private set; }
- public Dictionary<string, object> ConfigurationData { get; private set; }
-
- public override int GetHashCode()
- {
- return Enyim.HashCodeCombiner.Combine(
- this.hostNname == null ? -1 : this.hostNname.GetHashCode(),
- this.Status == null ? -1 : this.Status.GetHashCode(),
- Port);
- }
-
- #region [ Comparer ]
-
- private class Comparer : IEqualityComparer<ClusterNode>
- {
- bool IEqualityComparer<ClusterNode>.Equals(ClusterNode x, ClusterNode y)
- {
- return x.HostName == y.HostName
- && x.Port == y.Port
- && x.Status == y.Status;
- }
-
- int IEqualityComparer<ClusterNode>.GetHashCode(ClusterNode obj)
- {
- return obj.GetHashCode();
- }
- }
-
- #endregion
- #region [ JSON Converter ]
-
- private class Converter : System.Web.Script.Serialization.JavaScriptConverter
- {
- public override object Deserialize(IDictionary<string, object> dictionary, Type type, System.Web.Script.Serialization.JavaScriptSerializer serializer)
- {
- var retval = new ClusterNode();
-
- retval.HostName = GetRequired<string>(dictionary, "hostname");
- retval.Status = GetRequired<string>(dictionary, "status");
- retval.Version = GetRequired<string>(dictionary, "version");
-
- var ports = GetRequired<IDictionary<string, object>>(dictionary, "ports");
- if (ports != null)
- retval.Port = GetRequired<int>(ports, "direct");
-
- retval.ConfigurationData = new Dictionary<string, object>(dictionary);
-
- return retval;
- }
-
- private static TResult GetRequired<TResult>(IDictionary<string, object> dict, string key)
- {
- object tmp;
-
- if (!dict.TryGetValue(key, out tmp))
- throw new InvalidOperationException(String.Format("Key '{0}' was not found in the cluster node info.", key));
-
- return (TResult)tmp;
- }
-
- public override IDictionary<string, object> Serialize(object obj, System.Web.Script.Serialization.JavaScriptSerializer serializer)
- {
- throw new NotImplementedException();
- }
-
- public override IEnumerable<Type> SupportedTypes
- {
- get { return ClusterNode.SupportedTypes; }
- }
- }
-
- #endregion
- }
-#pragma warning restore 649
-}
-
-#region [ License information ]
-/* ************************************************************
- *
- * Copyright (c) 2010 Attila Kiskó, enyim.com
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * ************************************************************/
-#endregion
View
15 Membase/IMembaseOperationFactory.cs
@@ -1,15 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using Enyim.Caching.Memcached;
-
-namespace Membase
-{
- public interface IMembaseOperationFactory : IOperationFactory
- {
- ITouchOperation Touch(string key, uint newExpiration);
- IGetAndTouchOperation GetAndTouch(string key, uint newExpiration);
- ISyncOperation Sync(SyncMode mode, IList<KeyValuePair<string, ulong>> keys, int replicationCount);
- }
-}
View
13 Membase/IMembaseServerPool.cs
@@ -1,13 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using Enyim.Caching.Memcached;
-
-namespace Membase
-{
- public interface IMembaseServerPool : IServerPool
- {
- new IMembaseOperationFactory OperationFactory { get; }
- }
-}
View
91 Membase/Membase.csproj
@@ -1,91 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <PropertyGroup>
- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
- <ProductVersion>9.0.30729</ProductVersion>
- <SchemaVersion>2.0</SchemaVersion>
- <ProjectGuid>{708A2350-A26C-444D-B975-8164263951A7}</ProjectGuid>
- <OutputType>Library</OutputType>
- <AppDesignerFolder>Properties</AppDesignerFolder>
- <RootNamespace>Membase</RootNamespace>
- <AssemblyName>Membase</AssemblyName>
- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
- </PropertyGroup>
- <Import Project="..\build\CommonProperties.targets" />
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
- <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
- <NoWarn>1591</NoWarn>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
- <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
- <NoWarn>1591</NoWarn>
- <DocumentationFile>bin\Release\Membase.xml</DocumentationFile>
- </PropertyGroup>
- <ItemGroup>
- <Reference Include="System" />
- <Reference Include="System.configuration" />
- <Reference Include="System.Core">
- <RequiredTargetFramework>3.5</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.Web" />
- <Reference Include="System.Web.Extensions">
- <RequiredTargetFramework>3.5</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.Xml.Linq">
- <RequiredTargetFramework>3.5</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.Data.DataSetExtensions">
- <RequiredTargetFramework>3.5</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.Data" />
- <Reference Include="System.Xml" />
- </ItemGroup>
- <ItemGroup>
- <Compile Include="BucketConfigListener.cs" />
- <Compile Include="ConfigHelper.cs" />
- <Compile Include="Configuration\BucketPortType.cs" />
- <Compile Include="Configuration\DefaultPerformanceMonitorFactory.cs" />
- <Compile Include="Configuration\IMembasePerformanceMonitorFactory.cs" />
- <Compile Include="Configuration\IMembaseClientConfiguration.cs" />
- <Compile Include="Configuration\MembaseClientConfiguration.cs" />
- <Compile Include="Configuration\MembaseClientSection.cs" />
- <Compile Include="Configuration\ServersElement.cs" />
- <Compile Include="Configuration\UriElement.cs" />
- <Compile Include="Configuration\UriElementCollection.cs" />
- <Compile Include="Configuration\UriValidator.cs" />
- <Compile Include="Operations\GetAndTouchOperation.cs" />
- <Compile Include="BasicMembaseOperationFactory.cs" />
- <Compile Include="OperationInterfaces.cs" />
- <Compile Include="Deserialization.cs" />
- <Compile Include="IMembaseOperationFactory.cs" />
- <Compile Include="IMembaseServerPool.cs" />
- <Compile Include="MessageStreamListener.cs" />
- <Compile Include="MembaseClient.cs" />
- <Compile Include="MembasePool.cs" />
- <Compile Include="Operations\SyncOperation.cs" />
- <Compile Include="Properties\AssemblyInfo.cs" />
- <Compile Include="Operations\TouchOperation.cs" />
- <Compile Include="VBucketAwareOperationFactory.cs" />
- <Compile Include="WebClientWithTimeout.cs">
- <SubType>Component</SubType>
- </Compile>
- </ItemGroup>
- <ItemGroup>
- <ProjectReference Include="..\Enyim.Caching\Enyim.Caching.csproj">
- <Project>{D438C0B3-A168-40B8-BDDD-61F0939DFF35}</Project>
- <Name>Enyim.Caching</Name>
- </ProjectReference>
- </ItemGroup>
- <ItemGroup>
- <None Include="Config.transform" />
- <None Include="Demo.config" />
- <None Include="Changes.mdown" />
- <None Include="Membase.nuspec" />
- </ItemGroup>
- <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
- <PropertyGroup>
- <GitTagMatch>mb*</GitTagMatch>
- </PropertyGroup>
- <Import Project="..\build\VersionInfo.targets" />
-</Project>
View
19 Membase/Membase.nuspec
@@ -1,19 +0,0 @@
-<?xml version="1.0"?>
-<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
- <metadata>
- <id>Membase</id>
- <version>$version$</version>
- <authors>Attila Kiskó</authors>
- <owners>Attila Kiskó</owners>
- <licenseUrl>http://www.apache.org/licenses/LICENSE-2.0</licenseUrl>
- <projectUrl>https://github.com/enyim/EnyimMemcached</projectUrl>
- <requireLicenseAcceptance>false</requireLicenseAcceptance>
- <description>Membase client library for .NET based languages.</description>
- <tags>membase enyim cache caching nosql</tags>
- </metadata>
- <files>
- <file src="bin\Release\Enyim.Caching.*" target="lib\net35" />
- <file src="bin\Release\Membase.*" target="lib\net35" />
- <file src="config.transform" target="content\app.config.transform" />
- </files>
-</package>
View
464 Membase/MembaseClient.cs
@@ -1,464 +0,0 @@
-using System;
-using System.Linq;
-using System.Configuration;
-using Enyim.Caching;
-using Enyim.Caching.Memcached;
-using Membase.Configuration;
-using System.Collections.Generic;
-using System.Threading;
-using KVP_SU = System.Collections.Generic.KeyValuePair<string, ulong>;
-
-namespace Membase
-{
- /// <summary>
- /// Client which can be used to connect to NothScale's Memcached and Membase servers.
- /// </summary>
- public class MembaseClient : MemcachedClient
- {
- private static readonly Enyim.Caching.ILog log = Enyim.Caching.LogManager.GetLogger(typeof(MembaseClient));
- private static readonly IMembaseClientConfiguration DefaultConfig = (IMembaseClientConfiguration)ConfigurationManager.GetSection("membase");
-
- private IMembaseServerPool poolInstance;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="T:Membase.MembaseClient" /> class using the default configuration and bucket.
- /// </summary>
- /// <remarks>The configuration is taken from the /configuration/membase section.</remarks>
- public MembaseClient() : this(DefaultConfig) { }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="T:Membase.MembaseClient" /> class using the default configuration and the specified bucket.
- /// </summary>
- /// <remarks>The configuration is taken from the /configuration/membase section.</remarks>
- public MembaseClient(string bucketName, string bucketPassword) :
- this(DefaultConfig, bucketName, bucketPassword) { }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="T:Membase.MembaseClient" /> class using a custom configuration provider.
- /// </summary>
- /// <param name="configuration">The custom configuration provider.</param>
- public MembaseClient(IMembaseClientConfiguration configuration) :
- this(configuration, configuration.Bucket, configuration.BucketPassword) { }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="T:Membase.MembaseClient" /> class using the specified configuration
- /// section and the specified bucket.
- /// </summary>
- /// <param name="sectionName">The name of the configuration section to load.</param>
- /// <param name="bucketName">The name of the bucket this client will connect to.</param>
- /// <param name="bucketPassword">The password of the bucket this client will connect to.</param>
- public MembaseClient(string sectionName, string bucketName, string bucketPassword) :
- this((IMembaseClientConfiguration)ConfigurationManager.GetSection(sectionName), bucketName, bucketPassword) { }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="T:Membase.MembaseClient" /> class
- /// using a custom configuration provider and the specified bucket name and password.
- /// </summary>
- /// <param name="configuration">The custom configuration provider.</param>
- /// <param name="bucketName">The name of the bucket this client will connect to.</param>
- /// <param name="bucketPassword">The password of the bucket this client will connect to.</param>
- public MembaseClient(IMembaseClientConfiguration configuration, string bucketName, string bucketPassword) :
- this(new MembasePool(configuration, bucketName, bucketPassword), configuration) { }
-
- protected MembaseClient(IMembaseServerPool pool, IMembaseClientConfiguration configuration)
- : base(pool,
- configuration.CreateKeyTransformer(),
- configuration.CreateTranscoder(),
- configuration.CreatePerformanceMonitor())
- {
- this.poolInstance = (IMembaseServerPool)this.Pool;
- }
-
- #region Obsolete code
-
- /// <summary>Obsolete. Use .ctor(bucket, password) to explicitly set the bucket password.</summary>
- [Obsolete("Use .ctor(bucket, password) to explicitly set the bucket password.", true)]
- public MembaseClient(string bucketName)
- {
- throw new InvalidOperationException("Use .ctor(bucket, password) to explicitly set the bucket password.");
- }
-
- /// <summary>Obsolete. Use .ctor(config, bucket, password) to explicitly set the bucket password.</summary>
- [Obsolete("Use .ctor(config, bucket, password) to explicitly set the bucket password.", true)]
- public MembaseClient(IMembaseClientConfiguration configuration, string bucketName)
- {
- throw new InvalidOperationException("Use .ctor(config, bucket, password) to explicitly set the bucket password.");
- }
-
- #endregion
-
- protected override bool PerformTryGet(string key, out ulong cas, out object value)
- {
- var hashedKey = this.KeyTransformer.Transform(key);
- var node = this.Pool.Locate(hashedKey);
-
- if (node != null)
- {
- var command = this.Pool.OperationFactory.Get(hashedKey);
-
- if (ExecuteWithRedirect(node, command))
- {
- value = this.Transcoder.Deserialize(command.Result);
- cas = command.CasValue;
- if (this.PerformanceMonitor != null) this.PerformanceMonitor.Get(1, true);
-
- return true;
- }
- }
-
- value = null;
- cas = 0;
- if (this.PerformanceMonitor != null) this.PerformanceMonitor.Get(1, false);
-
- return false;
- }
-
- protected override ulong PerformMutate(MutationMode mode, string key, ulong defaultValue, ulong delta, uint expires, ref ulong cas)
- {
- var hashedKey = this.KeyTransformer.Transform(key);
- var node = this.Pool.Locate(hashedKey);
-
- if (node != null)
- {
- var command = this.Pool.OperationFactory.Mutate(mode, hashedKey, defaultValue, delta, expires, cas);
- var success = ExecuteWithRedirect(node, command);
-
- if (this.PerformanceMonitor != null) this.PerformanceMonitor.Mutate(mode, 1, success);
-
- cas = command.CasValue;
-
- if (success)
- return command.Result;
- }
-
- if (this.PerformanceMonitor != null) this.PerformanceMonitor.Mutate(mode, 1, false);
-
- return defaultValue;
- }
-
- protected override bool PerformConcatenate(ConcatenationMode mode, string key, ref ulong cas, ArraySegment<byte> data)
- {
- var hashedKey = this.KeyTransformer.Transform(key);
- var node = this.Pool.Locate(hashedKey);
-
- if (node != null)
- {
- var command = this.Pool.OperationFactory.Concat(mode, hashedKey, cas, data);
- var retval = this.ExecuteWithRedirect(node, command);
-
- cas = command.CasValue;
- if (this.PerformanceMonitor != null) this.PerformanceMonitor.Concatenate(mode, 1, true);
-
- return retval;
- }
-
- if (this.PerformanceMonitor != null) this.PerformanceMonitor.Concatenate(mode, 1, false);
-
- return false;
- }
-
- protected override bool PerformStore(StoreMode mode, string key, object value, uint expires, ref ulong cas, out int statusCode)
- {
- var hashedKey = this.KeyTransformer.Transform(key);
- var node = this.Pool.Locate(hashedKey);
- statusCode = -1;
-
- if (node != null)
- {
- CacheItem item;
-
- try { item = this.Transcoder.Serialize(value); }
- catch (Exception e)
- {
- log.Error(e);
-
- if (this.PerformanceMonitor != null) this.PerformanceMonitor.Store(mode, 1, false);
-
- return false;
- }
-
- var command = this.Pool.OperationFactory.Store(mode, hashedKey, item, expires, cas);
- var retval = ExecuteWithRedirect(node, command);
-
- cas = command.CasValue;
- statusCode = command.StatusCode;
-
- if (this.PerformanceMonitor != null) this.PerformanceMonitor.Store(mode, 1, true);
-
- return retval;
- }
-
- if (this.PerformanceMonitor != null) this.PerformanceMonitor.Store(mode, 1, false);
-
- return false;
- }
-
- private bool ExecuteWithRedirect(IMemcachedNode startNode, ISingleItemOperation op)
- {
- if (startNode.Execute(op)) return true;
-
- var iows = op as IOperationWithState;
-
- // different op factory, we do not know how to retry
- if (iows == null)
- return false;
-
-#if HAS_FORWARD_MAP
- // node responded with invalid vbucket
- // this should happen only when a node is in a transitioning state
- if (iows.State == OpState.InvalidVBucket)
- {
- // check if we have a forward-locator
- // (whihc supposedly reflects the state of the cluster when all vbuckets have been migrated succesfully)
- IMemcachedNodeLocator fl = this.nsPool.ForwardLocator;
- if (fl != null)
- {
- var nextNode = fl.Locate(op.Key);
- if (nextNode != null)
- {
- // the node accepted the requesta
- if (nextNode.Execute(op)) return true;
- }
- }
- }
-#endif
- // still invalid vbucket, try all nodes in sequence
- if (iows.State == OperationState.InvalidVBucket)
- {
- var nodes = this.Pool.GetWorkingNodes();
-
- foreach (var node in nodes)
- {
- if (node.Execute(op))
- return true;
-
- // the node accepted our request so quit
- if (iows.State != OperationState.InvalidVBucket)
- break;
- }
- }
-
- return false;
- }
-
- public void Touch(string key, DateTime nextExpiration)
- {
- PerformTouch(key, GetExpiration(null, nextExpiration));
- }
-
- public void Touch(string key, TimeSpan nextExpiration)
- {
- PerformTouch(key, GetExpiration(nextExpiration, null));
- }
-
- protected void PerformTouch(string key, uint nextExpiration)
- {
- var hashedKey = this.KeyTransformer.Transform(key);
- var node = this.Pool.Locate(hashedKey);
-
- if (node != null)
- {
- var command = this.poolInstance.OperationFactory.Touch(key, nextExpiration);
- var retval = ExecuteWithRedirect(node, command);
- }
- }
-
- public object Get(string key, DateTime newExpiration)
- {
- object tmp;
-
- return this.TryGet(key, newExpiration, out tmp) ? tmp : null;
- }
-
- public T Get<T>(string key, DateTime newExpiration)
- {
- object tmp;
-
- return TryGet(key, newExpiration, out tmp) ? (T)tmp : default(T);
- }
-
- public bool TryGet(string key, DateTime newExpiration, out object value)
- {
- ulong cas = 0;
-
- return this.PerformTryGetAndTouch(key, MemcachedClient.GetExpiration(null, newExpiration), out cas, out value);
- }
-
- public CasResult<object> GetWithCas(string key, DateTime newExpiration)
- {
- return this.GetWithCas<object>(key, newExpiration);
- }
-
- public CasResult<T> GetWithCas<T>(string key, DateTime newExpiration)
- {
- CasResult<object> tmp;
-
- return this.TryGetWithCas(key, newExpiration, out tmp)
- ? new CasResult<T> { Cas = tmp.Cas, Result = (T)tmp.Result }
- : new CasResult<T> { Cas = tmp.Cas, Result = default(T) };
- }
-
- public bool TryGetWithCas(string key, DateTime newExpiration, out CasResult<object> value)
- {
- object tmp;
- ulong cas;
-
- var retval = this.PerformTryGetAndTouch(key, MemcachedClient.GetExpiration(null, newExpiration), out cas, out tmp);
-
- value = new CasResult<object> { Cas = cas, Result = tmp };
-
- return retval;
- }
-
- protected bool PerformTryGetAndTouch(string key, uint nextExpiration, out ulong cas, out object value)
- {
- var hashedKey = this.KeyTransformer.Transform(key);
- var node = this.Pool.Locate(hashedKey);
-
- if (node != null)
- {
- var command = this.poolInstance.OperationFactory.GetAndTouch(hashedKey, nextExpiration);
-
- if (this.ExecuteWithRedirect(node, command))
- {
- value = this.Transcoder.Deserialize(command.Result);
- cas = command.CasValue;
- if (this.PerformanceMonitor != null) this.PerformanceMonitor.Get(1, true);
-
- return true;
- }
- }
-
- value = null;
- cas = 0;
- if (this.PerformanceMonitor != null) this.PerformanceMonitor.Get(1, false);
-
- return false;
- }
-
- public SyncResult Sync(string key, ulong cas, SyncMode mode)
- {
- return this.Sync(key, cas, mode, 0);
- }
-
- public SyncResult Sync(string key, ulong cas, SyncMode mode, int replicationCount)
- {
- var hashedKey = this.KeyTransformer.Transform(key);
- var node = this.Pool.Locate(hashedKey);
-
- var tmp = this.PerformMultiSync(mode, replicationCount, new[] { new KeyValuePair<string, ulong>(key, cas) });
- SyncResult retval;
-
- return tmp.TryGetValue(key, out retval)
- ? retval
- : null;
- }
-
- public IDictionary<string, SyncResult> Sync(SyncMode mode, IEnumerable<KeyValuePair<string, ulong>> items)
- {
- return this.PerformMultiSync(mode, 0, items);
- }
-
- protected IDictionary<string, SyncResult> PerformMultiSync(SyncMode mode, int replicationCount, IEnumerable<KeyValuePair<string, ulong>> items)
- {
- // transform the keys and index them by hashed => original
- // the results will be mapped using this index
- var hashed = new Dictionary<string, string>();
- var hashedAndMapped = new Dictionary<IMemcachedNode, IList<KVP_SU>>();
-
- foreach (var k in items)
- {
- var hashedKey = this.KeyTransformer.Transform(k.Key);
- var node = this.Pool.Locate(hashedKey);
-
- if (node == null) continue;
-
- hashed[hashedKey] = k.Key;
-
- IList<KVP_SU> list;
- if (!hashedAndMapped.TryGetValue(node, out list))
- hashedAndMapped[node] = list = new List<KVP_SU>(4);
-
- list.Add(k);
- }
-
- var retval = new Dictionary<string, SyncResult>(hashed.Count);
- if (hashedAndMapped.Count == 0) return retval;
-
- using (var spin = new ReaderWriterLockSlim())
- using (var latch = new CountdownEvent(hashedAndMapped.Count))
- {
- //execute each list of keys on their respective node
- foreach (var slice in hashedAndMapped)
- {
- var node = slice.Key;
- var nodeKeys = slice.Value;
-
- var sync = this.poolInstance.OperationFactory.Sync(mode, slice.Value, replicationCount);
-
- #region result gathering
- // ExecuteAsync will not call the delegate if the
- // node was already in a failed state but will return false immediately
- var execSuccess = node.ExecuteAsync(sync, success =>
- {
- if (success)
- try
- {
- var result = sync.Result;
-
- if (result != null && result.Length > 0)
- {
- string original;
-
- foreach (var kvp in result)
- if (hashed.TryGetValue(kvp.Key, out original))
- {
- spin.EnterWriteLock();
- try
- { retval[original] = kvp; }
- finally
- { spin.ExitWriteLock(); }
- }
- }
- }
- catch (Exception e)
- {
- log.Error(e);
- }
-
- latch.Signal();
- });
- #endregion
-
- // signal the latch when the node fails immediately (e.g. it was already dead)
- if (!execSuccess) latch.Signal();
- }
-
- latch.Wait();
- }
-
- return retval;
- }
-
- }
-}
-
-#region [ License information ]
-/* ************************************************************
- *
- * Copyright (c) 2010 Attila Kiskó, enyim.com
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * ************************************************************/
-#endregion
View
577 Membase/MembasePool.cs