AstrBot-Desktop/src-tauri/src/database/slots.rs
YokiiroBW 7dae4898cb
一些检测仍在等待运行
ci / Portable quality checks (push) Waiting to run
ci / Windows Tauri build (push) Waiting to run
feat(pet): separate remote identity and add paper pet window
2026-07-20 16:28:42 +08:00

295 行
9.9 KiB
Rust

use desktop_protocol::{ActiveSlotKind, ConnectionSlot, ConnectionState};
use rusqlite::{OptionalExtension, Row, params};
use super::{ApplicationDatabase, DatabaseError, ProfileMessageStore};
impl ApplicationDatabase {
pub fn list_connection_slots(&self) -> Result<Vec<ConnectionSlot>, DatabaseError> {
self.store
.lock()
.map_err(|_| DatabaseError::LockPoisoned)?
.list_connection_slots()
}
pub fn assign_connection_slot(
&self,
slot: ActiveSlotKind,
profile_id: &str,
updated_at: &str,
) -> Result<ConnectionSlot, DatabaseError> {
self.store
.lock()
.map_err(|_| DatabaseError::LockPoisoned)?
.set_connection_slot(slot, Some(profile_id), updated_at)
}
pub fn clear_connection_slot(
&self,
slot: ActiveSlotKind,
updated_at: &str,
) -> Result<ConnectionSlot, DatabaseError> {
self.store
.lock()
.map_err(|_| DatabaseError::LockPoisoned)?
.set_connection_slot(slot, None, updated_at)
}
}
impl ProfileMessageStore {
fn list_connection_slots(&self) -> Result<Vec<ConnectionSlot>, DatabaseError> {
let mut statement = self.connection.prepare(
"
SELECT slots.slot, slots.profile_id, profiles.server_instance_id
FROM connection_slots AS slots
LEFT JOIN connection_profiles AS profiles
ON profiles.id = slots.profile_id
ORDER BY CASE slots.slot
WHEN 'companion' THEN 0
WHEN 'operations' THEN 1
ELSE 2
END
",
)?;
let mut rows = statement.query([])?;
let mut slots = Vec::with_capacity(2);
while let Some(row) = rows.next()? {
slots.push(slot_from_row(row)?);
}
if slots.len() != 2 {
return Err(DatabaseError::InvalidStoredSlot);
}
Ok(slots)
}
fn connection_slot(&self, slot: ActiveSlotKind) -> Result<ConnectionSlot, DatabaseError> {
self.connection
.query_row(
"
SELECT slots.slot, slots.profile_id, profiles.server_instance_id
FROM connection_slots AS slots
LEFT JOIN connection_profiles AS profiles
ON profiles.id = slots.profile_id
WHERE slots.slot = ?1
",
params![slot_to_str(slot)],
slot_from_row,
)
.optional()?
.ok_or(DatabaseError::SlotNotFound)
}
fn set_connection_slot(
&mut self,
slot: ActiveSlotKind,
profile_id: Option<&str>,
updated_at: &str,
) -> Result<ConnectionSlot, DatabaseError> {
let transaction = self.connection.transaction()?;
if let Some(profile_id) = profile_id {
let profile_exists = transaction
.query_row(
"SELECT 1 FROM connection_profiles WHERE id = ?1",
params![profile_id],
|row| row.get::<_, u8>(0),
)
.optional()?
.is_some();
if !profile_exists {
return Err(DatabaseError::ProfileNotFound);
}
let assigned_slot = transaction
.query_row(
"SELECT slot FROM connection_slots WHERE profile_id = ?1",
params![profile_id],
|row| row.get::<_, String>(0),
)
.optional()?;
if assigned_slot
.as_deref()
.is_some_and(|assigned| assigned != slot_to_str(slot))
{
return Err(DatabaseError::ProfileAlreadyAssigned);
}
}
let changed = transaction.execute(
"
UPDATE connection_slots
SET profile_id = ?2,
updated_at = ?3
WHERE slot = ?1
",
params![slot_to_str(slot), profile_id, updated_at],
)?;
if changed == 0 {
return Err(DatabaseError::SlotNotFound);
}
transaction.commit()?;
self.connection_slot(slot)
}
}
fn slot_from_row(row: &Row<'_>) -> Result<ConnectionSlot, rusqlite::Error> {
let slot = match row.get::<_, String>(0)?.as_str() {
"companion" => ActiveSlotKind::Companion,
"operations" => ActiveSlotKind::Operations,
_ => {
return Err(rusqlite::Error::FromSqlConversionFailure(
0,
rusqlite::types::Type::Text,
Box::new(DatabaseError::InvalidStoredSlot),
));
}
};
Ok(ConnectionSlot {
slot,
profile_id: row.get(1)?,
state: ConnectionState::Disconnected,
server_instance_id: row.get(2)?,
active_conversation_id: None,
unread_count: 0,
last_event_id: None,
last_connected_at: None,
})
}
fn slot_to_str(slot: ActiveSlotKind) -> &'static str {
match slot {
ActiveSlotKind::Companion => "companion",
ActiveSlotKind::Operations => "operations",
}
}
#[cfg(test)]
mod tests {
use desktop_protocol::{AstrBotProfileRole, AuthenticationType, ConnectionProfile};
use super::*;
fn profile(index: usize) -> ConnectionProfile {
ConnectionProfile {
id: format!("00000000-0000-4000-8000-{index:012}"),
display_name: format!("Profile {index}"),
role: AstrBotProfileRole::General,
base_url: format!("https://example-{index}.test/"),
event_stream_url: None,
authentication_type: AuthenticationType::DeviceToken,
transport_kind: desktop_protocol::TransportKind::DesktopV1,
credential_reference: None,
allow_insecure_http: false,
pinned_certificate_fingerprint: None,
auto_connect_slot: None,
auto_connect: false,
server_instance_id: Some(format!("server-{index}")),
server_version: None,
protocol_version: None,
local_tool_policy_id: None,
last_connected_at: None,
remote_username: None,
remote_display_name: None,
sticky_session_id: None,
created_at: "2026-07-19T00:00:00Z".into(),
updated_at: "2026-07-19T00:00:00Z".into(),
}
}
#[test]
fn initializes_assigns_and_clears_two_fixed_slots() {
let database = ApplicationDatabase::in_memory().expect("database");
let initial = database
.list_connection_slots()
.expect("list initial slots");
assert_eq!(initial.len(), 2);
assert_eq!(initial[0].slot, ActiveSlotKind::Companion);
assert_eq!(initial[1].slot, ActiveSlotKind::Operations);
assert!(initial.iter().all(|slot| slot.profile_id.is_none()));
let companion = profile(1);
let operations = profile(2);
database
.create_profile(&companion)
.expect("create companion profile");
database
.create_profile(&operations)
.expect("create operations profile");
let assigned_companion = database
.assign_connection_slot(
ActiveSlotKind::Companion,
&companion.id,
"2026-07-19T01:00:00Z",
)
.expect("assign companion");
let assigned_operations = database
.assign_connection_slot(
ActiveSlotKind::Operations,
&operations.id,
"2026-07-19T01:00:00Z",
)
.expect("assign operations");
assert_eq!(
assigned_companion.profile_id.as_deref(),
Some(companion.id.as_str())
);
assert_eq!(
assigned_operations.profile_id.as_deref(),
Some(operations.id.as_str())
);
assert_eq!(
assigned_operations.server_instance_id.as_deref(),
Some("server-2")
);
let cleared = database
.clear_connection_slot(ActiveSlotKind::Companion, "2026-07-19T02:00:00Z")
.expect("clear companion");
assert!(cleared.profile_id.is_none());
}
#[test]
fn rejects_one_profile_in_both_slots_and_clears_deleted_profiles() {
let database = ApplicationDatabase::in_memory().expect("database");
let shared = profile(3);
database.create_profile(&shared).expect("create profile");
database
.assign_connection_slot(
ActiveSlotKind::Companion,
&shared.id,
"2026-07-19T01:00:00Z",
)
.expect("assign companion");
assert!(matches!(
database.assign_connection_slot(
ActiveSlotKind::Operations,
&shared.id,
"2026-07-19T01:00:00Z",
),
Err(DatabaseError::ProfileAlreadyAssigned)
));
database.delete_profile(&shared.id).expect("delete profile");
assert!(
database
.list_connection_slots()
.expect("list slots")
.iter()
.all(|slot| slot.profile_id.is_none())
);
}
#[test]
fn rejects_an_unknown_profile_assignment() {
let database = ApplicationDatabase::in_memory().expect("database");
assert!(matches!(
database.assign_connection_slot(
ActiveSlotKind::Operations,
"00000000-0000-4000-8000-999999999999",
"2026-07-19T01:00:00Z",
),
Err(DatabaseError::ProfileNotFound)
));
}
}