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 : //! The solution is to have a container structure ([`RequestContext`]) that
63 : //! carries the information. Functions that don't care about what's in it
64 : //! pass it along to callees.
65 : //!
66 : //! ### Why Not Task-Local Variables
67 : //!
68 : //! One could use task-local variables (the equivalent of thread-local variables)
69 : //! to address the immediate needs outlined above.
70 : //! However, we reject task-local variables because:
71 : //! 1. they are implicit, thereby making it harder to trace the data flow in code
72 : //! reviews and during debugging,
73 : //! 2. they can be mutable, which enables implicit return data flow,
74 : //! 3. they are restrictive in that code which fans out into multiple tasks,
75 : //! or even threads, needs to carefully propagate the state.
76 : //!
77 : //! In contrast, information flow with [`RequestContext`] is
78 : //! 1. always explicit,
79 : //! 2. strictly uni-directional because RequestContext is immutable,
80 : //! 3. tangible because a [`RequestContext`] is just a value.
81 : //! When creating child activities, regardless of whether it's a task,
82 : //! thread, or even an RPC to another service, the value can
83 : //! be used like any other argument.
84 : //!
85 : //! The solution is that all code paths are infected with precisely one
86 : //! [`RequestContext`] argument. Functions in the middle of the call chain
87 : //! only need to pass it on.
88 :
89 : use crate::task_mgr::TaskKind;
90 :
91 : // The main structure of this module, see module-level comment.
92 0 : #[derive(Clone, Debug)]
93 : pub struct RequestContext {
94 : task_kind: TaskKind,
95 : download_behavior: DownloadBehavior,
96 : access_stats_behavior: AccessStatsBehavior,
97 : }
98 :
99 : /// Desired behavior if the operation requires an on-demand download
100 : /// to proceed.
101 0 : #[derive(Clone, Copy, PartialEq, Eq, Debug)]
102 : pub enum DownloadBehavior {
103 : /// Download the layer file. It can take a while.
104 : Download,
105 :
106 : /// Download the layer file, but print a warning to the log. This should be used
107 : /// in code where the layer file is expected to already exist locally.
108 : Warn,
109 :
110 : /// Return a PageReconstructError::NeedsDownload error
111 : Error,
112 : }
113 :
114 : /// Whether this request should update access times used in LRU eviction
115 45700275 : #[derive(Clone, Copy, PartialEq, Eq, Debug)]
116 : pub(crate) enum AccessStatsBehavior {
117 : /// Update access times: this request's access to data should be taken
118 : /// as a hint that the accessed layer is likely to be accessed again
119 : Update,
120 :
121 : /// Do not update access times: this request is accessing the layer
122 : /// but does not want to indicate that the layer should be retained in cache,
123 : /// perhaps because the requestor is a compaction routine that will soon cover
124 : /// this layer with another.
125 : Skip,
126 : }
127 :
128 : pub struct RequestContextBuilder {
129 : inner: RequestContext,
130 : }
131 :
132 : impl RequestContextBuilder {
133 : /// A new builder with default settings
134 26116 : pub fn new(task_kind: TaskKind) -> Self {
135 26116 : Self {
136 26116 : inner: RequestContext {
137 26116 : task_kind,
138 26116 : download_behavior: DownloadBehavior::Download,
139 26116 : access_stats_behavior: AccessStatsBehavior::Update,
140 26116 : },
141 26116 : }
142 26116 : }
143 :
144 1399 : pub fn extend(original: &RequestContext) -> Self {
145 1399 : Self {
146 1399 : // This is like a Copy, but avoid implementing Copy because ordinary users of
147 1399 : // RequestContext should always move or ref it.
148 1399 : inner: RequestContext {
149 1399 : task_kind: original.task_kind,
150 1399 : download_behavior: original.download_behavior,
151 1399 : access_stats_behavior: original.access_stats_behavior,
152 1399 : },
153 1399 : }
154 1399 : }
155 :
156 : /// Configure the DownloadBehavior of the context: whether to
157 : /// download missing layers, and/or warn on the download.
158 26116 : pub fn download_behavior(mut self, b: DownloadBehavior) -> Self {
159 26116 : self.inner.download_behavior = b;
160 26116 : self
161 26116 : }
162 :
163 : /// Configure the AccessStatsBehavior of the context: whether layer
164 : /// accesses should update the access time of the layer.
165 1399 : pub(crate) fn access_stats_behavior(mut self, b: AccessStatsBehavior) -> Self {
166 1399 : self.inner.access_stats_behavior = b;
167 1399 : self
168 1399 : }
169 :
170 27515 : pub fn build(self) -> RequestContext {
171 27515 : self.inner
172 27515 : }
173 : }
174 :
175 : impl RequestContext {
176 : /// Create a new RequestContext that has no parent.
177 : ///
178 : /// The function is called `new` because, once we add children
179 : /// to it using `detached_child` or `attached_child`, the context
180 : /// form a tree (not implemented yet since cancellation will be
181 : /// the first feature that requires a tree).
182 : ///
183 : /// # Future: Cancellation
184 : ///
185 : /// The only reason why a context like this one can be canceled is
186 : /// because someone explicitly canceled it.
187 : /// It has no parent, so it cannot inherit cancellation from there.
188 26116 : pub fn new(task_kind: TaskKind, download_behavior: DownloadBehavior) -> Self {
189 26116 : RequestContextBuilder::new(task_kind)
190 26116 : .download_behavior(download_behavior)
191 26116 : .build()
192 26116 : }
193 :
194 : /// Create a detached child context for a task that may outlive `self`.
195 : ///
196 : /// Use this when spawning new background activity that should complete
197 : /// even if the current request is canceled.
198 : ///
199 : /// # Future: Cancellation
200 : ///
201 : /// Cancellation of `self` will not propagate to the child context returned
202 : /// by this method.
203 : ///
204 : /// # Future: Structured Concurrency
205 : ///
206 : /// We could add the Future as a parameter to this function, spawn it as a task,
207 : /// and pass to the new task the child context as an argument.
208 : /// That would be an ergonomic improvement.
209 : ///
210 : /// We could make new calls to this function fail if `self` is already canceled.
211 10140 : pub fn detached_child(&self, task_kind: TaskKind, download_behavior: DownloadBehavior) -> Self {
212 10140 : self.child_impl(task_kind, download_behavior)
213 10140 : }
214 :
215 : /// Create a child of context `self` for a task that shall not outlive `self`.
216 : ///
217 : /// Use this when fanning-out work to other async tasks.
218 : ///
219 : /// # Future: Cancellation
220 : ///
221 : /// Cancelling a context will propagate to its attached children.
222 : ///
223 : /// # Future: Structured Concurrency
224 : ///
225 : /// We could add the Future as a parameter to this function, spawn it as a task,
226 : /// and track its `JoinHandle` inside the `RequestContext`.
227 : ///
228 : /// We could then provide another method to allow waiting for all child tasks
229 : /// to finish.
230 : ///
231 : /// We could make new calls to this function fail if `self` is already canceled.
232 : /// Alternatively, we could allow the creation but not spawn the task.
233 : /// The method to wait for child tasks would return an error, indicating
234 : /// that the child task was not started because the context was canceled.
235 7166 : pub fn attached_child(&self) -> Self {
236 7166 : self.child_impl(self.task_kind(), self.download_behavior())
237 7166 : }
238 :
239 : /// Use this function when you should be creating a child context using
240 : /// [`attached_child`] or [`detached_child`], but your caller doesn't provide
241 : /// a context and you are unwilling to change all callers to provide one.
242 : ///
243 : /// Before we add cancellation, we should get rid of this method.
244 : ///
245 : /// [`attached_child`]: Self::attached_child
246 : /// [`detached_child`]: Self::detached_child
247 3785 : pub fn todo_child(task_kind: TaskKind, download_behavior: DownloadBehavior) -> Self {
248 3785 : Self::new(task_kind, download_behavior)
249 3785 : }
250 :
251 17306 : fn child_impl(&self, task_kind: TaskKind, download_behavior: DownloadBehavior) -> Self {
252 17306 : Self::new(task_kind, download_behavior)
253 17306 : }
254 :
255 131465610 : pub fn task_kind(&self) -> TaskKind {
256 131465610 : self.task_kind
257 131465610 : }
258 :
259 8911 : pub fn download_behavior(&self) -> DownloadBehavior {
260 8911 : self.download_behavior
261 8911 : }
262 :
263 45700275 : pub(crate) fn access_stats_behavior(&self) -> AccessStatsBehavior {
264 45700275 : self.access_stats_behavior
265 45700275 : }
266 : }
|