1use std::collections::{HashMap, HashSet};
27use std::fs;
28use std::io;
29use std::path::{Path, PathBuf};
30use std::sync::mpsc::{self, Receiver, Sender};
31use std::sync::{Arc, Mutex};
32use std::thread;
33
34use crate::grid::CellKey;
35use crate::stream::{CellSource, LoadError, PollResult};
36
37pub trait BlockStore: Send + Sync + 'static {
42 fn read(&self, cell: CellKey) -> io::Result<Option<Vec<u8>>>;
45}
46
47#[derive(Debug, Clone)]
50pub struct FileStore {
51 root: PathBuf,
52}
53
54impl FileStore {
55 pub fn new(root: impl Into<PathBuf>) -> Self {
56 Self { root: root.into() }
57 }
58
59 pub fn root(&self) -> &Path {
60 &self.root
61 }
62
63 pub fn block_file_name(cell: CellKey) -> String {
65 format!("l{}_x{}_y{}.bin", cell.level, cell.x, cell.y)
66 }
67
68 pub fn path_for(&self, cell: CellKey) -> PathBuf {
69 self.root.join(Self::block_file_name(cell))
70 }
71
72 pub fn write_block(&self, cell: CellKey, bytes: &[u8]) -> io::Result<()> {
76 let path = self.path_for(cell);
77 if let Some(parent) = path.parent() {
78 fs::create_dir_all(parent)?;
79 }
80 fs::write(path, bytes)
81 }
82}
83
84impl BlockStore for FileStore {
85 fn read(&self, cell: CellKey) -> io::Result<Option<Vec<u8>>> {
86 match fs::read(self.path_for(cell)) {
87 Ok(bytes) => Ok(Some(bytes)),
88 Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
89 Err(e) => Err(e),
90 }
91 }
92}
93
94pub type CellCodec<P> = Arc<dyn Fn(CellKey, &[u8]) -> Result<P, String> + Send + Sync + 'static>;
97
98#[derive(Clone, Copy)]
100struct Job {
101 cell: CellKey,
102 seq: u64,
105}
106
107struct Done<P> {
109 cell: CellKey,
110 seq: u64,
111 outcome: Outcome<P>,
112}
113
114enum Outcome<P> {
115 Ok {
116 payload: P,
117 bytes: u64,
118 },
119 Failed(String),
121}
122
123pub struct AsyncSource<P: Send + 'static> {
130 jobs: Sender<Job>,
131 results: Receiver<Done<P>>,
132 live: HashMap<CellKey, u64>,
134 cancelled: Arc<Mutex<HashSet<u64>>>,
137 ready: HashMap<CellKey, (P, u64)>,
139 failed: HashMap<CellKey, String>,
140 next_seq: u64,
141}
142
143impl<P: Send + 'static> AsyncSource<P> {
144 pub fn new<S: BlockStore>(store: S, codec: CellCodec<P>, workers: usize) -> Self {
148 let store = Arc::new(store);
149 let (job_tx, job_rx) = mpsc::channel::<Job>();
150 let (done_tx, done_rx) = mpsc::channel::<Done<P>>();
151 let job_rx = Arc::new(Mutex::new(job_rx));
152 let cancelled = Arc::new(Mutex::new(HashSet::new()));
153
154 for _ in 0..workers.max(1) {
155 let store = Arc::clone(&store);
156 let codec = Arc::clone(&codec);
157 let job_rx = Arc::clone(&job_rx);
158 let done_tx = done_tx.clone();
159 let cancelled_shared = Arc::clone(&cancelled);
160 thread::spawn(move || loop {
161 let job = {
162 let Ok(guard) = job_rx.lock() else { return };
163 match guard.recv() {
164 Ok(job) => job,
165 Err(_) => return,
167 }
168 };
169 if cancelled_shared.lock().unwrap().contains(&job.seq) {
173 continue;
174 }
175 let outcome = match store.read(job.cell) {
176 Ok(Some(bytes)) => match codec(job.cell, &bytes) {
177 Ok(payload) => Outcome::Ok {
178 payload,
179 bytes: bytes.len() as u64,
180 },
181 Err(msg) => Outcome::Failed(msg),
182 },
183 Ok(None) => Outcome::Failed("block not found".into()),
184 Err(e) => Outcome::Failed(e.to_string()),
185 };
186 if done_tx
187 .send(Done {
188 cell: job.cell,
189 seq: job.seq,
190 outcome,
191 })
192 .is_err()
193 {
194 return;
195 }
196 });
197 }
198 drop(done_tx);
202
203 Self {
204 jobs: job_tx,
205 results: done_rx,
206 live: HashMap::new(),
207 cancelled,
208 ready: HashMap::new(),
209 failed: HashMap::new(),
210 next_seq: 0,
211 }
212 }
213
214 pub fn pending_results(&self) -> usize {
216 self.ready.len() + self.failed.len()
217 }
218
219 fn harvest(&mut self) {
221 while let Ok(done) = self.results.try_recv() {
222 let is_current = self.live.get(&done.cell) == Some(&done.seq);
223 if !is_current {
224 self.cancelled.lock().unwrap().remove(&done.seq);
226 continue;
227 }
228 self.live.remove(&done.cell);
229 match done.outcome {
230 Outcome::Ok { payload, bytes } => {
231 self.ready.insert(done.cell, (payload, bytes));
232 }
233 Outcome::Failed(msg) => {
234 self.failed.insert(done.cell, msg);
235 }
236 }
237 }
238 }
239}
240
241impl<P: Send + 'static> CellSource for AsyncSource<P> {
242 type Payload = P;
243
244 fn start(&mut self, cell: CellKey, _now: f64) -> Result<(), LoadError> {
245 if self.live.contains_key(&cell) || self.ready.contains_key(&cell) {
246 return Ok(()); }
248 let seq = self.next_seq;
249 self.next_seq += 1;
250 self.live.insert(cell, seq);
251 self.jobs
252 .send(Job { cell, seq })
253 .map_err(|_| LoadError::Unsupported)?;
254 Ok(())
255 }
256
257 fn poll(&mut self, cell: CellKey, _now: f64) -> PollResult<P> {
258 self.harvest();
259 if let Some((payload, bytes)) = self.ready.remove(&cell) {
260 return PollResult::Ready { payload, bytes };
261 }
262 if self.failed.remove(&cell).is_some() {
263 return PollResult::Failed;
264 }
265 if self.live.contains_key(&cell) {
266 return PollResult::Pending;
267 }
268 PollResult::Failed
271 }
272
273 fn cancel(&mut self, cell: CellKey) {
274 if let Some(seq) = self.live.remove(&cell) {
275 self.cancelled.lock().unwrap().insert(seq);
276 }
277 self.ready.remove(&cell);
279 self.failed.remove(&cell);
280 }
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286 use crate::stream::{Priority, StreamConfig, Streamer};
287
288 fn temp_store(name: &str) -> FileStore {
289 let dir = std::env::temp_dir().join("re-world-tests").join(name);
290 let _ = fs::remove_dir_all(&dir);
291 FileStore::new(dir)
292 }
293
294 fn bytes_codec() -> CellCodec<Vec<u8>> {
296 Arc::new(|_, b| Ok(b.to_vec()))
297 }
298
299 fn key(level: u8, x: i64, y: i64) -> CellKey {
300 CellKey::new(level, x, y)
301 }
302
303 #[derive(Clone)]
306 struct GateStore {
307 gate: Arc<std::sync::atomic::AtomicBool>,
308 data: Arc<HashMap<CellKey, Vec<u8>>>,
309 }
310
311 impl GateStore {
312 fn new(cells: Vec<(CellKey, Vec<u8>)>) -> Self {
313 Self {
314 gate: Arc::new(std::sync::atomic::AtomicBool::new(false)),
315 data: Arc::new(cells.into_iter().collect()),
316 }
317 }
318 fn open(&self) {
319 self.gate.store(true, std::sync::atomic::Ordering::Relaxed);
320 }
321 }
322
323 impl BlockStore for GateStore {
324 fn read(&self, cell: CellKey) -> io::Result<Option<Vec<u8>>> {
325 while !self.gate.load(std::sync::atomic::Ordering::Relaxed) {
326 thread::sleep(std::time::Duration::from_millis(1));
327 }
328 Ok(self.data.get(&cell).cloned())
329 }
330 }
331
332 #[test]
333 fn rundlauf_laedt_dateien_ohne_hauptthread_block() {
334 let store = temp_store("rundlauf");
335 let a = key(0, 0, 0);
336 let b = key(0, 1, 2);
337 let c = key(2, -3, 4);
338 store.write_block(a, b"alpha").unwrap();
339 store.write_block(b, b"beta!!").unwrap();
340 store.write_block(c, b"c").unwrap();
341
342 let mut src = AsyncSource::new(store, bytes_codec(), 2);
343 src.start(a, 0.0).unwrap();
344 src.start(b, 0.0).unwrap();
345 src.start(c, 0.0).unwrap();
346
347 let mut got = HashMap::new();
349 for _ in 0..2000 {
350 for k in [a, b, c] {
351 if got.contains_key(&k) {
352 continue;
353 }
354 if let PollResult::Ready { payload, bytes } = src.poll(k, 0.0) {
355 assert_eq!(bytes, payload.len() as u64);
356 got.insert(k, payload);
357 }
358 }
359 if got.len() == 3 {
360 break;
361 }
362 thread::sleep(std::time::Duration::from_millis(1));
363 }
364 assert_eq!(got.get(&a).map(Vec::as_slice), Some(&b"alpha"[..]));
365 assert_eq!(got.get(&b).map(Vec::as_slice), Some(&b"beta!!"[..]));
366 assert_eq!(got.get(&c).map(Vec::as_slice), Some(&b"c"[..]));
367 }
368
369 #[test]
370 fn poll_blockiert_nie_und_liefert_spaeter() {
371 let gate = GateStore::new(vec![(key(0, 9, 9), b"spaet".to_vec())]);
372 let mut src = AsyncSource::new(gate.clone(), bytes_codec(), 1);
373 let k = key(0, 9, 9);
374 src.start(k, 0.0).unwrap();
375 for _ in 0..20 {
378 assert!(matches!(src.poll(k, 0.0), PollResult::Pending));
379 }
380 gate.open();
381 for _ in 0..2000 {
382 if let PollResult::Ready { payload, .. } = src.poll(k, 0.0) {
383 assert_eq!(payload, b"spaet");
384 return;
385 }
386 thread::sleep(std::time::Duration::from_millis(1));
387 }
388 panic!("Ladung wurde nie fertig");
389 }
390
391 #[test]
392 fn fehlender_block_scheitert_und_quelle_bleibt_nutzbar() {
393 let store = temp_store("fehlt");
394 store.write_block(key(0, 0, 0), b"x").unwrap();
395 let mut src = AsyncSource::new(store, bytes_codec(), 1);
396
397 let good = key(0, 0, 0);
398 let missing = key(0, 7, 7);
399 src.start(good, 0.0).unwrap();
400 src.start(missing, 0.0).unwrap();
401
402 let mut good_done = false;
403 let mut missing_failed = false;
404 for _ in 0..2000 {
405 if !good_done && matches!(src.poll(good, 0.0), PollResult::Ready { .. }) {
406 good_done = true;
407 }
408 if !missing_failed && matches!(src.poll(missing, 0.0), PollResult::Failed) {
409 missing_failed = true;
410 }
411 if good_done && missing_failed {
412 break;
413 }
414 thread::sleep(std::time::Duration::from_millis(1));
415 }
416 assert!(good_done, "vorhandener Block lädt");
417 assert!(missing_failed, "fehlender Block meldet Fehler");
418 src.start(good, 0.0).unwrap();
420 assert!(!matches!(src.poll(good, 0.0), PollResult::Failed));
421 }
422
423 #[test]
424 fn codec_fehler_zaehlt_als_zellfehler() {
425 let store = temp_store("codecfehler");
426 store.write_block(key(0, 1, 1), b"kaputt").unwrap();
427 let boom: CellCodec<Vec<u8>> = Arc::new(|_, _| Err("Codec sagt nein".into()));
428 let mut src = AsyncSource::new(store, boom, 1);
429 let k = key(0, 1, 1);
430 src.start(k, 0.0).unwrap();
431 for _ in 0..2000 {
432 match src.poll(k, 0.0) {
433 PollResult::Failed => return,
434 PollResult::Pending => thread::sleep(std::time::Duration::from_millis(1)),
435 PollResult::Ready { .. } => panic!("defekter Codec darf nicht Ready liefern"),
436 }
437 }
438 panic!("Fehlermeldung kam nie an");
439 }
440
441 #[test]
442 fn abbruch_verwirft_spaetere_ergebnisse() {
443 let gate = GateStore::new(vec![(key(0, 2, 2), b"egal".to_vec())]);
444 let mut src = AsyncSource::new(gate.clone(), bytes_codec(), 1);
445 let k = key(0, 2, 2);
446 src.start(k, 0.0).unwrap();
447 src.cancel(k);
448 gate.open();
449 for _ in 0..50 {
451 assert!(
452 matches!(src.poll(k, 0.0), PollResult::Failed),
453 "abgebrochene Ladung liefert nie Ready"
454 );
455 thread::sleep(std::time::Duration::from_millis(1));
456 }
457 assert_eq!(
458 src.pending_results(),
459 0,
460 "abgebrochene Ergebnisse sammeln sich nicht"
461 );
462 }
463
464 #[test]
465 fn streamer_betreibt_die_async_quelle() {
466 let store = temp_store("streamer_async");
467 let cells = [key(0, 0, 0), key(0, 1, 0), key(0, 2, 0), key(0, 3, 0)];
468 for (i, k) in cells.iter().enumerate() {
469 store.write_block(*k, &[b'a' + i as u8; 100]).unwrap();
470 }
471 let store_later = store.clone();
472 let src = AsyncSource::new(store, bytes_codec(), 3);
473 let mut s = Streamer::new(
474 src,
475 StreamConfig {
476 budget_bytes: 350,
477 max_inflight: 8,
478 },
479 );
480
481 s.sync_demand(
484 cells
485 .iter()
486 .map(|k| (*k, Priority(0, 0)))
487 .collect::<Vec<_>>(),
488 );
489 let mut loaded = 0;
490 let mut evicted = 0;
491 for step in 0..4000 {
492 s.set_now(step as f64 * 0.001);
493 let d = s.drive();
494 loaded += d.loaded.len();
495 evicted += d.evicted.len();
496 assert!(d.failed.is_empty(), "keine Fehler bei sauberen Blöcken");
497 if loaded >= 4 && evicted == 1 {
498 break;
499 }
500 thread::sleep(std::time::Duration::from_millis(1));
501 }
502 assert!(loaded >= 4, "alle Blöcke kommen durch den Pool an");
503 assert_eq!(evicted, 1, "Budget drängt genau eine raus");
504 assert!(s.resident_bytes() <= 350);
505 assert_eq!(s.resident().len(), 3);
506
507 let neu = key(0, 9, 9);
510 store_later.write_block(neu, &[b'x'; 100]).unwrap();
511 s.sync_demand(
512 cells[1..]
513 .iter()
514 .map(|k| (*k, Priority(0, 0)))
515 .chain([(neu, Priority(0, 1))])
516 .collect::<Vec<_>>(),
517 );
518 for step in 4000..8000 {
519 s.set_now(step as f64 * 0.001);
520 s.drive();
521 if s.is_resident(neu) && !s.is_resident(cells[0]) {
522 break;
523 }
524 thread::sleep(std::time::Duration::from_millis(1));
525 }
526 assert!(s.is_resident(neu), "neue Zelle lädt nach");
527 assert!(s.resident_bytes() <= 350);
528 }
529}