-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathstream.cc
388 lines (314 loc) · 11.4 KB
/
stream.cc
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
386
387
388
/*
* Copyright 2018 Google LLC
*
* Licensed 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.
*/
#include "Firestore/core/src/remote/stream.h"
#include <chrono> // NOLINT(build/c++11)
#include <utility>
#include "Firestore/core/include/firebase/firestore/firestore_errors.h"
#include "Firestore/core/src/model/mutation.h"
#include "Firestore/core/src/remote/datastore.h"
#include "Firestore/core/src/util/error_apple.h"
#include "Firestore/core/src/util/hard_assert.h"
#include "Firestore/core/src/util/log.h"
#include "Firestore/core/src/util/string_format.h"
namespace firebase {
namespace firestore {
namespace remote {
namespace {
using credentials::AuthToken;
using credentials::CredentialsProvider;
using credentials::User;
using util::AsyncQueue;
using util::LogIsDebugEnabled;
using util::Status;
using util::StatusOr;
using util::StringFormat;
using util::TimerId;
using AuthCredentialsProvider = CredentialsProvider<AuthToken, User>;
/**
* Initial backoff time after an error.
* Set to 1s according to https://cloud.google.com/apis/design/errors.
*/
const double kBackoffFactor = 1.5;
const AsyncQueue::Milliseconds kBackoffInitialDelay{std::chrono::seconds(1)};
const AsyncQueue::Milliseconds kBackoffMaxDelay{std::chrono::seconds(60)};
/** The time a stream stays open after it is marked idle. */
const AsyncQueue::Milliseconds kIdleTimeout{std::chrono::seconds(60)};
/** The time a stream stays open until we consider it healthy. */
const AsyncQueue::Milliseconds kHealthyTimeout{std::chrono::seconds(10)};
} // namespace
Stream::Stream(const std::shared_ptr<AsyncQueue>& worker_queue,
std::shared_ptr<credentials::AuthCredentialsProvider>
auth_credentials_provider,
std::shared_ptr<credentials::AppCheckCredentialsProvider>
app_check_credentials_provider,
GrpcConnection* grpc_connection,
TimerId backoff_timer_id,
TimerId idle_timer_id,
TimerId health_check_timer_id)
: backoff_{worker_queue, backoff_timer_id, kBackoffFactor,
kBackoffInitialDelay, kBackoffMaxDelay},
app_check_credentials_provider_{
std::move(app_check_credentials_provider)},
auth_credentials_provider_{std::move(auth_credentials_provider)},
worker_queue_{worker_queue},
grpc_connection_{grpc_connection},
idle_timer_id_{idle_timer_id},
health_check_timer_id_{health_check_timer_id} {
}
// Check state
bool Stream::IsOpen() const {
EnsureOnQueue();
return state_ == State::Open || state_ == State::Healthy;
}
bool Stream::IsStarted() const {
EnsureOnQueue();
return state_ == State::Starting || state_ == State::Backoff || IsOpen();
}
// Starting
void Stream::Start() {
EnsureOnQueue();
if (state_ == State::Error) {
BackoffAndTryRestarting();
return;
}
LOG_DEBUG("%s start", GetDebugDescription());
HARD_ASSERT(state_ == State::Initial, "Already started");
state_ = State::Starting;
RequestCredentials();
}
void Stream::RequestCredentials() {
EnsureOnQueue();
// Auth/AppCheck may outlive the stream, so make sure it doesn't try to access
// a deleted object.
std::weak_ptr<Stream> weak_this{shared_from_this()};
auto credentials = std::make_shared<CallCredentials>();
int initial_close_count = close_count_;
auto done = [weak_this, credentials, initial_close_count](
const absl::optional<StatusOr<AuthToken>>& auth,
const absl::optional<std::string>& app_check) {
auto strong_this = weak_this.lock();
if (!strong_this) {
return;
}
std::lock_guard<std::mutex> lock(credentials->mutex);
if (auth) {
credentials->auth = *auth;
credentials->auth_received = true;
}
if (app_check) {
credentials->app_check = *app_check;
credentials->app_check_received = true;
}
if (!credentials->auth_received || !credentials->app_check_received) {
return;
}
const StatusOr<AuthToken>& auth_token = credentials->auth;
const std::string& app_check_token = credentials->app_check;
strong_this->worker_queue_->EnqueueRelaxed(
[weak_this, auth_token, app_check_token, initial_close_count] {
auto strong_this = weak_this.lock();
// Streams can be stopped while waiting for authorization, so need
// to check the close count.
if (!strong_this ||
strong_this->close_count_ != initial_close_count) {
return;
}
strong_this->ResumeStartWithCredentials(auth_token, app_check_token);
});
};
auth_credentials_provider_->GetToken(
[done](const StatusOr<AuthToken>& auth) { done(auth, absl::nullopt); });
app_check_credentials_provider_->GetToken(
[done](const StatusOr<std::string>& app_check) {
done(absl::nullopt, app_check.ValueOrDie()); // AppCheck never fails
});
}
void Stream::ResumeStartWithCredentials(const StatusOr<AuthToken>& auth_token,
const std::string& app_check_token) {
EnsureOnQueue();
HARD_ASSERT(state_ == State::Starting,
"State should still be 'Starting' (was %s)", state_);
if (!auth_token.ok()) {
OnStreamFinish(auth_token.status());
return;
}
grpc_stream_ = CreateGrpcStream(grpc_connection_, auth_token.ValueOrDie(),
app_check_token);
grpc_stream_->Start();
}
void Stream::OnStreamStart() {
EnsureOnQueue();
state_ = State::Open;
NotifyStreamOpen();
health_check_ = worker_queue_->EnqueueAfterDelay(
kHealthyTimeout, health_check_timer_id_, [this] {
{
if (IsOpen()) {
state_ = State::Healthy;
}
}
});
}
// Backoff
void Stream::BackoffAndTryRestarting() {
EnsureOnQueue();
LOG_DEBUG("%s backoff", GetDebugDescription());
HARD_ASSERT(state_ == State::Error,
"Should only perform backoff in an error case");
state_ = State::Backoff;
backoff_.BackoffAndRun([this] {
HARD_ASSERT(state_ == State::Backoff,
"Backoff elapsed but state is now: %s", state_);
state_ = State::Initial;
Start();
HARD_ASSERT(IsStarted(), "Stream should have started.");
});
}
void Stream::InhibitBackoff() {
EnsureOnQueue();
HARD_ASSERT(!IsStarted(),
"Can only cancel backoff in a stopped state (was %s)", state_);
// Clear the error condition.
state_ = State::Initial;
backoff_.Reset();
}
// Idleness
void Stream::MarkIdle() {
EnsureOnQueue();
if (IsOpen() && !idleness_timer_) {
idleness_timer_ = worker_queue_->EnqueueAfterDelay(
kIdleTimeout, idle_timer_id_, [this] { Stop(); });
}
}
void Stream::CancelIdleCheck() {
EnsureOnQueue();
idleness_timer_.Cancel();
}
// Read/write
void Stream::OnStreamRead(const grpc::ByteBuffer& message) {
EnsureOnQueue();
HARD_ASSERT(IsStarted(), "OnStreamRead called for a stopped stream.");
if (LogIsDebugEnabled()) {
LOG_DEBUG("%s headers (allowlisted): %s", GetDebugDescription(),
Datastore::GetAllowlistedHeadersAsString(
grpc_stream_->GetResponseHeaders()));
}
Status read_status = NotifyStreamResponse(message);
if (!read_status.ok()) {
grpc_stream_->FinishImmediately();
// Don't expect gRPC to produce status -- since the error happened on the
// client, we have all the information we need.
OnStreamFinish(read_status);
return;
}
}
// Stopping
void Stream::Stop() {
EnsureOnQueue();
LOG_DEBUG("%s stop", GetDebugDescription());
Close(Status::OK());
}
void Stream::Close(const Status& status) {
// This function ensures that both graceful stop and stop due to error go
// through the same sequence of steps. While it leads to more conditional
// logic, the benefit is reducing the chance of divergence across the two
// cases.
EnsureOnQueue();
bool graceful_stop = status.ok();
// Step 1 (both): check current state.
if (graceful_stop && !IsStarted()) {
// Graceful stop is idempotent.
return;
}
HARD_ASSERT(IsStarted(), "Trying to close a non-started stream");
// Step 2 (both): cancel any outstanding timers (they're guaranteed not to
// execute).
CancelIdleCheck();
backoff_.Cancel();
health_check_.Cancel();
// Step 3 (both): increment close count, which invalidates long-lived
// callbacks, guaranteeing they won't execute against a new instance of the
// stream or when the stream has been destroyed.
++close_count_;
// Step 4 (both): make small adjustments (to backoff/etc.) based on the
// status.
if (graceful_stop) {
// If this is an intentional close, ensure we don't delay our next
// connection attempt.
backoff_.Reset();
} else {
HandleErrorStatus(status);
}
// Step 5 (graceful stop only): give subclasses a chance to send final
// messages.
if (graceful_stop && grpc_stream_) {
// If the stream is in the auth stage, gRPC stream might not have been
// created yet.
LOG_DEBUG("%s Finishing gRPC stream", GetDebugDescription());
TearDown(grpc_stream_.get());
}
// Step 6 (both): destroy the underlying stream.
grpc_stream_.reset();
// Step 7 (both): update the state machine and notify the listener.
// State must be updated before calling the delegate.
state_ = graceful_stop ? State::Initial : State::Error;
NotifyStreamClose(status);
}
void Stream::HandleErrorStatus(const Status& status) {
if (status.code() == Error::kErrorResourceExhausted) {
LOG_DEBUG(
"%s Using maximum backoff delay to prevent overloading the backend.",
GetDebugDescription());
backoff_.ResetToMax();
} else if (status.code() == Error::kErrorUnauthenticated &&
state_ != State::Healthy) {
// "unauthenticated" error means the token was rejected. This should rarely
// happen since both Auth and AppCheck ensure a sufficient TTL when we
// request a token. If a user manually resets their system clock this can
// fail, however. In this case, we should get a kErrorUnauthenticated error
// before we received the first message and we need to invalidate the token
// to ensure that we fetch a new token.
auth_credentials_provider_->InvalidateToken();
app_check_credentials_provider_->InvalidateToken();
}
}
void Stream::OnStreamFinish(const Status& status) {
EnsureOnQueue();
if (!status.ok()) {
LOG_WARN("%s Stream error: '%s'", GetDebugDescription(), status.ToString());
} else {
LOG_DEBUG("%s Stream closing: '%s'", GetDebugDescription(),
status.ToString());
}
Close(status);
}
// Protected helpers
void Stream::EnsureOnQueue() const {
worker_queue_->VerifyIsCurrentQueue();
}
void Stream::Write(grpc::ByteBuffer&& message) {
EnsureOnQueue();
HARD_ASSERT(IsOpen(), "Cannot write when the stream is not open.");
CancelIdleCheck();
grpc_stream_->Write(std::move(message));
}
std::string Stream::GetDebugDescription() const {
EnsureOnQueue();
return StringFormat("%s (%x)", GetDebugName(), this);
}
} // namespace remote
} // namespace firestore
} // namespace firebase