Пример #1
0
		public async Task<HttpResponseMessage> Cas([FromUri] string key, [FromUri] string val, [FromUri] string prevValue)
		{
			JToken jVal;
			try
			{
				jVal = JToken.Parse(val);
			}
			catch (JsonReaderException)
			{
				jVal = val;
			}

			JToken jPrevVal;
			try
			{
				jPrevVal = JToken.Parse(prevValue);
			}
			catch (JsonReaderException)
			{
				jPrevVal = prevValue;
			}

		
			var taskCompletionSource = new TaskCompletionSource<object>();
			var op = new CasCommand
			{
				Key = key,
				Value = jVal,
				PrevValue = jPrevVal,
				Completion = taskCompletionSource
			};
			try
			{
				RaftEngine.AppendCommand(op);
			}
			catch (NotLeadingException e)
			{
				return this.RedirectToLeader(e.CurrentLeader, Request.RequestUri);
			}
			var newValueSet = await taskCompletionSource.Task;
			return Request.CreateResponse(HttpStatusCode.OK, new
			{
				RaftEngine.State,
				Key = key,
				ValueChanged = newValueSet
			});
		}
Пример #2
0
        public bool Cas(CasCommand op)
        {
            using (var tx = _storageEnvironment.NewTransaction(TransactionFlags.ReadWrite))
            {
                var items = tx.ReadTree("items");
                var oldValue = items.Read(op.Key);
                var ms = new MemoryStream();
                var oldToken = oldValue == null ? JValue.CreateNull() : JToken.ReadFrom(new JsonTextReader(new StreamReader(oldValue.Reader.AsStream())));
                if (!new JTokenEqualityComparer().Equals(oldToken, op.PrevValue))
                {
                    return false;
                }

                ms.SetLength(0);

                var writer = new StreamWriter(ms);
                op.Value.WriteTo(new JsonTextWriter(writer));
                writer.Flush();

                ms.Position = 0;
                items.Add(op.Key, ms);
                tx.Commit();
                return true;
            }
        }