Coverage Report

Created: 2026-08-01 21:36

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/service/http/action/stream_load.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "service/http/action/stream_load.h"
19
20
// use string iequal
21
#include <event2/buffer.h>
22
#include <event2/http.h>
23
#include <gen_cpp/FrontendService.h>
24
#include <gen_cpp/FrontendService_types.h>
25
#include <gen_cpp/HeartbeatService_types.h>
26
#include <gen_cpp/PaloInternalService_types.h>
27
#include <gen_cpp/PlanNodes_types.h>
28
#include <gen_cpp/Types_types.h>
29
#include <sys/time.h>
30
#include <thrift/protocol/TDebugProtocol.h>
31
32
#include <algorithm>
33
#include <cstdint>
34
#include <cstdlib>
35
#include <ctime>
36
#include <functional>
37
#include <future>
38
#include <sstream>
39
#include <stdexcept>
40
#include <utility>
41
42
#include "cloud/config.h"
43
#include "common/config.h"
44
#include "common/consts.h"
45
#include "common/logging.h"
46
#include "common/metrics/doris_metrics.h"
47
#include "common/metrics/metrics.h"
48
#include "common/status.h"
49
#include "common/utils.h"
50
#include "io/fs/stream_load_pipe.h"
51
#include "load/group_commit/group_commit_mgr.h"
52
#include "load/load_path_mgr.h"
53
#include "load/message_body_sink.h"
54
#include "load/stream_load/new_load_stream_mgr.h"
55
#include "load/stream_load/stream_load_context.h"
56
#include "load/stream_load/stream_load_executor.h"
57
#include "load/stream_load/stream_load_recorder.h"
58
#include "runtime/exec_env.h"
59
#include "service/http/http_channel.h"
60
#include "service/http/http_common.h"
61
#include "service/http/http_headers.h"
62
#include "service/http/http_request.h"
63
#include "service/http/utils.h"
64
#include "storage/storage_engine.h"
65
#include "util/byte_buffer.h"
66
#include "util/client_cache.h"
67
#include "util/load_util.h"
68
#include "util/string_util.h"
69
#include "util/thrift_rpc_helper.h"
70
#include "util/time.h"
71
#include "util/uid_util.h"
72
#include "util/url_coding.h"
73
74
namespace doris {
75
using namespace ErrorCode;
76
77
DEFINE_COUNTER_METRIC_PROTOTYPE_2ARG(streaming_load_requests_total, MetricUnit::REQUESTS);
78
DEFINE_COUNTER_METRIC_PROTOTYPE_2ARG(streaming_load_duration_ms, MetricUnit::MILLISECONDS);
79
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(streaming_load_current_processing, MetricUnit::REQUESTS);
80
81
bvar::LatencyRecorder g_stream_load_receive_data_latency_ms("stream_load_receive_data_latency_ms");
82
bvar::LatencyRecorder g_stream_load_commit_and_publish_latency_ms("stream_load",
83
                                                                  "commit_and_publish_ms");
84
85
static constexpr size_t MIN_CHUNK_SIZE = 64 * 1024;
86
static constexpr size_t MEBIBYTE = 1024 * 1024;
87
static const std::string CHUNK = "chunked";
88
static const std::string OFF_MODE = "off_mode";
89
static const std::string SYNC_MODE = "sync_mode";
90
static const std::string ASYNC_MODE = "async_mode";
91
92
#ifdef BE_TEST
93
TStreamLoadPutResult k_stream_load_put_result;
94
#endif
95
96
StreamLoadAction::StreamLoadAction(ExecEnv* exec_env)
97
9
        : HttpHandlerWithAuth(exec_env, TPrivilegeHier::GLOBAL, TPrivilegeType::LOAD) {
98
    // Use LOAD privilege type: requires LOAD permission
99
9
    _stream_load_entity =
100
9
            DorisMetrics::instance()->metric_registry()->register_entity("stream_load");
101
9
    INT_COUNTER_METRIC_REGISTER(_stream_load_entity, streaming_load_requests_total);
102
9
    INT_COUNTER_METRIC_REGISTER(_stream_load_entity, streaming_load_duration_ms);
103
9
    INT_GAUGE_METRIC_REGISTER(_stream_load_entity, streaming_load_current_processing);
104
9
}
105
106
6
StreamLoadAction::~StreamLoadAction() {
107
6
    DorisMetrics::instance()->metric_registry()->deregister_entity(_stream_load_entity);
108
6
}
109
110
2.87k
void StreamLoadAction::handle(HttpRequest* req) {
111
2.87k
    std::shared_ptr<StreamLoadContext> ctx =
112
2.87k
            std::static_pointer_cast<StreamLoadContext>(req->handler_ctx());
113
2.87k
    if (ctx == nullptr) {
114
0
        return;
115
0
    }
116
117
2.87k
    {
118
2.87k
        std::unique_lock<std::mutex> lock1(ctx->_send_reply_lock);
119
2.87k
        ctx->_can_send_reply = true;
120
2.87k
        ctx->_can_send_reply_cv.notify_all();
121
2.87k
    }
122
123
    // status already set to fail
124
2.87k
    if (ctx->status.ok()) {
125
2.87k
        ctx->status = _handle(ctx, req);
126
2.87k
        if (!ctx->status.ok() && !ctx->status.is<PUBLISH_TIMEOUT>()) {
127
0
            _send_reply(ctx, req);
128
0
        }
129
2.87k
    }
130
2.87k
}
131
132
2.87k
Status StreamLoadAction::_handle(std::shared_ptr<StreamLoadContext> ctx, HttpRequest* req) {
133
2.87k
    if (ctx->body_bytes > 0 && ctx->receive_bytes != ctx->body_bytes) {
134
0
        LOG(WARNING) << "recevie body don't equal with body bytes, body_bytes=" << ctx->body_bytes
135
0
                     << ", receive_bytes=" << ctx->receive_bytes << ", id=" << ctx->id;
136
0
        return Status::Error<ErrorCode::NETWORK_ERROR>("receive body don't equal with body bytes");
137
0
    }
138
139
    // if we use non-streaming, MessageBodyFileSink.finish will close the file
140
2.87k
    RETURN_IF_ERROR(ctx->body_sink->finish());
141
2.87k
    if (!ctx->use_streaming) {
142
        // we need to close file first, then execute_plan_fragment here
143
4
        ctx->body_sink.reset();
144
4
        TPipelineFragmentParamsList mocked;
145
4
        RETURN_IF_ERROR(_exec_env->stream_load_executor()->execute_plan_fragment(
146
4
                ctx, mocked,
147
4
                [req, this](std::shared_ptr<StreamLoadContext> ctx) { _on_finish(ctx, req); }));
148
4
    }
149
150
2.87k
    return Status::OK();
151
2.87k
}
152
153
2.87k
void StreamLoadAction::_on_finish(std::shared_ptr<StreamLoadContext> ctx, HttpRequest* req) {
154
2.87k
    ctx->status = ctx->load_status_future.get();
155
2.87k
    if (ctx->status.ok()) {
156
2.86k
        if (ctx->group_commit) {
157
0
            LOG(INFO) << "skip commit because this is group commit, pipe_id="
158
0
                      << ctx->id.to_string();
159
2.86k
        } else if (ctx->two_phase_commit) {
160
0
            int64_t pre_commit_start_time = MonotonicNanos();
161
0
            ctx->status = _exec_env->stream_load_executor()->pre_commit_txn(ctx.get());
162
0
            ctx->pre_commit_txn_cost_nanos = MonotonicNanos() - pre_commit_start_time;
163
2.86k
        } else {
164
            // If put file success we need commit this load
165
2.86k
            int64_t commit_and_publish_start_time = MonotonicNanos();
166
2.86k
            ctx->status = _exec_env->stream_load_executor()->commit_txn(ctx.get());
167
2.86k
            ctx->commit_and_publish_txn_cost_nanos =
168
2.86k
                    MonotonicNanos() - commit_and_publish_start_time;
169
2.86k
            g_stream_load_commit_and_publish_latency_ms
170
2.86k
                    << ctx->commit_and_publish_txn_cost_nanos / 1000000;
171
2.86k
        }
172
2.86k
    }
173
2.87k
    _send_reply(ctx, req);
174
2.87k
}
175
176
2.87k
void StreamLoadAction::_send_reply(std::shared_ptr<StreamLoadContext> ctx, HttpRequest* req) {
177
2.87k
    std::unique_lock<std::mutex> lock1(ctx->_send_reply_lock);
178
    // 1. _can_send_reply: ensure `send_reply` is invoked only after on_header/handle complete,
179
    //    avoid client errors (e.g., broken pipe).
180
    // 2. _finish_send_reply: Prevent duplicate reply sending; skip reply if HTTP request is canceled
181
    //    due to long import execution time.
182
2.87k
    while (!ctx->_finish_send_reply && !ctx->_can_send_reply) {
183
0
        ctx->_can_send_reply_cv.wait(lock1);
184
0
    }
185
2.87k
    if (ctx->_finish_send_reply) {
186
0
        return;
187
0
    }
188
2.87k
    DCHECK(ctx->_can_send_reply);
189
2.87k
    ctx->_finish_send_reply = true;
190
2.87k
    ctx->_can_send_reply_cv.notify_all();
191
2.87k
    ctx->load_cost_millis = UnixMillis() - ctx->start_millis;
192
193
2.87k
    if (!ctx->status.ok() && !ctx->status.is<PUBLISH_TIMEOUT>()) {
194
8
        LOG(WARNING) << "handle streaming load failed, id=" << ctx->id
195
8
                     << ", errmsg=" << ctx->status;
196
8
        if (ctx->need_rollback) {
197
8
            _exec_env->stream_load_executor()->rollback_txn(ctx.get());
198
8
            ctx->need_rollback = false;
199
8
        }
200
8
        if (ctx->body_sink != nullptr) {
201
8
            ctx->body_sink->cancel(ctx->status.to_string());
202
8
        }
203
8
    }
204
205
2.87k
    auto str = ctx->to_json();
206
    // add new line at end
207
2.87k
    str = str + '\n';
208
209
2.87k
#ifndef BE_TEST
210
2.87k
    if (config::enable_stream_load_record || config::enable_stream_load_record_to_audit_log_table) {
211
2.87k
        if (req->header(HTTP_SKIP_RECORD_TO_AUDIT_LOG_TABLE).empty()) {
212
2.72k
            str = ctx->prepare_stream_load_record(str);
213
2.72k
            _save_stream_load_record(ctx, str);
214
2.72k
        }
215
2.87k
    }
216
2.87k
#endif
217
218
2.87k
    HttpChannel::send_reply(req, str);
219
220
2.87k
    LOG(INFO) << "finished to execute stream load. label=" << ctx->label
221
2.87k
              << ", txn_id=" << ctx->txn_id << ", query_id=" << ctx->id
222
2.87k
              << ", load_cost_ms=" << ctx->load_cost_millis << ", receive_data_cost_ms="
223
2.87k
              << (ctx->receive_and_read_data_cost_nanos - ctx->read_data_cost_nanos) / 1000000
224
2.87k
              << ", read_data_cost_ms=" << ctx->read_data_cost_nanos / 1000000
225
2.87k
              << ", write_data_cost_ms=" << ctx->write_data_cost_nanos / 1000000
226
2.87k
              << ", commit_and_publish_txn_cost_ms="
227
2.87k
              << ctx->commit_and_publish_txn_cost_nanos / 1000000
228
2.87k
              << ", number_total_rows=" << ctx->number_total_rows
229
2.87k
              << ", number_loaded_rows=" << ctx->number_loaded_rows
230
2.87k
              << ", receive_bytes=" << ctx->receive_bytes << ", loaded_bytes=" << ctx->loaded_bytes
231
2.87k
              << ", error_url=" << ctx->error_url;
232
233
    // update statistics
234
2.87k
    streaming_load_requests_total->increment(1);
235
2.87k
    streaming_load_duration_ms->increment(ctx->load_cost_millis);
236
2.87k
    if (!ctx->data_saved_path.empty()) {
237
4
        _exec_env->load_path_mgr()->clean_tmp_files(ctx->data_saved_path);
238
4
    }
239
2.87k
}
240
241
2.87k
int StreamLoadAction::on_header(HttpRequest* req) {
242
    // Call parent's auth check first
243
2.87k
    int ret = HttpHandlerWithAuth::on_header(req);
244
2.87k
    if (ret != 0) {
245
0
        return ret; // Auth failed, return error
246
0
    }
247
248
    // Continue with stream load specific header processing
249
2.87k
    req->mark_send_reply();
250
251
2.87k
    streaming_load_current_processing->increment(1);
252
253
2.87k
    std::shared_ptr<StreamLoadContext> ctx = std::make_shared<StreamLoadContext>(_exec_env);
254
2.87k
    req->set_handler_ctx(ctx);
255
256
2.87k
    ctx->load_type = TLoadType::MANUL_LOAD;
257
2.87k
    ctx->load_src_type = TLoadSourceType::RAW;
258
259
2.87k
    url_decode(req->param(HTTP_DB_KEY), &ctx->db);
260
2.87k
    url_decode(req->param(HTTP_TABLE_KEY), &ctx->table);
261
2.87k
    ctx->label = req->header(HTTP_LABEL_KEY);
262
2.87k
    ctx->two_phase_commit = req->header(HTTP_TWO_PHASE_COMMIT) == "true";
263
2.87k
    Status st = _handle_group_commit(req, ctx);
264
2.87k
    if (!ctx->group_commit && ctx->label.empty()) {
265
0
        ctx->label = generate_uuid_string();
266
0
    }
267
268
2.87k
    LOG(INFO) << "new income streaming load request." << ctx->brief() << ", db=" << ctx->db
269
2.87k
              << ", tbl=" << ctx->table << ", group_commit=" << ctx->group_commit
270
2.87k
              << ", group_commit_mode=" << ctx->group_commit_mode
271
2.87k
              << ", HTTP headers=" << req->get_all_headers();
272
2.87k
    ctx->begin_receive_and_read_data_cost_nanos = MonotonicNanos();
273
274
2.87k
    if (st.ok()) {
275
2.87k
        st = _on_header(req, ctx);
276
2.87k
        LOG(INFO) << "finished to handle HTTP header, " << ctx->brief();
277
2.87k
    }
278
2.87k
    if (!st.ok()) {
279
0
        ctx->status = std::move(st);
280
0
        {
281
0
            std::unique_lock<std::mutex> lock1(ctx->_send_reply_lock);
282
0
            ctx->_can_send_reply = true;
283
0
            ctx->_can_send_reply_cv.notify_all();
284
0
        }
285
0
        _send_reply(ctx, req);
286
0
        return -1;
287
0
    }
288
2.87k
    return 0;
289
2.87k
}
290
291
2.87k
Status StreamLoadAction::_on_header(HttpRequest* http_req, std::shared_ptr<StreamLoadContext> ctx) {
292
    // auth information
293
2.87k
    if (!parse_basic_auth(*http_req, &ctx->auth)) {
294
0
        LOG(WARNING) << "parse basic authorization failed." << ctx->brief();
295
0
        return Status::NotAuthorized("no valid Basic authorization");
296
0
    }
297
298
    // get format of this put
299
2.87k
    std::string format_str = http_req->header(HTTP_FORMAT_KEY);
300
2.87k
    if (iequal(format_str, BeConsts::CSV_WITH_NAMES) ||
301
2.87k
        iequal(format_str, BeConsts::CSV_WITH_NAMES_AND_TYPES)) {
302
4
        ctx->header_type = format_str;
303
        //treat as CSV
304
4
        format_str = BeConsts::CSV;
305
4
    }
306
2.87k
    LoadUtil::parse_format(format_str, http_req->header(HTTP_COMPRESS_TYPE), &ctx->format,
307
2.87k
                           &ctx->compress_type);
308
2.87k
    if (ctx->format == TFileFormatType::FORMAT_UNKNOWN) {
309
0
        return Status::Error<ErrorCode::DATA_FILE_TYPE_ERROR>("unknown data format, format={}",
310
0
                                                              http_req->header(HTTP_FORMAT_KEY));
311
0
    }
312
313
    // check content length
314
2.87k
    ctx->body_bytes = 0;
315
2.87k
    const auto csv_max_body_mb = config::streaming_load_max_mb;
316
2.87k
    size_t csv_max_body_bytes = csv_max_body_mb * MEBIBYTE;
317
2.87k
    const auto json_max_body_mb = config::streaming_load_json_max_mb;
318
2.87k
    size_t json_max_body_bytes = json_max_body_mb * MEBIBYTE;
319
2.87k
    bool read_json_by_line = false;
320
2.87k
    if (!http_req->header(HTTP_READ_JSON_BY_LINE).empty()) {
321
2.69k
        if (iequal(http_req->header(HTTP_READ_JSON_BY_LINE), "true")) {
322
2.69k
            read_json_by_line = true;
323
2.69k
        }
324
2.69k
    }
325
2.87k
    if (!http_req->header(HttpHeaders::CONTENT_LENGTH).empty()) {
326
2.87k
        try {
327
2.87k
            ctx->body_bytes = std::stol(http_req->header(HttpHeaders::CONTENT_LENGTH));
328
2.87k
        } catch (const std::exception& e) {
329
0
            return Status::InvalidArgument("invalid HTTP header CONTENT_LENGTH={}: {}",
330
0
                                           http_req->header(HttpHeaders::CONTENT_LENGTH), e.what());
331
0
        }
332
        // json max body size
333
2.87k
        if ((ctx->format == TFileFormatType::FORMAT_JSON) &&
334
2.87k
            (ctx->body_bytes > json_max_body_bytes) && !read_json_by_line) {
335
1
            return Status::Error<ErrorCode::EXCEEDED_LIMIT>(
336
1
                    "json body size {} bytes ({:.2f} MiB) exceeds the limit of {} bytes ({} MiB) "
337
1
                    "set by BE's conf streaming_load_json_max_mb. Increase it if you are sure "
338
1
                    "this load is reasonable",
339
1
                    ctx->body_bytes, static_cast<double>(ctx->body_bytes) / MEBIBYTE,
340
1
                    json_max_body_bytes, json_max_body_mb);
341
1
        }
342
        // csv max body size
343
2.87k
        else if (ctx->body_bytes > csv_max_body_bytes) {
344
1
            LOG(WARNING) << "body exceed max size." << ctx->brief();
345
1
            return Status::Error<ErrorCode::EXCEEDED_LIMIT>(
346
1
                    "body size {} bytes ({:.2f} MiB) exceeds the limit of {} bytes ({} MiB) set "
347
1
                    "by BE's conf streaming_load_max_mb. Increase it if you are sure this load is "
348
1
                    "reasonable",
349
1
                    ctx->body_bytes, static_cast<double>(ctx->body_bytes) / MEBIBYTE,
350
1
                    csv_max_body_bytes, csv_max_body_mb);
351
1
        }
352
2.87k
    } else {
353
0
#ifndef BE_TEST
354
0
        evhttp_connection_set_max_body_size(
355
0
                evhttp_request_get_connection(http_req->get_evhttp_request()), csv_max_body_bytes);
356
0
#endif
357
0
    }
358
359
2.87k
    if (!http_req->header(HttpHeaders::TRANSFER_ENCODING).empty()) {
360
0
        if (http_req->header(HttpHeaders::TRANSFER_ENCODING).find(CHUNK) != std::string::npos) {
361
0
            ctx->is_chunked_transfer = true;
362
0
        }
363
0
    }
364
2.87k
    if (UNLIKELY((http_req->header(HttpHeaders::CONTENT_LENGTH).empty() &&
365
2.87k
                  !ctx->is_chunked_transfer))) {
366
0
        LOG(WARNING) << "content_length is empty and transfer-encoding!=chunked, please set "
367
0
                        "content_length or transfer-encoding=chunked";
368
0
        return Status::InvalidArgument(
369
0
                "content_length is empty and transfer-encoding!=chunked, please set content_length "
370
0
                "or transfer-encoding=chunked");
371
2.87k
    } else if (UNLIKELY(!http_req->header(HttpHeaders::CONTENT_LENGTH).empty() &&
372
2.87k
                        ctx->is_chunked_transfer)) {
373
0
        LOG(WARNING) << "please do not set both content_length and transfer-encoding";
374
0
        return Status::InvalidArgument(
375
0
                "please do not set both content_length and transfer-encoding");
376
0
    }
377
378
2.87k
    if (!http_req->header(HTTP_TIMEOUT).empty()) {
379
148
        ctx->timeout_second = DORIS_TRY(safe_stoi(http_req->header(HTTP_TIMEOUT), HTTP_TIMEOUT));
380
148
    }
381
2.87k
    if (!http_req->header(HTTP_COMMENT).empty()) {
382
0
        ctx->load_comment = http_req->header(HTTP_COMMENT);
383
0
    }
384
    // begin transaction
385
2.87k
    if (!ctx->group_commit) {
386
2.87k
        int64_t begin_txn_start_time = MonotonicNanos();
387
2.87k
        RETURN_IF_ERROR(_exec_env->stream_load_executor()->begin_txn(ctx.get()));
388
2.87k
        ctx->begin_txn_cost_nanos = MonotonicNanos() - begin_txn_start_time;
389
2.87k
        if (ctx->group_commit) {
390
0
            RETURN_IF_ERROR(_check_wal_space(ctx->group_commit_mode, ctx->body_bytes));
391
0
        }
392
2.87k
    }
393
394
    // process put file
395
2.87k
    return _process_put(http_req, ctx);
396
2.87k
}
397
398
4.26k
void StreamLoadAction::on_chunk_data(HttpRequest* req) {
399
4.26k
    std::shared_ptr<StreamLoadContext> ctx =
400
4.26k
            std::static_pointer_cast<StreamLoadContext>(req->handler_ctx());
401
4.26k
    if (ctx == nullptr || !ctx->status.ok()) {
402
0
        return;
403
0
    }
404
405
4.26k
    struct evhttp_request* ev_req = req->get_evhttp_request();
406
4.26k
    auto evbuf = evhttp_request_get_input_buffer(ev_req);
407
408
4.26k
    SCOPED_ATTACH_TASK(ExecEnv::GetInstance()->stream_load_pipe_tracker());
409
410
4.26k
    int64_t start_read_data_time = MonotonicNanos();
411
8.52k
    while (evbuffer_get_length(evbuf) > 0) {
412
4.26k
        ByteBufferPtr bb;
413
4.26k
        Status st = ByteBuffer::allocate(128 * 1024, &bb);
414
4.26k
        if (!st.ok()) {
415
0
            ctx->status = st;
416
0
            return;
417
0
        }
418
4.26k
        auto remove_bytes = evbuffer_remove(evbuf, bb->ptr, bb->capacity);
419
4.26k
        bb->pos = remove_bytes;
420
4.26k
        bb->flip();
421
4.26k
        st = ctx->body_sink->append(bb);
422
4.26k
        if (!st.ok()) {
423
0
            LOG(WARNING) << "append body content failed. errmsg=" << st << ", " << ctx->brief();
424
0
            ctx->status = st;
425
0
            return;
426
0
        }
427
4.26k
        ctx->receive_bytes += remove_bytes;
428
4.26k
    }
429
4.26k
    int64_t read_data_time = MonotonicNanos() - start_read_data_time;
430
4.26k
    int64_t last_receive_and_read_data_cost_nanos = ctx->receive_and_read_data_cost_nanos;
431
4.26k
    ctx->read_data_cost_nanos += read_data_time;
432
4.26k
    ctx->receive_and_read_data_cost_nanos =
433
4.26k
            MonotonicNanos() - ctx->begin_receive_and_read_data_cost_nanos;
434
4.26k
    g_stream_load_receive_data_latency_ms
435
4.26k
            << (ctx->receive_and_read_data_cost_nanos - last_receive_and_read_data_cost_nanos -
436
4.26k
                read_data_time) /
437
4.26k
                       1000000;
438
4.26k
}
439
440
2.87k
void StreamLoadAction::free_handler_ctx(std::shared_ptr<void> param) {
441
2.87k
    std::shared_ptr<StreamLoadContext> ctx = std::static_pointer_cast<StreamLoadContext>(param);
442
2.87k
    if (ctx == nullptr) {
443
0
        return;
444
0
    }
445
    // sender is gone, make receiver know it
446
2.87k
    if (ctx->body_sink != nullptr) {
447
2.86k
        ctx->body_sink->cancel("sender is gone");
448
2.86k
    }
449
    // remove stream load context from stream load manager and the resource will be released
450
2.87k
    ctx->exec_env()->new_load_stream_mgr()->remove(ctx->id);
451
2.87k
    streaming_load_current_processing->increment(-1);
452
2.87k
}
453
454
Status StreamLoadAction::_process_put(HttpRequest* http_req,
455
2.87k
                                      std::shared_ptr<StreamLoadContext> ctx) {
456
    // Now we use stream
457
2.87k
    ctx->use_streaming = LoadUtil::is_format_support_streaming(ctx->format);
458
459
    // put request
460
2.87k
    TStreamLoadPutRequest request;
461
2.87k
    set_request_auth(&request, ctx->auth);
462
2.87k
    request.db = ctx->db;
463
2.87k
    request.tbl = ctx->table;
464
2.87k
    request.txnId = ctx->txn_id;
465
2.87k
    request.formatType = ctx->format;
466
2.87k
    request.__set_compress_type(ctx->compress_type);
467
2.87k
    request.__set_header_type(ctx->header_type);
468
2.87k
    request.__set_loadId(ctx->id.to_thrift());
469
2.87k
    if (ctx->use_streaming) {
470
2.86k
        std::shared_ptr<io::StreamLoadPipe> pipe;
471
2.86k
        if (ctx->is_chunked_transfer) {
472
0
            pipe = std::make_shared<io::StreamLoadPipe>(
473
0
                    io::kMaxPipeBufferedBytes /* max_buffered_bytes */);
474
0
            pipe->set_is_chunked_transfer(true);
475
2.86k
        } else {
476
2.86k
            pipe = std::make_shared<io::StreamLoadPipe>(
477
2.86k
                    io::kMaxPipeBufferedBytes /* max_buffered_bytes */,
478
2.86k
                    MIN_CHUNK_SIZE /* min_chunk_size */, ctx->body_bytes /* total_length */);
479
2.86k
        }
480
2.86k
        request.fileType = TFileType::FILE_STREAM;
481
2.86k
        ctx->body_sink = pipe;
482
2.86k
        ctx->pipe = pipe;
483
2.86k
        RETURN_IF_ERROR(_exec_env->new_load_stream_mgr()->put(ctx->id, ctx));
484
2.86k
    } else {
485
4
        RETURN_IF_ERROR(_data_saved_path(http_req, &request.path, ctx->body_bytes));
486
4
        auto file_sink = std::make_shared<MessageBodyFileSink>(request.path);
487
4
        RETURN_IF_ERROR(file_sink->open());
488
4
        request.__isset.path = true;
489
4
        request.fileType = TFileType::FILE_LOCAL;
490
4
        request.__set_file_size(ctx->body_bytes);
491
4
        ctx->body_sink = file_sink;
492
4
        ctx->data_saved_path = request.path;
493
4
    }
494
2.87k
    if (!http_req->header(HTTP_COLUMNS).empty()) {
495
148
        request.__set_columns(http_req->header(HTTP_COLUMNS));
496
148
    }
497
2.87k
    if (!http_req->header(HTTP_WHERE).empty()) {
498
0
        request.__set_where(http_req->header(HTTP_WHERE));
499
0
    }
500
2.87k
    if (!http_req->header(HTTP_COLUMN_SEPARATOR).empty()) {
501
142
        request.__set_columnSeparator(http_req->header(HTTP_COLUMN_SEPARATOR));
502
142
    }
503
2.87k
    if (!http_req->header(HTTP_LINE_DELIMITER).empty()) {
504
126
        request.__set_line_delimiter(http_req->header(HTTP_LINE_DELIMITER));
505
126
    }
506
2.87k
    if (!http_req->header(HTTP_ENCLOSE).empty() && !http_req->header(HTTP_ENCLOSE).empty()) {
507
0
        const auto& enclose_str = http_req->header(HTTP_ENCLOSE);
508
0
        if (enclose_str.length() != 1) {
509
0
            return Status::InvalidArgument("enclose must be single-char, actually is {}",
510
0
                                           enclose_str);
511
0
        }
512
0
        request.__set_enclose(http_req->header(HTTP_ENCLOSE)[0]);
513
0
    }
514
2.87k
    if (!http_req->header(HTTP_ESCAPE).empty() && !http_req->header(HTTP_ESCAPE).empty()) {
515
0
        const auto& escape_str = http_req->header(HTTP_ESCAPE);
516
0
        if (escape_str.length() != 1) {
517
0
            return Status::InvalidArgument("escape must be single-char, actually is {}",
518
0
                                           escape_str);
519
0
        }
520
0
        request.__set_escape(http_req->header(HTTP_ESCAPE)[0]);
521
0
    }
522
2.87k
    if (!http_req->header(HTTP_PARTITIONS).empty()) {
523
0
        request.__set_partitions(http_req->header(HTTP_PARTITIONS));
524
0
        request.__set_isTempPartition(false);
525
0
        if (!http_req->header(HTTP_TEMP_PARTITIONS).empty()) {
526
0
            return Status::InvalidArgument(
527
0
                    "Can not specify both partitions and temporary partitions");
528
0
        }
529
0
    }
530
2.87k
    if (!http_req->header(HTTP_TEMP_PARTITIONS).empty()) {
531
0
        request.__set_partitions(http_req->header(HTTP_TEMP_PARTITIONS));
532
0
        request.__set_isTempPartition(true);
533
0
        if (!http_req->header(HTTP_PARTITIONS).empty()) {
534
0
            return Status::InvalidArgument(
535
0
                    "Can not specify both partitions and temporary partitions");
536
0
        }
537
0
    }
538
2.87k
    if (!http_req->header(HTTP_NEGATIVE).empty() && http_req->header(HTTP_NEGATIVE) == "true") {
539
0
        request.__set_negative(true);
540
2.87k
    } else {
541
2.87k
        request.__set_negative(false);
542
2.87k
    }
543
2.87k
    bool strictMode = false;
544
2.87k
    if (!http_req->header(HTTP_STRICT_MODE).empty()) {
545
0
        if (iequal(http_req->header(HTTP_STRICT_MODE), "false")) {
546
0
            strictMode = false;
547
0
        } else if (iequal(http_req->header(HTTP_STRICT_MODE), "true")) {
548
0
            strictMode = true;
549
0
        } else {
550
0
            return Status::InvalidArgument("Invalid strict mode format. Must be bool type");
551
0
        }
552
0
        request.__set_strictMode(strictMode);
553
0
    }
554
    // timezone first. if not, try system time_zone
555
2.87k
    if (!http_req->header(HTTP_TIMEZONE).empty()) {
556
0
        request.__set_timezone(http_req->header(HTTP_TIMEZONE));
557
2.87k
    } else if (!http_req->header(HTTP_TIME_ZONE).empty()) {
558
0
        request.__set_timezone(http_req->header(HTTP_TIME_ZONE));
559
0
    }
560
2.87k
    if (!http_req->header(HTTP_EXEC_MEM_LIMIT).empty()) {
561
0
        try {
562
0
            request.__set_execMemLimit(std::stoll(http_req->header(HTTP_EXEC_MEM_LIMIT)));
563
0
        } catch (const std::invalid_argument& e) {
564
0
            return Status::InvalidArgument("Invalid mem limit format, {}", e.what());
565
0
        }
566
0
    }
567
2.87k
    if (!http_req->header(HTTP_JSONPATHS).empty()) {
568
0
        request.__set_jsonpaths(http_req->header(HTTP_JSONPATHS));
569
0
    }
570
2.87k
    if (!http_req->header(HTTP_JSONROOT).empty()) {
571
0
        request.__set_json_root(http_req->header(HTTP_JSONROOT));
572
0
    }
573
2.87k
    if (!http_req->header(HTTP_STRIP_OUTER_ARRAY).empty()) {
574
10
        if (iequal(http_req->header(HTTP_STRIP_OUTER_ARRAY), "true")) {
575
10
            request.__set_strip_outer_array(true);
576
10
        } else {
577
0
            request.__set_strip_outer_array(false);
578
0
        }
579
2.86k
    } else {
580
2.86k
        request.__set_strip_outer_array(false);
581
2.86k
    }
582
583
2.87k
    if (!http_req->header(HTTP_READ_JSON_BY_LINE).empty()) {
584
2.69k
        if (iequal(http_req->header(HTTP_READ_JSON_BY_LINE), "true")) {
585
2.69k
            request.__set_read_json_by_line(true);
586
2.69k
        } else {
587
0
            request.__set_read_json_by_line(false);
588
0
        }
589
2.69k
    } else {
590
174
        request.__set_read_json_by_line(false);
591
174
    }
592
593
2.87k
    if (http_req->header(HTTP_READ_JSON_BY_LINE).empty() &&
594
2.87k
        http_req->header(HTTP_STRIP_OUTER_ARRAY).empty()) {
595
164
        request.__set_read_json_by_line(true);
596
164
        request.__set_strip_outer_array(false);
597
164
    }
598
599
2.87k
    if (!http_req->header(HTTP_NUM_AS_STRING).empty()) {
600
0
        if (iequal(http_req->header(HTTP_NUM_AS_STRING), "true")) {
601
0
            request.__set_num_as_string(true);
602
0
        } else {
603
0
            request.__set_num_as_string(false);
604
0
        }
605
2.87k
    } else {
606
2.87k
        request.__set_num_as_string(false);
607
2.87k
    }
608
2.87k
    if (!http_req->header(HTTP_FUZZY_PARSE).empty()) {
609
0
        if (iequal(http_req->header(HTTP_FUZZY_PARSE), "true")) {
610
0
            request.__set_fuzzy_parse(true);
611
0
        } else {
612
0
            request.__set_fuzzy_parse(false);
613
0
        }
614
2.87k
    } else {
615
2.87k
        request.__set_fuzzy_parse(false);
616
2.87k
    }
617
618
2.87k
    if (!http_req->header(HTTP_FUNCTION_COLUMN + "." + HTTP_SEQUENCE_COL).empty()) {
619
0
        request.__set_sequence_col(
620
0
                http_req->header(HTTP_FUNCTION_COLUMN + "." + HTTP_SEQUENCE_COL));
621
0
    }
622
623
2.87k
    if (!http_req->header(HTTP_SEND_BATCH_PARALLELISM).empty()) {
624
0
        int parallelism = DORIS_TRY(safe_stoi(http_req->header(HTTP_SEND_BATCH_PARALLELISM),
625
0
                                              HTTP_SEND_BATCH_PARALLELISM));
626
0
        request.__set_send_batch_parallelism(parallelism);
627
0
    }
628
629
2.87k
    if (!http_req->header(HTTP_LOAD_TO_SINGLE_TABLET).empty()) {
630
0
        if (iequal(http_req->header(HTTP_LOAD_TO_SINGLE_TABLET), "true")) {
631
0
            request.__set_load_to_single_tablet(true);
632
0
        } else {
633
0
            request.__set_load_to_single_tablet(false);
634
0
        }
635
0
    }
636
637
2.87k
    if (ctx->timeout_second != -1) {
638
148
        request.__set_timeout(ctx->timeout_second);
639
148
    }
640
2.87k
    request.__set_thrift_rpc_timeout_ms(config::thrift_rpc_timeout_ms);
641
2.87k
    TMergeType::type merge_type = TMergeType::APPEND;
642
2.87k
    StringCaseMap<TMergeType::type> merge_type_map = {{"APPEND", TMergeType::APPEND},
643
2.87k
                                                      {"DELETE", TMergeType::DELETE},
644
2.87k
                                                      {"MERGE", TMergeType::MERGE}};
645
2.87k
    if (!http_req->header(HTTP_MERGE_TYPE).empty()) {
646
0
        std::string merge_type_str = http_req->header(HTTP_MERGE_TYPE);
647
0
        auto iter = merge_type_map.find(merge_type_str);
648
0
        if (iter != merge_type_map.end()) {
649
0
            merge_type = iter->second;
650
0
        } else {
651
0
            return Status::InvalidArgument("Invalid merge type {}", merge_type_str);
652
0
        }
653
0
        if (merge_type == TMergeType::MERGE && http_req->header(HTTP_DELETE_CONDITION).empty()) {
654
0
            return Status::InvalidArgument("Excepted DELETE ON clause when merge type is MERGE.");
655
0
        } else if (merge_type != TMergeType::MERGE &&
656
0
                   !http_req->header(HTTP_DELETE_CONDITION).empty()) {
657
0
            return Status::InvalidArgument(
658
0
                    "Not support DELETE ON clause when merge type is not MERGE.");
659
0
        }
660
0
    }
661
2.87k
    request.__set_merge_type(merge_type);
662
2.87k
    if (!http_req->header(HTTP_DELETE_CONDITION).empty()) {
663
0
        request.__set_delete_condition(http_req->header(HTTP_DELETE_CONDITION));
664
0
    }
665
666
2.87k
    if (!http_req->header(HTTP_MAX_FILTER_RATIO).empty()) {
667
162
        ctx->max_filter_ratio = strtod(http_req->header(HTTP_MAX_FILTER_RATIO).c_str(), nullptr);
668
162
        request.__set_max_filter_ratio(ctx->max_filter_ratio);
669
162
    }
670
671
2.87k
    if (!http_req->header(HTTP_HIDDEN_COLUMNS).empty()) {
672
2.69k
        request.__set_hidden_columns(http_req->header(HTTP_HIDDEN_COLUMNS));
673
2.69k
    }
674
2.87k
    if (!http_req->header(HTTP_TRIM_DOUBLE_QUOTES).empty()) {
675
0
        if (iequal(http_req->header(HTTP_TRIM_DOUBLE_QUOTES), "true")) {
676
0
            request.__set_trim_double_quotes(true);
677
0
        } else {
678
0
            request.__set_trim_double_quotes(false);
679
0
        }
680
0
    }
681
2.87k
    if (!http_req->header(HTTP_SKIP_LINES).empty()) {
682
0
        int skip_lines = DORIS_TRY(safe_stoi(http_req->header(HTTP_SKIP_LINES), HTTP_SKIP_LINES));
683
0
        if (skip_lines < 0) {
684
0
            return Status::InvalidArgument("Invalid 'skip_lines': {}", skip_lines);
685
0
        }
686
0
        request.__set_skip_lines(skip_lines);
687
0
    }
688
2.87k
    if (!http_req->header(HTTP_ENABLE_PROFILE).empty()) {
689
0
        if (iequal(http_req->header(HTTP_ENABLE_PROFILE), "true")) {
690
0
            request.__set_enable_profile(true);
691
0
        } else {
692
0
            request.__set_enable_profile(false);
693
0
        }
694
0
    }
695
696
2.87k
    if (!http_req->header(HTTP_UNIQUE_KEY_UPDATE_MODE).empty()) {
697
0
        static const StringCaseMap<TUniqueKeyUpdateMode::type> unique_key_update_mode_map = {
698
0
                {"UPSERT", TUniqueKeyUpdateMode::UPSERT},
699
0
                {"UPDATE_FIXED_COLUMNS", TUniqueKeyUpdateMode::UPDATE_FIXED_COLUMNS},
700
0
                {"UPDATE_FLEXIBLE_COLUMNS", TUniqueKeyUpdateMode::UPDATE_FLEXIBLE_COLUMNS}};
701
0
        std::string unique_key_update_mode_str = http_req->header(HTTP_UNIQUE_KEY_UPDATE_MODE);
702
0
        auto iter = unique_key_update_mode_map.find(unique_key_update_mode_str);
703
0
        if (iter != unique_key_update_mode_map.end()) {
704
0
            TUniqueKeyUpdateMode::type unique_key_update_mode = iter->second;
705
0
            if (unique_key_update_mode == TUniqueKeyUpdateMode::UPDATE_FLEXIBLE_COLUMNS) {
706
                // check constraints when flexible partial update is enabled
707
0
                if (ctx->format != TFileFormatType::FORMAT_JSON) {
708
0
                    return Status::InvalidArgument(
709
0
                            "flexible partial update only support json format as input file "
710
0
                            "currently");
711
0
                }
712
0
                if (!http_req->header(HTTP_FUZZY_PARSE).empty() &&
713
0
                    iequal(http_req->header(HTTP_FUZZY_PARSE), "true")) {
714
0
                    return Status::InvalidArgument(
715
0
                            "Don't support flexible partial update when 'fuzzy_parse' is enabled");
716
0
                }
717
0
                if (!http_req->header(HTTP_COLUMNS).empty()) {
718
0
                    return Status::InvalidArgument(
719
0
                            "Don't support flexible partial update when 'columns' is specified");
720
0
                }
721
0
                if (!http_req->header(HTTP_JSONPATHS).empty()) {
722
0
                    return Status::InvalidArgument(
723
0
                            "Don't support flexible partial update when 'jsonpaths' is specified");
724
0
                }
725
0
                if (!http_req->header(HTTP_HIDDEN_COLUMNS).empty()) {
726
0
                    return Status::InvalidArgument(
727
0
                            "Don't support flexible partial update when 'hidden_columns' is "
728
0
                            "specified");
729
0
                }
730
0
                if (!http_req->header(HTTP_FUNCTION_COLUMN + "." + HTTP_SEQUENCE_COL).empty()) {
731
0
                    return Status::InvalidArgument(
732
0
                            "Don't support flexible partial update when "
733
0
                            "'function_column.sequence_col' is specified");
734
0
                }
735
0
                if (!http_req->header(HTTP_MERGE_TYPE).empty()) {
736
0
                    return Status::InvalidArgument(
737
0
                            "Don't support flexible partial update when "
738
0
                            "'merge_type' is specified");
739
0
                }
740
0
                if (!http_req->header(HTTP_WHERE).empty()) {
741
0
                    return Status::InvalidArgument(
742
0
                            "Don't support flexible partial update when "
743
0
                            "'where' is specified");
744
0
                }
745
0
            }
746
0
            request.__set_unique_key_update_mode(unique_key_update_mode);
747
0
        } else {
748
0
            return Status::InvalidArgument(
749
0
                    "Invalid unique_key_partial_mode {}, must be one of 'UPSERT', "
750
0
                    "'UPDATE_FIXED_COLUMNS' or 'UPDATE_FLEXIBLE_COLUMNS'",
751
0
                    unique_key_update_mode_str);
752
0
        }
753
0
    }
754
755
2.87k
    if (http_req->header(HTTP_UNIQUE_KEY_UPDATE_MODE).empty() &&
756
2.87k
        !http_req->header(HTTP_PARTIAL_COLUMNS).empty()) {
757
        // only consider `partial_columns` parameter when `unique_key_update_mode` is not set
758
0
        if (iequal(http_req->header(HTTP_PARTIAL_COLUMNS), "true")) {
759
0
            request.__set_unique_key_update_mode(TUniqueKeyUpdateMode::UPDATE_FIXED_COLUMNS);
760
            // for backward compatibility
761
0
            request.__set_partial_update(true);
762
0
        }
763
0
    }
764
765
2.87k
    if (!http_req->header(HTTP_PARTIAL_UPDATE_NEW_ROW_POLICY).empty()) {
766
0
        static const std::map<std::string, TPartialUpdateNewRowPolicy::type> policy_map {
767
0
                {"APPEND", TPartialUpdateNewRowPolicy::APPEND},
768
0
                {"ERROR", TPartialUpdateNewRowPolicy::ERROR}};
769
770
0
        auto policy_name = http_req->header(HTTP_PARTIAL_UPDATE_NEW_ROW_POLICY);
771
0
        std::transform(policy_name.begin(), policy_name.end(), policy_name.begin(),
772
0
                       [](unsigned char c) { return std::toupper(c); });
773
0
        auto it = policy_map.find(policy_name);
774
0
        if (it == policy_map.end()) {
775
0
            return Status::InvalidArgument(
776
0
                    "Invalid partial_update_new_key_behavior {}, must be one of {'APPEND', "
777
0
                    "'ERROR'}",
778
0
                    policy_name);
779
0
        }
780
0
        request.__set_partial_update_new_key_policy(it->second);
781
0
    }
782
783
2.87k
    if (!http_req->header(HTTP_MEMTABLE_ON_SINKNODE).empty()) {
784
0
        bool value = iequal(http_req->header(HTTP_MEMTABLE_ON_SINKNODE), "true");
785
0
        request.__set_memtable_on_sink_node(value);
786
0
    }
787
2.87k
    if (!http_req->header(HTTP_LOAD_STREAM_PER_NODE).empty()) {
788
0
        int stream_per_node = DORIS_TRY(
789
0
                safe_stoi(http_req->header(HTTP_LOAD_STREAM_PER_NODE), HTTP_LOAD_STREAM_PER_NODE));
790
0
        request.__set_stream_per_node(stream_per_node);
791
0
    }
792
2.87k
    if (ctx->group_commit) {
793
0
        request.__set_group_commit_mode(ctx->group_commit_mode);
794
0
    }
795
796
    // Keep cloud_cluster for compatibility with old FEs during rolling upgrade. New FEs use
797
    // backend_id below to bind planning to the compute group of the receiving BE.
798
2.87k
    if (!http_req->header(HTTP_COMPUTE_GROUP).empty()) {
799
0
        request.__set_cloud_cluster(http_req->header(HTTP_COMPUTE_GROUP));
800
2.87k
    } else if (!http_req->header(HTTP_CLOUD_CLUSTER).empty()) {
801
0
        request.__set_cloud_cluster(http_req->header(HTTP_CLOUD_CLUSTER));
802
0
    }
803
804
2.87k
    if (_exec_env->cluster_info()->backend_id != 0) {
805
2.87k
        request.__set_backend_id(_exec_env->cluster_info()->backend_id);
806
2.87k
    } else {
807
0
        LOG(WARNING) << "_exec_env->cluster_info not set backend_id";
808
0
    }
809
810
2.87k
    if (!http_req->header(HTTP_EMPTY_FIELD_AS_NULL).empty()) {
811
0
        if (iequal(http_req->header(HTTP_EMPTY_FIELD_AS_NULL), "true")) {
812
0
            request.__set_empty_field_as_null(true);
813
0
        }
814
0
    }
815
816
2.87k
#ifndef BE_TEST
817
    // plan this load
818
2.87k
    TNetworkAddress master_addr = _exec_env->cluster_info()->master_fe_addr;
819
2.87k
    int64_t stream_load_put_start_time = MonotonicNanos();
820
2.87k
    RETURN_IF_ERROR(ThriftRpcHelper::rpc<FrontendServiceClient>(
821
2.87k
            master_addr.hostname, master_addr.port,
822
2.87k
            [&request, ctx](FrontendServiceConnection& client) {
823
2.87k
                client->streamLoadPut(ctx->put_result, request);
824
2.87k
            }));
825
2.87k
    ctx->stream_load_put_cost_nanos = MonotonicNanos() - stream_load_put_start_time;
826
#else
827
    ctx->put_result = k_stream_load_put_result;
828
#endif
829
2.87k
    Status plan_status(Status::create(ctx->put_result.status));
830
2.87k
    if (!plan_status.ok()) {
831
0
        LOG(WARNING) << "plan streaming load failed. errmsg=" << plan_status << ctx->brief();
832
0
        return plan_status;
833
0
    }
834
2.87k
    DCHECK(ctx->put_result.__isset.pipeline_params);
835
2.87k
    ctx->put_result.pipeline_params.query_options.__set_enable_strict_cast(false);
836
2.87k
    ctx->put_result.pipeline_params.query_options.__set_enable_insert_strict(strictMode);
837
2.87k
    if (config::is_cloud_mode() && ctx->two_phase_commit && ctx->is_mow_table()) {
838
0
        return Status::NotSupported("stream load 2pc is unsupported for mow table");
839
0
    }
840
2.87k
    if (iequal(ctx->group_commit_mode, ASYNC_MODE)) {
841
        // FIXME find a way to avoid chunked stream load write large WALs
842
0
        size_t content_length = 0;
843
0
        if (!http_req->header(HttpHeaders::CONTENT_LENGTH).empty()) {
844
0
            try {
845
0
                content_length = std::stol(http_req->header(HttpHeaders::CONTENT_LENGTH));
846
0
            } catch (const std::exception& e) {
847
0
                return Status::InvalidArgument("invalid HTTP header CONTENT_LENGTH={}: {}",
848
0
                                               http_req->header(HttpHeaders::CONTENT_LENGTH),
849
0
                                               e.what());
850
0
            }
851
0
            if (LoadUtil::is_compressed_load(ctx->compress_type, ctx->format)) {
852
0
                content_length *= 3;
853
0
            }
854
0
        }
855
0
        ctx->put_result.pipeline_params.__set_content_length(content_length);
856
0
    }
857
858
2.87k
    VLOG_NOTICE << "params is "
859
0
                << apache::thrift::ThriftDebugString(ctx->put_result.pipeline_params);
860
    // if we not use streaming, we must download total content before we begin
861
    // to process this load
862
2.87k
    if (!ctx->use_streaming) {
863
4
        return Status::OK();
864
4
    }
865
866
2.86k
    TPipelineFragmentParamsList mocked;
867
2.86k
    return _exec_env->stream_load_executor()->execute_plan_fragment(
868
2.86k
            ctx, mocked, [http_req, this](std::shared_ptr<StreamLoadContext> ctx) {
869
2.86k
                _on_finish(ctx, http_req);
870
2.86k
            });
871
2.87k
}
872
873
Status StreamLoadAction::_data_saved_path(HttpRequest* req, std::string* file_path,
874
4
                                          int64_t file_bytes) {
875
4
    std::string prefix;
876
4
    RETURN_IF_ERROR(_exec_env->load_path_mgr()->allocate_dir(req->param(HTTP_DB_KEY), "", &prefix,
877
4
                                                             file_bytes));
878
4
    timeval tv;
879
4
    gettimeofday(&tv, nullptr);
880
4
    struct tm tm;
881
4
    time_t cur_sec = tv.tv_sec;
882
4
    localtime_r(&cur_sec, &tm);
883
4
    char buf[64];
884
4
    strftime(buf, 64, "%Y%m%d%H%M%S", &tm);
885
4
    std::stringstream ss;
886
4
    ss << prefix << "/" << req->param(HTTP_TABLE_KEY) << "." << buf << "." << tv.tv_usec;
887
4
    *file_path = ss.str();
888
4
    return Status::OK();
889
4
}
890
891
void StreamLoadAction::_save_stream_load_record(std::shared_ptr<StreamLoadContext> ctx,
892
2.72k
                                                const std::string& str) {
893
2.72k
    std::shared_ptr<StreamLoadRecorder> stream_load_recorder =
894
2.72k
            ExecEnv::GetInstance()->storage_engine().get_stream_load_recorder();
895
896
2.72k
    if (stream_load_recorder != nullptr) {
897
2.72k
        std::string key =
898
2.72k
                std::to_string(ctx->start_millis + ctx->load_cost_millis) + "_" + ctx->label;
899
2.72k
        auto st = stream_load_recorder->put(key, str);
900
2.72k
        if (st.ok()) {
901
2.72k
            LOG(INFO) << "put stream_load_record rocksdb successfully. label: " << ctx->label
902
2.72k
                      << ", key: " << key;
903
2.72k
        }
904
2.72k
    } else {
905
0
        LOG(WARNING) << "put stream_load_record rocksdb failed. stream_load_recorder is null.";
906
0
    }
907
2.72k
}
908
909
Status StreamLoadAction::_check_wal_space(const std::string& group_commit_mode,
910
2.87k
                                          int64_t content_length) {
911
2.87k
    if (iequal(group_commit_mode, ASYNC_MODE) &&
912
2.87k
        !load_size_smaller_than_wal_limit(content_length)) {
913
0
        std::stringstream ss;
914
0
        ss << "There is no space for group commit stream load async WAL. This stream load "
915
0
              "size is "
916
0
           << content_length
917
0
           << ". WAL dir info: " << ExecEnv::GetInstance()->wal_mgr()->get_wal_dirs_info_string();
918
0
        LOG(WARNING) << ss.str();
919
0
        return Status::Error<EXCEEDED_LIMIT>(ss.str());
920
0
    }
921
2.87k
    return Status::OK();
922
2.87k
}
923
924
Status StreamLoadAction::_can_group_commit(HttpRequest* req, std::shared_ptr<StreamLoadContext> ctx,
925
                                           std::string& group_commit_header,
926
2.87k
                                           bool& can_group_commit) {
927
2.87k
    int64_t content_length = 0;
928
2.87k
    const auto& content_length_str = req->header(HttpHeaders::CONTENT_LENGTH);
929
2.87k
    if (!content_length_str.empty()) {
930
2.87k
        try {
931
2.87k
            content_length = std::stoll(content_length_str);
932
2.87k
        } catch (const std::exception& e) {
933
0
            return Status::InvalidArgument("invalid HTTP header CONTENT_LENGTH={}: {}",
934
0
                                           content_length_str, e.what());
935
0
        }
936
2.87k
    }
937
2.87k
    if (content_length < 0) {
938
0
        std::stringstream ss;
939
0
        ss << "This stream load content length <0 (" << content_length
940
0
           << "), please check your content length.";
941
0
        LOG(WARNING) << ss.str();
942
0
        return Status::InvalidArgument(ss.str());
943
0
    }
944
2.87k
    auto is_chunk = !req->header(HttpHeaders::TRANSFER_ENCODING).empty() &&
945
2.87k
                    req->header(HttpHeaders::TRANSFER_ENCODING).find(CHUNK) != std::string::npos;
946
2.87k
    if (content_length == 0 && !is_chunk) {
947
        // off_mode and empty
948
0
        can_group_commit = false;
949
0
        return Status::OK();
950
0
    }
951
2.87k
    if (is_chunk) {
952
0
        ctx->label = "";
953
0
    }
954
955
2.87k
    auto partial_columns = !req->header(HTTP_PARTIAL_COLUMNS).empty() &&
956
2.87k
                           iequal(req->header(HTTP_PARTIAL_COLUMNS), "true");
957
2.87k
    auto temp_partitions = !req->header(HTTP_TEMP_PARTITIONS).empty();
958
2.87k
    auto partitions = !req->header(HTTP_PARTITIONS).empty();
959
2.87k
    auto update_mode =
960
2.87k
            !req->header(HTTP_UNIQUE_KEY_UPDATE_MODE).empty() &&
961
2.87k
            (iequal(req->header(HTTP_UNIQUE_KEY_UPDATE_MODE), "UPDATE_FIXED_COLUMNS") ||
962
0
             iequal(req->header(HTTP_UNIQUE_KEY_UPDATE_MODE), "UPDATE_FLEXIBLE_COLUMNS"));
963
2.87k
    if (!partial_columns && !partitions && !temp_partitions && !ctx->two_phase_commit &&
964
2.87k
        !update_mode) {
965
2.87k
        if (!config::wait_internal_group_commit_finish && !group_commit_header.empty() &&
966
2.87k
            !ctx->label.empty()) {
967
0
            return Status::InvalidArgument("label and group_commit can't be set at the same time");
968
0
        }
969
2.87k
        RETURN_IF_ERROR(_check_wal_space(group_commit_header, content_length));
970
2.87k
        can_group_commit = true;
971
2.87k
    }
972
2.87k
    return Status::OK();
973
2.87k
}
974
975
Status StreamLoadAction::_handle_group_commit(HttpRequest* req,
976
2.87k
                                              std::shared_ptr<StreamLoadContext> ctx) {
977
2.87k
    std::string group_commit_header = req->header(HTTP_GROUP_COMMIT);
978
2.87k
    if (!group_commit_header.empty() && !iequal(group_commit_header, SYNC_MODE) &&
979
2.87k
        !iequal(group_commit_header, ASYNC_MODE) && !iequal(group_commit_header, OFF_MODE)) {
980
0
        return Status::InvalidArgument(
981
0
                "group_commit can only be [async_mode, sync_mode, off_mode]");
982
0
    }
983
2.87k
    if (config::wait_internal_group_commit_finish) {
984
0
        group_commit_header = SYNC_MODE;
985
0
    }
986
987
    // if group_commit_header is off_mode, we will not use group commit
988
2.87k
    if (iequal(group_commit_header, OFF_MODE)) {
989
0
        ctx->group_commit_mode = OFF_MODE;
990
0
        ctx->group_commit = false;
991
0
        return Status::OK();
992
0
    }
993
2.87k
    bool can_group_commit = false;
994
2.87k
    RETURN_IF_ERROR(_can_group_commit(req, ctx, group_commit_header, can_group_commit));
995
2.87k
    if (!can_group_commit) {
996
0
        ctx->group_commit_mode = OFF_MODE;
997
0
        ctx->group_commit = false;
998
2.87k
    } else {
999
2.87k
        if (!group_commit_header.empty()) {
1000
0
            ctx->group_commit_mode = group_commit_header;
1001
0
            ctx->group_commit = true;
1002
2.87k
        } else {
1003
            // use table property to decide group commit or not
1004
2.87k
            ctx->group_commit_mode = "";
1005
2.87k
            ctx->group_commit = false;
1006
2.87k
        }
1007
2.87k
    }
1008
2.87k
    return Status::OK();
1009
2.87k
}
1010
1011
} // namespace doris