-
Notifications
You must be signed in to change notification settings - Fork 820
/
ServerClient.cs
1351 lines (1214 loc) · 48.8 KB
/
ServerClient.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#if !SILVERLIGHT
//-----------------------------------------------------------------------
// <copyright file="ServerClient.cs" company="Hibernating Rhinos LTD">
// Copyright (c) Hibernating Rhinos LTD. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using Raven.Abstractions;
using Raven.Abstractions.Commands;
using Raven.Abstractions.Connection;
using Raven.Abstractions.Data;
using Raven.Abstractions.Exceptions;
using Raven.Abstractions.Extensions;
using Raven.Abstractions.Indexing;
using Raven.Client.Connection.Profiling;
using Raven.Client.Document;
using Raven.Client.Exceptions;
using Raven.Client.Extensions;
using Raven.Client.Indexes;
using Raven.Json.Linq;
namespace Raven.Client.Connection
{
/// <summary>
/// Access the RavenDB operations using HTTP
/// </summary>
public class ServerClient : IDatabaseCommands
{
private int requestCount;
private readonly string url;
private readonly DocumentConvention convention;
private readonly ICredentials credentials;
private readonly Func<string, ReplicationInformer> replicationInformerGetter;
private readonly string databaseName;
private readonly ReplicationInformer replicationInformer;
private readonly HttpJsonRequestFactory jsonRequestFactory;
private readonly Guid? currentSessionId;
private readonly ProfilingInformation profilingInformation;
private int readStripingBase;
/// <summary>
/// Notify when the failover status changed
/// </summary>
public event EventHandler<FailoverStatusChangedEventArgs> FailoverStatusChanged
{
add { replicationInformer.FailoverStatusChanged += value; }
remove { replicationInformer.FailoverStatusChanged -= value; }
}
/// <summary>
/// Initializes a new instance of the <see cref="ServerClient"/> class.
/// </summary>
public ServerClient(string url, DocumentConvention convention, ICredentials credentials, Func<string, ReplicationInformer> replicationInformerGetter, string databaseName, HttpJsonRequestFactory jsonRequestFactory, Guid? currentSessionId)
{
profilingInformation = ProfilingInformation.CreateProfilingInformation(currentSessionId);
this.credentials = credentials;
this.replicationInformerGetter = replicationInformerGetter;
this.databaseName = databaseName;
this.replicationInformer = replicationInformerGetter(databaseName);
this.jsonRequestFactory = jsonRequestFactory;
this.currentSessionId = currentSessionId;
this.url = url;
if (url.EndsWith("/"))
this.url = url.Substring(0, url.Length - 1);
this.convention = convention;
OperationsHeaders = new NameValueCollection();
replicationInformer.UpdateReplicationInformationIfNeeded(this);
readStripingBase = replicationInformer.GetReadStripingBase();
}
/// <summary>
/// Allow access to the replication informer used to determine how we replicate requests
/// </summary>
public ReplicationInformer ReplicationInformer
{
get { return replicationInformer; }
}
#region IDatabaseCommands Members
/// <summary>
/// Gets or sets the operations headers.
/// </summary>
/// <value>The operations headers.</value>
public NameValueCollection OperationsHeaders
{
get;
set;
}
/// <summary>
/// Gets the document for the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public JsonDocument Get(string key)
{
EnsureIsNotNullOrEmpty(key, "key");
return ExecuteWithReplication("GET", u => DirectGet(u, key));
}
/// <summary>
/// Gets documents for the specified key prefix
/// </summary>
public JsonDocument[] StartsWith(string keyPrefix, int start, int pageSize)
{
EnsureIsNotNullOrEmpty(keyPrefix, "keyPrefix");
return ExecuteWithReplication("GET", u => DirectStartsWith(u, keyPrefix, start, pageSize));
}
/// <summary>
/// Execute a GET request against the provided url
/// and return the result as a json object
/// </summary>
/// <param name="requestUrl">The relative url to the server</param>
/// <remarks>
/// This method respects the replication semantics against the database.
/// </remarks>
public RavenJToken ExecuteGetRequest(string requestUrl)
{
EnsureIsNotNullOrEmpty(requestUrl, "url");
return ExecuteWithReplication("GET", serverUrl =>
{
var metadata = new RavenJObject();
AddTransactionInformation(metadata);
var request = jsonRequestFactory.CreateHttpJsonRequest(this, serverUrl + requestUrl, "GET", metadata, credentials, convention);
request.AddOperationHeaders(OperationsHeaders);
return request.ReadResponseJson();
});
}
private void ExecuteWithReplication(string method, Action<string> operation)
{
ExecuteWithReplication<object>(method, operationUrl =>
{
operation(operationUrl);
return null;
});
}
/// <summary>
/// Allow to query whatever we are in failover mode or not
/// </summary>
/// <returns></returns>
public bool InFailoverMode()
{
return replicationInformer.GetFailureCount(url) > 0;
}
private T ExecuteWithReplication<T>(string method, Func<string, T> operation)
{
var currentRequest = Interlocked.Increment(ref requestCount);
T result;
var threadSafeCopy = replicationInformer.ReplicationDestinations;
var shouldReadFromAllServers = ((convention.FailoverBehavior & FailoverBehavior.ReadFromAllServers) == FailoverBehavior.ReadFromAllServers);
if (shouldReadFromAllServers && method == "GET")
{
var replicationIndex = readStripingBase%(threadSafeCopy.Count + 1);
// if replicationIndex == destinations count, then we want to use the master
// if replicationIndex < 0, then we were explicitly instructed to use the master
if (replicationIndex < threadSafeCopy.Count && replicationIndex >= 0)
{
// if it is failing, ignore that, and move to the master or any of the replicas
if (replicationInformer.ShouldExecuteUsing(threadSafeCopy[replicationIndex], currentRequest, method, false))
{
if (TryOperation(operation, threadSafeCopy[replicationIndex], true, out result))
return result;
}
}
}
if (replicationInformer.ShouldExecuteUsing(url, currentRequest, method, true))
{
if (TryOperation(operation, url, true, out result))
return result;
if (replicationInformer.IsFirstFailure(url) && TryOperation(operation, url, threadSafeCopy.Count > 0, out result))
return result;
replicationInformer.IncrementFailureCount(url);
}
for (var i = 0; i < threadSafeCopy.Count; i++)
{
var replicationDestination = threadSafeCopy[i];
if (replicationInformer.ShouldExecuteUsing(replicationDestination, currentRequest, method, false) == false)
continue;
if (TryOperation(operation, replicationDestination, true, out result))
return result;
if (replicationInformer.IsFirstFailure(url) && TryOperation(operation, replicationDestination, threadSafeCopy.Count > i + 1, out result))
return result;
replicationInformer.IncrementFailureCount(url);
}
// this should not be thrown, but since I know the value of should...
throw new InvalidOperationException(@"Attempted to connect to master and all replicas have failed, giving up.
There is a high probability of a network problem preventing access to all the replicas.
Failed to get in touch with any of the " + (1 + threadSafeCopy.Count) + " Raven instances.");
}
private bool TryOperation<T>(Func<string, T> operation, string operationUrl, bool avoidThrowing, out T result)
{
try
{
result = operation(operationUrl);
replicationInformer.ResetFailureCount(operationUrl);
return true;
}
catch (WebException e)
{
if (avoidThrowing == false)
throw;
result = default(T);
if (IsServerDown(e))
return false;
throw;
}
}
private static bool IsServerDown(WebException e)
{
return e.InnerException is SocketException ||
e.InnerException is IOException;
}
/// <summary>
/// Perform a direct get for a document with the specified key on the specified server URL.
/// </summary>
/// <param name="serverUrl">The server URL.</param>
/// <param name="key">The key.</param>
/// <returns></returns>
public JsonDocument DirectGet(string serverUrl, string key)
{
var metadata = new RavenJObject();
AddTransactionInformation(metadata);
var request = jsonRequestFactory.CreateHttpJsonRequest(this, serverUrl + "/docs/" + key, "GET", metadata, credentials, convention);
request.AddOperationHeaders(OperationsHeaders);
try
{
var responseJson = request.ReadResponseJson();
return SerializationHelper.DeserializeJsonDocument(key, responseJson, request.ResponseHeaders, request.ResponseStatusCode);
}
catch (WebException e)
{
var httpWebResponse = e.Response as HttpWebResponse;
if (httpWebResponse == null)
throw;
if (httpWebResponse.StatusCode == HttpStatusCode.NotFound)
return null;
if (httpWebResponse.StatusCode == HttpStatusCode.Conflict)
{
var conflicts = new StreamReader(httpWebResponse.GetResponseStreamWithHttpDecompression());
var conflictsDoc = RavenJObject.Load(new JsonTextReader(conflicts));
var conflictIds = conflictsDoc.Value<RavenJArray>("Conflicts").Select(x => x.Value<string>()).ToArray();
throw new ConflictException("Conflict detected on " + key +
", conflict must be resolved before the document will be accessible")
{
ConflictedVersionIds = conflictIds
};
}
throw;
}
}
private static void EnsureIsNotNullOrEmpty(string key, string argName)
{
if (string.IsNullOrEmpty(key))
throw new ArgumentException("Key cannot be null or empty", argName);
}
/// <summary>
/// Puts the document with the specified key in the database
/// </summary>
/// <param name="key">The key.</param>
/// <param name="etag">The etag.</param>
/// <param name="document">The document.</param>
/// <param name="metadata">The metadata.</param>
/// <returns></returns>
public PutResult Put(string key, Guid? etag, RavenJObject document, RavenJObject metadata)
{
return ExecuteWithReplication("PUT", u => DirectPut(metadata, key, etag, document, u));
}
private JsonDocument[] DirectStartsWith(string operationUrl, string keyPrefix, int start, int pageSize)
{
var metadata = new RavenJObject();
AddTransactionInformation(metadata);
var actualUrl = string.Format("{0}/docs?startsWith={1}&start={2}&pageSize={3}", operationUrl, Uri.EscapeDataString(keyPrefix), start, pageSize);
var request = jsonRequestFactory.CreateHttpJsonRequest(this, actualUrl, "GET", metadata, credentials, convention);
request.AddOperationHeaders(OperationsHeaders);
RavenJToken responseJson;
try
{
responseJson = request.ReadResponseJson();
}
catch (WebException e)
{
var httpWebResponse = e.Response as HttpWebResponse;
if (httpWebResponse == null ||
httpWebResponse.StatusCode != HttpStatusCode.Conflict)
throw;
throw ThrowConcurrencyException(e);
}
return SerializationHelper.RavenJObjectsToJsonDocuments(((RavenJArray)responseJson).OfType<RavenJObject>()).ToArray();
}
private PutResult DirectPut(RavenJObject metadata, string key, Guid? etag, RavenJObject document, string operationUrl)
{
if (metadata == null)
metadata = new RavenJObject();
var method = String.IsNullOrEmpty(key) ? "POST" : "PUT";
AddTransactionInformation(metadata);
if (etag != null)
metadata["ETag"] = new RavenJValue(etag.Value.ToString());
var request = jsonRequestFactory.CreateHttpJsonRequest(this, operationUrl + "/docs/" + key, method, metadata, credentials, convention);
request.AddOperationHeaders(OperationsHeaders);
request.Write(document.ToString());
RavenJToken responseJson;
try
{
responseJson = request.ReadResponseJson();
}
catch (WebException e)
{
var httpWebResponse = e.Response as HttpWebResponse;
if (httpWebResponse == null ||
httpWebResponse.StatusCode != HttpStatusCode.Conflict)
throw;
throw ThrowConcurrencyException(e);
}
var jsonSerializer = convention.CreateSerializer();
return jsonSerializer.Deserialize<PutResult>(new RavenJTokenReader(responseJson));
}
private void AddTransactionInformation(RavenJObject metadata)
{
if (convention.EnlistInDistributedTransactions == false)
return;
var transactionInformation = RavenTransactionAccessor.GetTransactionInformation();
if (transactionInformation == null)
return;
string txInfo = string.Format("{0}, {1}", transactionInformation.Id, transactionInformation.Timeout);
metadata["Raven-Transaction-Information"] = new RavenJValue(txInfo);
}
/// <summary>
/// Deletes the document with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="etag">The etag.</param>
public void Delete(string key, Guid? etag)
{
EnsureIsNotNullOrEmpty(key, "key");
ExecuteWithReplication<object>("DELETE", u =>
{
DirectDelete(key, etag, u);
return null;
});
}
/// <summary>
/// Puts the attachment with the specified key
/// </summary>
/// <param name="key">The key.</param>
/// <param name="etag">The etag.</param>
/// <param name="data">The data.</param>
/// <param name="metadata">The metadata.</param>
public void PutAttachment(string key, Guid? etag, Stream data, RavenJObject metadata)
{
ExecuteWithReplication("PUT", operationUrl => DirectPutAttachment(key, metadata, etag, data, operationUrl));
}
private void DirectPutAttachment(string key, RavenJObject metadata, Guid? etag, Stream data, string operationUrl)
{
if(etag != null)
{
metadata["ETag"] = etag.Value.ToString();
}
var webRequest = jsonRequestFactory.CreateHttpJsonRequest(this, operationUrl + "/static/" + key, "PUT", metadata, credentials, convention);
webRequest.Write(data);
try
{
webRequest.ExecuteRequest();
}
catch (WebException e)
{
var httpWebResponse = e.Response as HttpWebResponse;
if (httpWebResponse == null || httpWebResponse.StatusCode != HttpStatusCode.InternalServerError)
throw;
using (var stream = httpWebResponse.GetResponseStreamWithHttpDecompression())
using (var reader = new StreamReader(stream))
{
throw new InvalidOperationException("Internal Server Error: " + Environment.NewLine + reader.ReadToEnd());
}
}
}
/// <summary>
/// Gets the attachment by the specified key
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public Attachment GetAttachment(string key)
{
return ExecuteWithReplication("GET", operationUrl => DirectGetAttachment("GET", key, operationUrl));
}
/// <summary>
/// Retrieves the attachment metadata with the specified key, not the actual attachmet
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public Attachment HeadAttachment(string key)
{
return ExecuteWithReplication("HEAD", operationUrl => DirectGetAttachment("HEAD",key, operationUrl));
}
private Attachment DirectGetAttachment(string method, string key, string operationUrl)
{
var webRequest = jsonRequestFactory.CreateHttpJsonRequest(this,operationUrl + "/static/" + key,method, credentials, convention);
Func<Stream> data;
try
{
int len;
if (method == "GET")
{
var memoryStream = new MemoryStream(webRequest.ReadResponseBytes());
data = () => memoryStream;
len = (int)memoryStream.Length;
}
else
{
len = int.Parse(webRequest.ResponseHeaders["Content-Length"]);
data = () =>
{
throw new InvalidOperationException("Cannot get attachment data because it was loaded using: " + method);
};
}
return new Attachment
{
Data = data,
Size = len,
Etag = new Guid(webRequest.ResponseHeaders["ETag"]),
Metadata = webRequest.ResponseHeaders.FilterHeaders(isServerDocument: false)
};
}
catch (WebException e)
{
var httpWebResponse = e.Response as HttpWebResponse;
if (httpWebResponse == null)
throw;
if (httpWebResponse.StatusCode == HttpStatusCode.Conflict)
{
var conflictsDoc = RavenJObject.Load(new BsonReader(httpWebResponse.GetResponseStreamWithHttpDecompression()));
var conflictIds = conflictsDoc.Value<RavenJArray>("Conflicts").Select(x => x.Value<string>()).ToArray();
throw new ConflictException("Conflict detected on " + key +
", conflict must be resolved before the attachment will be accessible")
{
ConflictedVersionIds = conflictIds
};
}
if (httpWebResponse.StatusCode == HttpStatusCode.NotFound)
return null;
throw;
}
}
/// <summary>
/// Deletes the attachment with the specified key
/// </summary>
/// <param name="key">The key.</param>
/// <param name="etag">The etag.</param>
public void DeleteAttachment(string key, Guid? etag)
{
ExecuteWithReplication("DELETE", operationUrl => DirectDeleteAttachment(key, etag, operationUrl));
}
public string[] GetDatabaseNames(int pageSize)
{
var result = ExecuteGetRequest("".Databases(pageSize).NoCache());
var json = (RavenJArray) result;
return json
.Select(x => x.Value<RavenJObject>("@metadata").Value<string>("@id").Replace("Raven/Databases/", string.Empty))
.ToArray();
}
private void DirectDeleteAttachment(string key, Guid? etag, string operationUrl)
{
var metadata = new RavenJObject();
if(etag != null)
{
metadata["ETag"] = etag.Value.ToString();
}
var webRequest = jsonRequestFactory.CreateHttpJsonRequest(this, operationUrl + "/static/" + key, "DELETE", metadata,credentials, convention);
webRequest.ExecuteRequest();
}
/// <summary>
/// Gets the index names from the server
/// </summary>
/// <param name="start">Paging start</param>
/// <param name="pageSize">Size of the page.</param>
/// <returns></returns>
public string[] GetIndexNames(int start, int pageSize)
{
return ExecuteWithReplication("GET", u => DirectGetIndexNames(start, pageSize, u));
}
/// <summary>
/// Resets the specified index
/// </summary>
/// <param name="name">The name.</param>
public void ResetIndex(string name)
{
ExecuteWithReplication("RESET", u => DirectResetIndex(name, u));
}
private object DirectResetIndex(string name, string operationUrl)
{
var httpJsonRequest = jsonRequestFactory.CreateHttpJsonRequest(this, operationUrl + "/indexes/" + name, "RESET", credentials, convention);
httpJsonRequest.AddOperationHeaders(OperationsHeaders);
httpJsonRequest.ReadResponseJson();
return null;
}
private string[] DirectGetIndexNames(int start, int pageSize, string operationUrl)
{
var httpJsonRequest = jsonRequestFactory.CreateHttpJsonRequest(this, operationUrl + "/indexes/?namesOnly=true&start=" + start + "&pageSize=" + pageSize, "GET", credentials, convention);
httpJsonRequest.AddOperationHeaders(OperationsHeaders);
var responseJson = httpJsonRequest.ReadResponseJson();
return ((RavenJArray)responseJson).Select(x => x.Value<string>()).ToArray();
}
/// <summary>
/// Gets the index definition for the specified name
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public IndexDefinition GetIndex(string name)
{
EnsureIsNotNullOrEmpty(name, "name");
return ExecuteWithReplication("GET", u => DirectGetIndex(name, u));
}
private IndexDefinition DirectGetIndex(string indexName, string operationUrl)
{
var httpJsonRequest = jsonRequestFactory.CreateHttpJsonRequest(this, operationUrl + "/indexes/" + indexName + "?definition=yes", "GET", credentials, convention);
httpJsonRequest.AddOperationHeaders(OperationsHeaders);
RavenJToken indexDef;
try
{
indexDef = httpJsonRequest.ReadResponseJson();
}
catch (WebException e)
{
var httpWebResponse = e.Response as HttpWebResponse;
if (httpWebResponse != null &&
httpWebResponse.StatusCode == HttpStatusCode.NotFound)
return null;
throw;
}
var value = indexDef.Value<RavenJObject>("Index");
return convention.CreateSerializer().Deserialize<IndexDefinition>(
new RavenJTokenReader(value)
);
}
private void DirectDelete(string key, Guid? etag, string operationUrl)
{
var metadata = new RavenJObject();
if (etag != null)
metadata.Add("ETag", etag.Value.ToString());
AddTransactionInformation(metadata);
var httpJsonRequest = jsonRequestFactory.CreateHttpJsonRequest(this, operationUrl + "/docs/" + key, "DELETE", metadata, credentials, convention);
httpJsonRequest.AddOperationHeaders(OperationsHeaders);
try
{
httpJsonRequest.ExecuteRequest();
}
catch (WebException e)
{
var httpWebResponse = e.Response as HttpWebResponse;
if (httpWebResponse == null ||
httpWebResponse.StatusCode != HttpStatusCode.Conflict)
throw;
throw ThrowConcurrencyException(e);
}
}
private static Exception ThrowConcurrencyException(WebException e)
{
using (var sr = new StreamReader(e.Response.GetResponseStreamWithHttpDecompression()))
{
var text = sr.ReadToEnd();
var errorResults = JsonConvert.DeserializeAnonymousType(text, new
{
url = (string)null,
actualETag = Guid.Empty,
expectedETag = Guid.Empty,
error = (string)null
});
return new ConcurrencyException(errorResults.error)
{
ActualETag = errorResults.actualETag,
ExpectedETag = errorResults.expectedETag
};
}
}
/// <summary>
/// Puts the index.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="definition">The definition.</param>
/// <returns></returns>
public string PutIndex(string name, IndexDefinition definition)
{
return PutIndex(name, definition, false);
}
/// <summary>
/// Puts the index.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="definition">The definition.</param>
/// <param name="overwrite">if set to <c>true</c> overwrite the index.</param>
/// <returns></returns>
public string PutIndex(string name, IndexDefinition definition, bool overwrite)
{
EnsureIsNotNullOrEmpty(name, "name");
return ExecuteWithReplication("PUT", operationUrl => DirectPutIndex(name, operationUrl, overwrite, definition));
}
private string DirectPutIndex(string name, string operationUrl, bool overwrite, IndexDefinition definition)
{
string requestUri = operationUrl + "/indexes/" + name;
var checkIndexExists = jsonRequestFactory.CreateHttpJsonRequest(this, requestUri, "HEAD", credentials, convention);
checkIndexExists.AddOperationHeaders(OperationsHeaders);
try
{
checkIndexExists.ExecuteRequest();
if (overwrite == false)
throw new InvalidOperationException("Cannot put index: " + name + ", index already exists");
}
catch (WebException e)
{
var httpWebResponse = e.Response as HttpWebResponse;
if (httpWebResponse == null || httpWebResponse.StatusCode != HttpStatusCode.NotFound)
throw;
}
var request = jsonRequestFactory.CreateHttpJsonRequest(this, requestUri, "PUT", credentials, convention);
request.AddOperationHeaders(OperationsHeaders);
request.Write(JsonConvert.SerializeObject(definition, Default.Converters));
var responseJson = (RavenJObject)request.ReadResponseJson();
return responseJson.Value<string>("index");
}
/// <summary>
/// Puts the index definition for the specified name
/// </summary>
/// <typeparam name="TDocument">The type of the document.</typeparam>
/// <typeparam name="TReduceResult">The type of the reduce result.</typeparam>
/// <param name="name">The name.</param>
/// <param name="indexDef">The index def.</param>
/// <returns></returns>
public string PutIndex<TDocument, TReduceResult>(string name, IndexDefinitionBuilder<TDocument, TReduceResult> indexDef)
{
return PutIndex(name, indexDef.ToIndexDefinition(convention));
}
/// <summary>
/// Puts the index for the specified name
/// </summary>
/// <typeparam name="TDocument">The type of the document.</typeparam>
/// <typeparam name="TReduceResult">The type of the reduce result.</typeparam>
/// <param name="name">The name.</param>
/// <param name="indexDef">The index def.</param>
/// <param name="overwrite">if set to <c>true</c> [overwrite].</param>
/// <returns></returns>
public string PutIndex<TDocument, TReduceResult>(string name, IndexDefinitionBuilder<TDocument, TReduceResult> indexDef, bool overwrite)
{
return PutIndex(name, indexDef.ToIndexDefinition(convention), overwrite);
}
/// <summary>
/// Queries the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="query">The query.</param>
/// <param name="includes">The includes.</param>
/// <returns></returns>
public QueryResult Query(string index, IndexQuery query, string[] includes)
{
EnsureIsNotNullOrEmpty(index, "index");
return ExecuteWithReplication("GET", u => DirectQuery(index, query, u, includes));
}
private QueryResult DirectQuery(string index, IndexQuery query, string operationUrl, string[] includes)
{
string path = query.GetIndexQueryUrl(operationUrl, index, "indexes");
if (includes != null && includes.Length > 0)
{
path += "&" + string.Join("&", includes.Select(x => "include=" + x).ToArray());
}
var request = jsonRequestFactory.CreateHttpJsonRequest(this, path, "GET", credentials, convention);
request.AddOperationHeaders(OperationsHeaders);
RavenJObject json;
try
{
json = (RavenJObject)request.ReadResponseJson();
}
catch (WebException e)
{
var httpWebResponse = e.Response as HttpWebResponse;
if (httpWebResponse != null && httpWebResponse.StatusCode == HttpStatusCode.NotFound)
{
var text = new StreamReader(httpWebResponse.GetResponseStreamWithHttpDecompression()).ReadToEnd();
if (text.Contains("maxQueryString"))
throw new InvalidOperationException(text, e);
throw new InvalidOperationException("There is no index named: " + index);
}
throw;
}
return SerializationHelper.ToQueryResult(json, request.ResponseHeaders["ETag"]);
}
/// <summary>
/// Deletes the index.
/// </summary>
/// <param name="name">The name.</param>
public void DeleteIndex(string name)
{
EnsureIsNotNullOrEmpty(name, "name");
ExecuteWithReplication("DELETE", operationUrl => DirectDeleteIndex(name, operationUrl));
}
private void DirectDeleteIndex(string name, string operationUrl)
{
var request = jsonRequestFactory.CreateHttpJsonRequest(this, operationUrl + "/indexes/" + name, "DELETE", credentials, convention);
request.AddOperationHeaders(OperationsHeaders);
request.ExecuteRequest();
}
/// <summary>
/// Gets the results for the specified ids.
/// </summary>
/// <param name="ids">The ids.</param>
/// <param name="includes">The includes.</param>
/// <returns></returns>
public MultiLoadResult Get(string[] ids, string[] includes)
{
return ExecuteWithReplication("GET", u => DirectGet(ids, u, includes));
}
/// <summary>
/// Perform a direct get for loading multiple ids in one request
/// </summary>
/// <param name="ids">The ids.</param>
/// <param name="operationUrl">The operation URL.</param>
/// <param name="includes">The includes.</param>
/// <returns></returns>
public MultiLoadResult DirectGet(string[] ids, string operationUrl, string[] includes)
{
var path = operationUrl + "/queries/?";
if (includes != null && includes.Length > 0)
{
path += string.Join("&", includes.Select(x => "include=" + x).ToArray());
}
var uniqueIds = new HashSet<string>(ids);
// if it is too big, we drop to POST (note that means that we can't use the HTTP cache any longer)
// we are fine with that, requests to load that many items are probably going to be rare
HttpJsonRequest request;
if (uniqueIds.Sum(x=>x.Length) < 1024)
{
path += "&" + string.Join("&", uniqueIds.Select(x => "id=" + x).ToArray());
request = jsonRequestFactory.CreateHttpJsonRequest(this, path, "GET", credentials, convention);
}
else
{
request = jsonRequestFactory.CreateHttpJsonRequest(this, path, "POST", credentials, convention);
request.Write(new RavenJArray(uniqueIds).ToString(Formatting.None));
}
request.AddOperationHeaders(OperationsHeaders);
var result = (RavenJObject) request.ReadResponseJson();
var results = result.Value<RavenJArray>("Results").Cast<RavenJObject>().ToList();
return new MultiLoadResult
{
Includes = result.Value<RavenJArray>("Includes").Cast<RavenJObject>().ToList(),
Results = ids.Select(id => results.FirstOrDefault(r => string.Equals(r["@metadata"].Value<string>("@id"), id,StringComparison.InvariantCultureIgnoreCase))).ToList()
};
}
/// <summary>
/// Executed the specified commands as a single batch
/// </summary>
/// <param name="commandDatas">The command data.</param>
/// <returns></returns>
public BatchResult[] Batch(IEnumerable<ICommandData> commandDatas)
{
return ExecuteWithReplication("POST", u => DirectBatch(commandDatas, u));
}
private BatchResult[] DirectBatch(IEnumerable<ICommandData> commandDatas, string operationUrl)
{
var metadata = new RavenJObject();
AddTransactionInformation(metadata);
var req = jsonRequestFactory.CreateHttpJsonRequest(this, operationUrl + "/bulk_docs", "POST", metadata, credentials, convention);
req.AddOperationHeaders(OperationsHeaders);
var jArray = new RavenJArray(commandDatas.Select(x => x.ToJson()));
req.Write(jArray.ToString(Formatting.None));
RavenJArray response;
try
{
response = (RavenJArray) req.ReadResponseJson();
}
catch (WebException e)
{
var httpWebResponse = e.Response as HttpWebResponse;
if (httpWebResponse == null ||
httpWebResponse.StatusCode != HttpStatusCode.Conflict)
throw;
throw ThrowConcurrencyException(e);
}
return convention.CreateSerializer().Deserialize<BatchResult[]>(new RavenJTokenReader(response));
}
/// <summary>
/// Commits the specified tx id.
/// </summary>
/// <param name="txId">The tx id.</param>
public void Commit(Guid txId)
{
ExecuteWithReplication<object>("POST", u =>
{
DirectCommit(txId, u);
return null;
});
}
private void DirectCommit(Guid txId, string operationUrl)
{
var httpJsonRequest = jsonRequestFactory.CreateHttpJsonRequest(this, operationUrl + "/transaction/commit?tx=" + txId, "POST", credentials, convention);
httpJsonRequest.AddOperationHeaders(OperationsHeaders);
httpJsonRequest.ReadResponseJson();
}
/// <summary>
/// Rollbacks the specified tx id.
/// </summary>
/// <param name="txId">The tx id.</param>
public void Rollback(Guid txId)
{
ExecuteWithReplication<object>("POST", u =>
{
DirectRollback(txId, u);
return null;
});
}
/// <summary>
/// Promotes the transaction.
/// </summary>
/// <param name="fromTxId">From tx id.</param>
/// <returns></returns>
public byte[] PromoteTransaction(Guid fromTxId)
{
return ExecuteWithReplication("PUT", u => DirectPromoteTransaction(fromTxId, u));
}
/// <summary>
/// Stores the recovery information.
/// </summary>
/// <param name="resourceManagerId">The resource manager Id for this transaction</param>
/// <param name="txId">The tx id.</param>
/// <param name="recoveryInformation">The recovery information.</param>
public void StoreRecoveryInformation(Guid resourceManagerId, Guid txId, byte[] recoveryInformation)
{
ExecuteWithReplication<object>("PUT", u =>
{
var metadata = new RavenJObject
{
{"Resource-Manager-Id", resourceManagerId.ToString()},
{Constants.NotForReplication, true}
};
var webRequest = jsonRequestFactory.CreateHttpJsonRequest(this, u + "/static/transactions/recoveryInformation/" + txId, "PUT", metadata, credentials, convention);
webRequest.Write(new MemoryStream(recoveryInformation));
webRequest.ExecuteRequest();
return null;
});
}
private byte[] DirectPromoteTransaction(Guid fromTxId, string operationUrl)
{
var webRequest = jsonRequestFactory.CreateHttpJsonRequest(this,
operationUrl + "/transaction/promote?fromTxId=" + fromTxId,
"POST", credentials, convention);
return webRequest.ReadResponseBytes();
}
private void DirectRollback(Guid txId, string operationUrl)
{
var httpJsonRequest = jsonRequestFactory.CreateHttpJsonRequest(this, operationUrl + "/transaction/rollback?tx=" + txId, "POST", credentials, convention);
httpJsonRequest.AddOperationHeaders(OperationsHeaders);
httpJsonRequest.ReadResponseJson();
}
/// <summary>
/// Returns a new <see cref="IDatabaseCommands"/> using the specified credentials
/// </summary>
/// <param name="credentialsForSession">The credentials for session.</param>
/// <returns></returns>
public IDatabaseCommands With(ICredentials credentialsForSession)
{
return new ServerClient(url, convention, credentialsForSession, replicationInformerGetter, databaseName, jsonRequestFactory, currentSessionId);
}
/// <summary>
/// Force the database commands to read directly from the master, unless there has been a failover.
/// </summary>
public void ForceReadFromMaster()
{
readStripingBase = -1;// this means that will have to use the master url first
}
/// <summary>
/// Create a new instance of <see cref="IDatabaseCommands"/> that will interacts
/// with the specified database
/// </summary>
public IDatabaseCommands ForDatabase(string database)
{
var databaseUrl = MultiDatabase.GetRootDatabaseUrl(url);
databaseUrl = databaseUrl + "/databases/" + database;
if (databaseUrl == Url)
return this;
return new ServerClient(databaseUrl, convention, credentials, replicationInformerGetter, database, jsonRequestFactory, currentSessionId)
{
OperationsHeaders = OperationsHeaders
};
}
public IDatabaseCommands ForDefaultDatabase()
{
var databaseUrl = MultiDatabase.GetRootDatabaseUrl(url);
if (databaseUrl == Url)
return this;
return new ServerClient(databaseUrl, convention, credentials, replicationInformerGetter, null, jsonRequestFactory, currentSessionId)
{
OperationsHeaders = OperationsHeaders
};
}
/// <summary>
/// Gets a value indicating whether [supports promotable transactions].
/// </summary>
/// <value>
/// <c>true</c> if [supports promotable transactions]; otherwise, <c>false</c>.
/// </value>