forked from apache/ignite-3
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Table.cs
385 lines (311 loc) · 12.1 KB
/
Table.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
/*
* 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.
*/
namespace Apache.Ignite.Internal.Table
{
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Buffers;
using Ignite.Table;
using Ignite.Transactions;
using Proto;
using Proto.MsgPack;
using Serialization;
using Sql;
/// <summary>
/// Table API.
/// </summary>
internal sealed class Table : ITable
{
/** Socket. */
private readonly ClientFailoverSocket _socket;
/** SQL. */
private readonly Sql _sql;
/** Schemas. */
private readonly ConcurrentDictionary<int, Schema> _schemas = new();
/** Cached record views. */
private readonly ConcurrentDictionary<Type, object> _recordViews = new();
/** */
private readonly object _latestSchemaLock = new();
/** */
private readonly SemaphoreSlim _partitionAssignmentSemaphore = new(1);
/** */
private volatile int _latestSchemaVersion = -1;
/** */
private volatile int _partitionAssignmentVersion = -1;
/** */
private volatile string[]? _partitionAssignment;
/// <summary>
/// Initializes a new instance of the <see cref="Table"/> class.
/// </summary>
/// <param name="name">Table name.</param>
/// <param name="id">Table id.</param>
/// <param name="socket">Socket.</param>
/// <param name="sql">SQL.</param>
public Table(string name, Guid id, ClientFailoverSocket socket, Sql sql)
{
_socket = socket;
_sql = sql;
Name = name;
Id = id;
RecordBinaryView = new RecordView<IIgniteTuple>(
this,
new RecordSerializer<IIgniteTuple>(this, TupleSerializerHandler.Instance),
_sql);
// RecordView and KeyValueView are symmetric and perform the same operations on the protocol level.
// Only serialization is different - KeyValueView splits records into two parts.
// Therefore, KeyValueView below simply delegates to RecordView<KvPair>,
// and SerializerHandler writes KV pair as a single record and reads back record as two parts.
var pairSerializer = new RecordSerializer<KvPair<IIgniteTuple, IIgniteTuple>>(this, TuplePairSerializerHandler.Instance);
KeyValueBinaryView = new KeyValueView<IIgniteTuple, IIgniteTuple>(
new RecordView<KvPair<IIgniteTuple, IIgniteTuple>>(this, pairSerializer, _sql));
}
/// <inheritdoc/>
public string Name { get; }
/// <inheritdoc/>
public IRecordView<IIgniteTuple> RecordBinaryView { get; }
/// <inheritdoc/>
public IKeyValueView<IIgniteTuple, IIgniteTuple> KeyValueBinaryView { get; }
/// <summary>
/// Gets the associated socket.
/// </summary>
internal ClientFailoverSocket Socket => _socket;
/// <summary>
/// Gets the table id.
/// </summary>
internal Guid Id { get; }
/// <inheritdoc/>
public IRecordView<T> GetRecordView<T>()
where T : notnull => GetRecordViewInternal<T>();
/// <inheritdoc/>
public IKeyValueView<TK, TV> GetKeyValueView<TK, TV>()
where TK : notnull
where TV : notnull =>
new KeyValueView<TK, TV>(GetRecordViewInternal<KvPair<TK, TV>>());
/// <summary>
/// Gets the record view for the specified type.
/// </summary>
/// <typeparam name="T">Record type.</typeparam>
/// <returns>Record view.</returns>
internal RecordView<T> GetRecordViewInternal<T>()
where T : notnull
{
// ReSharper disable once HeapView.CanAvoidClosure (generics prevent this)
return (RecordView<T>)_recordViews.GetOrAdd(
typeof(T),
_ => new RecordView<T>(this, new RecordSerializer<T>(this, new ObjectSerializerHandler<T>()), _sql));
}
/// <summary>
/// Reads the schema.
/// </summary>
/// <param name="buf">Buffer.</param>
/// <returns>Schema or null.</returns>
internal async ValueTask<Schema?> ReadSchemaAsync(PooledBuffer buf)
{
var ver = ReadSchemaVersion(buf);
if (ver == null)
{
return null;
}
if (_schemas.TryGetValue(ver.Value, out var res))
{
return res;
}
return await LoadSchemaAsync(ver).ConfigureAwait(false);
static int? ReadSchemaVersion(PooledBuffer buf)
{
var reader = buf.GetReader();
return reader.ReadInt32Nullable();
}
}
/// <summary>
/// Gets the latest schema.
/// </summary>
/// <returns>Schema.</returns>
internal async ValueTask<Schema> GetLatestSchemaAsync()
{
var latestSchemaVersion = _latestSchemaVersion;
if (latestSchemaVersion >= 0)
{
return _schemas[latestSchemaVersion];
}
return await LoadSchemaAsync(null).ConfigureAwait(false);
}
/// <summary>
/// Gets the preferred node by colocation hash.
/// </summary>
/// <param name="colocationHash">Colocation hash.</param>
/// <param name="transaction">Transaction.</param>
/// <returns>Preferred node.</returns>
internal async ValueTask<PreferredNode> GetPreferredNode(int colocationHash, ITransaction? transaction)
{
if (transaction != null)
{
return default;
}
var assignment = await GetPartitionAssignmentAsync().ConfigureAwait(false);
if (assignment == null || assignment.Length == 0)
{
// Happens on table drop.
return default;
}
var partition = Math.Abs(colocationHash % assignment.Length);
var nodeId = assignment[partition];
return PreferredNode.FromId(nodeId);
}
private async ValueTask<string[]?> GetPartitionAssignmentAsync()
{
var socketVer = _socket.PartitionAssignmentVersion;
var assignment = _partitionAssignment;
// Async double-checked locking. Assignment changes rarely, so we avoid the lock if possible.
if (_partitionAssignmentVersion == socketVer && assignment != null)
{
return assignment;
}
await _partitionAssignmentSemaphore.WaitAsync().ConfigureAwait(false);
try
{
socketVer = _socket.PartitionAssignmentVersion;
assignment = _partitionAssignment;
if (_partitionAssignmentVersion == socketVer && assignment != null)
{
return assignment;
}
assignment = await LoadPartitionAssignmentAsync().ConfigureAwait(false);
_partitionAssignment = assignment;
_partitionAssignmentVersion = socketVer;
return assignment;
}
finally
{
_partitionAssignmentSemaphore.Release();
}
}
/// <summary>
/// Loads the schema.
/// </summary>
/// <param name="version">Version.</param>
/// <returns>Schema.</returns>
private async Task<Schema> LoadSchemaAsync(int? version)
{
using var writer = ProtoCommon.GetMessageWriter();
Write();
using var resBuf = await _socket.DoOutInOpAsync(ClientOp.SchemasGet, writer).ConfigureAwait(false);
return Read();
void Write()
{
var w = writer.MessageWriter;
w.Write(Id);
if (version == null)
{
w.WriteNil();
}
else
{
w.WriteArrayHeader(1);
w.Write(version.Value);
}
}
Schema Read()
{
var r = resBuf.GetReader();
var schemaCount = r.ReadMapHeader();
if (schemaCount == 0)
{
throw new IgniteClientException(ErrorGroups.Client.Protocol, "Schema not found: " + version);
}
Schema last = null!;
for (var i = 0; i < schemaCount; i++)
{
last = ReadSchema(ref r);
}
// Store all schemas in the map, and return last.
return last;
}
}
/// <summary>
/// Reads the schema.
/// </summary>
/// <param name="r">Reader.</param>
/// <returns>Schema.</returns>
private Schema ReadSchema(ref MsgPackReader r)
{
var schemaVersion = r.ReadInt32();
var columnCount = r.ReadArrayHeader();
var keyColumnCount = 0;
var columns = new Column[columnCount];
for (var i = 0; i < columnCount; i++)
{
var propertyCount = r.ReadArrayHeader();
const int expectedCount = 7;
Debug.Assert(propertyCount >= expectedCount, "propertyCount >= " + expectedCount);
var name = r.ReadString();
var type = r.ReadInt32();
var isKey = r.ReadBoolean();
var isNullable = r.ReadBoolean();
var isColocation = r.ReadBoolean(); // IsColocation.
var scale = r.ReadInt32();
var precision = r.ReadInt32();
r.Skip(propertyCount - expectedCount);
var column = new Column(name, (ClientDataType)type, isNullable, isColocation, isKey, i, scale, precision);
columns[i] = column;
if (isKey)
{
keyColumnCount++;
}
}
var schema = new Schema(schemaVersion, keyColumnCount, columns);
_schemas[schemaVersion] = schema;
lock (_latestSchemaLock)
{
if (schemaVersion > _latestSchemaVersion)
{
_latestSchemaVersion = schemaVersion;
}
}
return schema;
}
/// <summary>
/// Loads the partition assignment.
/// </summary>
/// <returns>Partition assignment.</returns>
private async Task<string[]?> LoadPartitionAssignmentAsync()
{
using var writer = ProtoCommon.GetMessageWriter();
writer.MessageWriter.Write(Id);
using var resBuf = await _socket.DoOutInOpAsync(ClientOp.PartitionAssignmentGet, writer).ConfigureAwait(false);
return Read();
string[]? Read()
{
var r = resBuf.GetReader();
var count = r.ReadArrayHeader();
if (count == 0)
{
return null;
}
var res = new string[count];
for (int i = 0; i < count; i++)
{
res[i] = r.ReadString();
}
return res;
}
}
}
}