forked from apache/lucenenet
/
CachedOrdinalsReader.cs
253 lines (230 loc) · 10.6 KB
/
CachedOrdinalsReader.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
// Lucene version compatibility level 4.8.1
using Lucene.Net.Support;
using Lucene.Net.Support.Threading;
using Lucene.Net.Util;
#if !FEATURE_CONDITIONALWEAKTABLE_ENUMERATOR
using Prism.Events;
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace Lucene.Net.Facet.Taxonomy
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
using ArrayUtil = Lucene.Net.Util.ArrayUtil;
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using BinaryDocValues = Lucene.Net.Index.BinaryDocValues;
using DocValuesFormat = Lucene.Net.Codecs.DocValuesFormat;
using IAccountable = Lucene.Net.Util.IAccountable;
using Int32sRef = Lucene.Net.Util.Int32sRef;
using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator;
/// <summary>
/// A per-segment cache of documents' facet ordinals. Every
/// <see cref="CachedOrds"/> holds the ordinals in a raw <see cref="T:int[]"/>,
/// and therefore consumes as much RAM as the total
/// number of ordinals found in the segment, but saves the
/// CPU cost of decoding ordinals during facet counting.
///
/// <para>
/// <b>NOTE:</b> every <see cref="CachedOrds"/> is limited to 2.1B
/// total ordinals. If that is a limitation for you then
/// consider limiting the segment size to fewer documents, or
/// use an alternative cache which pages through the category
/// ordinals.
///
/// </para>
/// <para>
/// <b>NOTE:</b> when using this cache, it is advised to use
/// a <see cref="DocValuesFormat"/> that does not cache the data in
/// memory, at least for the category lists fields, or
/// otherwise you'll be doing double-caching.
///
/// </para>
/// <para>
/// <b>NOTE:</b> create one instance of this and re-use it
/// for all facet implementations (the cache is per-instance,
/// not static).
/// </para>
/// </summary>
public class CachedOrdinalsReader : OrdinalsReader, IAccountable
{
private readonly OrdinalsReader source;
#if !FEATURE_CONDITIONALWEAKTABLE_ENUMERATOR
// LUCENENET specific: Add weak event handler for .NET Standard 2.0 and .NET Framework, since we don't have an enumerator to use
private readonly IEventAggregator eventAggregator = new EventAggregator();
#endif
private readonly ConditionalWeakTable<object, CachedOrds> ordsCache = new ConditionalWeakTable<object, CachedOrds>();
private readonly object syncLock = new object();
/// <summary>
/// Sole constructor. </summary>
public CachedOrdinalsReader(OrdinalsReader source)
{
this.source = source;
}
private CachedOrds GetCachedOrds(AtomicReaderContext context)
{
// LUCENENET NOTE: Since ConditionalWeakTable doesn't synchronize on enumeration in the RamBytesUsed() method,
// the lock is still required here despite it being a threadsafe collection.
UninterruptableMonitor.Enter(syncLock);
try
{
object cacheKey = context.Reader.CoreCacheKey;
if (!ordsCache.TryGetValue(cacheKey, out CachedOrds ords))
{
ords = new CachedOrds(source.GetReader(context), context.Reader.MaxDoc);
// LUCENENET specific: Since this is the only thread that can modify ordsCache
// and we just checked that the value doesn't exist above, we can simplify this to Add()
// which also means we don't need conditional compilation because ConditionalWeakTable
// doesn't support this[index].
ordsCache.Add(cacheKey, ords);
#if !FEATURE_CONDITIONALWEAKTABLE_ENUMERATOR
// LUCENENET specific: Add weak event handler for .NET Standard 2.0 and .NET Framework, since we don't have an enumerator to use
context.Reader.SubscribeToGetCacheKeysEvent(eventAggregator.GetEvent<Events.GetCacheKeysEvent>());
#endif
}
return ords;
}
finally
{
UninterruptableMonitor.Exit(syncLock);
}
}
public override string IndexFieldName => source.IndexFieldName;
public override OrdinalsSegmentReader GetReader(AtomicReaderContext context)
{
CachedOrds cachedOrds = GetCachedOrds(context);
return new OrdinalsSegmentReaderAnonymousClass(cachedOrds);
}
private class OrdinalsSegmentReaderAnonymousClass : OrdinalsSegmentReader
{
private readonly CachedOrds cachedOrds;
public OrdinalsSegmentReaderAnonymousClass(CachedOrds cachedOrds)
{
this.cachedOrds = cachedOrds;
}
public override void Get(int docID, Int32sRef ordinals)
{
ordinals.Int32s = cachedOrds.Ordinals;
ordinals.Offset = cachedOrds.Offsets[docID];
ordinals.Length = cachedOrds.Offsets[docID + 1] - ordinals.Offset;
}
}
/// <summary>
/// Holds the cached ordinals in two parallel <see cref="T:int[]"/> arrays.
/// </summary>
public sealed class CachedOrds : IAccountable
{
/// <summary>
/// Index into <see cref="Ordinals"/> for each document.
/// </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public int[] Offsets { get; private set; }
/// <summary>
/// Holds ords for all docs.
/// </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public int[] Ordinals { get; private set; }
/// <summary>
/// Creates a new <see cref="CachedOrds"/> from the <see cref="BinaryDocValues"/>.
/// Assumes that the <see cref="BinaryDocValues"/> is not <c>null</c>.
/// </summary>
public CachedOrds(OrdinalsSegmentReader source, int maxDoc)
{
Offsets = new int[maxDoc + 1];
int[] ords = new int[maxDoc]; // let's assume one ordinal per-document as an initial size
// this aggregator is limited to Integer.MAX_VALUE total ordinals.
long totOrds = 0;
Int32sRef values = new Int32sRef(32);
for (int docID = 0; docID < maxDoc; docID++)
{
Offsets[docID] = (int)totOrds;
source.Get(docID, values);
long nextLength = totOrds + values.Length;
if (nextLength > ords.Length)
{
if (nextLength > ArrayUtil.MAX_ARRAY_LENGTH)
{
throw IllegalStateException.Create("too many ordinals (>= " + nextLength + ") to cache");
}
ords = ArrayUtil.Grow(ords, (int)nextLength);
}
Array.Copy(values.Int32s, 0, ords, (int)totOrds, values.Length);
totOrds = nextLength;
}
Offsets[maxDoc] = (int)totOrds;
// if ords array is bigger by more than 10% of what we really need, shrink it
if ((double)totOrds / ords.Length < 0.9)
{
this.Ordinals = new int[(int)totOrds];
Array.Copy(ords, 0, this.Ordinals, 0, (int)totOrds);
}
else
{
this.Ordinals = ords;
}
}
public long RamBytesUsed()
{
long mem = RamUsageEstimator.ShallowSizeOf(this) + RamUsageEstimator.SizeOf(Offsets);
if (Offsets != Ordinals)
{
mem += RamUsageEstimator.SizeOf(Ordinals);
}
return mem;
}
}
public virtual long RamBytesUsed()
{
// LUCENENET specific - moved Reflection calls outside of the lock (similar to CachingWrapperFilter) to improve performance.
// Sync only to pull the current set of values:
IList<CachedOrds> cachedOrdsList;
UninterruptableMonitor.Enter(syncLock);
try
{
cachedOrdsList = new List<CachedOrds>();
#if FEATURE_CONDITIONALWEAKTABLE_ENUMERATOR
foreach (var pair in ordsCache)
cachedOrdsList.Add(pair.Value);
#else
// LUCENENET specific - since .NET Standard 2.0 and .NET Framework don't have a CondtionalWeakTable enumerator,
// we use a weak event to retrieve the CachedOrds instances. We look each of these up here to avoid the need
// to attach events to the CachedOrds instances themselves (thus using the existing IndexReader.Dispose()
// method to detach the events rather than using a finalizer in CachedOrds to ensure they are cleaned up).
var e = new Events.GetCacheKeysEventArgs();
eventAggregator.GetEvent<Events.GetCacheKeysEvent>().Publish(e);
foreach (var key in e.CacheKeys)
if (ordsCache.TryGetValue(key, out CachedOrds value))
cachedOrdsList.Add(value);
#endif
}
finally
{
UninterruptableMonitor.Exit(syncLock);
}
long total = 0;
foreach (CachedOrds ord in cachedOrdsList)
{
total += ord.RamBytesUsed();
}
return total;
}
}
}