Coverage Report

Created: 2026-08-31 12:43

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
common/cpp/obj-client/s3_common.h
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
#pragma once
19
20
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
21
#include <aws/core/utils/stream/PreallocatedStreamBuf.h>
22
23
#include <algorithm>
24
#include <cstring>
25
#include <streambuf>
26
#include <vector>
27
28
namespace doris {
29
30
// A non-copying iostream.
31
// See https://stackoverflow.com/questions/35322033/aws-c-sdk-uploadpart-times-out
32
// https://stackoverflow.com/questions/13059091/creating-an-input-stream-from-constant-memory
33
class StringViewStream : Aws::Utils::Stream::PreallocatedStreamBuf, public std::iostream {
34
public:
35
    StringViewStream(const void* buf, int64_t nbytes)
36
0
            : Aws::Utils::Stream::PreallocatedStreamBuf(
37
0
                      reinterpret_cast<unsigned char*>(const_cast<void*>(buf)),
38
0
                      static_cast<size_t>(nbytes)),
39
0
              std::iostream(this) {}
40
};
41
42
// The AWS SDK writes the body of every response into the stream built by the response
43
// stream factory of the request, whatever the status of that response is. Reading an
44
// object range straight into the buffer of the caller therefore breaks as soon as the
45
// server answers with an error: the XML body of a `429 SlowDown` is a few hundred bytes
46
// and does not fit into the buffer of a small range read. `PreallocatedStreamBuf` does not
47
// implement `overflow()`, so the stream turns bad, curl aborts the transfer with
48
// `CURLE_WRITE_ERROR`, and the SDK reports an `INTERNAL_FAILURE` named "Failed to flush
49
// response stream" while never recording the status code of the response. Both the retry
50
// strategy of the SDK and the retry of `S3FileReader` key on that status code, so an error
51
// the server asked us to retry ends up cancelling the query instead.
52
//
53
// This stream buffer writes into the buffer of the caller as long as the body fits, which
54
// is the case for every successful ranged read, and spills the rest into a buffer of its
55
// own. The stream never turns bad, so the SDK reports the real status code and can parse
56
// the error out of the body.
57
class S3ResponseStreamBuf final : public std::streambuf {
58
public:
59
    // Bodies beyond this size are truncated. Only error documents are expected to overflow
60
    // and one is a few hundred bytes, so this leaves them two orders of magnitude of room
61
    // while bounding what a single failing request can hold. Kept small on purpose: this
62
    // buffer is allocated on the transport thread of the SDK, out of the reach of the memory
63
    // tracker of the query, and every concurrent read that fails holds one of its own.
64
    static constexpr size_t MAX_SPILL_SIZE = 64 * 1024;
65
66
115k
    S3ResponseStreamBuf(void* buf, size_t nbytes) : _buf(static_cast<char*>(buf)) {
67
115k
        setp(_buf, _buf + nbytes);
68
115k
        setg(_buf, _buf, _buf);
69
115k
    }
70
71
protected:
72
1.70M
    std::streamsize xsputn(const char* s, std::streamsize n) override {
73
1.70M
        if (!_spilled) {
74
1.70M
            if (n <= epptr() - pptr()) {
75
1.70M
                std::memcpy(pptr(), s, n);
76
1.70M
                pbump(static_cast<int>(n));
77
1.70M
                return n;
78
1.70M
            }
79
94
            _spill_over();
80
94
        }
81
        // Saturating on its own: the spill is clamped when it is filled from the buffer of
82
        // the caller, and this must not underflow into an unbounded write if it ever is not.
83
18.4E
        auto room = _spill.size() < MAX_SPILL_SIZE ? MAX_SPILL_SIZE - _spill.size() : 0;
84
18.4E
        auto writable = std::min(static_cast<size_t>(n), room);
85
18.4E
        _spill.insert(_spill.end(), s, s + writable);
86
        // Always report the whole write as consumed. A short write is what makes curl
87
        // abort the transfer and lose the status code of the response.
88
18.4E
        return n;
89
1.70M
    }
90
91
0
    int_type overflow(int_type ch) override {
92
0
        if (traits_type::eq_int_type(ch, traits_type::eof())) {
93
0
            return traits_type::not_eof(ch);
94
0
        }
95
0
        auto c = traits_type::to_char_type(ch);
96
0
        xsputn(&c, 1);
97
0
        return ch;
98
0
    }
99
100
0
    int_type underflow() override {
101
0
        _reset_get_area(_read_pos());
102
0
        if (gptr() == egptr()) {
103
0
            return traits_type::eof();
104
0
        }
105
0
        return traits_type::to_int_type(*gptr());
106
0
    }
107
108
    pos_type seekoff(off_type off, std::ios_base::seekdir dir,
109
1.70M
                     std::ios_base::openmode which) override {
110
1.70M
        auto size = static_cast<off_type>(_written());
111
1.70M
        if ((which & std::ios_base::out) && !(which & std::ios_base::in)) {
112
            // The SDK only asks for the write position, to tell an empty body apart from a
113
            // body it has to parse. Moving the write pointer is not supported.
114
18.4E
            return dir == std::ios_base::cur && off == 0 ? pos_type(size) : pos_type(off_type(-1));
115
1.70M
        }
116
        // A seek asking for both areas at once, which is what the default argument of
117
        // `pubseekoff()` and `pubseekpos()` does, is served as a seek of the read area. The
118
        // write area is append only, so there is nothing to move there.
119
484
        off_type pos = off;
120
484
        if (dir == std::ios_base::cur) {
121
0
            pos += static_cast<off_type>(_read_pos());
122
484
        } else if (dir == std::ios_base::end) {
123
0
            pos += size;
124
0
        }
125
484
        if (pos < 0 || pos > size) {
126
0
            return pos_type(off_type(-1));
127
0
        }
128
484
        _reset_get_area(static_cast<size_t>(pos));
129
484
        return pos_type(pos);
130
484
    }
131
132
0
    pos_type seekpos(pos_type pos, std::ios_base::openmode which) override {
133
0
        return seekoff(pos, std::ios_base::beg, which);
134
0
    }
135
136
private:
137
    // Moves what has been written so far into the spill buffer, so that the body stays
138
    // contiguous and the SDK can parse the error out of it. Truncated right here: the buffer
139
    // of the caller is the size of the range that was asked for, `remote_storage_read_buffer_mb`
140
    // of it for a prefetched read and the whole file for a download, so it can be far larger
141
    // than the bound of the spill. Starting the spill beyond its own bound would leave no room
142
    // for the truncation to ever apply and let a server answering a ranged read with the whole
143
    // object be buffered in full.
144
0
    void _spill_over() {
145
0
        auto kept = std::min(static_cast<size_t>(pptr() - _buf), MAX_SPILL_SIZE);
146
0
        _spill.assign(_buf, _buf + kept);
147
0
        setp(nullptr, nullptr);
148
0
        _spilled = true;
149
0
    }
150
151
    // Bytes of the body held by this buffer, truncation excluded.
152
1.70M
    size_t _written() const { return _spilled ? _spill.size() : pptr() - _buf; }
153
154
    // Both areas start at the same logical offset, so the read position survives a spill.
155
0
    size_t _read_pos() const { return gptr() - eback(); }
156
157
0
    void _reset_get_area(size_t pos) {
158
0
        char* begin = _spilled ? _spill.data() : _buf;
159
0
        auto size = _written();
160
0
        pos = std::min(pos, size);
161
0
        setg(begin, begin + pos, begin + size);
162
0
    }
163
164
    char* _buf;
165
    std::vector<char> _spill;
166
    bool _spilled = false;
167
};
168
169
class S3ResponseStream final : public std::iostream {
170
public:
171
115k
    S3ResponseStream(void* buf, size_t nbytes) : std::iostream(&_buf), _buf(buf, nbytes) {}
172
173
private:
174
    S3ResponseStreamBuf _buf;
175
};
176
177
// By default, the AWS SDK reads object data into an auto-growing StringStream.
178
// To avoid copies, read the body directly into our preallocated buffer instead, and keep
179
// only what does not fit, which is an error document, in a buffer of the stream itself.
180
// See https://github.com/aws/aws-sdk-cpp/issues/64 for an alternative but
181
// functionally similar recipe.
182
115k
inline Aws::IOStreamFactory AwsWriteableStreamFactory(void* buf, int64_t nbytes) {
183
115k
    return [=]() { return Aws::New<S3ResponseStream>("", buf, static_cast<size_t>(nbytes)); };
184
115k
}
185
186
} // namespace doris