1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
use crate::persistence::{
    character::{load_character_data, load_character_list},
    error::PersistenceError,
    establish_connection, ConnectionMode, DatabaseSettings, PersistedComponents,
};
use common::{
    character::{CharacterId, CharacterItem},
    event::UpdateCharacterMetadata,
};
use crossbeam_channel::{self, TryIter};
use rusqlite::Connection;
use std::sync::{Arc, RwLock};
use tracing::{debug, error};

pub(crate) type CharacterListResult = Result<Vec<CharacterItem>, PersistenceError>;
pub(crate) type CharacterCreationResult =
    Result<(CharacterId, Vec<CharacterItem>), PersistenceError>;
pub(crate) type CharacterEditResult = Result<(CharacterId, Vec<CharacterItem>), PersistenceError>;
pub(crate) type CharacterDataResult =
    Result<(PersistedComponents, UpdateCharacterMetadata), PersistenceError>;
type CharacterLoaderRequest = (specs::Entity, CharacterLoaderRequestKind);

/// Available database operations when modifying a player's character list
enum CharacterLoaderRequestKind {
    LoadCharacterList {
        player_uuid: String,
    },
    LoadCharacterData {
        player_uuid: String,
        character_id: CharacterId,
    },
}

#[derive(Debug)]
pub enum CharacterUpdaterMessage {
    CharacterScreenResponse(CharacterScreenResponse),
    DatabaseBatchCompletion(u64),
}

/// An event emitted from CharacterUpdater in response to a request made from
/// the character selection/editing screen
#[derive(Debug)]
pub struct CharacterScreenResponse {
    pub target_entity: specs::Entity,
    pub response_kind: CharacterScreenResponseKind,
}

impl CharacterScreenResponse {
    pub fn is_err(&self) -> bool {
        matches!(
            &self.response_kind,
            CharacterScreenResponseKind::CharacterData(box Err(_))
                | CharacterScreenResponseKind::CharacterList(Err(_))
                | CharacterScreenResponseKind::CharacterCreation(Err(_))
        )
    }
}

#[derive(Debug)]
pub enum CharacterScreenResponseKind {
    CharacterList(CharacterListResult),
    CharacterData(Box<CharacterDataResult>),
    CharacterCreation(CharacterCreationResult),
    CharacterEdit(CharacterEditResult),
}

/// A bi-directional messaging resource for making requests to modify or load
/// character data in a background thread.
///
/// This is used on the character selection screen, and after character
/// selection when loading the components associated with a character.
///
/// Requests messages are sent in the form of
/// [`CharacterLoaderRequestKind`] and are dispatched at the character select
/// screen.
///
/// Responses are polled on each server tick in the format
/// [`CharacterLoaderResponse`]
pub struct CharacterLoader {
    update_rx: crossbeam_channel::Receiver<CharacterUpdaterMessage>,
    update_tx: crossbeam_channel::Sender<CharacterLoaderRequest>,
}

impl CharacterLoader {
    pub fn new(settings: Arc<RwLock<DatabaseSettings>>) -> Result<Self, PersistenceError> {
        let (update_tx, internal_rx) = crossbeam_channel::unbounded::<CharacterLoaderRequest>();
        let (internal_tx, update_rx) = crossbeam_channel::unbounded::<CharacterUpdaterMessage>();

        let builder = std::thread::Builder::new().name("persistence_loader".into());
        builder
            .spawn(move || {
                // Unwrap here is safe as there is no code that can panic when the write lock is
                // taken that could cause the RwLock to become poisoned.
                //
                // This connection -must- remain read-only to avoid lock contention with the
                // CharacterUpdater thread.
                let mut conn =
                    establish_connection(&settings.read().unwrap(), ConnectionMode::ReadOnly);

                for request in internal_rx {
                    conn.update_log_mode(&settings);

                    let response = CharacterLoader::process_request(request, &conn);
                    debug!("Processing complete");
                    if let Err(e) = internal_tx.send(response) {
                        error!(?e, "Could not send character loader response");
                    }
                    debug!("Sent character loader response");
                }
            })
            .unwrap();

        Ok(Self {
            update_rx,
            update_tx,
        })
    }

    // TODO: Refactor the way that we send errors to the client to not require a
    // specific Result type per CharacterLoaderResponseKind, and remove
    // CharacterLoaderResponse::is_err()
    fn process_request(
        request: CharacterLoaderRequest,
        connection: &Connection,
    ) -> CharacterUpdaterMessage {
        let (entity, kind) = request;
        CharacterUpdaterMessage::CharacterScreenResponse(CharacterScreenResponse {
            target_entity: entity,
            response_kind: match kind {
                CharacterLoaderRequestKind::LoadCharacterList { player_uuid } => {
                    debug!(?player_uuid, "Loading character list");
                    CharacterScreenResponseKind::CharacterList(load_character_list(
                        &player_uuid,
                        connection,
                    ))
                },
                CharacterLoaderRequestKind::LoadCharacterData {
                    player_uuid,
                    character_id,
                } => {
                    debug!(?player_uuid, ?character_id, "Loading character data");
                    let result = load_character_data(player_uuid, character_id, connection);
                    if result.is_err() {
                        error!(
                            ?result,
                            "Error loading character data for character_id: {}", character_id.0
                        );
                    }
                    CharacterScreenResponseKind::CharacterData(Box::new(result))
                },
            },
        })
    }

    /// Loads a list of characters belonging to the player identified by
    /// `player_uuid`
    pub fn load_character_list(&self, entity: specs::Entity, player_uuid: String) {
        debug!(?player_uuid, "Requesting character list");
        if let Err(e) = self
            .update_tx
            .send((entity, CharacterLoaderRequestKind::LoadCharacterList {
                player_uuid,
            }))
        {
            error!(?e, "Could not send character list load request");
        }
    }

    /// Loads components associated with a character
    pub fn load_character_data(
        &self,
        entity: specs::Entity,
        player_uuid: String,
        character_id: CharacterId,
    ) {
        debug!(?character_id, ?player_uuid, "Requesting character data");
        if let Err(e) =
            self.update_tx
                .send((entity, CharacterLoaderRequestKind::LoadCharacterData {
                    player_uuid,
                    character_id,
                }))
        {
            error!(?e, "Could not send character data load request");
        }
    }

    /// Returns a non-blocking iterator over CharacterLoaderResponse messages
    pub fn messages(&self) -> TryIter<CharacterUpdaterMessage> { self.update_rx.try_iter() }
}