Line data Source code
1 : //
2 : // This file contains common utilities for dealing with PostgreSQL WAL files and
3 : // LSNs.
4 : //
5 : // Many of these functions have been copied from PostgreSQL, and rewritten in
6 : // Rust. That's why they don't follow the usual Rust naming conventions, they
7 : // have been named the same as the corresponding PostgreSQL functions instead.
8 : //
9 :
10 : use super::super::waldecoder::WalStreamDecoder;
11 : use super::bindings::{
12 : CheckPoint, ControlFileData, DBState_DB_SHUTDOWNED, FullTransactionId, TimeLineID,
13 : XLogLongPageHeaderData, XLogPageHeaderData, XLogRecPtr, XLogRecord, XLogSegNo, XLOG_PAGE_MAGIC,
14 : MY_PGVERSION
15 : };
16 : use postgres_ffi_types::TimestampTz;
17 : use super::wal_generator::LogicalMessageGenerator;
18 : use crate::pg_constants;
19 : use crate::PG_TLI;
20 : use crate::{uint32, uint64, Oid};
21 : use crate::{WAL_SEGMENT_SIZE, XLOG_BLCKSZ};
22 :
23 : use bytes::BytesMut;
24 : use bytes::{Buf, Bytes};
25 :
26 : use serde::Serialize;
27 : use std::ffi::{CString, OsStr};
28 : use std::fs::File;
29 : use std::io::prelude::*;
30 : use std::io::ErrorKind;
31 : use std::io::SeekFrom;
32 : use std::path::Path;
33 : use std::time::SystemTime;
34 : use utils::bin_ser::DeserializeError;
35 : use utils::bin_ser::SerializeError;
36 :
37 : use utils::lsn::Lsn;
38 :
39 : pub const XLOG_FNAME_LEN: usize = 24;
40 : pub const XLP_BKP_REMOVABLE: u16 = 0x0004;
41 : pub const XLP_FIRST_IS_CONTRECORD: u16 = 0x0001;
42 : pub const XLP_REM_LEN_OFFS: usize = 2 + 2 + 4 + 8;
43 : pub const XLOG_RECORD_CRC_OFFS: usize = 4 + 4 + 8 + 1 + 1 + 2;
44 :
45 : pub const XLOG_SIZE_OF_XLOG_SHORT_PHD: usize = size_of::<XLogPageHeaderData>();
46 : pub const XLOG_SIZE_OF_XLOG_LONG_PHD: usize = size_of::<XLogLongPageHeaderData>();
47 : pub const XLOG_SIZE_OF_XLOG_RECORD: usize = size_of::<XLogRecord>();
48 : #[allow(clippy::identity_op)]
49 : pub const SIZE_OF_XLOG_RECORD_DATA_HEADER_SHORT: usize = 1 * 2;
50 :
51 : /// Interval of checkpointing metadata file. We should store metadata file to enforce
52 : /// predicate that checkpoint.nextXid is larger than any XID in WAL.
53 : /// But flushing checkpoint file for each transaction seems to be too expensive,
54 : /// so XID_CHECKPOINT_INTERVAL is used to forward align nextXid and so perform
55 : /// metadata checkpoint only once per XID_CHECKPOINT_INTERVAL transactions.
56 : /// XID_CHECKPOINT_INTERVAL should not be larger than BLCKSZ*CLOG_XACTS_PER_BYTE
57 : /// in order to let CLOG_TRUNCATE mechanism correctly extend CLOG.
58 : const XID_CHECKPOINT_INTERVAL: u32 = 1024;
59 :
60 209 : pub fn XLogSegmentsPerXLogId(wal_segsz_bytes: usize) -> XLogSegNo {
61 209 : (0x100000000u64 / wal_segsz_bytes as u64) as XLogSegNo
62 209 : }
63 :
64 61 : pub fn XLogSegNoOffsetToRecPtr(
65 61 : segno: XLogSegNo,
66 61 : offset: u32,
67 61 : wal_segsz_bytes: usize,
68 61 : ) -> XLogRecPtr {
69 61 : segno * (wal_segsz_bytes as u64) + (offset as u64)
70 61 : }
71 :
72 74 : pub fn XLogFileName(tli: TimeLineID, logSegNo: XLogSegNo, wal_segsz_bytes: usize) -> String {
73 74 : format!(
74 74 : "{:>08X}{:>08X}{:>08X}",
75 : tli,
76 74 : logSegNo / XLogSegmentsPerXLogId(wal_segsz_bytes),
77 74 : logSegNo % XLogSegmentsPerXLogId(wal_segsz_bytes)
78 : )
79 74 : }
80 :
81 61 : pub fn XLogFromFileName(
82 61 : fname: &OsStr,
83 61 : wal_seg_size: usize,
84 61 : ) -> anyhow::Result<(XLogSegNo, TimeLineID)> {
85 61 : if let Some(fname_str) = fname.to_str() {
86 61 : let tli = u32::from_str_radix(&fname_str[0..8], 16)?;
87 61 : let log = u32::from_str_radix(&fname_str[8..16], 16)? as XLogSegNo;
88 61 : let seg = u32::from_str_radix(&fname_str[16..24], 16)? as XLogSegNo;
89 61 : Ok((log * XLogSegmentsPerXLogId(wal_seg_size) + seg, tli))
90 : } else {
91 0 : anyhow::bail!("non-ut8 filename: {:?}", fname);
92 : }
93 61 : }
94 :
95 146 : pub fn IsXLogFileName(fname: &OsStr) -> bool {
96 146 : if let Some(fname) = fname.to_str() {
97 1944 : fname.len() == XLOG_FNAME_LEN && fname.chars().all(|c| c.is_ascii_hexdigit())
98 : } else {
99 0 : false
100 : }
101 146 : }
102 :
103 10 : pub fn IsPartialXLogFileName(fname: &OsStr) -> bool {
104 10 : if let Some(fname) = fname.to_str() {
105 10 : fname.ends_with(".partial") && IsXLogFileName(OsStr::new(&fname[0..fname.len() - 8]))
106 : } else {
107 0 : false
108 : }
109 10 : }
110 :
111 : /// If LSN points to the beginning of the page, then shift it to first record,
112 : /// otherwise align on 8-bytes boundary (required for WAL records)
113 7 : pub fn normalize_lsn(lsn: Lsn, seg_sz: usize) -> Lsn {
114 7 : if lsn.0 % XLOG_BLCKSZ as u64 == 0 {
115 0 : let hdr_size = if lsn.0 % seg_sz as u64 == 0 {
116 0 : XLOG_SIZE_OF_XLOG_LONG_PHD
117 : } else {
118 0 : XLOG_SIZE_OF_XLOG_SHORT_PHD
119 : };
120 0 : lsn + hdr_size as u64
121 : } else {
122 7 : lsn.align()
123 : }
124 7 : }
125 :
126 : /// Generate a pg_control file, for a basebackup for starting up Postgres at the given LSN
127 : ///
128 : /// 'pg_control_bytes' and 'checkpoint_bytes' are the contents of those keys persisted in
129 : /// the pageserver. They use the same format as the PostgreSQL control file and the
130 : /// checkpoint record, but see walingest.rs for how exactly they are kept up to date.
131 : /// 'lsn' is the LSN at which we're starting up.
132 : ///
133 : /// Returns:
134 : /// - pg_control file contents
135 : /// - system_identifier, extracted from the persisted information
136 : /// - true, if we're starting up from a "clean shutdown", i.e. if there was a shutdown
137 : /// checkpoint at the given LSN
138 0 : pub fn generate_pg_control(
139 0 : pg_control_bytes: &[u8],
140 0 : checkpoint_bytes: &[u8],
141 0 : lsn: Lsn,
142 0 : ) -> anyhow::Result<(Bytes, u64, bool)> {
143 0 : let mut pg_control = ControlFileData::decode(pg_control_bytes)?;
144 0 : let mut checkpoint = CheckPoint::decode(checkpoint_bytes)?;
145 :
146 : // Generate new pg_control needed for bootstrap
147 : //
148 : // NB: In the checkpoint struct that we persist in the pageserver, we have a different
149 : // convention for the 'redo' field than in PostgreSQL: On a shutdown checkpoint,
150 : // 'redo' points the *end* of the checkpoint WAL record. On PostgreSQL, it points to
151 : // the beginning. Furthermore, on an online checkpoint, 'redo' is set to 0.
152 : //
153 : // We didn't always have this convention however, and old persisted records will have
154 : // old REDO values that point to some old LSN.
155 : //
156 : // The upshot is that if 'redo' is equal to the "current" LSN, there was a shutdown
157 : // checkpoint record at that point in WAL, with no new WAL records after it. That case
158 : // can be treated as starting from a clean shutdown. All other cases are treated as
159 : // non-clean shutdown. In Neon, we don't do WAL replay at startup in either case, so
160 : // that distinction doesn't matter very much. As of this writing, it only affects
161 : // whether the persisted pg_stats information can be used or not.
162 : //
163 : // In the Checkpoint struct in the returned pg_control file, the redo pointer is
164 : // always set to the LSN we're starting at, to hint that no WAL replay is required.
165 : // (There's some neon-specific code in Postgres startup to make that work, though.
166 : // Just setting the redo pointer is not sufficient.)
167 0 : let was_shutdown = Lsn(checkpoint.redo) == lsn;
168 0 : checkpoint.redo = normalize_lsn(lsn, WAL_SEGMENT_SIZE).0;
169 :
170 : // We use DBState_DB_SHUTDOWNED even if it was not a clean shutdown. The
171 : // neon-specific code at postgres startup ignores the state stored in the control
172 : // file, similar to archive recovery in standalone PostgreSQL. Similarly, the
173 : // checkPoint pointer is ignored, so just set it to 0.
174 0 : pg_control.checkPoint = 0;
175 0 : pg_control.checkPointCopy = checkpoint;
176 0 : pg_control.state = DBState_DB_SHUTDOWNED;
177 :
178 0 : Ok((pg_control.encode(), pg_control.system_identifier, was_shutdown))
179 0 : }
180 :
181 4 : pub fn get_current_timestamp() -> TimestampTz {
182 4 : to_pg_timestamp(SystemTime::now())
183 4 : }
184 :
185 : // Module to reduce the scope of the constants
186 : mod timestamp_conversions {
187 : use std::time::Duration;
188 :
189 : use anyhow::Context;
190 :
191 : use super::*;
192 :
193 : const UNIX_EPOCH_JDATE: u64 = 2440588; // == date2j(1970, 1, 1)
194 : const POSTGRES_EPOCH_JDATE: u64 = 2451545; // == date2j(2000, 1, 1)
195 : const SECS_PER_DAY: u64 = 86400;
196 : const USECS_PER_SEC: u64 = 1000000;
197 : const SECS_DIFF_UNIX_TO_POSTGRES_EPOCH: u64 =
198 : (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY;
199 :
200 12 : pub fn to_pg_timestamp(time: SystemTime) -> TimestampTz {
201 12 : match time.duration_since(SystemTime::UNIX_EPOCH) {
202 12 : Ok(n) => {
203 12 : ((n.as_secs() - SECS_DIFF_UNIX_TO_POSTGRES_EPOCH) * USECS_PER_SEC
204 12 : + n.subsec_micros() as u64) as i64
205 : }
206 0 : Err(_) => panic!("SystemTime before UNIX EPOCH!"),
207 : }
208 12 : }
209 :
210 12 : pub fn try_from_pg_timestamp(time: TimestampTz) -> anyhow::Result<SystemTime> {
211 12 : let time: u64 = time
212 12 : .try_into()
213 12 : .context("timestamp before millenium (postgres epoch)")?;
214 12 : let since_unix_epoch = time + SECS_DIFF_UNIX_TO_POSTGRES_EPOCH * USECS_PER_SEC;
215 12 : SystemTime::UNIX_EPOCH
216 12 : .checked_add(Duration::from_micros(since_unix_epoch))
217 12 : .context("SystemTime overflow")
218 12 : }
219 : }
220 :
221 : pub use timestamp_conversions::{to_pg_timestamp, try_from_pg_timestamp};
222 :
223 : // Returns (aligned) end_lsn of the last record in data_dir with WAL segments.
224 : // start_lsn must point to some previously known record boundary (beginning of
225 : // the next record). If no valid record after is found, start_lsn is returned
226 : // back.
227 32 : pub fn find_end_of_wal(
228 32 : data_dir: &Path,
229 32 : wal_seg_size: usize,
230 32 : start_lsn: Lsn, // start reading WAL at this point; must point at record start_lsn.
231 32 : ) -> anyhow::Result<Lsn> {
232 32 : let mut result = start_lsn;
233 32 : let mut curr_lsn = start_lsn;
234 32 : let mut buf = [0u8; XLOG_BLCKSZ];
235 32 : let pg_version = MY_PGVERSION;
236 32 : tracing::debug!("find_end_of_wal PG_VERSION: {}", pg_version);
237 :
238 32 : let mut decoder = WalStreamDecoder::new(start_lsn, pg_version);
239 :
240 : // loop over segments
241 : loop {
242 40 : let segno = curr_lsn.segment_number(wal_seg_size);
243 40 : let seg_file_name = XLogFileName(PG_TLI, segno, wal_seg_size);
244 40 : let seg_file_path = data_dir.join(seg_file_name);
245 40 : match open_wal_segment(&seg_file_path)? {
246 : None => {
247 : // no more segments
248 0 : tracing::debug!(
249 0 : "find_end_of_wal reached end at {:?}, segment {:?} doesn't exist",
250 : result, seg_file_path
251 : );
252 0 : return Ok(result);
253 : }
254 40 : Some(mut segment) => {
255 40 : let seg_offs = curr_lsn.segment_offset(wal_seg_size);
256 40 : segment.seek(SeekFrom::Start(seg_offs as u64))?;
257 : // loop inside segment
258 16504 : while curr_lsn.segment_number(wal_seg_size) == segno {
259 16496 : let bytes_read = segment.read(&mut buf)?;
260 16496 : if bytes_read == 0 {
261 0 : tracing::debug!(
262 0 : "find_end_of_wal reached end at {:?}, EOF in segment {:?} at offset {}",
263 : result,
264 : seg_file_path,
265 0 : curr_lsn.segment_offset(wal_seg_size)
266 : );
267 0 : return Ok(result);
268 16496 : }
269 16496 : curr_lsn += bytes_read as u64;
270 16496 : decoder.feed_bytes(&buf[0..bytes_read]);
271 :
272 : // advance result past all completely read records
273 : loop {
274 16664 : match decoder.poll_decode() {
275 168 : Ok(Some(record)) => result = record.0,
276 32 : Err(e) => {
277 32 : tracing::debug!(
278 32 : "find_end_of_wal reached end at {:?}, decode error: {:?}",
279 : result, e
280 : );
281 32 : return Ok(result);
282 : }
283 16464 : Ok(None) => break, // need more data
284 : }
285 : }
286 : }
287 : }
288 : }
289 : }
290 32 : }
291 :
292 : // Open .partial or full WAL segment file, if present.
293 40 : fn open_wal_segment(seg_file_path: &Path) -> anyhow::Result<Option<File>> {
294 40 : let mut partial_path = seg_file_path.to_owned();
295 40 : partial_path.set_extension("partial");
296 40 : match File::open(partial_path) {
297 32 : Ok(file) => Ok(Some(file)),
298 8 : Err(e) => match e.kind() {
299 : ErrorKind::NotFound => {
300 : // .partial not found, try full
301 8 : match File::open(seg_file_path) {
302 8 : Ok(file) => Ok(Some(file)),
303 0 : Err(e) => match e.kind() {
304 0 : ErrorKind::NotFound => Ok(None),
305 0 : _ => Err(e.into()),
306 : },
307 : }
308 : }
309 0 : _ => Err(e.into()),
310 : },
311 : }
312 40 : }
313 :
314 : impl XLogRecord {
315 108199 : pub fn from_slice(buf: &[u8]) -> Result<XLogRecord, DeserializeError> {
316 : use utils::bin_ser::LeSer;
317 108199 : XLogRecord::des(buf)
318 108199 : }
319 :
320 73532 : pub fn from_bytes<B: Buf>(buf: &mut B) -> Result<XLogRecord, DeserializeError> {
321 : use utils::bin_ser::LeSer;
322 73532 : XLogRecord::des_from(&mut buf.reader())
323 73532 : }
324 :
325 24470 : pub fn encode(&self) -> Result<Bytes, SerializeError> {
326 : use utils::bin_ser::LeSer;
327 24470 : Ok(self.ser()?.into())
328 24470 : }
329 :
330 : // Is this record an XLOG_SWITCH record? They need some special processing,
331 108199 : pub fn is_xlog_switch_record(&self) -> bool {
332 108199 : self.xl_info == pg_constants::XLOG_SWITCH && self.xl_rmid == pg_constants::RM_XLOG_ID
333 108199 : }
334 : }
335 :
336 : impl XLogPageHeaderData {
337 19462 : pub fn from_bytes<B: Buf>(buf: &mut B) -> Result<XLogPageHeaderData, DeserializeError> {
338 : use utils::bin_ser::LeSer;
339 19462 : XLogPageHeaderData::des_from(&mut buf.reader())
340 19462 : }
341 :
342 784 : pub fn encode(&self) -> Result<Bytes, SerializeError> {
343 : use utils::bin_ser::LeSer;
344 784 : self.ser().map(|b| b.into())
345 784 : }
346 : }
347 :
348 : impl XLogLongPageHeaderData {
349 8 : pub fn from_bytes<B: Buf>(buf: &mut B) -> Result<XLogLongPageHeaderData, DeserializeError> {
350 : use utils::bin_ser::LeSer;
351 8 : XLogLongPageHeaderData::des_from(&mut buf.reader())
352 8 : }
353 :
354 5 : pub fn encode(&self) -> Result<Bytes, SerializeError> {
355 : use utils::bin_ser::LeSer;
356 5 : self.ser().map(|b| b.into())
357 5 : }
358 : }
359 :
360 : pub const SIZEOF_CHECKPOINT: usize = size_of::<CheckPoint>();
361 :
362 : impl CheckPoint {
363 4 : pub fn encode(&self) -> Result<Bytes, SerializeError> {
364 : use utils::bin_ser::LeSer;
365 4 : Ok(self.ser()?.into())
366 4 : }
367 :
368 19 : pub fn decode(buf: &[u8]) -> Result<CheckPoint, DeserializeError> {
369 : use utils::bin_ser::LeSer;
370 19 : CheckPoint::des(buf)
371 19 : }
372 :
373 : /// Update next XID based on provided new_xid and stored epoch.
374 : /// Next XID should be greater than new_xid. This handles 32-bit
375 : /// XID wraparound correctly.
376 : ///
377 : /// Returns 'true' if the XID was updated.
378 72933 : pub fn update_next_xid(&mut self, xid: u32) -> bool {
379 : // nextXid should be greater than any XID in WAL, so increment provided XID and check for wraparround.
380 72933 : let mut new_xid = std::cmp::max(
381 72933 : xid.wrapping_add(1),
382 : pg_constants::FIRST_NORMAL_TRANSACTION_ID,
383 : );
384 : // To reduce number of metadata checkpoints, we forward align XID on XID_CHECKPOINT_INTERVAL.
385 : // XID_CHECKPOINT_INTERVAL should not be larger than BLCKSZ*CLOG_XACTS_PER_BYTE
386 72933 : new_xid =
387 72933 : new_xid.wrapping_add(XID_CHECKPOINT_INTERVAL - 1) & !(XID_CHECKPOINT_INTERVAL - 1);
388 72933 : let full_xid = self.nextXid.value;
389 72933 : let old_xid = full_xid as u32;
390 72933 : if new_xid.wrapping_sub(old_xid) as i32 > 0 {
391 9 : let mut epoch = full_xid >> 32;
392 9 : if new_xid < old_xid {
393 0 : // wrap-around
394 0 : epoch += 1;
395 9 : }
396 9 : let nextXid = (epoch << 32) | new_xid as u64;
397 :
398 9 : if nextXid != self.nextXid.value {
399 9 : self.nextXid = FullTransactionId { value: nextXid };
400 9 : return true;
401 0 : }
402 72924 : }
403 72924 : false
404 72933 : }
405 :
406 : /// Advance next multi-XID/offset to those given in arguments.
407 : ///
408 : /// It's important that this handles wraparound correctly. This should match the
409 : /// MultiXactAdvanceNextMXact() logic in PostgreSQL's xlog_redo() function.
410 : ///
411 : /// Returns 'true' if the Checkpoint was updated.
412 24 : pub fn update_next_multixid(&mut self, multi_xid: u32, multi_offset: u32) -> bool {
413 24 : let mut modified = false;
414 :
415 24 : if multi_xid.wrapping_sub(self.nextMulti) as i32 > 0 {
416 16 : self.nextMulti = multi_xid;
417 16 : modified = true;
418 16 : }
419 :
420 24 : if multi_offset.wrapping_sub(self.nextMultiOffset) as i32 > 0 {
421 20 : self.nextMultiOffset = multi_offset;
422 20 : modified = true;
423 20 : }
424 :
425 24 : modified
426 24 : }
427 : }
428 :
429 : /// Generate new, empty WAL segment, with correct block headers at the first
430 : /// page of the segment and the page that contains the given LSN.
431 : /// We need this segment to start compute node.
432 5 : pub fn generate_wal_segment(segno: u64, system_id: u64, lsn: Lsn) -> Result<Bytes, SerializeError> {
433 5 : let mut seg_buf = BytesMut::with_capacity(WAL_SEGMENT_SIZE);
434 :
435 5 : let pageaddr = XLogSegNoOffsetToRecPtr(segno, 0, WAL_SEGMENT_SIZE);
436 :
437 5 : let page_off = lsn.block_offset();
438 5 : let seg_off = lsn.segment_offset(WAL_SEGMENT_SIZE);
439 :
440 5 : let first_page_only = seg_off < XLOG_BLCKSZ;
441 : // If first records starts in the middle of the page, pretend in page header
442 : // there is a fake record which ends where first real record starts. This
443 : // makes pg_waldump etc happy.
444 5 : let (shdr_rem_len, infoflags) = if first_page_only && seg_off > 0 {
445 0 : assert!(seg_off >= XLOG_SIZE_OF_XLOG_LONG_PHD);
446 : // xlp_rem_len doesn't include page header, hence the subtraction.
447 0 : (
448 0 : seg_off - XLOG_SIZE_OF_XLOG_LONG_PHD,
449 0 : pg_constants::XLP_FIRST_IS_CONTRECORD,
450 0 : )
451 : } else {
452 5 : (0, 0)
453 : };
454 :
455 5 : let hdr = XLogLongPageHeaderData {
456 5 : std: {
457 5 : XLogPageHeaderData {
458 5 : xlp_magic: XLOG_PAGE_MAGIC as u16,
459 5 : xlp_info: pg_constants::XLP_LONG_HEADER | infoflags,
460 5 : xlp_tli: PG_TLI,
461 5 : xlp_pageaddr: pageaddr,
462 5 : xlp_rem_len: shdr_rem_len as u32,
463 5 : ..Default::default() // Put 0 in padding fields.
464 5 : }
465 5 : },
466 5 : xlp_sysid: system_id,
467 5 : xlp_seg_size: WAL_SEGMENT_SIZE as u32,
468 5 : xlp_xlog_blcksz: XLOG_BLCKSZ as u32,
469 5 : };
470 :
471 5 : let hdr_bytes = hdr.encode()?;
472 5 : seg_buf.extend_from_slice(&hdr_bytes);
473 :
474 : //zero out the rest of the file
475 5 : seg_buf.resize(WAL_SEGMENT_SIZE, 0);
476 :
477 5 : if !first_page_only {
478 5 : let block_offset = lsn.page_offset_in_segment(WAL_SEGMENT_SIZE) as usize;
479 : // see comments above about XLP_FIRST_IS_CONTRECORD and xlp_rem_len.
480 5 : let (xlp_rem_len, xlp_info) = if page_off > 0 {
481 5 : assert!(page_off >= XLOG_SIZE_OF_XLOG_SHORT_PHD as u64);
482 5 : (
483 5 : (page_off - XLOG_SIZE_OF_XLOG_SHORT_PHD as u64) as u32,
484 5 : pg_constants::XLP_FIRST_IS_CONTRECORD,
485 5 : )
486 : } else {
487 0 : (0, 0)
488 : };
489 5 : let header = XLogPageHeaderData {
490 5 : xlp_magic: XLOG_PAGE_MAGIC as u16,
491 5 : xlp_info,
492 5 : xlp_tli: PG_TLI,
493 5 : xlp_pageaddr: lsn.page_lsn().0,
494 5 : xlp_rem_len,
495 5 : ..Default::default() // Put 0 in padding fields.
496 5 : };
497 5 : let hdr_bytes = header.encode()?;
498 :
499 5 : debug_assert!(seg_buf.len() > block_offset + hdr_bytes.len());
500 5 : debug_assert_ne!(block_offset, 0);
501 :
502 5 : seg_buf[block_offset..block_offset + hdr_bytes.len()].copy_from_slice(&hdr_bytes[..]);
503 0 : }
504 :
505 5 : Ok(seg_buf.freeze())
506 5 : }
507 :
508 : #[repr(C)]
509 : #[derive(Serialize)]
510 : pub struct XlLogicalMessage {
511 : pub db_id: Oid,
512 : pub transactional: uint32, // bool, takes 4 bytes due to alignment in C structures
513 : pub prefix_size: uint64,
514 : pub message_size: uint64,
515 : }
516 :
517 : impl XlLogicalMessage {
518 12235 : pub fn encode(&self) -> Bytes {
519 : use utils::bin_ser::LeSer;
520 12235 : self.ser().unwrap().into()
521 12235 : }
522 : }
523 :
524 : /// Create new WAL record for non-transactional logical message.
525 : /// Used for creating artificial WAL for tests, as LogicalMessage
526 : /// record is basically no-op.
527 4 : pub fn encode_logical_message(prefix: &str, message: &str) -> Bytes {
528 : // This function can take untrusted input, so discard any NUL bytes in the prefix string.
529 4 : let prefix = CString::new(prefix.replace('\0', "")).expect("no NULs");
530 4 : let message = message.as_bytes();
531 4 : LogicalMessageGenerator::new(&prefix, message)
532 4 : .next()
533 4 : .unwrap()
534 4 : .encode(Lsn(0))
535 4 : }
536 :
537 : #[cfg(test)]
538 : mod tests {
539 : use super::*;
540 :
541 : #[test]
542 4 : fn test_ts_conversion() {
543 4 : let now = SystemTime::now();
544 4 : let round_trip = try_from_pg_timestamp(to_pg_timestamp(now)).unwrap();
545 :
546 4 : let now_since = now.duration_since(SystemTime::UNIX_EPOCH).unwrap();
547 4 : let round_trip_since = round_trip.duration_since(SystemTime::UNIX_EPOCH).unwrap();
548 4 : assert_eq!(now_since.as_micros(), round_trip_since.as_micros());
549 :
550 4 : let now_pg = get_current_timestamp();
551 4 : let round_trip_pg = to_pg_timestamp(try_from_pg_timestamp(now_pg).unwrap());
552 :
553 4 : assert_eq!(now_pg, round_trip_pg);
554 4 : }
555 :
556 : // If you need to craft WAL and write tests for this module, put it at wal_craft crate.
557 : }
|