risingwave_common/transaction/transaction_id.rs
1// Copyright 2025 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::sync::atomic::{AtomicU32, Ordering};
16
17use risingwave_common::id::WorkerId;
18
19use crate::util::worker_util::WorkerNodeId;
20
21const WORKER_ID_SHIFT_BITS: u8 = 32;
22
23/// `TxnIdGenerator` generates unique transaction ids as following format:
24///
25/// | worker id | sequence |
26/// |-----------|----------|
27/// | 32 bits | 32 bits |
28///
29/// Currently, we just need to guarantee the transaction ids are unique at runtime.
30/// It doesn't matter, even if the sequence starts from zero after recovery.
31#[derive(Debug)]
32pub struct TxnIdGenerator {
33 worker_id: WorkerId,
34 sequence: AtomicU32,
35}
36
37pub type TxnId = u64;
38
39impl TxnIdGenerator {
40 pub fn new(worker_id: WorkerNodeId) -> Self {
41 Self {
42 worker_id,
43 sequence: AtomicU32::new(0),
44 }
45 }
46
47 pub fn gen_txn_id(&self) -> TxnId {
48 let sequence = self.sequence.fetch_add(1, Ordering::Relaxed);
49 (self.worker_id.as_raw_id() as u64) << WORKER_ID_SHIFT_BITS | sequence as u64
50 }
51}