enshwick 1.0.0-alpha.2

The Enshwick Loader's modding API for Enshrouded: the one crate mods are written against
Documentation
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
//! State that outlives a session, in the mod's data folder.

use std::marker::PhantomData;
use std::path::{Path, PathBuf};

use crate::Off;

/// Why a [`Store`], [`WorldStore`] or [`Hold`] could not read or write its
/// file at run time.
///
/// # Examples
///
/// ```
/// use enshwick::state::StoreError;
///
/// fn report(error: &StoreError) -> String {
///     format!("kept in memory: {error}")
/// }
/// ```
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum StoreError {
    /// The file could not be read, written or removed.
    #[error("cannot read or write {}: {source}", path.display())]
    #[non_exhaustive]
    Io {
        /// The file.
        path: PathBuf,
        /// What the system answered.
        #[source]
        source: std::io::Error,
    },
    /// The file does not parse into the stored type.
    #[error("{} does not parse: {message}", path.display())]
    #[non_exhaustive]
    Parse {
        /// The file.
        path: PathBuf,
        /// What the parser said.
        message: String,
    },
    /// The value cannot be written as TOML.
    #[error("the value for {} does not serialise: {message}", path.display())]
    #[non_exhaustive]
    Serialize {
        /// The file.
        path: PathBuf,
        /// What the serialiser said.
        message: String,
    },
}

impl StoreError {
    fn io(path: &Path, source: std::io::Error) -> Self {
        Self::Io {
            path: path.to_owned(),
            source,
        }
    }
}

/// A store's error at init turns the mod off with its text.
impl From<StoreError> for Off {
    fn from(error: StoreError) -> Self {
        Self::new(error.to_string())
    }
}

/// A value kept in a TOML file under the mod's data folder, written atomically
/// so a crash never leaves half a file.
///
/// # Examples
///
/// ```
/// use enshwick::state::Store;
///
/// #[derive(Default, serde::Deserialize, serde::Serialize, PartialEq, Debug)]
/// struct Progress {
///     highest_experience: u64,
/// }
///
/// # fn main() -> Result<(), enshwick::Off> {
/// let dir = std::env::temp_dir().join("enshwick-store-doc");
/// let store: Store<Progress> = Store::new(&dir, "progress");
/// store.save(&Progress { highest_experience: 42 })?;
/// assert_eq!(store.load()?.highest_experience, 42);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Store<T> {
    path: PathBuf,
    _value: PhantomData<T>,
}

impl<T: serde::de::DeserializeOwned + serde::Serialize + Default> Store<T> {
    /// A store for `<dir>/<name>.toml`; get `dir` from
    /// [`Load::data_dir`](crate::Load::data_dir).
    ///
    /// # Examples
    ///
    /// See [`Store`].
    #[must_use]
    pub fn new(dir: &Path, name: &str) -> Self {
        Self {
            path: dir.join(format!("{name}.toml")),
            _value: PhantomData,
        }
    }

    /// The stored value, or `T::default()` when nothing is stored yet.
    ///
    /// # Errors
    ///
    /// [`StoreError`] when the file exists but cannot be read or does not
    /// parse into `T`.
    ///
    /// # Examples
    ///
    /// See [`Store`].
    pub fn load(&self) -> Result<T, StoreError> {
        match std::fs::read_to_string(&self.path) {
            Ok(text) => toml::from_str(&text).map_err(|e| StoreError::Parse {
                path: self.path.clone(),
                message: e.message().to_owned(),
            }),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(T::default()),
            Err(e) => Err(StoreError::io(&self.path, e)),
        }
    }

    /// Writes `value`: to a temporary file first, then renamed over the old one.
    ///
    /// # Errors
    ///
    /// [`StoreError`] when the value cannot be serialised or the file
    /// written.
    ///
    /// # Examples
    ///
    /// See [`Store`].
    pub fn save(&self, value: &T) -> Result<(), StoreError> {
        write_atomically(&self.path, &self.text(value)?)
    }

    /// `value` as the file's text.
    fn text(&self, value: &T) -> Result<String, StoreError> {
        toml::to_string(value).map_err(|e| StoreError::Serialize {
            path: self.path.clone(),
            message: e.to_string(),
        })
    }
}

/// Writes `text` to `path`: to a temporary file first, then renamed over the
/// old one.
fn write_atomically(path: &Path, text: &str) -> Result<(), StoreError> {
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir).map_err(|e| StoreError::io(dir, e))?;
    }
    let temporary = path.with_extension("toml.tmp");
    // On disk before the rename, so a crash leaves the old file or the new.
    let written = std::fs::File::create(&temporary).and_then(|mut file| {
        std::io::Write::write_all(&mut file, text.as_bytes())?;
        file.sync_all()
    });
    written
        .and_then(|()| std::fs::rename(&temporary, path))
        .map_err(|e| StoreError::io(path, e))
}

/// The file a [`Hold`] keeps in its mod's data folder.
pub const HOLD_FILE: &str = "hold.txt";

/// A hold on the game for a world the vanilla game cannot open safely, such
/// as one with more altars than the game groups.
///
/// While a mod's hold is set, the loader refuses to let the game go on
/// without that mod: when the game build is unknown (the loader would leave
/// the game vanilla), or the mod is missing, skipped or off, it logs the
/// reason and stops the game before the world loads. The hold is a file,
/// `mod-data/<id>/hold.txt`, holding the reason; a player who accepts the
/// risk deletes it.
///
/// # Examples
///
/// ```
/// use enshwick::state::{Hold, holds};
///
/// let data = std::env::temp_dir().join("enshwick-hold-doc");
/// let hold = Hold::new(&data.join("flame-altar-count"));
/// hold.set("the world has 20 altar zones")?;
/// assert_eq!(
///     holds(&data),
///     vec![("flame-altar-count".to_owned(), "the world has 20 altar zones".to_owned())]
/// );
/// hold.clear()?;
/// assert!(holds(&data).is_empty());
/// # Ok::<(), enshwick::state::StoreError>(())
/// ```
#[derive(Debug, Clone)]
pub struct Hold {
    path: PathBuf,
}

impl Hold {
    /// The hold of the mod whose data folder is `dir`, from
    /// [`Load::data_dir`](crate::Load::data_dir).
    ///
    /// # Examples
    ///
    /// See [`Hold`].
    #[must_use]
    pub fn new(dir: &Path) -> Self {
        Self {
            path: dir.join(HOLD_FILE),
        }
    }

    /// Sets the hold with `reason`, one line the loader logs; written to a
    /// temporary file first, then renamed.
    ///
    /// # Errors
    ///
    /// [`StoreError`] when the file cannot be written.
    ///
    /// # Examples
    ///
    /// See [`Hold`].
    pub fn set(&self, reason: &str) -> Result<(), StoreError> {
        if let Some(dir) = self.path.parent() {
            std::fs::create_dir_all(dir).map_err(|e| StoreError::io(dir, e))?;
        }
        let temporary = self.path.with_extension("txt.tmp");
        std::fs::write(&temporary, reason.lines().next().unwrap_or_default())
            .and_then(|()| std::fs::rename(&temporary, &self.path))
            .map_err(|e| StoreError::io(&self.path, e))
    }

    /// Releases the hold; nothing happens when it is not set.
    ///
    /// # Errors
    ///
    /// [`StoreError`] when the file exists and cannot be removed.
    ///
    /// # Examples
    ///
    /// See [`Hold`].
    pub fn clear(&self) -> Result<(), StoreError> {
        match std::fs::remove_file(&self.path) {
            Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
                Err(StoreError::io(&self.path, e))
            }
            _ => Ok(()),
        }
    }

    /// The reason, while the hold is set.
    ///
    /// # Examples
    ///
    /// ```
    /// let hold = enshwick::state::Hold::new(&std::env::temp_dir().join("enshwick-no-hold"));
    /// assert_eq!(hold.reason(), None);
    /// ```
    #[must_use]
    pub fn reason(&self) -> Option<String> {
        std::fs::read_to_string(&self.path)
            .ok()
            .map(|reason| reason.trim().to_owned())
    }
}

/// Every hold under the `mod-data` folder `mod_data`, as `(mod id, reason)`,
/// ordered by id.
///
/// # Examples
///
/// See [`Hold`].
#[must_use]
pub fn holds(mod_data: &Path) -> Vec<(String, String)> {
    let Ok(entries) = std::fs::read_dir(mod_data) else {
        return Vec::new();
    };
    let mut found: Vec<(String, String)> = entries
        .filter_map(Result::ok)
        .filter_map(|entry| {
            let id = entry.file_name().into_string().ok()?;
            let reason = Hold::new(&entry.path()).reason()?;
            Some((id, reason))
        })
        .collect();
    found.sort();
    found
}

/// A value kept per world, in `mod-data/<id>/worlds/<key>/<name>.toml`,
/// never inside the game's save: removing the mod leaves the world vanilla.
/// The value is a TOML table, such as a struct.
///
/// Get it from [`Load::world_store`](crate::Load::world_store). It reads the
/// running world's file when the world has loaded and writes it, when
/// changed, as the world saves and at shutdown, so the mod's state and the
/// world's save move together. The key names the world's save file and
/// folder (see [`World::key`](crate::world::World::key)), so a hosted game
/// switching worlds switches files.
///
/// # Examples
///
/// ```
/// #[derive(Default, serde::Deserialize, serde::Serialize)]
/// struct Bounties {
///     paid: u64,
/// }
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     let bounties = load.world_store::<Bounties>("bounties")?;
///     load.on::<enshwick::events::PlayerJoined>(move |_| {
///         let _paid = bounties.update(|b| b.paid += 1);
///     })
/// }
/// ```
pub struct WorldStore<T> {
    slot: std::sync::Arc<std::sync::Mutex<WorldSlot<T>>>,
    /// The background write under way, joined before the next one.
    writing: std::sync::Arc<std::sync::Mutex<Option<std::thread::JoinHandle<()>>>>,
}

impl<T> Clone for WorldStore<T> {
    fn clone(&self) -> Self {
        Self {
            slot: std::sync::Arc::clone(&self.slot),
            writing: std::sync::Arc::clone(&self.writing),
        }
    }
}

impl<T> WorldStore<T> {
    /// Waits for the background write under way, if any; the guard keeps
    /// the next one from starting.
    fn wait_for_writes(&self) -> std::sync::MutexGuard<'_, Option<std::thread::JoinHandle<()>>> {
        let mut writing = self
            .writing
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(handle) = writing.take()
            && handle.join().is_err()
        {
            crate::error!("a world store write panicked");
        }
        writing
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, WorldSlot<T>> {
        self.slot
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }
}

impl<T> core::fmt::Debug for WorldStore<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let slot = self.lock();
        f.debug_struct("WorldStore")
            .field("name", &slot.name)
            .field("key", &slot.open.as_ref().map(|open| &open.key))
            .finish_non_exhaustive()
    }
}

/// What a [`WorldStore`] holds: where its files go and the open world's
/// value.
struct WorldSlot<T> {
    worlds: PathBuf,
    name: String,
    open: Option<OpenWorld<T>>,
}

/// The value of the world whose file is open.
struct OpenWorld<T> {
    key: String,
    store: Store<T>,
    value: T,
    changed: bool,
}

/// Whether `name` may name a store's file: 1 to 64 of `[a-z0-9_-]`.
fn is_store_name(name: &str) -> bool {
    (1..=64).contains(&name.len())
        && name
            .bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
}

impl<T> WorldStore<T>
where
    T: serde::de::DeserializeOwned + serde::Serialize + Default + Send + 'static,
{
    /// A store named `name` under the mod's data folder `dir`; the file of
    /// the world with `key` is `<dir>/worlds/<key>/<name>.toml`.
    ///
    /// # Errors
    ///
    /// [`Off`] when `name` is not 1 to 64 of `[a-z0-9_-]`.
    pub(crate) fn new(dir: &Path, name: &str) -> Result<Self, Off> {
        if !is_store_name(name) {
            return Err(Off::new(format!(
                "world store {name:?}: a name is 1 to 64 of [a-z0-9_-]"
            )));
        }
        Ok(Self {
            slot: std::sync::Arc::new(std::sync::Mutex::new(WorldSlot {
                worlds: dir.join("worlds"),
                name: name.to_owned(),
                open: None,
            })),
            writing: std::sync::Arc::default(),
        })
    }

    /// Reads the file of the world with `key`, writing the open one first.
    /// A file that does not parse stays as it is and the store stays shut.
    ///
    /// # Errors
    ///
    /// [`StoreError`] when the open world's file cannot be written or the
    /// new one does not parse.
    pub(crate) fn open(&self, key: &str) -> Result<(), StoreError> {
        self.close()?;
        let mut slot = self.lock();
        let store = Store::new(&slot.worlds.join(key), &slot.name);
        let value = store.load()?;
        slot.open = Some(OpenWorld {
            key: key.to_owned(),
            store,
            value,
            changed: false,
        });
        Ok(())
    }

    /// Writes the open world's value when it changed and shuts the store.
    ///
    /// # Errors
    ///
    /// [`StoreError`] when the file cannot be written; the store stays open.
    pub(crate) fn close(&self) -> Result<(), StoreError> {
        drop(self.wait_for_writes());
        self.flush()?;
        self.lock().open = None;
        Ok(())
    }

    /// Writes the open world's value now, when it changed since the last
    /// write; the store does so itself when the world saves.
    ///
    /// # Errors
    ///
    /// [`StoreError`] when the value cannot be written.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[derive(Default, serde::Deserialize, serde::Serialize)]
    /// # struct Bounties { paid: u64 }
    /// fn now(store: &enshwick::state::WorldStore<Bounties>) {
    ///     if let Err(error) = store.flush() {
    ///         enshwick::warn!("{error}");
    ///     }
    /// }
    /// ```
    pub fn flush(&self) -> Result<(), StoreError> {
        let mut slot = self.lock();
        // A background write still running would land after this one.
        let _writing = self.wait_for_writes();
        if let Some(open) = slot.open.as_mut().filter(|open| open.changed) {
            open.store.save(&open.value)?;
            open.changed = false;
        }
        Ok(())
    }

    /// Writes the open world's value on a thread of its own when it changed;
    /// the game thread waits only for a previous write still under way.
    pub(crate) fn flush_in_background(&self) {
        let mut slot = self.lock();
        let Some(open) = slot.open.as_mut().filter(|open| open.changed) else {
            return;
        };
        let text = match open.store.text(&open.value) {
            Ok(text) => text,
            Err(error) => {
                crate::error!("{error}");
                return;
            }
        };
        open.changed = false;
        let path = open.store.path.clone();
        let mut writing = self.wait_for_writes();
        let spawned = std::thread::Builder::new()
            .name("world-store".to_owned())
            .spawn(move || {
                if let Err(error) = write_atomically(&path, &text) {
                    crate::error!("{error}");
                }
            });
        match spawned {
            Ok(handle) => *writing = Some(handle),
            Err(e) => {
                open.changed = true;
                crate::error!("world store kept for the next save: {e}");
            }
        }
    }

    /// `f` on the running world's value; `None` while no world is open. The
    /// store stays locked while `f` runs, so `f` must not use it.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[derive(Default, serde::Deserialize, serde::Serialize)]
    /// # struct Bounties { paid: u64 }
    /// fn paid(store: &enshwick::state::WorldStore<Bounties>) -> u64 {
    ///     store.with(|b| b.paid).unwrap_or(0)
    /// }
    /// ```
    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
        self.lock().open.as_ref().map(|open| f(&open.value))
    }

    /// `f` on the running world's value, which is written when the world
    /// next saves; `None`, changing nothing, while no world is open. As for
    /// [`WorldStore::with`], `f` must not use the store.
    ///
    /// # Examples
    ///
    /// See [`WorldStore`].
    pub fn update<R>(&self, f: impl FnOnce(&mut T) -> R) -> Option<R> {
        let mut slot = self.lock();
        let open = slot.open.as_mut()?;
        open.changed = true;
        Some(f(&mut open.value))
    }

    /// The key of the world whose value is open.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[derive(Default, serde::Deserialize, serde::Serialize)]
    /// # struct Bounties { paid: u64 }
    /// fn which(store: &enshwick::state::WorldStore<Bounties>) -> String {
    ///     store.key().unwrap_or_else(|| "no world".to_owned())
    /// }
    /// ```
    #[must_use]
    pub fn key(&self) -> Option<String> {
        self.lock().open.as_ref().map(|open| open.key.clone())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize)]
    struct Count {
        n: u32,
    }

    #[test]
    fn a_world_store_writes_its_world_s_file_and_switches_worlds() {
        let dir = std::env::temp_dir().join(format!("enshwick-world-store-{}", std::process::id()));
        let _gone = std::fs::remove_dir_all(&dir);
        let store: WorldStore<Count> = WorldStore::new(&dir, "count").unwrap();
        assert_eq!(store.update(|c| c.n += 1), None);
        store.open("world0-aa").unwrap();
        store.update(|c| c.n = 5);
        store.flush().unwrap();
        store.open("world1-bb").unwrap();
        assert_eq!(store.with(|c| c.n), Some(0));
        store.open("world0-aa").unwrap();
        assert_eq!(store.with(|c| c.n), Some(5));
        assert!(dir.join("worlds/world0-aa/count.toml").exists());
        store.update(|c| c.n = 6);
        store.flush_in_background();
        store.close().unwrap();
        let text = std::fs::read_to_string(dir.join("worlds/world0-aa/count.toml")).unwrap();
        assert!(text.contains('6'), "{text}");
        store.open("world0-aa").unwrap();
        store.close().unwrap();
        assert_eq!(store.key(), None);
        assert!(WorldStore::<Count>::new(&dir, "a/b").is_err());
        let _gone = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_flush_lands_after_a_background_write() {
        let dir = std::env::temp_dir().join(format!("enshwick-world-flush-{}", std::process::id()));
        let _gone = std::fs::remove_dir_all(&dir);
        let store: WorldStore<Count> = WorldStore::new(&dir, "count").unwrap();
        store.open("world0-aa").unwrap();
        let file = dir.join("worlds/world0-aa/count.toml");
        for n in 0..20 {
            store.update(|c| c.n = n);
            store.flush_in_background();
            store.update(|c| c.n = n + 100);
            store.flush().unwrap();
            let saved: Count = toml::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();
            assert_eq!(saved.n, n + 100);
        }
        store.close().unwrap();
        let _gone = std::fs::remove_dir_all(&dir);
    }
}