Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 0a06b7dd5b
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 272 lines (243 sloc) 8.814 kb
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
//-----------------------------------------------------------------------
// <copyright file="DocumentRetriever.cs" company="Hibernating Rhinos LTD">
// Copyright (c) Hibernating Rhinos LTD. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using Newtonsoft.Json.Linq;
using NLog;
using Raven.Abstractions.Data;
using Raven.Abstractions.Indexing;
using Raven.Abstractions.Linq;
using Raven.Abstractions.MEF;
using Raven.Database.Data;
using Raven.Database.Indexing;
using Raven.Database.Linq;
using Raven.Database.Plugins;
using Raven.Database.Storage;
using Raven.Abstractions.Json;
using System.Linq;
using Raven.Json.Linq;

namespace Raven.Database.Impl
{
public class DocumentRetriever : ITranslatorDatabaseAccessor
{
private static Logger log = LogManager.GetCurrentClassLogger();

private readonly IDictionary<string, JsonDocument> cache = new Dictionary<string, JsonDocument>(StringComparer.InvariantCultureIgnoreCase);
private readonly HashSet<string> loadedIdsForRetrieval = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
private readonly HashSet<string> loadedIdsForFilter = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
private readonly IStorageActionsAccessor actions;
private readonly OrderedPartCollection<AbstractReadTrigger> triggers;
private readonly HashSet<string> itemsToInclude;

public DocumentRetriever(IStorageActionsAccessor actions, OrderedPartCollection<AbstractReadTrigger> triggers,
HashSet<string> itemsToInclude = null)
{
this.actions = actions;
this.triggers = triggers;
this.itemsToInclude = itemsToInclude ?? new HashSet<string>();
}

public JsonDocument RetrieveDocumentForQuery(IndexQueryResult queryResult, IndexDefinition indexDefinition, FieldsToFetch fieldsToFetch)
{
return ExecuteReadTriggers(ProcessReadVetoes(
RetrieveDocumentInternal(queryResult, loadedIdsForRetrieval, fieldsToFetch, indexDefinition),
null, ReadOperation.Query), null, ReadOperation.Query);
}


public JsonDocument ExecuteReadTriggers(JsonDocument document, TransactionInformation transactionInformation, ReadOperation operation)
{
return ExecuteReadTriggersOnRead(ProcessReadVetoes(document, transactionInformation, operation),
transactionInformation, operation);
}

private JsonDocument ExecuteReadTriggersOnRead(JsonDocument resultingDocument, TransactionInformation transactionInformation, ReadOperation operation)
{
if (resultingDocument == null)
return null;

triggers.Apply(
trigger =>
trigger.OnRead(resultingDocument.Key, resultingDocument.DataAsJson, resultingDocument.Metadata, operation,
transactionInformation));

return resultingDocument;
}

private JsonDocument RetrieveDocumentInternal(
IndexQueryResult queryResult,
HashSet<string> loadedIds,
FieldsToFetch fieldsToFetch,
IndexDefinition indexDefinition)
{
var queryScore = queryResult.Score;

if (float.IsNaN(queryScore))
queryScore = 0f;

if (queryResult.Projection == null)
{
// duplicate document, filter it out
if (loadedIds.Add(queryResult.Key) == false)
return null;
var document = GetDocumentWithCaching(queryResult.Key);
if (document != null)
document.Metadata[Constants.TemporaryScoreValue] = queryScore;
return document;
}

if (fieldsToFetch.IsProjection)
{
if (indexDefinition.IsMapReduce == false)
{
bool hasStoredFields = false;
foreach (var fieldToFetch in fieldsToFetch)
{
FieldStorage value;
if (indexDefinition.Stores.TryGetValue(fieldToFetch, out value) == false &&
value != FieldStorage.No)
continue;
hasStoredFields = true;
}
if (hasStoredFields == false)
{
// duplicate document, filter it out
if (loadedIds.Add(queryResult.Key) == false)
return null;
}
}
var fieldsToFetchFromDocument = fieldsToFetch.Where(fieldToFetch => queryResult.Projection[fieldToFetch] == null).ToArray();
if (fieldsToFetchFromDocument.Length > 0)
{
var doc = GetDocumentWithCaching(queryResult.Key);
if (doc != null)
{
var result = doc.DataAsJson.SelectTokenWithRavenSyntax(fieldsToFetchFromDocument.ToArray());
foreach (var property in result)
{
if (property.Value == null || property.Value.Type == JTokenType.Null)
continue;
queryResult.Projection[property.Key] = property.Value;
}
}
}
}

return new JsonDocument
{
Key = queryResult.Key,
DataAsJson = queryResult.Projection,
Metadata = new RavenJObject{{Constants.TemporaryScoreValue, queryScore}}
};
}


private JsonDocument GetDocumentWithCaching(string key)
{
if (key == null)
return null;
JsonDocument doc;
if (cache.TryGetValue(key, out doc))
return doc;
doc = actions.Documents.DocumentByKey(key, null);
EnsureIdInMetadata(doc);
cache[key] = doc;
return doc;
}

public static void EnsureIdInMetadata(IJsonDocumentMetadata doc)
{
if (doc == null || doc.Metadata == null)
return;

doc.Metadata["@id"] = new RavenJValue(doc.Key);
}

public bool ShouldIncludeResultInQuery(IndexQueryResult arg, IndexDefinition indexDefinition, FieldsToFetch fieldsToFetch)
{
var doc = RetrieveDocumentInternal(arg, loadedIdsForFilter, fieldsToFetch, indexDefinition);
if (doc == null)
return false;
doc = ProcessReadVetoes(doc, null, ReadOperation.Query);
return doc != null;
}

public T ProcessReadVetoes<T>(T document, TransactionInformation transactionInformation, ReadOperation operation)
where T : class, IJsonDocumentMetadata, new()
{
if (document == null)
return document;
foreach (var readTrigger in triggers)
{
var readVetoResult = readTrigger.Value.AllowRead(document.Key, document.Metadata, operation, transactionInformation);
switch (readVetoResult.Veto)
{
case ReadVetoResult.ReadAllow.Allow:
break;
case ReadVetoResult.ReadAllow.Deny:
return new T
{
Etag = Guid.Empty,
LastModified = DateTime.MinValue,
NonAuthoritativeInformation = false,
Metadata = new RavenJObject
{
{
"Raven-Read-Veto", new RavenJObject
{
{"Reason", readVetoResult.Reason},
{"Trigger", readTrigger.ToString()}
}
}
}
};
case ReadVetoResult.ReadAllow.Ignore:
log.Debug("Triggered {0} asked us to ignore {1}", readTrigger.Value, document.Key);
return null;
default:
throw new ArgumentOutOfRangeException(readVetoResult.Veto.ToString());
}
}

return document;
}

public dynamic Include(object maybeId)
{
if (maybeId == null || maybeId is DynamicNullObject)
return new DynamicNullObject();
var id = maybeId as string;
if (id != null)
return Include(id);
var jId = maybeId as RavenJValue;
if (jId != null)
return Include(jId.Value.ToString());

foreach (var itemId in (IEnumerable)maybeId)
{
Include(itemId);
}
return new DynamicNullObject();

}
public dynamic Include(string id)
{
itemsToInclude.Add(id);
return new DynamicNullObject();
}

public dynamic Include(IEnumerable<string> ids)
{
foreach (var id in ids)
{
itemsToInclude.Add(id);
}
return new DynamicNullObject();
}

public dynamic Load(string id)
{
var document = GetDocumentWithCaching(id);
if(document == null)
return new DynamicNullObject();
return new DynamicJsonObject(document.ToJson());
}

public dynamic Load(object maybeId)
{
if (maybeId == null || maybeId is DynamicNullObject)
return new DynamicNullObject();
var id = maybeId as string;
if (id != null)
return Load(id);
var jId = maybeId as RavenJValue;
if (jId != null)
return Load(jId.Value.ToString());

var items = new List<dynamic>();
foreach (var itemId in (IEnumerable)maybeId)
{
items.Add(Load(itemId));
}
return new DynamicList(items.Select(x => (object) x).ToArray());
}
}
}
Something went wrong with that request. Please try again.