Skip to main content

tuwunel_service/transaction_ids/
mod.rs

1//! Durable transaction-response deduplication.
2//!
3//! Opaque response bytes are keyed by user, optional device, and transaction
4//! identifier. Room operations add a domain tag, the room, and a scope (the
5//! event type of a send, the target of a redaction) so independent scopes
6//! cannot replay one another's responses.
7
8use std::sync::Arc;
9
10use ruma::{DeviceId, EventId, RoomId, TransactionId, UserId};
11use tuwunel_core::{Result, implement};
12use tuwunel_database::{Handle, Map, Txn};
13
14/// Persistent transaction-response lookup service.
15///
16/// Responses remain stored across process restarts and have no service-level
17/// expiry. Adding a response for an existing key replaces the stored bytes.
18/// Lookup and insertion are separate operations; the service does not reserve a
19/// transaction identifier against concurrent execution.
20pub struct Service {
21	db: Data,
22}
23
24/// A client transaction against one room.
25///
26/// Paired with a [`RoomScope`], it keys the response a retry replays.
27#[derive(Clone, Copy)]
28pub struct RoomTxn<'a> {
29	/// The user who sent the transaction.
30	pub user_id: &'a UserId,
31
32	/// The sending device, absent for a device-less sender.
33	pub device_id: Option<&'a DeviceId>,
34
35	/// The client's transaction identifier.
36	pub txn_id: &'a TransactionId,
37
38	/// The room the transaction acts on.
39	pub room_id: &'a RoomId,
40}
41
42/// What a room transaction acts on within its room.
43///
44/// Each variant has its own domain tag, so a send and a redaction never share
45/// a key.
46#[derive(Clone, Copy)]
47pub enum RoomScope<'a> {
48	/// A send, scoped by its event type.
49	Send(&'a str),
50
51	/// A redaction, scoped by its target event.
52	Redact(&'a EventId),
53
54	/// A delayed event's scheduling, scoped by its event type.
55	Delayed(&'a str),
56}
57
58struct Data {
59	userdevicetxnid_response: Arc<Map>,
60}
61
62type Key<'a> = (&'a UserId, Option<&'a DeviceId>, &'a TransactionId);
63type RoomKey<'a> = (
64	&'a UserId,
65	Option<&'a DeviceId>,
66	&'a TransactionId,
67	&'static str,
68	&'a RoomId,
69	&'a str,
70);
71
72const ROOM_SEND_TAG: &str = "room-send";
73const ROOM_REDACT_TAG: &str = "room-redact";
74const ROOM_DELAYED_TAG: &str = "room-delayed";
75
76impl crate::Service for Service {
77	fn build(args: &crate::Args<'_>) -> Result<Arc<Self>> {
78		Ok(Arc::new(Self {
79			db: Data {
80				userdevicetxnid_response: args.db["userdevicetxnid_response"].clone(),
81			},
82		}))
83	}
84
85	fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
86}
87
88#[implement(Service)]
89/// Records a response under the legacy transaction scope.
90///
91/// The key contains the user, optional device, and transaction identifier.
92/// Writing the same key again replaces its opaque response bytes while
93/// preserving the original non-room key layout.
94pub fn add_txnid(
95	&self,
96	user_id: &UserId,
97	device_id: Option<&DeviceId>,
98	txn_id: &TransactionId,
99	data: &[u8],
100) {
101	let key = txnid_key(user_id, device_id, txn_id);
102
103	self.db
104		.userdevicetxnid_response
105		.put_raw(key, data);
106}
107
108#[implement(Service)]
109/// Looks up a response under the legacy transaction scope.
110///
111/// The key contains the user, optional device, and transaction identifier.
112/// A missing row remains a database not-found error, and a hit returns the
113/// stored opaque bytes through a database handle.
114pub async fn existing_txnid(
115	&self,
116	user_id: &UserId,
117	device_id: Option<&DeviceId>,
118	txn_id: &TransactionId,
119) -> Result<Handle<'_>> {
120	let key = txnid_key(user_id, device_id, txn_id);
121
122	self.db.userdevicetxnid_response.qry(&key).await
123}
124
125#[implement(Service)]
126/// Records a response under a scoped room transaction key.
127///
128/// A domain tag, the room, and the scope extend the legacy key so unrelated
129/// room operations cannot alias. Writing the same complete key again replaces
130/// its opaque response bytes.
131pub fn add_room_txnid(&self, txn: RoomTxn<'_>, scope: RoomScope<'_>, data: &[u8]) {
132	let key = room_txnid_key(txn, scope);
133
134	self.db
135		.userdevicetxnid_response
136		.put_raw(key, data);
137}
138
139#[implement(Service)]
140/// Queues a response under a scoped room transaction key into a batch.
141///
142/// The response commits with the caller's other writes, so a retry never
143/// finds the operation without its response or the response without it.
144pub fn add_room_txnid_batch(
145	&self,
146	batch: &mut Txn,
147	txn: RoomTxn<'_>,
148	scope: RoomScope<'_>,
149	data: &[u8],
150) {
151	batch.put_raw(&self.db.userdevicetxnid_response, room_txnid_key(txn, scope), data);
152}
153
154#[implement(Service)]
155/// Looks up a response under a scoped room transaction key.
156///
157/// A domain tag, the room, and the scope extend the legacy key so unrelated
158/// room operations cannot alias. A missing row remains a database not-found
159/// error, and a hit returns the stored opaque bytes through a database handle.
160pub async fn existing_room_txnid(
161	&self,
162	txn: RoomTxn<'_>,
163	scope: RoomScope<'_>,
164) -> Result<Handle<'_>> {
165	let key = room_txnid_key(txn, scope);
166
167	self.db.userdevicetxnid_response.qry(&key).await
168}
169
170fn txnid_key<'a>(
171	user_id: &'a UserId,
172	device_id: Option<&'a DeviceId>,
173	txn_id: &'a TransactionId,
174) -> Key<'a> {
175	(user_id, device_id, txn_id)
176}
177
178fn room_txnid_key<'a>(txn: RoomTxn<'a>, scope: RoomScope<'a>) -> RoomKey<'a> {
179	let (tag, scope) = match scope {
180		| RoomScope::Send(event_type) => (ROOM_SEND_TAG, event_type),
181		| RoomScope::Redact(event_id) => (ROOM_REDACT_TAG, event_id.as_str()),
182		| RoomScope::Delayed(event_type) => (ROOM_DELAYED_TAG, event_type),
183	};
184
185	(txn.user_id, txn.device_id, txn.txn_id, tag, txn.room_id, scope)
186}
187
188#[cfg(test)]
189mod tests;