LCOV - code coverage report
Current view: top level - safekeeper/src - json_ctrl.rs (source / functions) Coverage Total Hit
Test: 691a4c28fe7169edd60b367c52d448a0a6605f1f.info Lines: 0.0 % 93 0
Test Date: 2024-05-10 13:18:37 Functions: 0.0 % 26 0

            Line data    Source code
       1              : //!
       2              : //! This module implements JSON_CTRL protocol, which allows exchange
       3              : //! JSON messages over psql for testing purposes.
       4              : //!
       5              : //! Currently supports AppendLogicalMessage, which is used for WAL
       6              : //! modifications in tests.
       7              : //!
       8              : 
       9              : use std::sync::Arc;
      10              : 
      11              : use anyhow::Context;
      12              : use bytes::Bytes;
      13              : use postgres_backend::QueryError;
      14              : use serde::{Deserialize, Serialize};
      15              : use tokio::io::{AsyncRead, AsyncWrite};
      16              : use tracing::*;
      17              : use utils::id::TenantTimelineId;
      18              : 
      19              : use crate::handler::SafekeeperPostgresHandler;
      20              : use crate::safekeeper::{AcceptorProposerMessage, AppendResponse, ServerInfo};
      21              : use crate::safekeeper::{
      22              :     AppendRequest, AppendRequestHeader, ProposerAcceptorMessage, ProposerElected,
      23              : };
      24              : use crate::safekeeper::{Term, TermHistory, TermLsn};
      25              : use crate::state::TimelinePersistentState;
      26              : use crate::timeline::Timeline;
      27              : use crate::GlobalTimelines;
      28              : use postgres_backend::PostgresBackend;
      29              : use postgres_ffi::encode_logical_message;
      30              : use postgres_ffi::WAL_SEGMENT_SIZE;
      31              : use pq_proto::{BeMessage, RowDescriptor, TEXT_OID};
      32              : use utils::lsn::Lsn;
      33              : 
      34            0 : #[derive(Serialize, Deserialize, Debug)]
      35              : pub struct AppendLogicalMessage {
      36              :     // prefix and message to build LogicalMessage
      37              :     pub lm_prefix: String,
      38              :     pub lm_message: String,
      39              : 
      40              :     // if true, commit_lsn will match flush_lsn after append
      41              :     pub set_commit_lsn: bool,
      42              : 
      43              :     // if true, ProposerElected will be sent before append
      44              :     pub send_proposer_elected: bool,
      45              : 
      46              :     // fields from AppendRequestHeader
      47              :     pub term: Term,
      48              :     #[serde(with = "utils::lsn::serde_as_u64")]
      49              :     pub epoch_start_lsn: Lsn,
      50              :     #[serde(with = "utils::lsn::serde_as_u64")]
      51              :     pub begin_lsn: Lsn,
      52              :     #[serde(with = "utils::lsn::serde_as_u64")]
      53              :     pub truncate_lsn: Lsn,
      54              :     pub pg_version: u32,
      55              : }
      56              : 
      57              : #[derive(Debug, Serialize)]
      58              : struct AppendResult {
      59              :     // safekeeper state after append
      60              :     state: TimelinePersistentState,
      61              :     // info about new record in the WAL
      62              :     inserted_wal: InsertedWAL,
      63              : }
      64              : 
      65              : /// Handles command to craft logical message WAL record with given
      66              : /// content, and then append it with specified term and lsn. This
      67              : /// function is used to test safekeepers in different scenarios.
      68            0 : pub async fn handle_json_ctrl<IO: AsyncRead + AsyncWrite + Unpin>(
      69            0 :     spg: &SafekeeperPostgresHandler,
      70            0 :     pgb: &mut PostgresBackend<IO>,
      71            0 :     append_request: &AppendLogicalMessage,
      72            0 : ) -> Result<(), QueryError> {
      73            0 :     info!("JSON_CTRL request: {append_request:?}");
      74              : 
      75              :     // need to init safekeeper state before AppendRequest
      76            0 :     let tli = prepare_safekeeper(spg.ttid, append_request.pg_version).await?;
      77              : 
      78              :     // if send_proposer_elected is true, we need to update local history
      79            0 :     if append_request.send_proposer_elected {
      80            0 :         send_proposer_elected(&tli, append_request.term, append_request.epoch_start_lsn).await?;
      81            0 :     }
      82              : 
      83            0 :     let inserted_wal = append_logical_message(&tli, append_request).await?;
      84            0 :     let response = AppendResult {
      85            0 :         state: tli.get_state().await.1,
      86            0 :         inserted_wal,
      87              :     };
      88            0 :     let response_data = serde_json::to_vec(&response)
      89            0 :         .with_context(|| format!("Response {response:?} is not a json array"))?;
      90              : 
      91            0 :     pgb.write_message_noflush(&BeMessage::RowDescription(&[RowDescriptor {
      92            0 :         name: b"json",
      93            0 :         typoid: TEXT_OID,
      94            0 :         typlen: -1,
      95            0 :         ..Default::default()
      96            0 :     }]))?
      97            0 :     .write_message_noflush(&BeMessage::DataRow(&[Some(&response_data)]))?
      98            0 :     .write_message_noflush(&BeMessage::CommandComplete(b"JSON_CTRL"))?;
      99            0 :     Ok(())
     100            0 : }
     101              : 
     102              : /// Prepare safekeeper to process append requests without crashes,
     103              : /// by sending ProposerGreeting with default server.wal_seg_size.
     104            0 : async fn prepare_safekeeper(
     105            0 :     ttid: TenantTimelineId,
     106            0 :     pg_version: u32,
     107            0 : ) -> anyhow::Result<Arc<Timeline>> {
     108            0 :     GlobalTimelines::create(
     109            0 :         ttid,
     110            0 :         ServerInfo {
     111            0 :             pg_version,
     112            0 :             wal_seg_size: WAL_SEGMENT_SIZE as u32,
     113            0 :             system_id: 0,
     114            0 :         },
     115            0 :         Lsn::INVALID,
     116            0 :         Lsn::INVALID,
     117            0 :     )
     118            0 :     .await
     119            0 : }
     120              : 
     121            0 : async fn send_proposer_elected(tli: &Arc<Timeline>, term: Term, lsn: Lsn) -> anyhow::Result<()> {
     122              :     // add new term to existing history
     123            0 :     let history = tli.get_state().await.1.acceptor_state.term_history;
     124            0 :     let history = history.up_to(lsn.checked_sub(1u64).unwrap());
     125            0 :     let mut history_entries = history.0;
     126            0 :     history_entries.push(TermLsn { term, lsn });
     127            0 :     let history = TermHistory(history_entries);
     128            0 : 
     129            0 :     let proposer_elected_request = ProposerAcceptorMessage::Elected(ProposerElected {
     130            0 :         term,
     131            0 :         start_streaming_at: lsn,
     132            0 :         term_history: history,
     133            0 :         timeline_start_lsn: lsn,
     134            0 :     });
     135            0 : 
     136            0 :     tli.process_msg(&proposer_elected_request).await?;
     137            0 :     Ok(())
     138            0 : }
     139              : 
     140              : #[derive(Debug, Serialize)]
     141              : pub struct InsertedWAL {
     142              :     begin_lsn: Lsn,
     143              :     pub end_lsn: Lsn,
     144              :     append_response: AppendResponse,
     145              : }
     146              : 
     147              : /// Extend local WAL with new LogicalMessage record. To do that,
     148              : /// create AppendRequest with new WAL and pass it to safekeeper.
     149            0 : pub async fn append_logical_message(
     150            0 :     tli: &Arc<Timeline>,
     151            0 :     msg: &AppendLogicalMessage,
     152            0 : ) -> anyhow::Result<InsertedWAL> {
     153            0 :     let wal_data = encode_logical_message(&msg.lm_prefix, &msg.lm_message);
     154            0 :     let sk_state = tli.get_state().await.1;
     155              : 
     156            0 :     let begin_lsn = msg.begin_lsn;
     157            0 :     let end_lsn = begin_lsn + wal_data.len() as u64;
     158              : 
     159            0 :     let commit_lsn = if msg.set_commit_lsn {
     160            0 :         end_lsn
     161              :     } else {
     162            0 :         sk_state.commit_lsn
     163              :     };
     164              : 
     165            0 :     let append_request = ProposerAcceptorMessage::AppendRequest(AppendRequest {
     166            0 :         h: AppendRequestHeader {
     167            0 :             term: msg.term,
     168            0 :             epoch_start_lsn: begin_lsn,
     169            0 :             begin_lsn,
     170            0 :             end_lsn,
     171            0 :             commit_lsn,
     172            0 :             truncate_lsn: msg.truncate_lsn,
     173            0 :             proposer_uuid: [0u8; 16],
     174            0 :         },
     175            0 :         wal_data: Bytes::from(wal_data),
     176            0 :     });
     177              : 
     178            0 :     let response = tli.process_msg(&append_request).await?;
     179              : 
     180            0 :     let append_response = match response {
     181            0 :         Some(AcceptorProposerMessage::AppendResponse(resp)) => resp,
     182            0 :         _ => anyhow::bail!("not AppendResponse"),
     183              :     };
     184              : 
     185            0 :     Ok(InsertedWAL {
     186            0 :         begin_lsn,
     187            0 :         end_lsn,
     188            0 :         append_response,
     189            0 :     })
     190            0 : }
        

Generated by: LCOV version 2.1-beta