Line data Source code
1 : use std::collections::{HashMap, HashSet, VecDeque};
2 : use std::future::Future;
3 : use std::num::NonZeroUsize;
4 : use std::pin::Pin;
5 : use std::sync::atomic::{AtomicU64, Ordering};
6 : use std::sync::{Arc, Mutex};
7 : use std::time::{Duration, Instant};
8 :
9 : use anyhow::Context;
10 : use async_trait::async_trait;
11 : use bytes::Bytes;
12 : use camino::Utf8PathBuf;
13 : use pageserver_api::key::Key;
14 : use pageserver_api::keyspace::KeySpaceAccum;
15 : use pageserver_api::models::{PagestreamGetPageRequest, PagestreamRequest};
16 : use pageserver_api::reltag::RelTag;
17 : use pageserver_api::shard::TenantShardId;
18 : use pageserver_page_api::proto;
19 : use rand::prelude::*;
20 : use tokio::task::JoinSet;
21 : use tokio_util::sync::CancellationToken;
22 : use tracing::info;
23 : use utils::id::TenantTimelineId;
24 : use utils::lsn::Lsn;
25 :
26 : use crate::util::tokio_thread_local_stats::AllThreadLocalStats;
27 : use crate::util::{request_stats, tokio_thread_local_stats};
28 :
29 : #[derive(clap::ValueEnum, Clone, Debug)]
30 : enum Protocol {
31 : Libpq,
32 : Grpc,
33 : }
34 :
35 : /// GetPage@LatestLSN, uniformly distributed across the compute-accessible keyspace.
36 : #[derive(clap::Parser)]
37 : pub(crate) struct Args {
38 : #[clap(long, default_value = "http://localhost:9898")]
39 0 : mgmt_api_endpoint: String,
40 : #[clap(long, default_value = "postgres://postgres@localhost:64000")]
41 0 : page_service_connstring: String,
42 : #[clap(long)]
43 : pageserver_jwt: Option<String>,
44 : #[clap(long, default_value = "1")]
45 0 : num_clients: NonZeroUsize,
46 : #[clap(long)]
47 : runtime: Option<humantime::Duration>,
48 : #[clap(long, value_enum, default_value = "libpq")]
49 0 : protocol: Protocol,
50 : /// Each client sends requests at the given rate.
51 : ///
52 : /// If a request takes too long and we should be issuing a new request already,
53 : /// we skip that request and account it as `MISSED`.
54 : #[clap(long)]
55 : per_client_rate: Option<usize>,
56 : /// Probability for sending `latest=true` in the request (uniform distribution).
57 : #[clap(long, default_value = "1")]
58 0 : req_latest_probability: f64,
59 : #[clap(long)]
60 : limit_to_first_n_targets: Option<usize>,
61 : /// For large pageserver installations, enumerating the keyspace takes a lot of time.
62 : /// If specified, the specified path is used to maintain a cache of the keyspace enumeration result.
63 : /// The cache is tagged and auto-invalided by the tenant/timeline ids only.
64 : /// It doesn't get invalidated if the keyspace changes under the hood, e.g., due to new ingested data or compaction.
65 : #[clap(long)]
66 : keyspace_cache: Option<Utf8PathBuf>,
67 : /// Before starting the benchmark, live-reconfigure the pageserver to use the given
68 : /// [`pageserver_api::models::virtual_file::IoEngineKind`].
69 : #[clap(long)]
70 : set_io_engine: Option<pageserver_api::models::virtual_file::IoEngineKind>,
71 :
72 : /// Before starting the benchmark, live-reconfigure the pageserver to use specified io mode (buffered vs. direct).
73 : #[clap(long)]
74 : set_io_mode: Option<pageserver_api::models::virtual_file::IoMode>,
75 :
76 : /// Queue depth generated in each client.
77 : #[clap(long, default_value = "1")]
78 0 : queue_depth: NonZeroUsize,
79 :
80 : /// Batch size of contiguous pages generated by each client. This is equivalent to how Postgres
81 : /// will request page batches (e.g. prefetches or vectored reads). A batch counts as 1 RPS and
82 : /// 1 queue depth.
83 : ///
84 : /// The libpq protocol does not support client-side batching, and will submit batches as many
85 : /// individual requests, in the hope that the server will batch them. Each batch still counts as
86 : /// 1 RPS and 1 queue depth.
87 : #[clap(long, default_value = "1")]
88 0 : batch_size: NonZeroUsize,
89 :
90 : #[clap(long)]
91 : only_relnode: Option<u32>,
92 :
93 0 : targets: Option<Vec<TenantTimelineId>>,
94 : }
95 :
96 : /// State shared by all clients
97 : #[derive(Debug)]
98 : struct SharedState {
99 : start_work_barrier: tokio::sync::Barrier,
100 : live_stats: LiveStats,
101 : }
102 :
103 : #[derive(Debug, Default)]
104 : struct LiveStats {
105 : completed_requests: AtomicU64,
106 : missed: AtomicU64,
107 : }
108 :
109 : impl LiveStats {
110 0 : fn request_done(&self) {
111 0 : self.completed_requests.fetch_add(1, Ordering::Relaxed);
112 0 : }
113 0 : fn missed(&self, n: u64) {
114 0 : self.missed.fetch_add(n, Ordering::Relaxed);
115 0 : }
116 : }
117 :
118 0 : #[derive(Clone, serde::Serialize, serde::Deserialize)]
119 : struct KeyRange {
120 : timeline: TenantTimelineId,
121 : timeline_lsn: Lsn,
122 : start: i128,
123 : end: i128,
124 : }
125 :
126 : impl KeyRange {
127 0 : fn len(&self) -> i128 {
128 0 : self.end - self.start
129 0 : }
130 : }
131 :
132 : #[derive(PartialEq, Eq, Hash, Copy, Clone)]
133 : struct WorkerId {
134 : timeline: TenantTimelineId,
135 : num_client: usize, // from 0..args.num_clients
136 : }
137 :
138 : #[derive(serde::Serialize)]
139 : struct Output {
140 : total: request_stats::Output,
141 : }
142 :
143 : tokio_thread_local_stats::declare!(STATS: request_stats::Stats);
144 :
145 0 : pub(crate) fn main(args: Args) -> anyhow::Result<()> {
146 0 : tokio_thread_local_stats::main!(STATS, move |thread_local_stats| {
147 0 : main_impl(args, thread_local_stats)
148 0 : })
149 0 : }
150 :
151 0 : async fn main_impl(
152 0 : args: Args,
153 0 : all_thread_local_stats: AllThreadLocalStats<request_stats::Stats>,
154 0 : ) -> anyhow::Result<()> {
155 0 : let args: &'static Args = Box::leak(Box::new(args));
156 0 :
157 0 : let mgmt_api_client = Arc::new(pageserver_client::mgmt_api::Client::new(
158 0 : reqwest::Client::new(), // TODO: support ssl_ca_file for https APIs in pagebench.
159 0 : args.mgmt_api_endpoint.clone(),
160 0 : args.pageserver_jwt.as_deref(),
161 0 : ));
162 :
163 0 : if let Some(engine_str) = &args.set_io_engine {
164 0 : mgmt_api_client.put_io_engine(engine_str).await?;
165 0 : }
166 :
167 0 : if let Some(mode) = &args.set_io_mode {
168 0 : mgmt_api_client.put_io_mode(mode).await?;
169 0 : }
170 :
171 : // discover targets
172 0 : let timelines: Vec<TenantTimelineId> = crate::util::cli::targets::discover(
173 0 : &mgmt_api_client,
174 0 : crate::util::cli::targets::Spec {
175 0 : limit_to_first_n_targets: args.limit_to_first_n_targets,
176 0 : targets: args.targets.clone(),
177 0 : },
178 0 : )
179 0 : .await?;
180 :
181 0 : #[derive(serde::Deserialize)]
182 : struct KeyspaceCacheDe {
183 : tag: Vec<TenantTimelineId>,
184 : data: Vec<KeyRange>,
185 : }
186 : #[derive(serde::Serialize)]
187 : struct KeyspaceCacheSer<'a> {
188 : tag: &'a [TenantTimelineId],
189 : data: &'a [KeyRange],
190 : }
191 0 : let cache = args
192 0 : .keyspace_cache
193 0 : .as_ref()
194 0 : .map(|keyspace_cache_file| {
195 0 : let contents = match std::fs::read(keyspace_cache_file) {
196 0 : Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
197 0 : return anyhow::Ok(None);
198 : }
199 0 : x => x.context("read keyspace cache file")?,
200 : };
201 0 : let cache: KeyspaceCacheDe =
202 0 : serde_json::from_slice(&contents).context("deserialize cache file")?;
203 0 : let tag_ok = HashSet::<TenantTimelineId>::from_iter(cache.tag.into_iter())
204 0 : == HashSet::from_iter(timelines.iter().cloned());
205 0 : info!("keyspace cache file matches tag: {tag_ok}");
206 0 : anyhow::Ok(if tag_ok { Some(cache.data) } else { None })
207 0 : })
208 0 : .transpose()?
209 0 : .flatten();
210 0 : let all_ranges: Vec<KeyRange> = if let Some(cached) = cache {
211 0 : info!("using keyspace cache file");
212 0 : cached
213 : } else {
214 0 : let mut js = JoinSet::new();
215 0 : for timeline in &timelines {
216 0 : js.spawn({
217 0 : let mgmt_api_client = Arc::clone(&mgmt_api_client);
218 0 : let timeline = *timeline;
219 0 : async move {
220 0 : let partitioning = mgmt_api_client
221 0 : .keyspace(
222 0 : TenantShardId::unsharded(timeline.tenant_id),
223 0 : timeline.timeline_id,
224 0 : )
225 0 : .await?;
226 0 : let lsn = partitioning.at_lsn;
227 0 : let start = Instant::now();
228 0 : let mut filtered = KeySpaceAccum::new();
229 : // let's hope this is inlined and vectorized...
230 : // TODO: turn this loop into a is_rel_block_range() function.
231 0 : for r in partitioning.keys.ranges.iter() {
232 0 : let mut i = r.start;
233 0 : while i != r.end {
234 0 : let mut include = true;
235 0 : include &= i.is_rel_block_key();
236 0 : if let Some(only_relnode) = args.only_relnode {
237 0 : include &= i.is_rel_block_of_rel(only_relnode);
238 0 : }
239 0 : if include {
240 0 : filtered.add_key(i);
241 0 : }
242 0 : i = i.next();
243 : }
244 : }
245 0 : let filtered = filtered.to_keyspace();
246 0 : let filter_duration = start.elapsed();
247 0 :
248 0 : anyhow::Ok((
249 0 : filter_duration,
250 0 : filtered.ranges.into_iter().map(move |r| KeyRange {
251 0 : timeline,
252 0 : timeline_lsn: lsn,
253 0 : start: r.start.to_i128(),
254 0 : end: r.end.to_i128(),
255 0 : }),
256 0 : ))
257 0 : }
258 0 : });
259 0 : }
260 0 : let mut total_filter_duration = Duration::from_secs(0);
261 0 : let mut all_ranges: Vec<KeyRange> = Vec::new();
262 0 : while let Some(res) = js.join_next().await {
263 0 : let (filter_duration, range) = res.unwrap().unwrap();
264 0 : all_ranges.extend(range);
265 0 : total_filter_duration += filter_duration;
266 0 : }
267 0 : info!("filter duration: {}", total_filter_duration.as_secs_f64());
268 0 : if let Some(cachefile) = args.keyspace_cache.as_ref() {
269 0 : let cache = KeyspaceCacheSer {
270 0 : tag: &timelines,
271 0 : data: &all_ranges,
272 0 : };
273 0 : let bytes = serde_json::to_vec(&cache).context("serialize keyspace for cache file")?;
274 0 : std::fs::write(cachefile, bytes).context("write keyspace cache file to disk")?;
275 0 : info!("successfully wrote keyspace cache file");
276 0 : }
277 0 : all_ranges
278 : };
279 :
280 0 : let num_live_stats_dump = 1;
281 0 : let num_work_sender_tasks = args.num_clients.get() * timelines.len();
282 0 : let num_main_impl = 1;
283 0 :
284 0 : let shared_state = Arc::new(SharedState {
285 0 : start_work_barrier: tokio::sync::Barrier::new(
286 0 : num_live_stats_dump + num_work_sender_tasks + num_main_impl,
287 0 : ),
288 0 : live_stats: LiveStats::default(),
289 0 : });
290 0 : let cancel = CancellationToken::new();
291 0 :
292 0 : let ss = shared_state.clone();
293 0 : tokio::spawn({
294 0 : async move {
295 0 : ss.start_work_barrier.wait().await;
296 : loop {
297 0 : let start = std::time::Instant::now();
298 0 : tokio::time::sleep(std::time::Duration::from_secs(1)).await;
299 0 : let stats = &ss.live_stats;
300 0 : let completed_requests = stats.completed_requests.swap(0, Ordering::Relaxed);
301 0 : let missed = stats.missed.swap(0, Ordering::Relaxed);
302 0 : let elapsed = start.elapsed();
303 0 : info!(
304 0 : "RPS: {:.0} MISSED: {:.0}",
305 0 : completed_requests as f64 / elapsed.as_secs_f64(),
306 0 : missed as f64 / elapsed.as_secs_f64()
307 : );
308 : }
309 0 : }
310 0 : });
311 0 :
312 0 : let rps_period = args
313 0 : .per_client_rate
314 0 : .map(|rps_limit| Duration::from_secs_f64(1.0 / (rps_limit as f64)));
315 0 : let make_worker: &dyn Fn(WorkerId) -> Pin<Box<dyn Send + Future<Output = ()>>> = &|worker_id| {
316 0 : let ss = shared_state.clone();
317 0 : let cancel = cancel.clone();
318 0 : let ranges: Vec<KeyRange> = all_ranges
319 0 : .iter()
320 0 : .filter(|r| r.timeline == worker_id.timeline)
321 0 : .cloned()
322 0 : .collect();
323 0 : let weights =
324 0 : rand::distributions::weighted::WeightedIndex::new(ranges.iter().map(|v| v.len()))
325 0 : .unwrap();
326 0 :
327 0 : Box::pin(async move {
328 0 : let client: Box<dyn Client> = match args.protocol {
329 : Protocol::Libpq => Box::new(
330 0 : LibpqClient::new(args.page_service_connstring.clone(), worker_id.timeline)
331 0 : .await
332 0 : .unwrap(),
333 : ),
334 :
335 : Protocol::Grpc => Box::new(
336 0 : GrpcClient::new(args.page_service_connstring.clone(), worker_id.timeline)
337 0 : .await
338 0 : .unwrap(),
339 : ),
340 : };
341 0 : run_worker(args, client, ss, cancel, rps_period, ranges, weights).await
342 0 : })
343 0 : };
344 :
345 0 : info!("spawning workers");
346 0 : let mut workers = JoinSet::new();
347 0 : for timeline in timelines.iter().cloned() {
348 0 : for num_client in 0..args.num_clients.get() {
349 0 : let worker_id = WorkerId {
350 0 : timeline,
351 0 : num_client,
352 0 : };
353 0 : workers.spawn(make_worker(worker_id));
354 0 : }
355 : }
356 0 : let workers = async move {
357 0 : while let Some(res) = workers.join_next().await {
358 0 : res.unwrap();
359 0 : }
360 0 : };
361 :
362 0 : info!("waiting for everything to become ready");
363 0 : shared_state.start_work_barrier.wait().await;
364 0 : info!("work started");
365 0 : if let Some(runtime) = args.runtime {
366 0 : tokio::time::sleep(runtime.into()).await;
367 0 : info!("runtime over, signalling cancellation");
368 0 : cancel.cancel();
369 0 : workers.await;
370 0 : info!("work sender exited");
371 : } else {
372 0 : workers.await;
373 0 : unreachable!("work sender never terminates");
374 : }
375 :
376 0 : let output = Output {
377 : total: {
378 0 : let mut agg_stats = request_stats::Stats::new();
379 0 : for stats in all_thread_local_stats.lock().unwrap().iter() {
380 0 : let stats = stats.lock().unwrap();
381 0 : agg_stats.add(&stats);
382 0 : }
383 0 : agg_stats.output()
384 0 : },
385 0 : };
386 0 :
387 0 : let output = serde_json::to_string_pretty(&output).unwrap();
388 0 : println!("{output}");
389 0 :
390 0 : anyhow::Ok(())
391 0 : }
392 :
393 0 : async fn run_worker(
394 0 : args: &Args,
395 0 : mut client: Box<dyn Client>,
396 0 : shared_state: Arc<SharedState>,
397 0 : cancel: CancellationToken,
398 0 : rps_period: Option<Duration>,
399 0 : ranges: Vec<KeyRange>,
400 0 : weights: rand::distributions::weighted::WeightedIndex<i128>,
401 0 : ) {
402 0 : shared_state.start_work_barrier.wait().await;
403 0 : let client_start = Instant::now();
404 0 : let mut ticks_processed = 0;
405 0 : let mut req_id = 0;
406 0 : let batch_size: usize = args.batch_size.into();
407 0 :
408 0 : // Track inflight requests by request ID and start time. This times the request duration, and
409 0 : // ensures responses match requests. We don't expect responses back in any particular order.
410 0 : //
411 0 : // NB: this does not check that all requests received a response, because we don't wait for the
412 0 : // inflight requests to complete when the duration elapses.
413 0 : let mut inflight: HashMap<u64, Instant> = HashMap::new();
414 :
415 0 : while !cancel.is_cancelled() {
416 : // Detect if a request took longer than the RPS rate
417 0 : if let Some(period) = &rps_period {
418 0 : let periods_passed_until_now =
419 0 : usize::try_from(client_start.elapsed().as_micros() / period.as_micros()).unwrap();
420 0 :
421 0 : if periods_passed_until_now > ticks_processed {
422 0 : shared_state
423 0 : .live_stats
424 0 : .missed((periods_passed_until_now - ticks_processed) as u64);
425 0 : }
426 0 : ticks_processed = periods_passed_until_now;
427 0 : }
428 :
429 0 : while inflight.len() < args.queue_depth.get() {
430 0 : req_id += 1;
431 0 : let start = Instant::now();
432 0 : let (req_lsn, mod_lsn, rel, blks) = {
433 0 : /// Converts a compact i128 key to a relation tag and block number.
434 0 : fn key_to_block(key: i128) -> (RelTag, u32) {
435 0 : let key = Key::from_i128(key);
436 0 : assert!(key.is_rel_block_key());
437 0 : key.to_rel_block()
438 0 : .expect("we filter non-rel-block keys out above")
439 0 : }
440 :
441 : // Pick a random page from a random relation.
442 0 : let mut rng = rand::thread_rng();
443 0 : let r = &ranges[weights.sample(&mut rng)];
444 0 : let key: i128 = rng.gen_range(r.start..r.end);
445 0 : let (rel_tag, block_no) = key_to_block(key);
446 0 :
447 0 : let mut blks = VecDeque::with_capacity(batch_size);
448 0 : blks.push_back(block_no);
449 :
450 : // If requested, populate a batch of sequential pages. This is how Postgres will
451 : // request page batches (e.g. prefetches). If we hit the end of the relation, we
452 : // grow the batch towards the start too.
453 0 : for i in 1..batch_size {
454 0 : let (r, b) = key_to_block(key + i as i128);
455 0 : if r != rel_tag {
456 0 : break; // went outside relation
457 0 : }
458 0 : blks.push_back(b)
459 : }
460 :
461 0 : if blks.len() < batch_size {
462 : // Grow batch backwards if needed.
463 0 : for i in 1..batch_size {
464 0 : let (r, b) = key_to_block(key - i as i128);
465 0 : if r != rel_tag {
466 0 : break; // went outside relation
467 0 : }
468 0 : blks.push_front(b)
469 : }
470 0 : }
471 :
472 : // We assume that the entire batch can fit within the relation.
473 0 : assert_eq!(blks.len(), batch_size, "incomplete batch");
474 :
475 0 : let req_lsn = if rng.gen_bool(args.req_latest_probability) {
476 0 : Lsn::MAX
477 : } else {
478 0 : r.timeline_lsn
479 : };
480 0 : (req_lsn, r.timeline_lsn, rel_tag, blks.into())
481 0 : };
482 0 : client
483 0 : .send_get_page(req_id, req_lsn, mod_lsn, rel, blks)
484 0 : .await
485 0 : .unwrap();
486 0 : let old = inflight.insert(req_id, start);
487 0 : assert!(old.is_none(), "duplicate request ID {req_id}");
488 : }
489 :
490 0 : let (req_id, pages) = client.recv_get_page().await.unwrap();
491 0 : assert_eq!(pages.len(), batch_size, "unexpected page count");
492 0 : assert!(pages.iter().all(|p| !p.is_empty()), "empty page");
493 0 : let start = inflight
494 0 : .remove(&req_id)
495 0 : .expect("response for unknown request ID");
496 0 : let end = Instant::now();
497 0 : shared_state.live_stats.request_done();
498 0 : ticks_processed += 1;
499 0 : STATS.with(|stats| {
500 0 : stats
501 0 : .borrow()
502 0 : .lock()
503 0 : .unwrap()
504 0 : .observe(end.duration_since(start))
505 0 : .unwrap();
506 0 : });
507 :
508 0 : if let Some(period) = &rps_period {
509 0 : let next_at = client_start
510 0 : + Duration::from_micros(
511 0 : (ticks_processed) as u64 * u64::try_from(period.as_micros()).unwrap(),
512 0 : );
513 0 : tokio::time::sleep_until(next_at.into()).await;
514 0 : }
515 : }
516 0 : }
517 :
518 : /// A benchmark client, to allow switching out the transport protocol.
519 : ///
520 : /// For simplicity, this just uses separate asynchronous send/recv methods. The send method could
521 : /// return a future that resolves when the response is received, but we don't really need it.
522 : #[async_trait]
523 : trait Client: Send {
524 : /// Sends an asynchronous GetPage request to the pageserver.
525 : async fn send_get_page(
526 : &mut self,
527 : req_id: u64,
528 : req_lsn: Lsn,
529 : mod_lsn: Lsn,
530 : rel: RelTag,
531 : blks: Vec<u32>,
532 : ) -> anyhow::Result<()>;
533 :
534 : /// Receives the next GetPage response from the pageserver.
535 : async fn recv_get_page(&mut self) -> anyhow::Result<(u64, Vec<Bytes>)>;
536 : }
537 :
538 : /// A libpq-based Pageserver client.
539 : struct LibpqClient {
540 : inner: pageserver_client::page_service::PagestreamClient,
541 : // Track sent batches, so we know how many responses to expect.
542 : batch_sizes: VecDeque<usize>,
543 : }
544 :
545 : impl LibpqClient {
546 0 : async fn new(connstring: String, ttid: TenantTimelineId) -> anyhow::Result<Self> {
547 0 : let inner = pageserver_client::page_service::Client::new(connstring)
548 0 : .await?
549 0 : .pagestream(ttid.tenant_id, ttid.timeline_id)
550 0 : .await?;
551 0 : Ok(Self {
552 0 : inner,
553 0 : batch_sizes: VecDeque::new(),
554 0 : })
555 0 : }
556 : }
557 :
558 : #[async_trait]
559 : impl Client for LibpqClient {
560 0 : async fn send_get_page(
561 0 : &mut self,
562 0 : req_id: u64,
563 0 : req_lsn: Lsn,
564 0 : mod_lsn: Lsn,
565 0 : rel: RelTag,
566 0 : blks: Vec<u32>,
567 0 : ) -> anyhow::Result<()> {
568 : // libpq doesn't support client-side batches, so we send a bunch of individual requests
569 : // instead in the hope that the server will batch them for us. We use the same request ID
570 : // for all, because we'll return a single batch response.
571 0 : self.batch_sizes.push_back(blks.len());
572 0 : for blkno in blks {
573 0 : let req = PagestreamGetPageRequest {
574 0 : hdr: PagestreamRequest {
575 0 : reqid: req_id,
576 0 : request_lsn: req_lsn,
577 0 : not_modified_since: mod_lsn,
578 0 : },
579 0 : rel,
580 0 : blkno,
581 0 : };
582 0 : self.inner.getpage_send(req).await?;
583 : }
584 0 : Ok(())
585 0 : }
586 :
587 0 : async fn recv_get_page(&mut self) -> anyhow::Result<(u64, Vec<Bytes>)> {
588 0 : let batch_size = self.batch_sizes.pop_front().unwrap();
589 0 : let mut batch = Vec::with_capacity(batch_size);
590 0 : let mut req_id = None;
591 0 : for _ in 0..batch_size {
592 0 : let resp = self.inner.getpage_recv().await?;
593 0 : if req_id.is_none() {
594 0 : req_id = Some(resp.req.hdr.reqid);
595 0 : }
596 0 : assert_eq!(req_id, Some(resp.req.hdr.reqid), "request ID mismatch");
597 0 : batch.push(resp.page);
598 : }
599 0 : Ok((req_id.unwrap(), batch))
600 0 : }
601 : }
602 :
603 : /// A gRPC client using the raw, no-frills gRPC client.
604 : struct GrpcClient {
605 : req_tx: tokio::sync::mpsc::Sender<proto::GetPageRequest>,
606 : resp_rx: tonic::Streaming<proto::GetPageResponse>,
607 : }
608 :
609 : impl GrpcClient {
610 0 : async fn new(connstring: String, ttid: TenantTimelineId) -> anyhow::Result<Self> {
611 0 : let mut client = pageserver_page_api::proto::PageServiceClient::connect(connstring).await?;
612 :
613 : // The channel has a buffer size of 1, since 0 is not allowed. It does not matter, since the
614 : // benchmark will control the queue depth (i.e. in-flight requests) anyway, and requests are
615 : // buffered by Tonic and the OS too.
616 0 : let (req_tx, req_rx) = tokio::sync::mpsc::channel(1);
617 0 : let req_stream = tokio_stream::wrappers::ReceiverStream::new(req_rx);
618 0 : let mut req = tonic::Request::new(req_stream);
619 0 : let metadata = req.metadata_mut();
620 0 : metadata.insert("neon-tenant-id", ttid.tenant_id.to_string().try_into()?);
621 0 : metadata.insert("neon-timeline-id", ttid.timeline_id.to_string().try_into()?);
622 0 : metadata.insert("neon-shard-id", "0000".try_into()?);
623 :
624 0 : let resp = client.get_pages(req).await?;
625 0 : let resp_stream = resp.into_inner();
626 0 :
627 0 : Ok(Self {
628 0 : req_tx,
629 0 : resp_rx: resp_stream,
630 0 : })
631 0 : }
632 : }
633 :
634 : #[async_trait]
635 : impl Client for GrpcClient {
636 0 : async fn send_get_page(
637 0 : &mut self,
638 0 : req_id: u64,
639 0 : req_lsn: Lsn,
640 0 : mod_lsn: Lsn,
641 0 : rel: RelTag,
642 0 : blks: Vec<u32>,
643 0 : ) -> anyhow::Result<()> {
644 0 : let req = proto::GetPageRequest {
645 0 : request_id: req_id,
646 0 : request_class: proto::GetPageClass::Normal as i32,
647 0 : read_lsn: Some(proto::ReadLsn {
648 0 : request_lsn: req_lsn.0,
649 0 : not_modified_since_lsn: mod_lsn.0,
650 0 : }),
651 0 : rel: Some(rel.into()),
652 0 : block_number: blks,
653 0 : };
654 0 : self.req_tx.send(req).await?;
655 0 : Ok(())
656 0 : }
657 :
658 0 : async fn recv_get_page(&mut self) -> anyhow::Result<(u64, Vec<Bytes>)> {
659 0 : let resp = self.resp_rx.message().await?.unwrap();
660 0 : anyhow::ensure!(
661 0 : resp.status_code == proto::GetPageStatusCode::Ok as i32,
662 0 : "unexpected status code: {}",
663 : resp.status_code
664 : );
665 0 : Ok((resp.request_id, resp.page_image))
666 0 : }
667 : }
|