/
AsyncServerClient.cs
2405 lines (2081 loc) · 94.3 KB
/
AsyncServerClient.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
//-----------------------------------------------------------------------
// <copyright file="AsyncServerClient.cs" company="Hibernating Rhinos LTD">
// Copyright (c) Hibernating Rhinos LTD. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Raven.Client.Indexes;
using Raven.Database.Data;
using Raven.Imports.Newtonsoft.Json.Linq;
#if SILVERLIGHT || NETFX_CORE
using Raven.Abstractions.Replication;
using Raven.Abstractions.Util;
#else
using System.Transactions;
#endif
#if SILVERLIGHT
using Raven.Client.Silverlight.Connection;
#elif NETFX_CORE
using Raven.Client.WinRT.Connection;
#endif
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.Abstractions.Json;
using Raven.Abstractions.Replication;
using Raven.Abstractions.Util;
using Raven.Client.Changes;
using Raven.Client.Connection.Profiling;
using Raven.Client.Document;
using Raven.Client.Exceptions;
using Raven.Client.Extensions;
using Raven.Client.Listeners;
using Raven.Client.Connection;
using Raven.Imports.Newtonsoft.Json;
using Raven.Imports.Newtonsoft.Json.Bson;
using Raven.Json.Linq;
using System.Collections.Specialized;
namespace Raven.Client.Connection.Async
{
/// <summary>
/// Access the database commands in async fashion
/// </summary>
public class AsyncServerClient : IAsyncDatabaseCommands, IAsyncAdminDatabaseCommands, IAsyncInfoDatabaseCommands,
IAsyncGlobalAdminDatabaseCommands
{
private readonly ProfilingInformation profilingInformation;
private readonly IDocumentConflictListener[] conflictListeners;
private readonly string url;
private readonly string rootUrl;
private readonly OperationCredentials credentialsThatShouldBeUsedOnlyInOperationsWithoutReplication;
internal readonly DocumentConvention convention;
private NameValueCollection operationsHeaders = new NameValueCollection();
internal readonly HttpJsonRequestFactory jsonRequestFactory;
private readonly Guid? sessionId;
private readonly Func<string, ReplicationInformer> replicationInformerGetter;
private readonly string databaseName;
private readonly ReplicationInformer replicationInformer;
private int requestCount;
private int readStripingBase;
public string Url
{
get { return url; }
}
public ReplicationInformer ReplicationInformer
{
get { return replicationInformer; }
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncServerClient"/> class.
/// </summary>
public AsyncServerClient(string url, DocumentConvention convention, OperationCredentials credentials,
HttpJsonRequestFactory jsonRequestFactory, Guid? sessionId,
Func<string, ReplicationInformer> replicationInformerGetter, string databaseName,
IDocumentConflictListener[] conflictListeners)
{
profilingInformation = ProfilingInformation.CreateProfilingInformation(sessionId);
this.url = url;
if (this.url.EndsWith("/"))
this.url = this.url.Substring(0, this.url.Length - 1);
rootUrl = this.url;
var databasesIndex = rootUrl.IndexOf("/databases/", StringComparison.OrdinalIgnoreCase);
if (databasesIndex > 0)
{
rootUrl = rootUrl.Substring(0, databasesIndex);
}
this.jsonRequestFactory = jsonRequestFactory;
this.sessionId = sessionId;
this.convention = convention;
this.credentialsThatShouldBeUsedOnlyInOperationsWithoutReplication = credentials;
this.databaseName = databaseName;
this.conflictListeners = conflictListeners;
this.replicationInformerGetter = replicationInformerGetter;
this.replicationInformer = replicationInformerGetter(databaseName);
this.readStripingBase = replicationInformer.GetReadStripingBase();
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
}
/// <summary>
/// Gets the index names from the server asynchronously
/// </summary>
/// <param name="start">Paging start</param>
/// <param name="pageSize">Size of the page.</param>
public Task<string[]> GetIndexNamesAsync(int start, int pageSize)
{
return ExecuteWithReplication("GET", async operationMetadata =>
{
var json = (RavenJArray)await operationMetadata.Url.IndexNames(start, pageSize)
.NoCache()
.ToJsonRequest(this, operationMetadata.Credentials, convention)
.AddReplicationStatusHeaders(url, operationMetadata.Url, replicationInformer,
convention.FailoverBehavior,
HandleReplicationStatusChanges)
.ReadResponseJsonAsync();
return json.Select(x => x.Value<string>()).ToArray();
});
}
/// <summary>
/// Gets the indexes from the server asynchronously
/// </summary>
/// <param name="start">Paging start</param>
/// <param name="pageSize">Size of the page.</param>
public Task<IndexDefinition[]> GetIndexesAsync(int start, int pageSize)
{
return ExecuteWithReplication("GET", async operationMetadata =>
{
var url2 = (operationMetadata.Url + "/indexes/?start=" + start + "&pageSize=" + pageSize).NoCache();
var request =
jsonRequestFactory.CreateHttpJsonRequest(new CreateHttpJsonRequestParams(this, url2, "GET", operationMetadata.Credentials, convention));
request.AddReplicationStatusHeaders(url, operationMetadata.Url, replicationInformer, convention.FailoverBehavior,
HandleReplicationStatusChanges);
var json = (RavenJArray)await request.ReadResponseJsonAsync();
//NOTE: To review, I'm not confidence this is the correct way to deserialize the index definition
return json.Select(x =>
{
var value = ((RavenJObject)x)["definition"].ToString();
return JsonConvert.DeserializeObject<IndexDefinition>(value, new JsonToJsonConverter());
})
.ToArray();
});
}
/// <summary>
/// Gets the transformers from the server asynchronously
/// </summary>
public Task<TransformerDefinition[]> GetTransformersAsync(int start, int pageSize)
{
return ExecuteWithReplication("GET", async operationMetadata =>
{
var url2 = (operationMetadata.Url + "/transformers?start=" + start + "&pageSize=" + pageSize).NoCache();
var request =
jsonRequestFactory.CreateHttpJsonRequest(new CreateHttpJsonRequestParams(this, url2, "GET", operationMetadata.Credentials, convention));
request.AddReplicationStatusHeaders(url, operationMetadata.Url, replicationInformer, convention.FailoverBehavior,
HandleReplicationStatusChanges);
var json = (RavenJArray)await request.ReadResponseJsonAsync();
//NOTE: To review, I'm not confidence this is the correct way to deserialize the transformer definition
return
json.Select(
x =>
JsonConvert.DeserializeObject<TransformerDefinition>(((RavenJObject)x)["definition"].ToString(),
new JsonToJsonConverter()))
.ToArray();
});
}
/// <summary>
/// Resets the specified index asynchronously
/// </summary>
/// <param name="name">The name.</param>
public Task ResetIndexAsync(string name)
{
return ExecuteWithReplication("RESET", operationMetadata =>
{
var httpJsonRequestAsync =
jsonRequestFactory.CreateHttpJsonRequest(new CreateHttpJsonRequestParams(this, operationMetadata.Url + "/indexes/" + name,
"RESET", operationMetadata.Credentials, convention));
httpJsonRequestAsync.AddOperationHeaders(OperationsHeaders);
httpJsonRequestAsync.AddReplicationStatusHeaders(url, operationMetadata.Url, replicationInformer, convention.FailoverBehavior,
HandleReplicationStatusChanges);
return httpJsonRequestAsync.ReadResponseJsonAsync();
});
}
public Task<string> PutIndexAsync<TDocument, TReduceResult>(string name,
IndexDefinitionBuilder<TDocument, TReduceResult> indexDef, bool overwrite = false)
{
return PutIndexAsync(name, indexDef.ToIndexDefinition(convention), overwrite);
}
/// <summary>
/// Puts the index definition for the specified name asynchronously
/// </summary>
/// <param name="name">The name.</param>
/// <param name="indexDef">The index def.</param>
/// <param name="overwrite">Should overwrite index</param>
public Task<string> PutIndexAsync(string name, IndexDefinition indexDef, bool overwrite)
{
return ExecuteWithReplication("PUT", operationMetadata => DirectPutIndexAsync(name, indexDef, overwrite, operationMetadata));
}
/// <summary>
/// Puts the transformer definition for the specified name asynchronously
/// </summary>
public Task<string> PutTransformerAsync(string name, TransformerDefinition transformerDefinition)
{
return ExecuteWithReplication("PUT", operationMetadata => DirectPutTransformerAsync(name, transformerDefinition, operationMetadata));
}
/// <summary>
/// Puts the index definition for the specified name asynchronously with url
/// </summary>
/// <param name="name">The name.</param>
/// <param name="indexDef">The index def.</param>
/// <param name="overwrite">Should overwrite index</param>
/// <param name="operationMetadata">The metadata that contains URL and credentials to perform operation</param>
public async Task<string> DirectPutIndexAsync(string name, IndexDefinition indexDef, bool overwrite, OperationMetadata operationMetadata)
{
var requestUri = operationMetadata.Url + "/indexes/" + Uri.EscapeUriString(name) + "?definition=yes";
var webRequest = jsonRequestFactory.CreateHttpJsonRequest(
new CreateHttpJsonRequestParams(this, requestUri.NoCache(), "GET", operationMetadata.Credentials, convention)
.AddOperationHeaders(OperationsHeaders));
webRequest.AddReplicationStatusHeaders(url, operationMetadata.Url, replicationInformer, convention.FailoverBehavior,
HandleReplicationStatusChanges);
try
{
await webRequest.ExecuteRequestAsync();
if (overwrite == false)
throw new InvalidOperationException("Cannot put index: " + name + ", index already exists");
}
catch (ErrorResponseException e)
{
if (e.StatusCode != HttpStatusCode.NotFound)
throw;
}
var request = jsonRequestFactory.CreateHttpJsonRequest(
new CreateHttpJsonRequestParams(this, requestUri, "PUT", operationMetadata.Credentials, convention)
.AddOperationHeaders(OperationsHeaders));
var serializeObject = JsonConvert.SerializeObject(indexDef, Default.Converters);
ErrorResponseException responseException;
try
{
await request.WriteAsync(serializeObject);
var result = await request.ReadResponseJsonAsync();
return result.Value<string>("Index");
}
catch (ErrorResponseException e)
{
if (e.StatusCode != HttpStatusCode.BadRequest)
throw;
responseException = e;
}
var error =
await
responseException.TryReadErrorResponseObject(
new { Error = "", Message = "", IndexDefinitionProperty = "", ProblematicText = "" });
if (error == null)
throw responseException;
throw new IndexCompilationException(error.Message)
{
IndexDefinitionProperty = error.IndexDefinitionProperty,
ProblematicText = error.ProblematicText
};
}
/// <summary>
/// Puts the transformer definition for the specified name asynchronously with url
/// </summary>
public async Task<string> DirectPutTransformerAsync(string name, TransformerDefinition transformerDefinition,
OperationMetadata operationMetadata)
{
var requestUri = operationMetadata.Url + "/transformers/" + name;
var request = jsonRequestFactory.CreateHttpJsonRequest(
new CreateHttpJsonRequestParams(this, requestUri, "PUT", operationMetadata.Credentials, convention)
.AddOperationHeaders(OperationsHeaders));
var serializeObject = JsonConvert.SerializeObject(transformerDefinition, Default.Converters);
ErrorResponseException responseException;
try
{
await request.WriteAsync(serializeObject);
var result = await request.ReadResponseJsonAsync();
return result.Value<string>("Transformer");
}
catch (ErrorResponseException e)
{
if (e.StatusCode != HttpStatusCode.BadRequest)
throw;
responseException = e;
}
var error = await responseException.TryReadErrorResponseObject(new { Error = "", Message = "" });
if (error == null)
throw responseException;
throw new TransformCompilationException(error.Message);
}
/// <summary>
/// Deletes the index definition for the specified name asynchronously
/// </summary>
/// <param name="name">The name.</param>
public Task DeleteIndexAsync(string name)
{
return ExecuteWithReplication("DELETE", operationMetadata => operationMetadata.Url.Indexes(name)
.ToJsonRequest(this, operationMetadata.Credentials, convention,
OperationsHeaders, "DELETE")
.AddReplicationStatusHeaders(url, operationMetadata.Url,
replicationInformer,
convention
.FailoverBehavior,
HandleReplicationStatusChanges)
.ExecuteRequestAsync());
}
public Task<Operation> DeleteByIndexAsync(string indexName, IndexQuery queryToDelete, bool allowStale)
{
return ExecuteWithReplication("DELETE", async operationMetadata =>
{
string path = queryToDelete.GetIndexQueryUrl(operationMetadata.Url, indexName, "bulk_docs") + "&allowStale=" + allowStale;
var request = jsonRequestFactory.CreateHttpJsonRequest(
new CreateHttpJsonRequestParams(this, path, "DELETE", operationMetadata.Credentials, convention)
.AddOperationHeaders(OperationsHeaders));
request.AddReplicationStatusHeaders(url, operationMetadata.Url, replicationInformer, convention.FailoverBehavior,
HandleReplicationStatusChanges);
RavenJToken jsonResponse;
try
{
jsonResponse = await request.ReadResponseJsonAsync();
}
catch (ErrorResponseException e)
{
if (e.StatusCode == HttpStatusCode.NotFound)
throw new InvalidOperationException("There is no index named: " + indexName, e);
throw;
}
// Be compitable with the resopnse from v2.0 server
var serverBuild = request.ResponseHeaders.GetAsInt("Raven-Server-Build");
if (serverBuild < 2500)
{
if (serverBuild != 13 || (serverBuild == 13 && jsonResponse.Value<long>("OperationId") == default(long)))
{
return null;
}
}
var opId = ((RavenJObject)jsonResponse)["OperationId"];
if (opId == null || opId.Type != JTokenType.Integer)
return null;
return new Operation(this, opId.Value<long>());
});
}
public Task DeleteTransformerAsync(string name)
{
return ExecuteWithReplication("DELETE", operationMetadata => operationMetadata.Url.Transformer(name)
.ToJsonRequest(this, operationMetadata.Credentials, convention, OperationsHeaders, "DELETE")
.AddReplicationStatusHeaders(url, operationMetadata.Url, replicationInformer, convention.FailoverBehavior, HandleReplicationStatusChanges)
.ExecuteRequestAsync());
}
/// <summary>
/// Deletes the document for the specified id asynchronously
/// </summary>
/// <param name="id">The id.</param>
public Task DeleteDocumentAsync(string id)
{
return ExecuteWithReplication("DELETE", operationMetadata =>
{
return operationMetadata.Url.Doc(id)
.ToJsonRequest(this, operationMetadata.Credentials, convention, OperationsHeaders, "DELETE")
.ExecuteRequestAsync();
});
}
/// <summary>
/// Sends a patch request for a specific document, ignoring the document's Etag
/// </summary>
/// <param name="key">Id of the document to patch</param>
/// <param name="patches">Array of patch requests</param>
/// <param name="ignoreMissing">true if the patch request should ignore a missing document, false to throw DocumentDoesNotExistException</param>
public async Task<RavenJObject> PatchAsync(string key, PatchRequest[] patches, bool ignoreMissing)
{
var batchResults = await BatchAsync(new ICommandData[]
{
new PatchCommandData
{
Key = key,
Patches = patches,
}
}).ConfigureAwait(false);
if (!ignoreMissing && batchResults[0].PatchResult != null &&
batchResults[0].PatchResult == PatchResult.DocumentDoesNotExists)
throw new DocumentDoesNotExistsException("Document with key " + key + " does not exist.");
return batchResults[0].AdditionalData;
}
/// <summary>
/// Sends a patch request for a specific document
/// </summary>
/// <param name="key">Id of the document to patch</param>
/// <param name="patches">Array of patch requests</param>
/// <param name="etag">Require specific Etag [null to ignore]</param>
public async Task<RavenJObject> PatchAsync(string key, PatchRequest[] patches, Etag etag)
{
var batchResults = await BatchAsync(new ICommandData[]
{
new PatchCommandData
{
Key = key,
Patches = patches,
Etag = etag
}
}).ConfigureAwait(false);
return batchResults[0].AdditionalData;
}
/// <summary>
/// Sends a patch request for a specific document which may or may not currently exist
/// </summary>
/// <param name="key">Id of the document to patch</param>
/// <param name="patchesToExisting">Array of patch requests to apply to an existing document</param>
/// <param name="patchesToDefault">Array of patch requests to apply to a default document when the document is missing</param>
/// <param name="defaultMetadata">The metadata for the default document when the document is missing</param>
public async Task<RavenJObject> PatchAsync(string key, PatchRequest[] patchesToExisting,
PatchRequest[] patchesToDefault, RavenJObject defaultMetadata)
{
var batchResults = await BatchAsync(new ICommandData[]
{
new PatchCommandData
{
Key = key,
Patches = patchesToExisting,
PatchesIfMissing = patchesToDefault,
Metadata = defaultMetadata
}
}).ConfigureAwait(false);
return batchResults[0].AdditionalData;
}
/// <summary>
/// Sends a patch request for a specific document, ignoring the document's Etag
/// </summary>
/// <param name="key">Id of the document to patch</param>
/// <param name="patch">The patch request to use (using JavaScript)</param>
/// <param name="ignoreMissing">true if the patch request should ignore a missing document, false to throw DocumentDoesNotExistException</param>
public async Task<RavenJObject> PatchAsync(string key, ScriptedPatchRequest patch, bool ignoreMissing)
{
var batchResults = await BatchAsync(new ICommandData[]
{
new ScriptedPatchCommandData
{
Key = key,
Patch = patch,
}
}).ConfigureAwait(false);
if (!ignoreMissing && batchResults[0].PatchResult != null &&
batchResults[0].PatchResult == PatchResult.DocumentDoesNotExists)
throw new DocumentDoesNotExistsException("Document with key " + key + " does not exist.");
return batchResults[0].AdditionalData;
}
/// <summary>
/// Sends a patch request for a specific document
/// </summary>
/// <param name="key">Id of the document to patch</param>
/// <param name="patch">The patch request to use (using JavaScript)</param>
/// <param name="etag">Require specific Etag [null to ignore]</param>
public async Task<RavenJObject> PatchAsync(string key, ScriptedPatchRequest patch, Etag etag)
{
var batchResults = await BatchAsync(new ICommandData[]
{
new ScriptedPatchCommandData
{
Key = key,
Patch = patch,
Etag = etag
}
}).ConfigureAwait(false);
return batchResults[0].AdditionalData;
}
/// <summary>
/// Sends a patch request for a specific document which may or may not currently exist
/// </summary>
/// <param name="key">Id of the document to patch</param>
/// <param name="patchExisting">The patch request to use (using JavaScript) to an existing document</param>
/// <param name="patchDefault">The patch request to use (using JavaScript) to a default document when the document is missing</param>
/// <param name="defaultMetadata">The metadata for the default document when the document is missing</param>
public async Task<RavenJObject> PatchAsync(string key, ScriptedPatchRequest patchExisting,
ScriptedPatchRequest patchDefault, RavenJObject defaultMetadata)
{
var batchResults = await BatchAsync(new ICommandData[]
{
new ScriptedPatchCommandData
{
Key = key,
Patch = patchExisting,
PatchIfMissing = patchDefault,
Metadata = defaultMetadata
}
}).ConfigureAwait(false);
return batchResults[0].AdditionalData;
}
/// <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>
public Task<PutResult> PutAsync(string key, Etag etag, RavenJObject document, RavenJObject metadata)
{
return ExecuteWithReplication("PUT", operationMetadata => DirectPutAsync(operationMetadata, key, etag, document, metadata));
}
private async Task<PutResult> DirectPutAsync(OperationMetadata operationMetadata, string key, Etag etag, RavenJObject document, RavenJObject metadata)
{
if (metadata == null)
metadata = new RavenJObject();
var method = String.IsNullOrEmpty(key) ? "POST" : "PUT";
if (etag != null)
metadata["ETag"] = new RavenJValue((string)etag);
if (key != null)
key = Uri.EscapeDataString(key);
var request = jsonRequestFactory.CreateHttpJsonRequest(
new CreateHttpJsonRequestParams(this, operationMetadata.Url + "/docs/" + key, method, metadata, operationMetadata.Credentials, convention)
.AddOperationHeaders(OperationsHeaders));
request.AddReplicationStatusHeaders(url, operationMetadata.Url, replicationInformer, convention.FailoverBehavior,
HandleReplicationStatusChanges);
ErrorResponseException responseException;
try
{
await request.WriteAsync(document);
var result = await request.ReadResponseJsonAsync();
return convention.CreateSerializer().Deserialize<PutResult>(new RavenJTokenReader(result));
}
catch (ErrorResponseException e)
{
if (e.StatusCode != HttpStatusCode.Conflict)
throw;
responseException = e;
}
throw FetchConcurrencyException(responseException);
}
/// <summary>
/// Create a new instance of <see cref="IDatabaseCommands"/> that will interacts
/// with the specified database
/// </summary>
public IAsyncDatabaseCommands ForDatabase(string database)
{
if (database == Constants.SystemDatabase)
return ForSystemDatabase();
var databaseUrl = MultiDatabase.GetRootDatabaseUrl(url);
databaseUrl = databaseUrl + "/databases/" + database + "/";
if (databaseUrl == url)
return this;
return new AsyncServerClient(databaseUrl, convention, credentialsThatShouldBeUsedOnlyInOperationsWithoutReplication, jsonRequestFactory, sessionId,
replicationInformerGetter, database, conflictListeners)
{
operationsHeaders = operationsHeaders
};
}
/// <summary>
/// Create a new instance of <see cref="IDatabaseCommands"/> that will interact
/// with the root database. Useful if the database has works against a tenant database.
/// </summary>
public IAsyncDatabaseCommands ForSystemDatabase()
{
var databaseUrl = MultiDatabase.GetRootDatabaseUrl(url);
if (databaseUrl == url)
return this;
return new AsyncServerClient(databaseUrl, convention, credentialsThatShouldBeUsedOnlyInOperationsWithoutReplication, jsonRequestFactory, sessionId,
replicationInformerGetter, databaseName, conflictListeners)
{
operationsHeaders = operationsHeaders
};
}
/// <summary>
/// Gets or sets the operations headers.
/// </summary>
/// <value>The operations headers.</value>
public NameValueCollection OperationsHeaders
{
get { return operationsHeaders; }
set { operationsHeaders = value; }
}
/// <summary>
/// Begins an async get operation
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public Task<JsonDocument> GetAsync(string key)
{
EnsureIsNotNullOrEmpty(key, "key");
return ExecuteWithReplication("GET", operationMetadata => DirectGetAsync(operationMetadata, key));
}
/// <summary>
/// Gets the transformer definition for the specified name asynchronously
/// </summary>
/// <param name="name">The name.</param>
public Task<TransformerDefinition> GetTransformerAsync(string name)
{
return ExecuteWithReplication("GET", async operationMetadata =>
{
try
{
var transformerDefinitionJson = (RavenJObject)await operationMetadata.Url.Transformer(name)
.NoCache()
.ToJsonRequest(this, operationMetadata.Credentials, convention)
.AddReplicationStatusHeaders(url, operationMetadata.Url, replicationInformer, convention.FailoverBehavior, HandleReplicationStatusChanges)
.ReadResponseJsonAsync();
var value = transformerDefinitionJson.Value<RavenJObject>("Transformer");
return convention.CreateSerializer().Deserialize<TransformerDefinition>(new RavenJTokenReader(value));
}
catch (ErrorResponseException we)
{
if (we.StatusCode == HttpStatusCode.NotFound)
return null;
throw;
}
});
}
/// <summary>
/// Gets the index definition for the specified name asynchronously
/// </summary>
/// <param name="name">The name.</param>
public Task<IndexDefinition> GetIndexAsync(string name)
{
return ExecuteWithReplication("GET", async operationMetadata =>
{
try
{
var indexDefinitionJson = (RavenJObject)await operationMetadata.Url.IndexDefinition(name)
.NoCache()
.ToJsonRequest(this, operationMetadata.Credentials, convention)
.AddReplicationStatusHeaders(url, operationMetadata.Url,
replicationInformer,
convention.FailoverBehavior,
HandleReplicationStatusChanges)
.ReadResponseJsonAsync();
var value = indexDefinitionJson.Value<RavenJObject>("Index");
return convention.CreateSerializer().Deserialize<IndexDefinition>(new RavenJTokenReader(value));
}
catch (ErrorResponseException we)
{
if (we.StatusCode == HttpStatusCode.NotFound)
return null;
throw;
}
});
}
public async Task<JsonDocument> DirectGetAsync(OperationMetadata operationMetadata, string key)
{
if (key.Length > 127)
{
// avoid hitting UrlSegmentMaxLength limits in Http.sys
var multiLoadResult = await DirectGetAsync(operationMetadata, new[] { key }, new string[0], null, new Dictionary<string, RavenJToken>(), false);
var result = multiLoadResult.Results.FirstOrDefault();
if (result == null)
return null;
return SerializationHelper.RavenJObjectToJsonDocument(result);
}
var metadata = new RavenJObject();
AddTransactionInformation(metadata);
var createHttpJsonRequestParams = new CreateHttpJsonRequestParams(this, (operationMetadata.Url + "/docs?id=" + Uri.EscapeDataString(key)), "GET", metadata, operationMetadata.Credentials, convention);
var request = jsonRequestFactory.CreateHttpJsonRequest(createHttpJsonRequestParams.AddOperationHeaders(OperationsHeaders))
.AddReplicationStatusHeaders(url, operationMetadata.Url, replicationInformer, convention.FailoverBehavior, HandleReplicationStatusChanges);
Task<JsonDocument> resolveConflictTask;
try
{
var requestJson = await request.ReadResponseJsonAsync();
var docKey = request.ResponseHeaders.Get(Constants.DocumentIdFieldName) ?? key;
docKey = Uri.UnescapeDataString(docKey);
request.ResponseHeaders.Remove(Constants.DocumentIdFieldName);
var deserializeJsonDocument = SerializationHelper.DeserializeJsonDocument(docKey, requestJson, request.ResponseHeaders, request.ResponseStatusCode);
return deserializeJsonDocument;
}
catch (ErrorResponseException e)
{
switch (e.StatusCode)
{
case HttpStatusCode.NotFound:
return null;
case HttpStatusCode.Conflict:
resolveConflictTask = ResolveConflict(e.ResponseString, e.Etag, operationMetadata, key);
break;
default:
throw;
}
}
return await resolveConflictTask;
}
private async Task<JsonDocument> ResolveConflict(string httpResponse, Etag etag, OperationMetadata operationMetadata, string key)
{
var conflicts = new StringReader(httpResponse);
var conflictsDoc = RavenJObject.Load(new RavenJsonTextReader(conflicts));
var result =
await TryResolveConflictOrCreateConcurrencyException(operationMetadata, key, conflictsDoc, etag);
if (result != null)
throw result;
return await DirectGetAsync(operationMetadata, key);
}
/// <summary>
/// Begins an async multi get operation
/// </summary>
public Task<MultiLoadResult> GetAsync(string[] keys, string[] includes, string transformer = null,
Dictionary<string, RavenJToken> queryInputs = null, bool metadataOnly = false)
{
return ExecuteWithReplication("GET", operationMetadata => DirectGetAsync(operationMetadata, keys, includes, transformer, queryInputs, metadataOnly));
}
private async Task<MultiLoadResult> DirectGetAsync(OperationMetadata operationMetadata, string[] keys, string[] includes, string transformer,
Dictionary<string, RavenJToken> queryInputs, bool metadataOnly)
{
var path = operationMetadata.Url + "/queries/?";
if (metadataOnly)
path += "&metadata-only=true";
if (includes != null && includes.Length > 0)
{
path += string.Join("&", includes.Select(x => "include=" + x).ToArray());
}
if (string.IsNullOrEmpty(transformer) == false)
path += "&transformer=" + transformer;
if (queryInputs != null)
{
path = queryInputs.Aggregate(path,
(current, queryInput) =>
current + ("&" + string.Format("qp-{0}={1}", queryInput.Key, queryInput.Value)));
}
var metadata = new RavenJObject();
AddTransactionInformation(metadata);
var uniqueIds = new HashSet<string>(keys);
HttpJsonRequest request;
// 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 > 128 items are going to be rare
if (uniqueIds.Sum(x => x.Length) < 1024)
{
path += "&" + string.Join("&", uniqueIds.Select(x => "id=" + Uri.EscapeDataString(x)).ToArray());
request =
jsonRequestFactory.CreateHttpJsonRequest(new CreateHttpJsonRequestParams(this, path.NoCache(), "GET", metadata, operationMetadata.Credentials,
convention)
.AddOperationHeaders(OperationsHeaders));
request.AddReplicationStatusHeaders(url, operationMetadata.Url, replicationInformer, convention.FailoverBehavior,
HandleReplicationStatusChanges);
var result = await request.ReadResponseJsonAsync();
return await CompleteMultiGetAsync(operationMetadata, keys, includes, result);
}
request =
jsonRequestFactory.CreateHttpJsonRequest(new CreateHttpJsonRequestParams(this, path, "POST", metadata, operationMetadata.Credentials, convention)
.AddOperationHeaders(OperationsHeaders));
await request.WriteAsync(new RavenJArray(uniqueIds));
var responseResult = await request.ReadResponseJsonAsync();
return await CompleteMultiGetAsync(operationMetadata, keys, includes, responseResult);
}
private async Task<MultiLoadResult> CompleteMultiGetAsync(OperationMetadata operationMetadata, string[] keys, string[] includes,
RavenJToken result)
{
ErrorResponseException responseException;
try
{
var multiLoadResult = new MultiLoadResult
{
Includes = result.Value<RavenJArray>("Includes").Cast<RavenJObject>().ToList(),
Results = result.Value<RavenJArray>("Results").Cast<RavenJObject>().ToList()
};
var docResults = multiLoadResult.Results.Concat(multiLoadResult.Includes);
return
await
RetryOperationBecauseOfConflict(operationMetadata, docResults, multiLoadResult,
() => DirectGetAsync(operationMetadata, keys, includes, null, null, false));
}
catch (ErrorResponseException e)
{
if (e.StatusCode != HttpStatusCode.Conflict)
throw;
responseException = e;
}
throw FetchConcurrencyException(responseException);
}
/// <summary>
/// Begins an async get operation for documents
/// </summary>
/// <remarks>
/// This is primarily useful for administration of a database
/// </remarks>
public Task<JsonDocument[]> GetDocumentsAsync(int start, int pageSize, bool metadataOnly = false)
{
return ExecuteWithReplication("GET", async operationMetadata =>
{
var result = await GetDocumentsInternalAsync(start, null, pageSize, operationMetadata, metadataOnly);
return result.Cast<RavenJObject>()
.ToJsonDocuments()
.ToArray();
});
}
public Task<JsonDocument[]> GetDocumentsAsync(Etag fromEtag, int pageSize, bool metadataOnly = false)
{
return ExecuteWithReplication("GET", async operationMetadata =>
{
var result = await GetDocumentsInternalAsync(null, fromEtag, pageSize, operationMetadata, metadataOnly);
return result.Cast<RavenJObject>()
.ToJsonDocuments()
.ToArray();
});
}
public async Task<RavenJArray> GetDocumentsInternalAsync(int? start, Etag fromEtag, int pageSize, OperationMetadata operationMetadata, bool metadataOnly = false)
{
var requestUri = url + "/docs/?";
if (start.HasValue && start.Value > 0)
{
requestUri += "start=" + start;
}
else if (fromEtag != null)
{
requestUri += "etag=" + fromEtag;
}
requestUri += "&pageSize=" + pageSize;
if (metadataOnly)
requestUri += "&metadata-only=true";
var @params = new CreateHttpJsonRequestParams(this, requestUri.NoCache(), "GET", operationMetadata.Credentials, convention)
.AddOperationHeaders(OperationsHeaders);
return (RavenJArray) await jsonRequestFactory.CreateHttpJsonRequest(@params)
.ReadResponseJsonAsync();
}
public Task<Operation> UpdateByIndexAsync(string indexName, IndexQuery queryToUpdate, ScriptedPatchRequest patch, bool allowStale)
{
var requestData = RavenJObject.FromObject(patch).ToString(Formatting.Indented);
return UpdateByIndexImpl(indexName, queryToUpdate, allowStale, requestData, "EVAL");
}
public Task<Operation> UpdateByIndexAsync(string indexName, IndexQuery queryToUpdate, PatchRequest[] patchRequests,
bool allowStale = false)
{
var requestData = new RavenJArray(patchRequests.Select(x => x.ToJson())).ToString(Formatting.Indented);
return UpdateByIndexImpl(indexName, queryToUpdate, allowStale, requestData, "PATCH");
}
public async Task<MultiLoadResult> MoreLikeThisAsync(MoreLikeThisQuery query)
{
var requestUrl = query.GetRequestUri();
EnsureIsNotNullOrEmpty(requestUrl, "url");
var result = await ExecuteWithReplication("GET", async operationMetadata =>
{
var metadata = new RavenJObject();
AddTransactionInformation(metadata);
var request = jsonRequestFactory.CreateHttpJsonRequest(
new CreateHttpJsonRequestParams(this, operationMetadata.Url + requestUrl, "GET", metadata, operationMetadata.Credentials, convention)
.AddOperationHeaders(OperationsHeaders));
return await request.ReadResponseJsonAsync();
});
return ((RavenJObject)result).Deserialize<MultiLoadResult>(convention);
}
public Task<long> NextIdentityForAsync(string name)
{
return ExecuteWithReplication("POST", async operationMetadata =>
{
var request = jsonRequestFactory.CreateHttpJsonRequest(
new CreateHttpJsonRequestParams(this, operationMetadata.Url + "/identity/next?name=" + Uri.EscapeDataString(name), "POST", operationMetadata.Credentials, convention)
.AddOperationHeaders(OperationsHeaders));
var readResponseJson = await request.ReadResponseJsonAsync();
return readResponseJson.Value<long>("Value");
});
}
private Task<Operation> UpdateByIndexImpl(string indexName, IndexQuery queryToUpdate, bool allowStale, String requestData, String method)
{
return ExecuteWithReplication(method, async operationMetadata =>
{
string path = queryToUpdate.GetIndexQueryUrl(operationMetadata.Url, indexName, "bulk_docs") + "&allowStale=" + allowStale;
var request = jsonRequestFactory.CreateHttpJsonRequest(
new CreateHttpJsonRequestParams(this, path, method, operationMetadata.Credentials, convention));
request.AddOperationHeaders(OperationsHeaders);
await request.WriteAsync(requestData);
RavenJToken jsonResponse;
try
{
jsonResponse = await request.ReadResponseJsonAsync();
}
catch (ErrorResponseException e)
{
if (e.StatusCode == HttpStatusCode.NotFound)
throw new InvalidOperationException("There is no index named: " + indexName);
throw;
}
return new Operation(this, jsonResponse.Value<long>("OperationId"));
});
}
/// <summary>
/// Using the given Index, calculate the facets as per the specified doc with the given start and pageSize
/// </summary>
/// <param name="index">Name of the index</param>
/// <param name="query">Query to build facet results</param>
/// <param name="facetSetupDoc">Name of the FacetSetup document</param>
/// <param name="start">Start index for paging</param>
/// <param name="pageSize">Paging PageSize. If set, overrides Facet.MaxResults</param>
public Task<FacetResults> GetFacetsAsync(string index, IndexQuery query, string facetSetupDoc, int start = 0,
int? pageSize = null)
{
return ExecuteWithReplication("GET", async operationMetadata =>
{
var requestUri = operationMetadata.Url + string.Format("/facets/{0}?facetDoc={1}{2}&facetStart={3}&facetPageSize={4}",
Uri.EscapeUriString(index),
Uri.EscapeDataString(facetSetupDoc),
query.GetMinimalQueryString(),
start,
pageSize);