1
//! The per-user account hierarchy lock. Every hierarchy writer takes it first,
2
//! then the tag keys, then the account rows.
3

            
4
use sqlx::PgConnection;
5
use uuid::Uuid;
6

            
7
/// Advisory lock class of the account hierarchy ("hier").
8
const HIERARCHY_LOCK_CLASS: i32 = 0x6869_6572;
9

            
10
/// A stable 32-bit key for `user_id`: the xor of its four big-endian words.
11
100559
pub(crate) fn hierarchy_key(user_id: Uuid) -> i32 {
12
100559
    user_id
13
100559
        .as_bytes()
14
100559
        .as_chunks::<4>()
15
100559
        .0
16
100559
        .iter()
17
402236
        .fold(0, |key, word| key ^ i32::from_be_bytes(*word))
18
100559
}
19

            
20
/// Lock the account hierarchy of `user_id` until the transaction ends.
21
100554
pub(crate) async fn lock_hierarchy(
22
100554
    conn: &mut PgConnection,
23
100554
    user_id: Uuid,
24
100554
) -> Result<(), sqlx::Error> {
25
100554
    sqlx::query_file!(
26
100554
        "sql/select/accounts/lock_hierarchy.sql",
27
        HIERARCHY_LOCK_CLASS,
28
100554
        hierarchy_key(user_id)
29
    )
30
100554
    .fetch_one(conn)
31
100554
    .await?;
32
100553
    Ok(())
33
100554
}