store_api/logstore.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
15//! LogStore APIs.
16
17pub mod entry;
18pub mod provider;
19
20use std::collections::HashMap;
21use std::pin::Pin;
22
23use common_error::ext::ErrorExt;
24use entry::Entry;
25use futures::Stream;
26
27pub type SendableEntryStream<'a, I, E> = Pin<Box<dyn Stream<Item = Result<Vec<I>, E>> + Send + 'a>>;
28
29pub use crate::logstore::entry::Id as EntryId;
30use crate::logstore::provider::Provider;
31use crate::storage::RegionId;
32
33/// Allows a log store to initiate object-store I/O.
34///
35/// A metasrv-controlled datanode supplies this from its node lease. The log
36/// store deliberately does not know how the permission is renewed.
37pub trait ObjectStoreWalIoPermit: Send + Sync + 'static {
38 /// Returns whether a new object-store create or delete may start now.
39 fn allows_object_store_io(&self) -> bool;
40}
41
42/// `LogStore` serves as a Write-Ahead-Log for storage engine.
43#[async_trait::async_trait]
44pub trait LogStore: Send + Sync + 'static + std::fmt::Debug {
45 type Error: ErrorExt + Send + Sync + 'static;
46
47 /// Returns regions whose retained WAL is under storage pressure and may be
48 /// released by flushing. This is an advisory snapshot, not permission to
49 /// flush or delete entries. The caller checks the current region state and
50 /// uses [`Self::obsolete`] only after persisting its data.
51 ///
52 /// Implementations inspect local metadata without I/O. Backends without
53 /// pressure-driven flushing return no candidates.
54 fn flush_candidates(&self) -> Vec<RegionId> {
55 Vec::new()
56 }
57
58 /// Resolves a metadata provider into the namespace used by this store.
59 /// Backends with node-local namespaces validate the configured root here.
60 /// Providers already naming a concrete namespace remain compatible.
61 fn resolve_provider(&self, provider: Provider) -> Result<Provider, Self::Error> {
62 Ok(provider)
63 }
64
65 /// Stops components of the logstore.
66 async fn stop(&self) -> Result<(), Self::Error>;
67
68 /// Appends a batch of entries and returns a response containing a map where the key is a region id
69 /// while the value is the id of the last successfully written entry of the region.
70 async fn append_batch(&self, entries: Vec<Entry>) -> Result<AppendBatchResponse, Self::Error>;
71
72 /// Creates a new `EntryStream` to asynchronously generates `Entry` with ids
73 /// starting from `id`.
74 async fn read(
75 &self,
76 provider: &Provider,
77 id: EntryId,
78 ) -> Result<SendableEntryStream<'static, Entry, Self::Error>, Self::Error>;
79
80 /// Creates a new `Namespace` from the given ref.
81 async fn create_namespace(&self, ns: &Provider) -> Result<(), Self::Error>;
82
83 /// Deletes an existing `Namespace` specified by the given ref.
84 async fn delete_namespace(&self, ns: &Provider) -> Result<(), Self::Error>;
85
86 /// Lists all existing namespaces.
87 async fn list_namespaces(&self) -> Result<Vec<Provider>, Self::Error>;
88
89 /// Marks all entries with ids `<=entry_id` of the given `namespace` as obsolete,
90 /// so that the log store can safely delete those entries. This method does not guarantee
91 /// that the obsolete entries are deleted immediately.
92 async fn obsolete(
93 &self,
94 provider: &Provider,
95 region_id: RegionId,
96 entry_id: EntryId,
97 ) -> Result<(), Self::Error>;
98
99 /// Marks all entries of a region as obsolete and removes its dedicated namespace when
100 /// supported by the backend.
101 async fn obsolete_all(
102 &self,
103 provider: &Provider,
104 region_id: RegionId,
105 ) -> Result<(), Self::Error>;
106
107 /// Makes an entry instance of the associated Entry type
108 fn entry(
109 &self,
110 data: Vec<u8>,
111 entry_id: EntryId,
112 region_id: RegionId,
113 provider: &Provider,
114 ) -> Result<Entry, Self::Error>;
115
116 /// Returns the latest entry id in the log store.
117 fn latest_entry_id(&self, provider: &Provider) -> Result<EntryId, Self::Error>;
118
119 /// Waits until every entry of the provider's region with an id at or below
120 /// `entry_id` has the persistence this log store guarantees for an
121 /// acknowledged append, so that a caller can persist `entry_id` as a
122 /// replay watermark.
123 ///
124 /// The default returns at once and keeps each log store's own
125 /// acknowledgement guarantee, whatever it is: Raft Engine with
126 /// `sync_write = false`, for example, acknowledges an append before its
127 /// periodic sync. A log store that acknowledges an append before its
128 /// entries have that persistence overrides this method.
129 async fn wait_durable(
130 &self,
131 _provider: &Provider,
132 _entry_id: EntryId,
133 ) -> Result<(), Self::Error> {
134 Ok(())
135 }
136
137 /// Releases every entry of a region the caller dropped, after `obsolete`
138 /// marked them obsolete, so that the log store keeps none of them even
139 /// across a restart, which never opens the region again to mark its
140 /// entries obsolete.
141 ///
142 /// The default does nothing and keeps each log store's existing handling
143 /// of a dropped region. A log store that keeps obsolete marks only in
144 /// memory overrides this method and returns once the release is durable.
145 async fn release_region(
146 &self,
147 _provider: &Provider,
148 _region_id: RegionId,
149 ) -> Result<(), Self::Error> {
150 Ok(())
151 }
152
153 /// Queues a persistent release of a region's entries through `entry_id`.
154 ///
155 /// The caller must ensure these entries are no longer needed for recovery.
156 /// Success means the store accepted the release, not that it is durable.
157 /// A stopped store may ignore the hint successfully, retaining extra history.
158 /// Implementations may batch records and retry failed writes; a crash before
159 /// persistence may retain extra history. Later entries remain readable.
160 /// The default does nothing, preserving other stores' reclamation policies.
161 async fn release_entries(
162 &self,
163 _provider: &Provider,
164 _region_id: RegionId,
165 _entry_id: EntryId,
166 ) -> Result<(), Self::Error> {
167 Ok(())
168 }
169
170 /// Checks, before an existing region is replayed from its persisted
171 /// state, that the log store holds the region's WAL history through
172 /// `entry_id`, the largest replay watermark the region persisted, so that
173 /// an open against a WAL that lost that history fails instead of
174 /// silently replaying nothing.
175 ///
176 /// The default accepts, which keeps the behaviour of every log store that
177 /// does not override it.
178 async fn check_region_history(
179 &self,
180 _provider: &Provider,
181 _entry_id: EntryId,
182 ) -> Result<(), Self::Error> {
183 Ok(())
184 }
185
186 /// Records that the WAL history of the provider's region starts in this
187 /// log store, as it does for a region created on it, so that
188 /// [`check_region_history`](Self::check_region_history) accepts a later
189 /// open of the region by the same log store.
190 ///
191 /// The default does nothing.
192 fn start_region_history(&self, _provider: &Provider) -> Result<(), Self::Error> {
193 Ok(())
194 }
195
196 /// Hands the provider's region over to this log store before the region
197 /// becomes writable on it, and returns the bound: an id at or above
198 /// `entry_id` and every id of the region the log store still holds or
199 /// assigned since it opened. Ids it assigned before and no longer holds
200 /// need not be covered; they stay below every id it assigns later.
201 ///
202 /// Once it returns:
203 /// - every id the log store assigns to the region is above the bound,
204 /// also after a restart;
205 /// - no entry of the region is obsolete that was not before;
206 /// - [`check_region_history`](Self::check_region_history) accepts the
207 /// region, as [`start_region_history`](Self::start_region_history)
208 /// makes it.
209 ///
210 /// The default does nothing and returns `entry_id`. It suits a log store
211 /// that never assigns a region an id at or below one already used for the
212 /// region, wherever it was used, and that accepts every history.
213 async fn handoff(
214 &self,
215 _provider: &Provider,
216 entry_id: EntryId,
217 ) -> Result<EntryId, Self::Error> {
218 Ok(entry_id)
219 }
220
221 /// Streams the entries of `region_id` in `(after, upper]` from the WAL of node `node_id`,
222 /// which shares this log store's storage, without writing to that WAL.
223 ///
224 /// The default returns `None`: the log store cannot read the WAL of another node.
225 async fn read_node(
226 &self,
227 _node_id: u64,
228 _region_id: RegionId,
229 _after: EntryId,
230 _upper: WalReadUpperBound,
231 ) -> Result<Option<SendableEntryStream<'static, Entry, Self::Error>>, Self::Error> {
232 Ok(None)
233 }
234}
235
236/// Upper bound of a WAL range read through [`LogStore::read_node`]. A reported final entry
237/// must be present, whereas a LIST boundary need not contain entries of the region.
238#[derive(Debug, Clone, Copy, PartialEq, Eq)]
239pub enum WalReadUpperBound {
240 /// The durable last entry reported by the source on downgrade.
241 LastEntry(EntryId),
242 /// A conservative bound obtained by listing the source prefix.
243 Listed(EntryId),
244}
245
246impl WalReadUpperBound {
247 /// Returns the bound.
248 pub fn entry_id(self) -> EntryId {
249 match self {
250 Self::LastEntry(id) | Self::Listed(id) => id,
251 }
252 }
253}
254
255/// The response of an `append` operation.
256#[derive(Debug, Default)]
257pub struct AppendResponse {
258 /// The id of the entry appended to the log store.
259 pub last_entry_id: EntryId,
260}
261
262/// The response of an `append_batch` operation.
263#[derive(Debug, Default)]
264pub struct AppendBatchResponse {
265 /// Key: region id (as u64). Value: the id of the last successfully written entry of the region.
266 pub last_entry_ids: HashMap<RegionId, EntryId>,
267}