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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
use std::str::from_utf8;
use std::sync::Arc;
use std::time::Duration;

use crate::db::{self, DBEntity, User, ZoneOwnership};
use crate::enums::{RecordClass, RecordType};
use crate::zones::{FileZone, ZoneRecord};
use log::debug;
use sqlx::{Pool, Sqlite};
use tokio::sync::mpsc;
use tokio::sync::oneshot;

type Responder<T> = oneshot::Sender<T>;

#[derive(Debug)]
pub enum Command {
    GetRecord {
        /// Reversed vec of the name
        name: Vec<u8>,
        rrtype: RecordType,
        rclass: RecordClass,
        resp: Responder<Option<ZoneRecord>>,
    },
    GetZone {
        id: Option<i64>,
        name: Option<String>,
        resp: Responder<Option<FileZone>>,
    },
    GetZoneNames {
        user: User,
        offset: i64,
        limit: i64,
        resp: Responder<Vec<FileZone>>,
    },
    ImportFile {
        filename: String,
        zone_name: Option<String>,
        resp: Responder<()>,
    },
    Shutdown,

    PostZone,
    DeleteZone,
    PatchZone,

    DeleteUser,
    CreateUser {
        username: String,
        authref: String,
        admin: bool,
        disabled: bool,
        resp: Responder<bool>,
    },
    GetUser {
        id: Option<i64>,
        username: Option<String>,
        resp: Responder<()>,
    },
    PostUser,
    PatchUser,

    DeleteOwnership {
        zoneid: Option<i64>,
        userid: Option<i64>,
        resp: Responder<()>,
    },
    GetOwnership {
        zoneid: Option<i64>,
        userid: Option<i64>,
        resp: Responder<Vec<Arc<ZoneOwnership>>>,
    },
    PostOwnership {
        zoneid: i64,
        userid: i64,
        resp: Responder<ZoneOwnership>,
    },
    // TODO: create a setter when we're ready to accept updates
    // Set {
    //     name: Vec<u8>,
    //     rrtype: RecordType,
    // }
    // CreateZone {
    //     zone: FileZone,
    // }
}

async fn handle_get_command(
    // database pool
    conn: &Pool<Sqlite>,
    // this is the result from the things in memory
    // zone_get: Option<&ZoneRecord>,
    name: Vec<u8>,
    rrtype: RecordType,
    rclass: RecordClass,
    resp: oneshot::Sender<Option<ZoneRecord>>,
) -> Result<(), String> {
    debug!(
        "query name={:?} rrtype={rrtype:?} rclass={rclass}",
        from_utf8(&name).unwrap_or("-"),
    );

    // query the database
    let db_name =
        from_utf8(&name).map_err(|e| format!("Failed to convert name to utf8 - {e:?}"))?;

    let mut zr = ZoneRecord {
        name: name.clone(),
        typerecords: vec![],
    };

    match db::get_records(conn, db_name.to_string(), rrtype, rclass, true).await {
        Ok(value) => zr.typerecords.extend(value),
        Err(err) => {
            log::error!("Failed to query db: {err:?}")
        }
    };

    // if let Some(value) = zone_get {
    //     // check if the type we want is in there, and only return the matching records
    //     let res: Vec<InternalResourceRecord> = value
    //         .to_owned()
    //         .typerecords
    //         .into_iter()
    //         .filter(|r| r == &rrtype && r == &rclass)
    //         .collect();
    //     zr.typerecords.extend(res);
    // };

    let result = match zr.typerecords.is_empty() {
        true => None,
        false => Some(zr),
    };

    if let Err(error) = resp.send(result) {
        debug!("error sending response from data store: {:?}", error)
    };
    Ok(())
}

/// Import a file directly into the database. Normally, you shouldn't use this directly, call it through calls to the datastore.
pub async fn handle_import_file(
    pool: &Pool<Sqlite>,
    filename: String,
    zone_name: Option<String>,
) -> Result<(), String> {
    let mut txn = pool
        .begin()
        .await
        .map_err(|e| format!("Failed to start transaction: {e:?}"))?;

    let zones: Vec<FileZone> = crate::zones::load_zones(&filename)?;

    let zones = match zone_name {
        Some(name) => zones.into_iter().filter(|z| z.name == name).collect(),
        None => zones,
    };

    if zones.is_empty() {
        log::warn!("No zones to import!");
        return Err("No zones to import!".to_string());
    }

    for zone in zones {
        let _saved_zone = match zone.save_with_txn(&mut txn).await {
            Err(err) => {
                let errmsg = format!("Failed to save zone {}: {err:?}", zone.name);
                log::error!("{errmsg}");
                return Err(errmsg);
            }
            Ok(val) => val,
        };
        log::info!("Imported {}", zone.name);
    }
    txn.commit().await.map_err(|e| {
        log::error!("Failed to commit transaction!");
        format!("Failed to commit transaction: {e:?}")
    })?;
    log::info!("Completed import process");
    Ok(())
}

async fn handle_get_zone(
    tx: oneshot::Sender<Option<FileZone>>,
    pool: &Pool<Sqlite>,
    id: Option<i64>,
    name: Option<String>,
) -> Result<(), String> {
    let mut txn = pool.begin().await.map_err(|e| format!("{e:?}"))?;

    let zone = crate::db::get_zone_with_txn(&mut txn, id, name)
        .await
        .map_err(|e| format!("{e:?}"))?;

    tx.send(zone).map_err(|e| format!("{e:?}"))
}

async fn handle_get_zone_names(
    user: User,
    tx: oneshot::Sender<Vec<FileZone>>,
    pool: &Pool<Sqlite>,
    offset: i64,
    limit: i64,
) -> Result<(), String> {
    let mut txn = pool.begin().await.map_err(|e| format!("{e:?}"))?;

    log::debug!("handle_get_zone_names: user={user:?}");
    let zones = user
        .get_zones_for_user(&mut txn, offset, limit)
        .await
        .map_err(|e| format!("{e:?}"))?;

    log::debug!("handle_get_zone_names: {zones:?}");
    tx.send(zones).map_err(|e| format!("{e:?}"))
}

/// Manages the datastore, waits for signals from the server instances and responds with data
pub async fn manager(
    mut rx: mpsc::Receiver<crate::datastore::Command>,
    connpool: Pool<Sqlite>,
    cron_db_cleanup_timer: Option<Duration>,
) -> Result<(), String> {
    if let Some(timer) = cron_db_cleanup_timer {
        log::debug!("Spawning DB cron cleanup task");
        tokio::spawn(db::cron_db_cleanup(connpool.clone(), timer, None));
    }

    while let Some(cmd) = rx.recv().await {
        match cmd {
            Command::GetZone { id, name, resp } => {
                let res = handle_get_zone(resp, &connpool, id, name).await;
                if let Err(e) = res {
                    log::error!("{e:?}")
                };
            }
            Command::GetZoneNames {
                resp,
                user,
                offset,
                limit,
            } => {
                let res = handle_get_zone_names(user, resp, &connpool, offset, limit).await;
                if let Err(e) = res {
                    log::error!("{e:?}")
                };
            }
            Command::Shutdown => {
                #[cfg(test)]
                println!("### Datastore was sent shutdown message, shutting down.");
                log::info!("Datastore was sent shutdown message, shutting down.");
                break;
            }
            Command::ImportFile {
                filename,
                resp,
                zone_name,
            } => {
                handle_import_file(&connpool, filename, zone_name)
                    .await
                    .map_err(|e| format!("{e:?}"))?;
                match resp.send(()) {
                    Ok(_) => log::info!("DS Sent Success"),
                    Err(err) => {
                        let res = format!("Failed to send response: {err:?}");
                        log::info!("{res}");
                    }
                }
            }
            Command::GetRecord {
                name,
                rrtype,
                rclass,
                resp,
            } => {
                let res = handle_get_command(
                    &connpool, // zones.get(name.to_ascii_lowercase()),
                    name, rrtype, rclass, resp,
                )
                .await;
                if let Err(e) = res {
                    log::error!("{e:?}")
                };
            }
            Command::PostZone => todo!(),
            Command::DeleteZone => todo!(),
            Command::PatchZone => todo!(),
            Command::CreateUser {
                username,
                authref,
                admin,
                disabled,
                resp,
            } => {
                let new_user = User {
                    username: username.clone(),
                    authref: Some(authref.clone()),
                    admin,
                    disabled,
                    ..Default::default()
                };
                log::debug!("Creating: {new_user:?}");
                let res = match new_user.save(&connpool).await {
                    Ok(_) => true,
                    Err(error) => {
                        log::error!("Failed to create {username}: {error:?}");
                        false
                    }
                };
                if let Err(error) = resp.send(res) {
                    log::error!("Failed to send message back to caller: {error:?}");
                }
            }
            Command::DeleteUser => todo!(),
            Command::GetUser { .. } => todo!(),
            Command::PostUser => todo!(),
            Command::PatchUser => todo!(),
            Command::DeleteOwnership { .. } => todo!(),
            Command::GetOwnership {
                zoneid: _,
                userid,
                resp,
            } => {
                if let Some(userid) = userid {
                    match ZoneOwnership::get_all_user(&connpool, userid).await {
                        Ok(zone) => {
                            if let Err(err) = resp.send(zone) {
                                log::error!("Failed to send zone_ownership response: {err:?}")
                            };
                        }
                        Err(_) => todo!(),
                    }
                } else {
                    log::error!("Unmatched arm in getownership")
                }
            }
            Command::PostOwnership { .. } => todo!(),
        }
    }
    #[cfg(test)]
    println!("### manager is done!");
    Ok(())
}