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