summaryrefslogtreecommitdiff
path: root/src/buildtool/execution_api/remote/bazel/bytestream_client.hpp
blob: 1bd44c42912ac530de232e8b79056c172db26393 (plain)
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
#ifndef INCLUDED_SRC_BUILDTOOL_EXECUTION_API_REMOTE_BAZEL_BYTESTREAM_CLIENT_HPP
#define INCLUDED_SRC_BUILDTOOL_EXECUTION_API_REMOTE_BAZEL_BYTESTREAM_CLIENT_HPP

#include <algorithm>
#include <functional>
#include <iomanip>
#include <optional>
#include <string>
#include <vector>

#include "google/bytestream/bytestream.grpc.pb.h"
#include "src/buildtool/execution_api/remote/bazel/bazel_client_common.hpp"
#include "src/buildtool/logging/logger.hpp"

/// Implements client side for google.bytestream.ByteStream service.
class ByteStreamClient {
  public:
    class IncrementalReader {
        friend class ByteStreamClient;

      public:
        /// \brief Read next chunk of data.
        /// \returns empty string if stream finished and std::nullopt on error.
        [[nodiscard]] auto Next() -> std::optional<std::string> {
            google::bytestream::ReadResponse response{};
            if (reader_->Read(&response)) {
                return std::move(*response.mutable_data());
            }

            if (not finished_) {
                auto status = reader_->Finish();
                if (not status.ok()) {
                    LogStatus(logger_, LogLevel::Debug, status);
                    return std::nullopt;
                }
                finished_ = true;
            }
            return std::string{};
        }

      private:
        Logger const* logger_;
        grpc::ClientContext ctx_;
        std::unique_ptr<grpc::ClientReader<google::bytestream::ReadResponse>>
            reader_;
        bool finished_{false};

        IncrementalReader(
            gsl::not_null<google::bytestream::ByteStream::Stub*> const& stub,
            Logger const* logger,
            std::string const& resource_name)
            : logger_{logger} {
            google::bytestream::ReadRequest request{};
            request.set_resource_name(resource_name);
            reader_ = stub->Read(&ctx_, request);
        }
    };

    ByteStreamClient(std::string const& server,
                     Port port,
                     std::string const& user = "",
                     std::string const& pwd = "") noexcept {
        stub_ = google::bytestream::ByteStream::NewStub(
            CreateChannelWithCredentials(server, port, user, pwd));
    }

    [[nodiscard]] auto IncrementalRead(
        std::string const& resource_name) const noexcept -> IncrementalReader {
        return IncrementalReader{stub_.get(), &logger_, resource_name};
    }

    [[nodiscard]] auto Read(std::string const& resource_name) const noexcept
        -> std::optional<std::string> {
        auto reader = IncrementalRead(resource_name);
        std::string output{};
        auto data = reader.Next();
        while (data and not data->empty()) {
            output.append(data->begin(), data->end());
            data = reader.Next();
        }
        if (not data) {
            return std::nullopt;
        }
        return output;
    }

    [[nodiscard]] auto Write(std::string const& resource_name,
                             std::string const& data) const noexcept -> bool {
        grpc::ClientContext ctx;
        google::bytestream::WriteResponse response{};
        auto writer = stub_->Write(&ctx, &response);

        auto* allocated_data =
            std::make_unique<std::string>(kChunkSize, '\0').release();
        google::bytestream::WriteRequest request{};
        request.set_resource_name(resource_name);
        request.set_allocated_data(allocated_data);
        std::size_t pos{};
        do {
            auto const size = std::min(data.size() - pos, kChunkSize);
            allocated_data->resize(size);
            data.copy(allocated_data->data(), size, pos);
            request.set_write_offset(static_cast<int>(pos));
            request.set_finish_write(pos + size >= data.size());
            if (not writer->Write(request)) {
                // According to the docs, quote:
                // If there is an error or the connection is broken during the
                // `Write()`, the client should check the status of the
                // `Write()` by calling `QueryWriteStatus()` and continue
                // writing from the returned `committed_size`.
                auto const committed_size = QueryWriteStatus(resource_name);
                if (committed_size <= 0) {
                    logger_.Emit(LogLevel::Debug,
                                 "broken stream for upload to resource name {}",
                                 resource_name);
                    return false;
                }
                pos = gsl::narrow<std::size_t>(committed_size);
            }
            else {
                pos += kChunkSize;
            }
        } while (pos < data.size());
        if (not writer->WritesDone()) {
            logger_.Emit(LogLevel::Debug,
                         "broken stream for upload to resource name {}",
                         resource_name);
            return false;
        }

        auto status = writer->Finish();
        if (not status.ok()) {
            LogStatus(&logger_, LogLevel::Debug, status);
            return false;
        }

        return gsl::narrow<std::size_t>(response.committed_size()) ==
               data.size();
    }

    template <class T_Input>
    void ReadMany(
        std::vector<T_Input> const& inputs,
        std::function<std::string(T_Input const&)> const& to_resource_name,
        std::function<void(std::string)> const& parse_data) const noexcept {
        for (auto const& i : inputs) {
            auto data = Read(to_resource_name(i));
            if (data) {
                parse_data(std::move(*data));
            }
        }
    }

    template <class T_Input>
    [[nodiscard]] auto WriteMany(
        std::vector<T_Input> const& inputs,
        std::function<std::string(T_Input const&)> const& to_resource_name,
        std::function<std::string(T_Input const&)> const& to_data)
        const noexcept -> bool {
        return std::all_of(inputs.begin(),
                           inputs.end(),
                           [this, &to_resource_name, &to_data](auto const& i) {
                               return Write(to_resource_name(i), to_data(i));
                           });
    }

  private:
    // Chunk size for uploads (default size used by BuildBarn)
    constexpr static std::size_t kChunkSize = 64 * 1024;

    std::unique_ptr<google::bytestream::ByteStream::Stub> stub_;
    Logger logger_{"ByteStreamClient"};

    [[nodiscard]] auto QueryWriteStatus(
        std::string const& resource_name) const noexcept -> std::int64_t {
        grpc::ClientContext ctx;
        google::bytestream::QueryWriteStatusRequest request{};
        request.set_resource_name(resource_name);
        google::bytestream::QueryWriteStatusResponse response{};
        stub_->QueryWriteStatus(&ctx, request, &response);
        return response.committed_size();
    }
};

#endif  // INCLUDED_SRC_BUILDTOOL_EXECUTION_API_REMOTE_BAZEL_BYTESTREAM_CLIENT_HPP