Line data Source code
1 : //! This module defines `RequestContext`, a structure that we use throughout
2 : //! the pageserver to propagate high-level context from places
3 : //! that _originate_ activity down to the shared code paths at the
4 : //! heart of the pageserver. It's inspired by Golang's `context.Context`.
5 : //!
6 : //! For example, in `Timeline::get(page_nr, lsn)` we need to answer the following questions:
7 : //! 1. What high-level activity ([`TaskKind`]) needs this page?
8 : //! We need that information as a categorical dimension for page access
9 : //! statistics, which we, in turn, need to guide layer eviction policy design.
10 : //! 2. How should we behave if, to produce the page image, we need to
11 : //! on-demand download a layer file ([`DownloadBehavior`]).
12 : //!
13 : //! [`RequestContext`] satisfies those needs.
14 : //! The current implementation is a small `struct` that is passed through
15 : //! the call chain by reference.
16 : //!
17 : //! ### Future Work
18 : //!
19 : //! However, we do not intend to stop here, since there are other needs that
20 : //! require carrying information from high to low levels of the app.
21 : //!
22 : //! Most importantly, **cancellation signaling** in response to
23 : //! 1. timeouts (page_service max response time) and
24 : //! 2. lifecycle requests (detach tenant, delete timeline).
25 : //!
26 : //! Related to that, there is sometimes a need to ensure that all tokio tasks spawned
27 : //! by the transitive callees of a request have finished. The keyword here
28 : //! is **Structured Concurrency**, and right now, we use `task_mgr` in most places,
29 : //! `TaskHandle` in some places, and careful code review around `FuturesUnordered`
30 : //! or `JoinSet` in other places.
31 : //!
32 : //! We do not yet have a systematic cancellation story in pageserver, and it is
33 : //! pretty clear that [`RequestContext`] will be responsible for that.
34 : //! So, the API already prepares for this role through the
35 : //! [`RequestContext::detached_child`] and [`RequestContext::attached_child`] methods.
36 : //! See their doc comments for details on how we will use them in the future.
37 : //!
38 : //! It is not clear whether or how we will enforce Structured Concurrency, and
39 : //! what role [`RequestContext`] will play there.
40 : //! So, the API doesn't prepare us for this topic.
41 : //!
42 : //! Other future uses of `RequestContext`:
43 : //! - Communicate compute & IO priorities (user-initiated request vs. background-loop)
44 : //! - Request IDs for distributed tracing
45 : //! - Request/Timeline/Tenant-scoped log levels
46 : //!
47 : //! RequestContext might look quite different once it supports those features.
48 : //! Likely, it will have a shape similar to Golang's `context.Context`.
49 : //!
50 : //! ### Why A Struct Instead Of Method Parameters
51 : //!
52 : //! What's typical about such information is that it needs to be passed down
53 : //! along the call chain from high level to low level, but few of the functions
54 : //! in the middle need to understand it.
55 : //! Further, it is to be expected that we will need to propagate more data
56 : //! in the future (see the earlier section on future work).
57 : //! Hence, for functions in the middle of the call chain, we have the following
58 : //! requirements:
59 : //! 1. It should be easy to forward the context to callees.
60 : //! 2. To propagate more data from high-level to low-level code, the functions in
61 : //! the middle should not need to be modified.
62 : //!
63 : //! The solution is to have a container structure ([`RequestContext`]) that
64 : //! carries the information. Functions that don't care about what's in it
65 : //! pass it along to callees.
66 : //!
67 : //! ### Why Not Task-Local Variables
68 : //!
69 : //! One could use task-local variables (the equivalent of thread-local variables)
70 : //! to address the immediate needs outlined above.
71 : //! However, we reject task-local variables because:
72 : //! 1. they are implicit, thereby making it harder to trace the data flow in code
73 : //! reviews and during debugging,
74 : //! 2. they can be mutable, which enables implicit return data flow,
75 : //! 3. they are restrictive in that code which fans out into multiple tasks,
76 : //! or even threads, needs to carefully propagate the state.
77 : //!
78 : //! In contrast, information flow with [`RequestContext`] is
79 : //! 1. always explicit,
80 : //! 2. strictly uni-directional because RequestContext is immutable,
81 : //! 3. tangible because a [`RequestContext`] is just a value.
82 : //! When creating child activities, regardless of whether it's a task,
83 : //! thread, or even an RPC to another service, the value can
84 : //! be used like any other argument.
85 : //!
86 : //! The solution is that all code paths are infected with precisely one
87 : //! [`RequestContext`] argument. Functions in the middle of the call chain
88 : //! only need to pass it on.
89 :
90 : use crate::task_mgr::TaskKind;
91 :
92 : pub(crate) mod optional_counter;
93 :
94 : // The main structure of this module, see module-level comment.
95 : #[derive(Debug)]
96 : pub struct RequestContext {
97 : task_kind: TaskKind,
98 : download_behavior: DownloadBehavior,
99 : access_stats_behavior: AccessStatsBehavior,
100 : page_content_kind: PageContentKind,
101 : pub micros_spent_throttled: optional_counter::MicroSecondsCounterU32,
102 : }
103 :
104 : /// The kind of access to the page cache.
105 15480 : #[derive(Clone, Copy, PartialEq, Eq, Debug, enum_map::Enum, strum_macros::IntoStaticStr)]
106 : pub enum PageContentKind {
107 : Unknown,
108 : DeltaLayerBtreeNode,
109 : DeltaLayerValue,
110 : ImageLayerBtreeNode,
111 : ImageLayerValue,
112 : InMemoryLayer,
113 : }
114 :
115 : /// Desired behavior if the operation requires an on-demand download
116 : /// to proceed.
117 : #[derive(Clone, Copy, PartialEq, Eq, Debug)]
118 : pub enum DownloadBehavior {
119 : /// Download the layer file. It can take a while.
120 : Download,
121 :
122 : /// Download the layer file, but print a warning to the log. This should be used
123 : /// in code where the layer file is expected to already exist locally.
124 : Warn,
125 :
126 : /// Return a PageReconstructError::NeedsDownload error
127 : Error,
128 : }
129 :
130 : /// Whether this request should update access times used in LRU eviction
131 : #[derive(Clone, Copy, PartialEq, Eq, Debug)]
132 : pub(crate) enum AccessStatsBehavior {
133 : /// Update access times: this request's access to data should be taken
134 : /// as a hint that the accessed layer is likely to be accessed again
135 : Update,
136 :
137 : /// Do not update access times: this request is accessing the layer
138 : /// but does not want to indicate that the layer should be retained in cache,
139 : /// perhaps because the requestor is a compaction routine that will soon cover
140 : /// this layer with another.
141 : Skip,
142 : }
143 :
144 : pub struct RequestContextBuilder {
145 : inner: RequestContext,
146 : }
147 :
148 : impl RequestContextBuilder {
149 : /// A new builder with default settings
150 2388 : pub fn new(task_kind: TaskKind) -> Self {
151 2388 : Self {
152 2388 : inner: RequestContext {
153 2388 : task_kind,
154 2388 : download_behavior: DownloadBehavior::Download,
155 2388 : access_stats_behavior: AccessStatsBehavior::Update,
156 2388 : page_content_kind: PageContentKind::Unknown,
157 2388 : micros_spent_throttled: Default::default(),
158 2388 : },
159 2388 : }
160 2388 : }
161 :
162 5910276 : pub fn extend(original: &RequestContext) -> Self {
163 5910276 : Self {
164 5910276 : // This is like a Copy, but avoid implementing Copy because ordinary users of
165 5910276 : // RequestContext should always move or ref it.
166 5910276 : inner: RequestContext {
167 5910276 : task_kind: original.task_kind,
168 5910276 : download_behavior: original.download_behavior,
169 5910276 : access_stats_behavior: original.access_stats_behavior,
170 5910276 : page_content_kind: original.page_content_kind,
171 5910276 : micros_spent_throttled: Default::default(),
172 5910276 : },
173 5910276 : }
174 5910276 : }
175 :
176 : /// Configure the DownloadBehavior of the context: whether to
177 : /// download missing layers, and/or warn on the download.
178 2388 : pub fn download_behavior(mut self, b: DownloadBehavior) -> Self {
179 2388 : self.inner.download_behavior = b;
180 2388 : self
181 2388 : }
182 :
183 : /// Configure the AccessStatsBehavior of the context: whether layer
184 : /// accesses should update the access time of the layer.
185 364 : pub(crate) fn access_stats_behavior(mut self, b: AccessStatsBehavior) -> Self {
186 364 : self.inner.access_stats_behavior = b;
187 364 : self
188 364 : }
189 :
190 5909912 : pub(crate) fn page_content_kind(mut self, k: PageContentKind) -> Self {
191 5909912 : self.inner.page_content_kind = k;
192 5909912 : self
193 5909912 : }
194 :
195 5912664 : pub fn build(self) -> RequestContext {
196 5912664 : self.inner
197 5912664 : }
198 : }
199 :
200 : impl RequestContext {
201 : /// Create a new RequestContext that has no parent.
202 : ///
203 : /// The function is called `new` because, once we add children
204 : /// to it using `detached_child` or `attached_child`, the context
205 : /// form a tree (not implemented yet since cancellation will be
206 : /// the first feature that requires a tree).
207 : ///
208 : /// # Future: Cancellation
209 : ///
210 : /// The only reason why a context like this one can be canceled is
211 : /// because someone explicitly canceled it.
212 : /// It has no parent, so it cannot inherit cancellation from there.
213 2388 : pub fn new(task_kind: TaskKind, download_behavior: DownloadBehavior) -> Self {
214 2388 : RequestContextBuilder::new(task_kind)
215 2388 : .download_behavior(download_behavior)
216 2388 : .build()
217 2388 : }
218 :
219 : /// Create a detached child context for a task that may outlive `self`.
220 : ///
221 : /// Use this when spawning new background activity that should complete
222 : /// even if the current request is canceled.
223 : ///
224 : /// # Future: Cancellation
225 : ///
226 : /// Cancellation of `self` will not propagate to the child context returned
227 : /// by this method.
228 : ///
229 : /// # Future: Structured Concurrency
230 : ///
231 : /// We could add the Future as a parameter to this function, spawn it as a task,
232 : /// and pass to the new task the child context as an argument.
233 : /// That would be an ergonomic improvement.
234 : ///
235 : /// We could make new calls to this function fail if `self` is already canceled.
236 208 : pub fn detached_child(&self, task_kind: TaskKind, download_behavior: DownloadBehavior) -> Self {
237 208 : self.child_impl(task_kind, download_behavior)
238 208 : }
239 :
240 : /// Create a child of context `self` for a task that shall not outlive `self`.
241 : ///
242 : /// Use this when fanning-out work to other async tasks.
243 : ///
244 : /// # Future: Cancellation
245 : ///
246 : /// Cancelling a context will propagate to its attached children.
247 : ///
248 : /// # Future: Structured Concurrency
249 : ///
250 : /// We could add the Future as a parameter to this function, spawn it as a task,
251 : /// and track its `JoinHandle` inside the `RequestContext`.
252 : ///
253 : /// We could then provide another method to allow waiting for all child tasks
254 : /// to finish.
255 : ///
256 : /// We could make new calls to this function fail if `self` is already canceled.
257 : /// Alternatively, we could allow the creation but not spawn the task.
258 : /// The method to wait for child tasks would return an error, indicating
259 : /// that the child task was not started because the context was canceled.
260 1490 : pub fn attached_child(&self) -> Self {
261 1490 : self.child_impl(self.task_kind(), self.download_behavior())
262 1490 : }
263 :
264 : /// Use this function when you should be creating a child context using
265 : /// [`attached_child`] or [`detached_child`], but your caller doesn't provide
266 : /// a context and you are unwilling to change all callers to provide one.
267 : ///
268 : /// Before we add cancellation, we should get rid of this method.
269 : ///
270 : /// [`attached_child`]: Self::attached_child
271 : /// [`detached_child`]: Self::detached_child
272 392 : pub fn todo_child(task_kind: TaskKind, download_behavior: DownloadBehavior) -> Self {
273 392 : Self::new(task_kind, download_behavior)
274 392 : }
275 :
276 1698 : fn child_impl(&self, task_kind: TaskKind, download_behavior: DownloadBehavior) -> Self {
277 1698 : Self::new(task_kind, download_behavior)
278 1698 : }
279 :
280 6523254 : pub fn task_kind(&self) -> TaskKind {
281 6523254 : self.task_kind
282 6523254 : }
283 :
284 1498 : pub fn download_behavior(&self) -> DownloadBehavior {
285 1498 : self.download_behavior
286 1498 : }
287 :
288 212631 : pub(crate) fn access_stats_behavior(&self) -> AccessStatsBehavior {
289 212631 : self.access_stats_behavior
290 212631 : }
291 :
292 5669576 : pub(crate) fn page_content_kind(&self) -> PageContentKind {
293 5669576 : self.page_content_kind
294 5669576 : }
295 : }
|