Skip to main content

common_meta/election/object_store/authority/
writer.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::sync::Arc;
16use std::time::Duration;
17
18use object_store::ErrorKind;
19use snafu::{IntoError, OptionExt};
20use tokio::sync::{mpsc, oneshot};
21use tokio::time::{Instant, sleep_until};
22
23use crate::election::object_store::authority::{
24    Admission, AuthorityMutation, AuthorityPrecondition, AuthorityStatus, CLOCK_GUARD,
25    FencingToken, Inner, LEASE, RENEW_INTERVAL, SnapshotFloor, TakeoverOutcome, closed, rejected,
26    timeout,
27};
28use crate::election::object_store::{AuthorityHead, AuthorityState};
29use crate::error::{self, Error, Result};
30
31const PUT_TIMEOUT: Duration = Duration::from_secs(2);
32const READBACK_RESERVE: Duration = Duration::from_secs(1);
33const INITIAL_BACKOFF: Duration = Duration::from_millis(50);
34const MAX_BACKOFF: Duration = Duration::from_millis(400);
35
36pub(crate) enum Request {
37    Takeover(oneshot::Sender<Result<TakeoverOutcome>>),
38    Mutate {
39        epoch: u64,
40        mutation: AuthorityMutation,
41        precondition: AuthorityPrecondition,
42        response: oneshot::Sender<Result<()>>,
43    },
44}
45
46impl Request {
47    fn reject(self, error: Error) {
48        match self {
49            Self::Takeover(response) => {
50                let _ = response.send(Err(error));
51            }
52            Self::Mutate { response, .. } => {
53                let _ = response.send(Err(error));
54            }
55        }
56    }
57}
58
59pub(crate) struct Resignation {
60    pub(crate) epoch: u64,
61    pub(crate) response: oneshot::Sender<Result<()>>,
62}
63
64pub(crate) struct Writer {
65    inner: Arc<Inner>,
66    request_rx: mpsc::Receiver<Request>,
67    ambiguous_takeover: Option<AuthorityState>,
68}
69
70impl Writer {
71    pub(crate) fn new(inner: Arc<Inner>, request_rx: mpsc::Receiver<Request>) -> Self {
72        Self {
73            inner,
74            request_rx,
75            ambiguous_takeover: None,
76        }
77    }
78
79    pub(crate) async fn run(mut self) {
80        let mut changes = self.inner.status_tx.subscribe();
81        loop {
82            let (status, resignation) = self
83                .inner
84                .update(|control, _| (control.status, control.resignation.take()));
85            if status == AuthorityStatus::Closed {
86                if let Some(request) = resignation {
87                    let _ = request.response.send(Err(closed()));
88                }
89                break;
90            }
91            if let Some(request) = resignation {
92                self.drain_resigning(request.epoch);
93                let result = self.resign(request.epoch).await;
94                let _ = request.response.send(result);
95                continue;
96            }
97            let term = match status {
98                AuthorityStatus::Leader { epoch, deadline } => Some((epoch, deadline)),
99                _ => None,
100            };
101            let deadline = term.map_or_else(Instant::now, |(_, deadline)| deadline);
102            tokio::select! {
103                biased;
104                _ = changes.changed() => {}
105                _ = sleep_until(deadline), if term.is_some() => {}
106                _ = sleep_until(renew_at(deadline)), if term.is_some() => {
107                    if let Some((epoch, _)) = term {
108                        self.renew(epoch).await;
109                    }
110                }
111                request = self.request_rx.recv() => match request {
112                    Some(request) => self.process(request).await,
113                    None => break,
114                }
115            }
116        }
117        self.request_rx.close();
118        self.drain(closed);
119    }
120
121    fn drain_resigning(&mut self, epoch: u64) {
122        // Once the term retires, the FIFO can also contain a new takeover.
123        while let Some(request) = self.inner.update(|control, _| {
124            Admission::Resign(epoch).check(control.status).ok()?;
125            self.request_rx.try_recv().ok()
126        }) {
127            request.reject(rejected("resignation stopped admission before PUT"));
128        }
129    }
130
131    fn drain(&mut self, error: impl Fn() -> Error) {
132        while let Ok(request) = self.request_rx.try_recv() {
133            request.reject(error());
134        }
135    }
136
137    async fn process(&mut self, request: Request) {
138        match request {
139            Request::Takeover(response) => {
140                let _ = response.send(self.takeover().await);
141            }
142            Request::Mutate {
143                epoch,
144                mutation,
145                precondition,
146                response,
147            } => {
148                let result = loop {
149                    let put = match mutation {
150                        AuthorityMutation::Renew => {
151                            self.prepare_renewal(epoch, precondition, false).await
152                        }
153                        AuthorityMutation::Resign => {
154                            self.prepare_term(
155                                Admission::ConditionalResign(epoch),
156                                precondition,
157                                true,
158                            )
159                            .await
160                        }
161                    };
162                    match put {
163                        Ok(Some(put)) => {
164                            if matches!(mutation, AuthorityMutation::Resign) {
165                                self.drain_resigning(epoch);
166                            }
167                            break self.write(&put).await.map(|_| ());
168                        }
169                        Ok(None) => self.renew(epoch).await,
170                        Err(error) => break Err(error),
171                    }
172                };
173                let _ = response.send(result);
174            }
175        }
176    }
177
178    async fn takeover(&mut self) -> Result<TakeoverOutcome> {
179        let base = self.inner.read(Admission::Takeover, None).await?;
180        let ambiguous = if let Some(previous) = &self.ambiguous_takeover {
181            self.inner
182                .store
183                .same_version(previous.metadata(), base.metadata())?
184        } else {
185            false
186        };
187        if !ambiguous {
188            self.ambiguous_takeover = None;
189        }
190
191        if base.head().owner.is_some() {
192            let modified = base
193                .metadata()
194                .last_modified()
195                .context(error::AuthorityMetadataSnafu {
196                    reason: "read returned no last_modified",
197                })?
198                .into_inner()
199                .as_nanosecond();
200            if (self.inner.wall_now_ns)() <= modified + (LEASE + CLOCK_GUARD).as_nanos() as i128 {
201                return Ok(TakeoverOutcome::NotEligible);
202            }
203        }
204        let mut next = base
205            .head()
206            .clone()
207            .with_next_epoch()?
208            .with_next_write_seq()?;
209        next.owner = Some(self.inner.identity.clone());
210        next.lease_deadline_ms = self.inner.diagnostic_deadline();
211        let put = self.inner.update(|control, now| {
212            Admission::Takeover.check(control.status)?;
213            if let Some(floor) = &control.snapshot {
214                floor.validate(&self.inner.store, &base)?;
215            }
216            Ok(Put {
217                admission: Admission::Takeover,
218                base,
219                next,
220                sent_at: now,
221                deadline: now + LEASE,
222                ambiguous,
223            })
224        })?;
225
226        match self.write(&put).await {
227            Ok(true) => Ok(TakeoverOutcome::Acquired(FencingToken {
228                epoch: put.next.epoch(),
229            })),
230            Ok(false) => Ok(TakeoverOutcome::AppliedButInactive),
231            Err(error) => {
232                if matches!(error, Error::AuthorityUnknown { .. }) {
233                    let base_unresolved = self.inner.update(|control, _| {
234                        control.snapshot.as_ref().is_none_or(|observed| {
235                            observed.head().write_seq() <= put.base.head().write_seq()
236                        })
237                    });
238                    self.ambiguous_takeover = base_unresolved.then_some(put.base);
239                }
240                Err(error)
241            }
242        }
243    }
244
245    async fn renew(&self, epoch: u64) {
246        if let Ok(Some(put)) = self
247            .prepare_renewal(epoch, AuthorityPrecondition::Any, true)
248            .await
249            && let Err(error) = self.write(&put).await
250        {
251            common_telemetry::warn!(error; "Authority renewal of epoch {epoch} failed");
252        }
253    }
254
255    async fn prepare_renewal(
256        &self,
257        epoch: u64,
258        precondition: AuthorityPrecondition,
259        scheduled: bool,
260    ) -> Result<Option<Put>> {
261        let admission = Admission::Renew(epoch);
262        let result = self.prepare_term(admission, precondition, !scheduled).await;
263        if let Err(error) = &result
264            && !matches!(error, Error::AuthorityWriteSeqMismatch { .. })
265        {
266            // Resignation or shutdown can take over while the preparation GET is in flight.
267            let retired = self.inner.update(|control, _| {
268                if admission.check(control.status).is_ok() {
269                    control.retire(epoch);
270                    true
271                } else {
272                    false
273                }
274            });
275            if scheduled && retired {
276                common_telemetry::warn!(error; "Authority renewal of epoch {epoch} failed");
277            }
278        }
279        result
280    }
281
282    async fn resign(&self, epoch: u64) -> Result<()> {
283        let result = match self
284            .prepare_term(Admission::Resign(epoch), AuthorityPrecondition::Any, false)
285            .await
286        {
287            Ok(Some(put)) => self.write(&put).await.map(|_| ()),
288            Ok(None) => Err(rejected("resignation could not be authorized")),
289            Err(error) => Err(error),
290        };
291        self.inner.update(|control, _| control.retire(epoch));
292        result
293    }
294
295    /// An empty result keeps the FIFO request in hand while we perform a due renewal.
296    async fn prepare_term(
297        &self,
298        admission: Admission,
299        precondition: AuthorityPrecondition,
300        defer_for_renewal: bool,
301    ) -> Result<Option<Put>> {
302        let (epoch, deadline) = self.inner.update(|control, _| {
303            admission.check(control.status)?;
304            control
305                .status
306                .term()
307                .ok_or_else(|| rejected("term is inactive"))
308        })?;
309        let read = match admission {
310            Admission::Renew(_) => {
311                self.read_renewal_head(admission, deadline, defer_for_renewal)
312                    .await
313            }
314            _ => self.inner.read(admission, Some(deadline)).await,
315        };
316        let base = match read {
317            Ok(base) => base,
318            Err(error) => {
319                let renew_due = defer_for_renewal
320                    && self.inner.update(|control, now| {
321                        admission.check(control.status).is_ok() && now >= renew_at(deadline)
322                    });
323                return if renew_due { Ok(None) } else { Err(error) };
324            }
325        };
326        let next = base.head().clone().with_next_write_seq().map(|mut next| {
327            if matches!(
328                admission,
329                Admission::Resign(_) | Admission::ConditionalResign(_)
330            ) {
331                next.owner = None;
332                next.lease_deadline_ms = 0;
333            } else {
334                next.lease_deadline_ms = self.inner.diagnostic_deadline();
335            }
336            next
337        });
338        self.inner.update(|control, now| {
339            admission.check(control.status)?;
340            if defer_for_renewal && now >= renew_at(deadline) {
341                return Ok(None);
342            }
343            if now + READBACK_RESERVE >= deadline {
344                control.retire(epoch);
345                return Err(timeout("write budget"));
346            }
347            if base.head().epoch() != epoch
348                || base.head().owner.as_ref() != Some(&self.inner.identity)
349            {
350                return Err(rejected("Head is not owned by this term"));
351            }
352            if let Some(floor) = &control.snapshot {
353                floor.validate(&self.inner.store, &base)?;
354            }
355            precondition.check(base.head())?;
356            let next = next?;
357            let admission = if matches!(admission, Admission::ConditionalResign(_)) {
358                // Close admission and authorize the CAS against this read under one lock.
359                control.status = AuthorityStatus::Resigning { epoch, deadline };
360                Admission::Resign(epoch)
361            } else {
362                admission
363            };
364            Ok(Some(Put {
365                admission,
366                base,
367                next,
368                sent_at: now,
369                deadline,
370                ambiguous: false,
371            }))
372        })
373    }
374
375    async fn read_renewal_head(
376        &self,
377        admission: Admission,
378        deadline: Instant,
379        defer_for_renewal: bool,
380    ) -> Result<AuthorityState> {
381        let prepare_deadline = deadline - READBACK_RESERVE;
382        // A queued renewal yields to the scheduled renewal during read backoff.
383        let retry_until = if defer_for_renewal {
384            prepare_deadline.min(renew_at(deadline))
385        } else {
386            prepare_deadline
387        };
388        let mut backoff = INITIAL_BACKOFF;
389        loop {
390            let error = match self.inner.read(admission, Some(prepare_deadline)).await {
391                Ok(head) => return Ok(head),
392                Err(error) => error,
393            };
394            let retryable = matches!(
395                error,
396                Error::AuthorityTimeout {
397                    operation: "read",
398                    ..
399                }
400            ) || error.authority_storage_error().is_some_and(|source| {
401                source.is_temporary()
402                    && !matches!(
403                        source.kind(),
404                        ErrorKind::PermissionDenied | ErrorKind::NotFound
405                    )
406            });
407            let now = Instant::now();
408            if !retryable || now >= retry_until {
409                return Err(error);
410            }
411            tokio::select! {
412                biased;
413                _ = self.inner.wait_until(|status| admission.check(status).is_err()) => {}
414                _ = sleep_until((now + backoff).min(retry_until)) => {}
415            }
416            self.inner
417                .update(|control, _| admission.check(control.status))?;
418            if Instant::now() >= retry_until {
419                return Err(error);
420            }
421            backoff = (backoff * 2).min(MAX_BACKOFF);
422        }
423    }
424
425    async fn write(&self, put: &Put) -> Result<bool> {
426        let response = self.send(put).await;
427        match response {
428            PutResponse::Applied => Ok(self.confirm(put, true)),
429            PutResponse::Unsent(error) | PutResponse::Failed(error) => {
430                self.retire(put);
431                Err(error)
432            }
433            PutResponse::Conflict(error) => {
434                self.retire(put);
435                // Re-evaluate the observed version and term without replaying the CAS.
436                let _ = self.inner.read(Admission::Read, Some(put.deadline)).await;
437                Err(error)
438            }
439            PutResponse::Unknown(error) => {
440                self.retire(put);
441                if self.resolve(put).await {
442                    Ok(self.confirm(put, false))
443                } else {
444                    Err(error::AuthorityUnknownSnafu.into_error(Box::new(error)))
445                }
446            }
447        }
448    }
449
450    async fn send(&self, put: &Put) -> PutResponse {
451        let stop = (put.sent_at + PUT_TIMEOUT).min(put.deadline - READBACK_RESERVE);
452        let request = async {
453            if let Err(error) =
454                Admission::Read.check(self.inner.update(|control, _| control.status))
455            {
456                return PutResponse::Unsent(error);
457            }
458            if Instant::now() >= stop {
459                return PutResponse::Unsent(timeout("write budget"));
460            }
461            match self.inner.store.replace_head(&put.base, &put.next).await {
462                Ok(()) => PutResponse::Applied,
463                Err(error) => match error.authority_storage_error() {
464                    Some(storage)
465                        if matches!(
466                            storage.kind(),
467                            ErrorKind::ConditionNotMatch
468                                | ErrorKind::AlreadyExists
469                                | ErrorKind::Conflict
470                                | ErrorKind::NotFound
471                        ) =>
472                    {
473                        PutResponse::Conflict(error)
474                    }
475                    Some(storage)
476                        if storage.is_temporary() || storage.kind() == ErrorKind::Unexpected =>
477                    {
478                        PutResponse::Unknown(error)
479                    }
480                    _ => PutResponse::Failed(error),
481                },
482            }
483        };
484        // A response already available when the task wakes still determines the PUT
485        // result. The state transition separately checks the clock under the lock.
486        tokio::select! {
487            biased;
488            result = request => result,
489            _ = self.inner.wait_until(|status| status == AuthorityStatus::Closed) => PutResponse::Unknown(closed()),
490            _ = sleep_until(stop) => PutResponse::Unknown(timeout("write")),
491        }
492    }
493
494    async fn resolve(&self, put: &Put) -> bool {
495        let mut backoff = INITIAL_BACKOFF;
496        while Instant::now() < put.deadline {
497            match self.inner.read(Admission::Read, Some(put.deadline)).await {
498                Ok(state) => {
499                    let advanced = self
500                        .inner
501                        .store
502                        .same_version(put.base.metadata(), state.metadata());
503                    if matches!(advanced, Ok(false))
504                        && state.head().write_seq() >= put.next.write_seq()
505                    {
506                        // A later or competing write may have overwritten our evidence.
507                        // With an older ambiguous takeover, even an exact match is inconclusive.
508                        return !put.ambiguous && state.head() == &put.next;
509                    }
510                }
511                Err(
512                    Error::AuthorityClosed { .. }
513                    | Error::AuthorityMissing { .. }
514                    | Error::AuthorityRecoveryRequired { .. },
515                ) => return false,
516                Err(_) => {}
517            }
518            let retry_at = (Instant::now() + backoff).min(put.deadline);
519            tokio::select! {
520                _ = self.inner.wait_until(|status| Admission::Read.check(status).is_err()) => return false,
521                _ = sleep_until(retry_at) => {}
522            }
523            backoff = (backoff * 2).min(MAX_BACKOFF);
524        }
525        false
526    }
527
528    fn confirm(&self, put: &Put, direct: bool) -> bool {
529        self.inner.update(|control, now| {
530            let current = control.snapshot.as_ref().map(SnapshotFloor::head);
531            let still_current = current
532                .is_none_or(|head| head.write_seq() < put.next.write_seq() || head == &put.next);
533            if current.is_none_or(|head| head.write_seq() < put.next.write_seq()) {
534                control.snapshot = Some(SnapshotFloor::Applied {
535                    head: put.next.clone(),
536                    base: put.base.clone(),
537                });
538            }
539            let epoch = put.next.epoch();
540            if matches!(put.admission, Admission::Resign(_)) {
541                control.retire(epoch);
542                return false;
543            }
544            if still_current && now < put.deadline {
545                match put.admission {
546                    Admission::Takeover if control.status == AuthorityStatus::Follower => {
547                        control.status = AuthorityStatus::Leader {
548                            epoch,
549                            deadline: put.deadline,
550                        };
551                        return true;
552                    }
553                    Admission::Renew(_)
554                        if direct && Admission::Renew(epoch).check(control.status).is_ok() =>
555                    {
556                        control.status = AuthorityStatus::Leader {
557                            epoch,
558                            deadline: put.sent_at + LEASE,
559                        };
560                    }
561                    _ => {}
562                }
563            }
564            false
565        })
566    }
567
568    fn retire(&self, put: &Put) {
569        if let Admission::Renew(epoch) | Admission::Resign(epoch) = put.admission {
570            self.inner.update(|control, _| control.retire(epoch));
571        }
572    }
573}
574
575fn renew_at(deadline: Instant) -> Instant {
576    deadline - (LEASE - RENEW_INTERVAL)
577}
578
579/// The writer obtains this single-use authorization under the state lock and
580/// owns it until the PUT outcome is classified. No other code sends a Head PUT.
581struct Put {
582    admission: Admission,
583    base: AuthorityState,
584    next: AuthorityHead,
585    sent_at: Instant,
586    deadline: Instant,
587    ambiguous: bool,
588}
589
590enum PutResponse {
591    Applied,
592    Unsent(Error),
593    Conflict(Error),
594    Failed(Error),
595    Unknown(Error),
596}