Coverage for lode / helpers / site_zip.py: 29%

66 statements  

« prev     ^ index     » next       coverage.py v7.13.0, created at 2026-11-22 15:54 +0000

1"""ZIP build of a static site: workspace, disk quota and concurrency limit. 

2 

3Builds write hundreds of files each, so they get their own directory with an 

4explicit budget instead of filling up /tmp. Nothing here knows about HTTP: when 

5the service is at capacity it raises BuildCapacityError and the caller decides 

6how to tell the client. 

7""" 

8import os 

9import re 

10import shutil 

11import tempfile 

12import threading 

13import time 

14from pathlib import Path 

15from typing import Optional, Tuple 

16 

17import lode.core as core 

18from lode.exceptions import BuildCapacityError 

19 

20# ========================================================================== 

21# 1. BUILD WORKSPACE 

22# ========================================================================== 

23BUILD_DIR = os.path.realpath( 

24 os.getenv("LODE_BUILD_DIR", os.path.join(tempfile.gettempdir(), "lode-builds")) 

25) 

26os.makedirs(BUILD_DIR, exist_ok=True) 

27_BUILD_TTL = 30 * 60 # orphans (aborted downloads) age out 

28_BUILD_MAX_BYTES = 2 * 1024 ** 3 # 2 GB for all pending builds 

29_BUILD_SLOTS = threading.BoundedSemaphore(2) # concurrent builds, per worker process 

30_BUILD_WAIT = 5 # seconds a request waits for a slot 

31 

32 

33def _prune_builds() -> int: 

34 """Drop orphaned build directories and return the bytes still in use. 

35 

36 A build is orphaned when the caller never removed it, i.e. the client 

37 opened the connection and never finished reading the archive. 

38 """ 

39 cutoff = time.time() - _BUILD_TTL 

40 total = 0 

41 for name in os.listdir(BUILD_DIR): 

42 p = os.path.join(BUILD_DIR, name) 

43 try: 

44 st = os.stat(p) 

45 except OSError: 

46 continue 

47 if st.st_mtime < cutoff: 

48 shutil.rmtree(p, ignore_errors=True) 

49 continue 

50 for root, _, files in os.walk(p): 

51 for f in files: 

52 try: 

53 total += os.path.getsize(os.path.join(root, f)) 

54 except OSError: 

55 pass 

56 return total 

57 

58 

59# ========================================================================== 

60# 2. SLUG 

61# ========================================================================== 

62def slugify(name: Optional[str]) -> str: 

63 """Safe directory/file stem derived from a URL or filename. 

64 

65 Must never yield '.' or '..': those would let make_archive(base_dir=...) 

66 escape the build directory and archive its parent. 

67 """ 

68 if not name: 

69 return "ontology" 

70 raw = name.rstrip("/").split("#")[0].split("/")[-1] 

71 raw = re.sub(r"\.(ttl|rdf|owl|n3|nt|jsonld|xml)$", "", raw, flags=re.I) 

72 raw = re.sub(r"[^A-Za-z0-9._-]", "-", raw).strip("-.") 

73 if not raw or raw in {".", ".."}: 

74 return "ontology" 

75 return raw[:64] 

76 

77 

78# ========================================================================== 

79# 3. BUILD 

80# ========================================================================== 

81def build_zip(artefact, slug: str, lang: Optional[str] = None) -> Tuple[str, str]: 

82 """Render the whole static site of an artefact and return (zip_path, workdir). 

83 

84 The caller owns `workdir` and must delete it once the archive has been sent; 

85 orphans are pruned by age. Raises BuildCapacityError when no build slot frees 

86 up in time or the workspace quota is used up. Blocking and disk-heavy: keep 

87 it off the event loop. 

88 """ 

89 if not _BUILD_SLOTS.acquire(timeout=_BUILD_WAIT): 

90 raise BuildCapacityError("Server busy: too many concurrent builds", retry_after=30) 

91 workdir = None 

92 try: 

93 if _prune_builds() > _BUILD_MAX_BYTES: 

94 raise BuildCapacityError("Build storage full, retry shortly", retry_after=60) 

95 

96 workdir = tempfile.mkdtemp(prefix="build_", dir=BUILD_DIR) 

97 # The slug is already sanitised by slugify; this check keeps the site inside the 

98 # workdir even if a caller passes a slug that was not, so it cannot be a path escape. 

99 site_path = os.path.normpath(os.path.join(workdir, slug)) 

100 if not site_path.startswith(os.path.normpath(workdir) + os.sep): 

101 raise ValueError(f"Unsafe site directory name: {slug!r}") 

102 site_dir = Path(site_path) 

103 site_dir.mkdir(parents=True, exist_ok=True) 

104 

105 core.build_site(artefact, site_dir, lang=lang or "en") 

106 

107 zip_path = shutil.make_archive( 

108 os.path.join(workdir, f"{slug}-lode"), "zip", 

109 root_dir=workdir, base_dir=slug, 

110 ) 

111 # The loose pages are redundant once archived: halve the disk peak. 

112 shutil.rmtree(site_dir, ignore_errors=True) 

113 except BaseException: 

114 if workdir: 

115 shutil.rmtree(workdir, ignore_errors=True) 

116 raise 

117 finally: 

118 # Free the slot as soon as the build ends, not when the client is done 

119 # downloading: a slow reader must not hold a build slot hostage. 

120 _BUILD_SLOTS.release() 

121 return zip_path, workdir