-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathDatabricksCompositeReader.cs
More file actions
309 lines (281 loc) · 13.3 KB
/
DatabricksCompositeReader.cs
File metadata and controls
309 lines (281 loc) · 13.3 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
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
/*
* Copyright (c) 2025 ADBC Drivers Contributors
*
* This file has been modified from its original version, which is
* under the Apache License:
*
* 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 System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using AdbcDrivers.Databricks.Reader.CloudFetch;
using AdbcDrivers.Databricks.Telemetry.TagDefinitions;
using Apache.Arrow;
using AdbcDrivers.HiveServer2.Hive2;
using Apache.Arrow.Adbc.Tracing;
using Apache.Hive.Service.Rpc.Thrift;
namespace AdbcDrivers.Databricks.Reader
{
/// <summary>
/// A composite reader for Databricks that delegates to either CloudFetchReader or DatabricksReader
/// based on CloudFetch configuration and result set characteristics. This was introduced because some
/// older DBR do not accurately report the result set characteristics in the MetadataResponse
/// </summary>
internal class DatabricksCompositeReader : TracingReader
{
public override string AssemblyName => DatabricksConnection.s_assemblyName;
public override string AssemblyVersion => DatabricksConnection.s_assemblyVersion;
public override Schema Schema { get { return _schema; } }
private BaseDatabricksReader? _activeReader;
private readonly IHiveServer2Statement _statement;
private readonly Schema _schema;
private readonly IResponse _response;
private readonly bool _isLz4Compressed;
private IOperationStatusPoller? operationStatusPoller;
private bool _disposed;
private readonly HttpClient _httpClient;
/// <summary>
/// Initializes a new instance of the <see cref="DatabricksCompositeReader"/> class.
/// </summary>
/// <param name="statement">The Databricks statement.</param>
/// <param name="schema">The Arrow schema.</param>
/// <param name="isLz4Compressed">Whether the results are LZ4 compressed.</param>
/// <param name="httpClient">The HTTP client for CloudFetch operations.</param>
internal DatabricksCompositeReader(
IHiveServer2Statement statement,
Schema schema,
IResponse response,
bool isLz4Compressed,
HttpClient httpClient,
IOperationStatusPoller? operationPoller = null)
: base(statement)
{
_statement = statement ?? throw new ArgumentNullException(nameof(statement));
_schema = schema ?? throw new ArgumentNullException(nameof(schema));
_response = response;
_isLz4Compressed = isLz4Compressed;
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
// use direct results if available
if (_statement.TryGetDirectResults(_response, out TSparkDirectResults? directResults)
&& directResults!.__isset.resultSet
&& directResults.ResultSet != null)
{
_activeReader = DetermineReader(directResults.ResultSet);
}
if (_response.DirectResults?.ResultSet?.HasMoreRows ?? true)
{
operationStatusPoller = operationPoller ?? new DatabricksOperationStatusPoller(_statement, response, GetHeartbeatIntervalFromConnection(), GetRequestTimeoutFromConnection(), activityTracer: this);
operationStatusPoller.Start();
}
}
/// <summary>
/// Determines whether CloudFetch should be used based on the fetch results.
/// </summary>
/// <param name="initialResults">The initial fetch results.</param>
/// <returns>True if CloudFetch should be used, false otherwise.</returns>
internal static bool ShouldUseCloudFetch(TFetchResultsResp initialResults)
{
return initialResults.__isset.results &&
initialResults.Results.__isset.resultLinks &&
initialResults.Results.ResultLinks?.Count > 0;
}
private BaseDatabricksReader DetermineReader(TFetchResultsResp initialResults, Activity? activity = null)
{
bool useCloudFetch = ShouldUseCloudFetch(initialResults);
activity?.AddEvent("composite_reader.determine_reader", [
new("use_cloudfetch", useCloudFetch),
new("has_result_links", initialResults.__isset.results && initialResults.Results.__isset.resultLinks),
new("result_links_count", initialResults.Results?.ResultLinks?.Count ?? 0)
]);
// Add telemetry tag for result format
activity?.SetTag(StatementExecutionEvent.ResultFormat, useCloudFetch ? "cloudfetch" : "inline");
// Add telemetry tag for chunk count if using CloudFetch
if (useCloudFetch && initialResults.Results?.ResultLinks != null)
{
activity?.SetTag(StatementExecutionEvent.ResultChunkCount, initialResults.Results.ResultLinks.Count);
}
if (useCloudFetch)
{
return CreateCloudFetchReader(initialResults);
}
else
{
return CreateDatabricksReader(initialResults);
}
}
/// <summary>
/// Reads the next record batch from the active reader.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <param name="activity">The activity for logging.</param>
/// <returns>The next record batch, or null if there are no more batches.</returns>
private async ValueTask<RecordBatch?> ReadNextRecordBatchInternalAsync(CancellationToken cancellationToken, Activity? activity)
{
// Initialize the active reader if not already done
if (_activeReader == null)
{
activity?.AddEvent("composite_reader.initializing_reader");
// if no reader, we did not have direct results
// Make a FetchResults call to get the initial result set
// and determine the reader based on the result set
TFetchResultsReq request = new TFetchResultsReq(_response.OperationHandle!, TFetchOrientation.FETCH_NEXT, this._statement.BatchSize);
// Set MaxBytes from DatabricksStatement
if (this._statement is DatabricksStatement databricksStatement)
{
request.MaxBytes = databricksStatement.MaxBytesPerFetchRequest;
}
TFetchResultsResp response = await this._statement.Client!.FetchResults(request, cancellationToken);
_activeReader = DetermineReader(response, activity);
activity?.AddEvent("composite_reader.reader_determined", [
new("reader_type", _activeReader.GetType().Name)
]);
}
return await _activeReader.ReadNextRecordBatchAsync(cancellationToken);
}
/// <summary>
/// Creates a CloudFetchReader instance using the factory.
/// Virtual to allow testing.
/// </summary>
/// <param name="initialResults">The initial fetch results.</param>
/// <returns>A new CloudFetchReader instance.</returns>
protected virtual BaseDatabricksReader CreateCloudFetchReader(TFetchResultsResp initialResults)
{
return CloudFetchReaderFactory.CreateThriftReader(
_statement,
_schema,
_response,
initialResults,
_httpClient,
_isLz4Compressed);
}
/// <summary>
/// Creates a DatabricksReader instance. Virtual to allow testing.
/// </summary>
/// <param name="initialResults">The initial fetch results.</param>
/// <returns>A new DatabricksReader instance.</returns>
protected virtual BaseDatabricksReader CreateDatabricksReader(TFetchResultsResp initialResults)
{
return new DatabricksReader(_statement, _schema, _response, initialResults, _isLz4Compressed);
}
public override async ValueTask<RecordBatch?> ReadNextRecordBatchAsync(CancellationToken cancellationToken = default)
{
return await this.TraceActivityAsync(async activity =>
{
if (_activeReader != null)
{
activity?.SetTag("reader.active_reader_type", _activeReader.GetType().Name);
}
var result = await ReadNextRecordBatchInternalAsync(cancellationToken, activity);
// Stop the poller when we've reached the end of results
if (result == null)
{
activity?.AddEvent("composite_reader.end_of_results");
StopOperationStatusPoller();
}
else
{
activity?.AddEvent("composite_reader.batch_read", [
new("row_count", result.Length)
]);
}
return result;
});
}
protected override void Dispose(bool disposing)
{
this.TraceActivity(activity =>
{
if (_activeReader != null)
{
activity?.SetTag("reader.active_reader_type", _activeReader.GetType().Name);
}
try
{
if (!_disposed)
{
if (disposing)
{
activity?.AddEvent("composite_reader.disposing");
StopOperationStatusPoller();
// Always close the operation here at the composite level.
// CloudFetchReader is protocol-agnostic and does not send CloseOperation,
// so we must not rely on the contained reader to do it.
activity?.AddEvent("composite_reader.close_operation");
_ = HiveServer2Reader.CloseOperationAsync(_statement, _response)
.ConfigureAwait(false).GetAwaiter().GetResult();
if (_activeReader != null)
{
activity?.AddEvent("composite_reader.disposing_active_reader", [
new("reader_type", _activeReader.GetType().Name)
]);
_activeReader.Dispose();
_activeReader = null;
}
activity?.AddEvent("composite_reader.disposed");
}
}
}
finally
{
base.Dispose(disposing);
_disposed = true;
}
}, activityName: nameof(DatabricksCompositeReader) + "." + nameof(Dispose));
}
private void StopOperationStatusPoller()
{
operationStatusPoller?.Stop();
operationStatusPoller?.Dispose();
operationStatusPoller = null;
}
/// <summary>
/// Gets the heartbeat interval from the statement's connection.
/// </summary>
/// <returns>The heartbeat interval in seconds, or default if not available.</returns>
private int GetHeartbeatIntervalFromConnection()
{
if (_statement is DatabricksStatement databricksStatement)
{
var connection = databricksStatement.Connection;
if (connection is DatabricksConnection databricksConnection)
{
return databricksConnection.FetchHeartbeatIntervalSeconds;
}
}
return DatabricksConstants.DefaultOperationStatusPollingIntervalSeconds;
}
/// <summary>
/// Gets the request timeout from the statement's connection.
/// </summary>
/// <returns>The request timeout in seconds, or default if not available.</returns>
private int GetRequestTimeoutFromConnection()
{
if (_statement is DatabricksStatement databricksStatement)
{
var connection = databricksStatement.Connection;
if (connection is DatabricksConnection databricksConnection)
{
return databricksConnection.OperationStatusRequestTimeoutSeconds;
}
}
return DatabricksConstants.DefaultOperationStatusRequestTimeoutSeconds;
}
}
}