Debian Codegraph @

debian/rust-vendor/jiff/src/tz/db/concatenated/enabled.rs

raw
1 use alloc::{
2 string::{String, ToString},
3 vec,
4 vec::Vec,
5 };
6
7 use std::{
8 ffi::OsString,
9 fs::File,
10 path::{Path, PathBuf},
11 sync::{Arc, RwLock},
12 time::Duration,
13 };
14
15 use jcore::util::ArrayStr;
16
17 use crate::{
18 error::{tz::db::Error as E, Error},
19 timestamp::Timestamp,
20 tz::{
21 concatenated::ConcatenatedTzif, db::special_time_zone, TimeZone,
22 TimeZoneNameIter,
23 },
24 util::{self, cache::Expiration, utf8},
25 };
26
27 const DEFAULT_TTL: Duration = Duration::new(5 * 60, 0);
28
29 /// The places to look for a concatenated `tzdata` file.
30 static TZDATA_LOCATIONS: &[TzdataLocation] = &[
31 TzdataLocation::Env {
32 name: "ANDROID_ROOT",
33 default: "/system",
34 suffix: "usr/share/zoneinfo/tzdata",
35 },
36 TzdataLocation::Env {
37 name: "ANDROID_DATA",
38 default: "/data/misc",
39 suffix: "zoneinfo/current/tzdata",
40 },
41 ];
42
43 pub(crate) struct Database {
44 path: Option<PathBuf>,
45 names: Option<Names>,
46 zones: RwLock<CachedZones>,
47 }
48
49 impl Database {
50 pub(crate) fn from_env() -> Database {
51 let mut attempted = vec![];
52 for loc in TZDATA_LOCATIONS {
53 let path = loc.to_path_buf();
54 trace!(
55 "opening concatenated tzdata database at {}",
56 path.display()
57 );
58 match Database::from_path(&path) {
59 Ok(db) => return db,
60 Err(_err) => {
61 trace!("failed opening {}: {_err}", path.display());
62 }
63 }
64 attempted.push(path.to_string_lossy().into_owned());
65 }
66 debug!(
67 "could not find concatenated tzdata database at any of the \
68 following paths: {}",
69 attempted.join(", "),
70 );
71 Database::none()
72 }
73
74 pub(crate) fn from_path(path: &Path) -> Result<Database, Error> {
75 let names = Some(Names::new(path)?);
76 let zones = RwLock::new(CachedZones::new());
77 Ok(Database { path: Some(path.to_path_buf()), names, zones })
78 }
79
80 /// Creates a "dummy" zoneinfo database in which all lookups fail.
81 pub(crate) fn none() -> Database {
82 let path = None;
83 let names = None;
84 let zones = RwLock::new(CachedZones::new());
85 Database { path, names, zones }
86 }
87
88 pub(crate) fn reset(&self) {
89 let mut zones = self.zones.write().unwrap();
90 if let Some(ref names) = self.names {
91 names.reset();
92 }
93 zones.reset();
94 }
95
96 pub(crate) fn get(&self, query: &str) -> Option<TimeZone> {
97 if let Some(tz) = special_time_zone(query) {
98 return Some(tz);
99 }
100 let path = self.path.as_ref()?;
101 // The fast path is when the query matches a pre-existing unexpired
102 // time zone.
103 {
104 let zones = self.zones.read().unwrap();
105 if let Some(czone) = zones.get(query) {
106 if !czone.is_expired() {
107 trace!(
108 "for time zone query `{query}`, \
109 found cached zone `{}` \
110 (expiration={}, last_modified={:?})",
111 czone.tz.diagnostic_name(),
112 czone.expiration,
113 czone.last_modified,
114 );
115 return Some(czone.tz.clone());
116 }
117 }
118 }
119 // At this point, one of three possible cases is true:
120 //
121 // 1. The given query does not match any time zone in this database.
122 // 2. A time zone exists, but isn't cached.
123 // 3. A zime exists and is cached, but needs to be revalidated.
124 //
125 // While (3) is probably the common case since our TTLs are pretty
126 // short, both (2) and (3) require write access. Thus we rule out (1)
127 // before acquiring a write lock on the entire database. Plus, we'll
128 // need the zone info for case (2) and possibly for (3) if cache
129 // revalidation fails.
130 //
131 // I feel kind of bad about all this because it seems to me like there
132 // is too much work being done while holding on to the write lock.
133 // In particular, it seems like bad juju to do any I/O of any kind
134 // while holding any lock at all. I think I could design something
135 // that avoids doing I/O while holding a lock, but it seems a lot more
136 // complicated. (And what happens if the I/O becomes outdated by the
137 // time you acquire the lock?)
138 let mut zones = self.zones.write().unwrap();
139 let ttl = zones.ttl;
140 match zones.get_zone_index(query) {
141 Ok(i) => {
142 let czone = &mut zones.zones[i];
143 if czone.revalidate(path, ttl) {
144 // Metadata on the file didn't change, so we assume the
145 // file hasn't either.
146 return Some(czone.tz.clone());
147 }
148 // Revalidation failed. Re-read the TZif data.
149 let (scratch1, scratch2) = zones.scratch();
150 let czone = match CachedTimeZone::new(
151 path, query, ttl, scratch1, scratch2,
152 ) {
153 Ok(Some(czone)) => czone,
154 Ok(None) => return None,
155 Err(_err) => {
156 warn!(
157 "failed to re-cache time zone {query} \
158 from {path}: {_err}",
159 path = path.display(),
160 );
161 return None;
162 }
163 };
164 let tz = czone.tz.clone();
165 zones.zones[i] = czone;
166 Some(tz)
167 }
168 Err(i) => {
169 let (scratch1, scratch2) = zones.scratch();
170 let czone = match CachedTimeZone::new(
171 path, query, ttl, scratch1, scratch2,
172 ) {
173 Ok(Some(czone)) => czone,
174 Ok(None) => return None,
175 Err(_err) => {
176 warn!(
177 "failed to cache time zone {query} \
178 from {path}: {_err}",
179 path = path.display(),
180 );
181 return None;
182 }
183 };
184 let tz = czone.tz.clone();
185 zones.zones.insert(i, czone);
186 Some(tz)
187 }
188 }
189 }
190
191 pub(crate) fn available<'d>(&'d self) -> TimeZoneNameIter<'d> {
192 let Some(path) = self.path.as_ref() else {
193 return TimeZoneNameIter::empty();
194 };
195 let Some(names) = self.names.as_ref() else {
196 return TimeZoneNameIter::empty();
197 };
198 TimeZoneNameIter::from_iter(names.available(path).into_iter())
199 }
200
201 pub(crate) fn is_definitively_empty(&self) -> bool {
202 self.names.is_none()
203 }
204 }
205
206 impl core::fmt::Debug for Database {
207 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
208 f.write_str("Concatenated(")?;
209 if let Some(ref path) = self.path {
210 path.display().fmt(f)?;
211 } else {
212 f.write_str("unavailable")?;
213 }
214 f.write_str(")")
215 }
216 }
217
218 #[derive(Debug)]
219 struct CachedZones {
220 zones: Vec<CachedTimeZone>,
221 ttl: Duration,
222 scratch1: Vec<u8>,
223 scratch2: Vec<u8>,
224 }
225
226 impl CachedZones {
227 const DEFAULT_TTL: Duration = DEFAULT_TTL;
228
229 fn new() -> CachedZones {
230 CachedZones {
231 zones: vec![],
232 ttl: CachedZones::DEFAULT_TTL,
233 scratch1: vec![],
234 scratch2: vec![],
235 }
236 }
237
238 fn get(&self, query: &str) -> Option<&CachedTimeZone> {
239 self.get_zone_index(query).ok().map(|i| &self.zones[i])
240 }
241
242 fn get_zone_index(&self, query: &str) -> Result<usize, usize> {
243 self.zones.binary_search_by(|zone| {
244 utf8::cmp_ignore_ascii_case(zone.name(), query)
245 })
246 }
247
248 fn reset(&mut self) {
249 self.zones.clear();
250 }
251
252 fn scratch(&mut self) -> (&mut Vec<u8>, &mut Vec<u8>) {
253 (&mut self.scratch1, &mut self.scratch2)
254 }
255 }
256
257 #[derive(Clone, Debug)]
258 struct CachedTimeZone {
259 tz: TimeZone,
260 expiration: Expiration,
261 last_modified: Option<Timestamp>,
262 }
263
264 impl CachedTimeZone {
265 /// Create a new cached time zone.
266 ///
267 /// `path` should be a concatenated `tzdata` file. `query` is the IANA time
268 /// zone identifier we're looing for. The `ttl` says how long
269 /// the cached time zone should minimally remain fresh for.
270 ///
271 /// The `scratch1` and `scratch2` given are used to help amortize
272 /// allocation when deserializing TZif data from the concatenated `tzdata`
273 /// file.
274 ///
275 /// If no such time zone exists and no other error occurred, then
276 /// `Ok(None)` is returned.
277 fn new(
278 path: &Path,
279 query: &str,
280 ttl: Duration,
281 scratch1: &mut Vec<u8>,
282 scratch2: &mut Vec<u8>,
283 ) -> Result<Option<CachedTimeZone>, Error> {
284 let file = File::open(path).map_err(|e| Error::io(e).path(path))?;
285 let db = ConcatenatedTzif::open(&file)?;
286 let Some(tz) = db.get(query, scratch1, scratch2)? else {
287 return Ok(None);
288 };
289 let last_modified = util::fs::last_modified_from_file(path, &file);
290 let expiration = Expiration::after(ttl);
291 Ok(Some(CachedTimeZone { tz, expiration, last_modified }))
292 }
293
294 /// Returns true if this time zone has gone stale and should, at minimum,
295 /// be revalidated.
296 fn is_expired(&self) -> bool {
297 self.expiration.is_expired()
298 }
299
300 /// Returns the IANA time zone identifier of this cached time zone.
301 fn name(&self) -> &str {
302 // OK because `ConcatenatedTzif` guarantees all `TimeZone` values it
303 // returns have an IANA name.
304 self.tz.iana_name().unwrap()
305 }
306
307 /// Attempts to revalidate this cached time zone.
308 ///
309 /// Upon successful revalidation (that is, the cached time zone is still
310 /// fresh and okay to use), this returns true. Otherwise, the cached time
311 /// zone should be considered stale and must be re-created.
312 ///
313 /// Note that technically another layer of revalidation could be done.
314 /// For example, we could keep a checksum of the TZif data, and only
315 /// consider rebuilding the time zone when the checksum changes. But I
316 /// think the last modified metadata will in practice be good enough, and
317 /// parsing TZif data should be quite fast.
318 ///
319 /// `path` should be a concatenated `tzdata` file.
320 fn revalidate(&mut self, path: &Path, ttl: Duration) -> bool {
321 // If we started with no last modified timestamp, then I guess we
322 // should always fail revalidation? I suppose a case could be made to
323 // do the opposite: always pass revalidation.
324 let Some(old_last_modified) = self.last_modified else {
325 trace!(
326 "revalidation for {name} in {path} failed because \
327 old last modified time is unavailable",
328 name = self.name(),
329 path = path.display(),
330 );
331 return false;
332 };
333 let Some(new_last_modified) = util::fs::last_modified_from_path(path)
334 else {
335 trace!(
336 "revalidation for {name} in {path} failed because \
337 new last modified time is unavailable",
338 name = self.name(),
339 path = path.display(),
340 );
341 return false;
342 };
343 // We consider any change to invalidate cache.
344 if old_last_modified != new_last_modified {
345 trace!(
346 "revalidation for {name} in {path} failed because \
347 last modified times do not match: old = {old} != {new} = new",
348 name = self.name(),
349 path = path.display(),
350 old = old_last_modified,
351 new = new_last_modified,
352 );
353 return false;
354 }
355 trace!(
356 "revalidation for {name} in {path} succeeded because \
357 last modified times match: old = {old} == {new} = new",
358 name = self.name(),
359 path = path.display(),
360 old = old_last_modified,
361 new = new_last_modified,
362 );
363 self.expiration = Expiration::after(ttl);
364 true
365 }
366 }
367
368 /// A collection of time zone names extracted from a concatenated tzdata file.
369 ///
370 /// This type is responsible not just for providing the names, but also for
371 /// updating them periodically.
372 ///
373 /// Every name _should_ correspond to an entry in the data block of the
374 /// corresponding `tzdata` file, but we generally don't take advantage of this.
375 /// The reason is that the file could theoretically change. Between when we
376 /// extract the names and when we do a TZif lookup later. This is all perfectly
377 /// manageable, but it should only be done if there's a benchmark demanding
378 /// more effort be spent here. As it stands, we do have a rudimentary caching
379 /// mechanism, so not all time zone lookups go through this slower path. (This
380 /// is also why `Names` has no lookup routine. There's just a routine to return
381 /// all names.)
382 #[derive(Debug)]
383 struct Names {
384 inner: RwLock<NamesInner>,
385 }
386
387 #[derive(Debug)]
388 struct NamesInner {
389 /// All available names from the `tzdata` file.
390 names: Vec<Arc<str>>,
391 /// The version string read from the `tzdata` file.
392 version: ArrayStr<5>,
393 /// Scratch space used to help amortize allocation when extracting names
394 /// from a `tzdata` file.
395 scratch: Vec<u8>,
396 /// The expiration time of these cached names.
397 ///
398 /// Note that this is a necessary but not sufficient criterion for
399 /// invalidating the cached value.
400 ttl: Duration,
401 /// The time at which the data in `names` becomes stale.
402 expiration: Expiration,
403 }
404
405 impl Names {
406 /// See comments in `tz/db/zoneinfo/enabled.rs` about this. We just copied
407 /// it from there.
408 const DEFAULT_TTL: Duration = DEFAULT_TTL;
409
410 /// Create a new collection of names from the concatenated `tzdata` file
411 /// path given.
412 ///
413 /// If no names of time zones could be found in the given directory, then
414 /// an error is returned.
415 fn new(path: &Path) -> Result<Names, Error> {
416 let path = path.to_path_buf();
417 let mut scratch = vec![];
418 let (names, version) = read_names_and_version(&path, &mut scratch)?;
419 trace!(
420 "found concatenated tzdata at {path} \
421 with version {version} and {len} \
422 IANA time zone identifiers",
423 path = path.display(),
424 len = names.len(),
425 );
426 let ttl = Names::DEFAULT_TTL;
427 let expiration = Expiration::after(ttl);
428 let inner = NamesInner { names, version, scratch, ttl, expiration };
429 Ok(Names { inner: RwLock::new(inner) })
430 }
431
432 /// Returns all available time zone names after attempting a refresh of
433 /// the underlying data if it's stale.
434 fn available(&self, path: &Path) -> Vec<String> {
435 let mut inner = self.inner.write().unwrap();
436 inner.attempt_refresh(path);
437 inner.available()
438 }
439
440 fn reset(&self) {
441 self.inner.write().unwrap().reset();
442 }
443 }
444
445 impl NamesInner {
446 /// Returns all available time zone names.
447 fn available(&self) -> Vec<String> {
448 self.names.iter().map(|name| name.to_string()).collect()
449 }
450
451 /// Attempts a refresh, but only follows through if the TTL has been
452 /// exceeded.
453 ///
454 /// The caller must ensure that the other cache invalidation criteria
455 /// have been upheld. For example, this should only be called for a missed
456 /// zone name lookup.
457 fn attempt_refresh(&mut self, path: &Path) {
458 if self.expiration.is_expired() {
459 self.refresh(path);
460 }
461 }
462
463 /// Forcefully refreshes the cached names with possibly new data from disk.
464 /// If an error occurs when fetching the names, then no names are updated
465 /// (but the `expires_at` is updated). This will also emit a warning log on
466 /// failure.
467 fn refresh(&mut self, path: &Path) {
468 // PERF: Should we try to move this tzdb handling to run outside of a
469 // lock? It probably happens pretty rarely, so it might not matter.
470 let result = read_names_and_version(path, &mut self.scratch);
471 self.expiration = Expiration::after(self.ttl);
472 match result {
473 Ok((names, version)) => {
474 trace!(
475 "refreshed concatenated tzdata at {path} \
476 with version {version} and {len} \
477 IANA time zone identifiers",
478 path = path.display(),
479 len = names.len(),
480 );
481 self.names = names;
482 self.version = version;
483 }
484 Err(_err) => {
485 warn!(
486 "failed to refresh concatenated time zone name cache \
487 for {path}: {_err}",
488 path = path.display(),
489 )
490 }
491 }
492 }
493
494 /// Resets the state such that the next lookup is guaranteed to force a
495 /// cache refresh, and that it is impossible for any data to be stale.
496 fn reset(&mut self) {
497 // This will force the next lookup to fail.
498 self.names.clear();
499 // And this will force the next failed lookup to result in a refresh.
500 self.expiration = Expiration::expired();
501 }
502 }
503
504 /// A type representing how to find a `tzdata` file.
505 ///
506 /// This currently only supports an Android-centric lookup via env vars, but if
507 /// we wanted to check a fixed path like we do for `ZoneInfo`, then adding a
508 /// `Fixed` variant here would be appropriate.
509 #[derive(Debug)]
510 enum TzdataLocation {
511 Env { name: &'static str, default: &'static str, suffix: &'static str },
512 }
513
514 impl TzdataLocation {
515 /// Converts this location to an actual path, which might involve an
516 /// environment variable lookup.
517 fn to_path_buf(&self) -> PathBuf {
518 match *self {
519 TzdataLocation::Env { name, default, suffix } => {
520 let var = std::env::var_os(name)
521 .unwrap_or_else(|| OsString::from(default));
522 let prefix = PathBuf::from(var);
523 prefix.join(suffix)
524 }
525 }
526 }
527 }
528
529 /// Reads only the IANA time zone identifiers from the given path (and the
530 /// version of the database).
531 ///
532 /// The `scratch` given is used to help amortize allocation when deserializing
533 /// names from the concatenated `tzdata` file.
534 ///
535 /// This returns an error if reading was successful but no names were found.
536 fn read_names_and_version(
537 path: &Path,
538 scratch: &mut Vec<u8>,
539 ) -> Result<(Vec<Arc<str>>, ArrayStr<5>), Error> {
540 let file = File::open(path).map_err(|e| Error::io(e).path(path))?;
541 let db = ConcatenatedTzif::open(file)?;
542 let names: Vec<Arc<str>> =
543 db.available(scratch)?.into_iter().map(Arc::from).collect();
544 if names.is_empty() {
545 return Err(Error::from(E::ConcatenatedMissingIanaIdentifiers));
546 }
547 Ok((names, db.version()))
548 }
549
550 #[cfg(test)]
551 mod tests {
552 use super::*;
553
554 /// DEBUG COMMAND
555 ///
556 /// Takes environment variable `JIFF_DEBUG_ZONEINFO_DIR` as input and
557 /// prints a list of all time zone names in the directory (one per line).
558 ///
559 /// Callers may also set `RUST_LOG` to get extra debugging output.
560 #[test]
561 fn debug_tzdata_list() -> anyhow::Result<()> {
562 let _ = crate::logging::Logger::init();
563
564 const ENV: &str = "JIFF_DEBUG_CONCATENATED_TZDATA";
565 let Some(val) = std::env::var_os(ENV) else { return Ok(()) };
566 let path = PathBuf::from(val);
567 let db = Database::from_path(&path)?;
568 for name in db.available() {
569 std::eprintln!("{name}");
570 }
571 Ok(())
572 }
573 }