gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit0ee5a6f20ee5a6f2Tickets conductor: T36 resumedmre0ee5a6f2/plugins/fs/fs.zig

59.6 KB

  1. // hl:fs plugin — native shared library
  2. // Compiled to fs.so, loaded by runtime via dlopen
  3. //
  4. // Exports:
  5. // hl_fs_file(path) → file descriptor with metadata + line iterator
  6. // hl_fs_read_file(path) → entire file as string (raw bytes, unchecked)
  7. // hl_fs_write_file(path, text, mode?) / hl_fs_write_file_hex(path, hex, mode?)
  8. // hl_fs_append_file(path, text, mode?) / hl_fs_append_file_hex(path, hex, mode?)
  9. // hl_fs_list_dir(path) → streaming directory iterator
  10. const std = @import("std");
  11. const api = @import("plugin_api");
  12. const linux = std.os.linux;
  13. const HlValue = api.HlValue;
  14. const HlObject = api.HlObject;
  15. const HlField = api.HlField;
  16. const HlIterator = api.HlIterator;
  17. const HlString = api.HlString;
  18. // the plugins' allocator (plugin_api.zig)
  19. const allocator = api.allocator;
  20. // =========================================================================
  21. // Path resolution (mission 068)
  22. //
  23. // CONTRACT: relative paths passed to hl:fs resolve against the MAIN SCRIPT's
  24. // directory, not the process CWD — Hybriel path resolution is file-relative
  25. // everywhere (import, inherit, plugin discovery), and fs follows suit.
  26. // Absolute paths are used as-is. The runtime injects the script dir via the
  27. // optional plugin hook hl_fs_set_script_dir right after dlopen.
  28. // =========================================================================
  29. var script_dir: ?[]u8 = null;
  30. export fn hl_fs_set_script_dir(ptr: [*]const u8, len: usize) callconv(.c) void {
  31. if (script_dir) |old| allocator.free(old);
  32. script_dir = allocator.dupe(u8, ptr[0..len]) catch null;
  33. }
  34. /// A compiled binary's unpacked `ship` files (mission 316): a relative path
  35. /// one of them answers resolves there; any other as it would without it.
  36. var ship_dir: ?[]u8 = null;
  37. export fn hl_fs_set_ship_dir(ptr: [*]const u8, len: usize) callconv(.c) void {
  38. if (ship_dir) |old| allocator.free(old);
  39. ship_dir = allocator.dupe(u8, ptr[0..len]) catch null;
  40. }
  41. /// THE READ TRACE (326 rung 12, the build cache): while a trace file is named
  42. /// — by hl:fs `traceReads(path)`, or by HL_FS_TRACE in the environment, which a build
  43. /// hands the programs it runs — every path this plugin reads, lists or probes
  44. /// is appended to it as one line, `r <path>`, `l <path>` or `e <path>`, the
  45. /// path as resolved (absolute when the process's was). A build records what it
  46. /// depends on this way; nothing else changes.
  47. var trace_path: ?[:0]u8 = null;
  48. var trace_env_read = false;
  49. export fn hl_fs_trace(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  50. trace_env_read = true;
  51. if (trace_path) |old| allocator.free(old);
  52. trace_path = null;
  53. if (argc >= 1 and argv[0].type == .hl_string) {
  54. const p = argv[0].data.string.ptr[0..argv[0].data.string.len];
  55. if (p.len > 0) trace_path = allocator.dupeZ(u8, p) catch null;
  56. }
  57. return api.makeNull();
  58. }
  59. fn traceAccess(kind: u8, resolved: []const u8) void {
  60. if (!trace_env_read) {
  61. trace_env_read = true;
  62. if (std.c.getenv("HL_FS_TRACE")) |e| {
  63. const p = std.mem.span(e);
  64. if (p.len > 0) trace_path = allocator.dupeZ(u8, p) catch null;
  65. }
  66. }
  67. const tp = trace_path orelse return;
  68. var cwd_buf: [4096]u8 = undefined;
  69. const line = if (resolved.len > 0 and resolved[0] == '/')
  70. std.fmt.allocPrint(allocator, "{c} {s}\n", .{ kind, resolved }) catch return
  71. else blk: {
  72. const rc: isize = @bitCast(linux.getcwd(&cwd_buf, cwd_buf.len));
  73. if (rc <= 0) return;
  74. const cwd = std.mem.sliceTo(&cwd_buf, 0);
  75. break :blk std.fmt.allocPrint(allocator, "{c} {s}/{s}\n", .{ kind, cwd, resolved }) catch return;
  76. };
  77. defer allocator.free(line);
  78. const rc = linuxOpenRc(tp, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true }, 0o600);
  79. if (rc < 0) return;
  80. const fd: i32 = @intCast(rc);
  81. defer _ = linux.close(fd);
  82. _ = linux.write(fd, line.ptr, line.len);
  83. }
  84. /// hl_fs_digest(path) — the SHA-256 of a file's bytes as 64 hex digits, or
  85. /// null when it cannot be read; hl_fs_digest_text(text) — of a text's. The
  86. /// build cache's content keys (326 rung 12): hashed here, in the plugin, so
  87. /// every engine has them and nothing crosses as a value but the answer.
  88. export fn hl_fs_digest(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  89. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.digest expects a string path");
  90. const path_str = argv[0].data.string;
  91. const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();
  92. defer allocator.free(resolved);
  93. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  94. defer allocator.free(path_z);
  95. const rc = linuxOpenRc(path_z, .{}, 0);
  96. if (rc < 0) return api.makeNull();
  97. const fd: i32 = @intCast(rc);
  98. defer _ = linux.close(fd);
  99. var h = std.crypto.hash.sha2.Sha256.init(.{});
  100. var buf: [65536]u8 = undefined;
  101. while (true) {
  102. const n: isize = @bitCast(linux.read(fd, &buf, buf.len));
  103. if (n == 0) break;
  104. if (n < 0) {
  105. if (@as(usize, @intCast(-n)) == @intFromEnum(linux.E.INTR)) continue;
  106. return api.makeNull();
  107. }
  108. h.update(buf[0..@intCast(n)]);
  109. }
  110. return hexDigest(&h);
  111. }
  112. export fn hl_fs_digest_text(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  113. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.digestText expects a string");
  114. const t = argv[0].data.string;
  115. var h = std.crypto.hash.sha2.Sha256.init(.{});
  116. h.update(t.ptr[0..t.len]);
  117. return hexDigest(&h);
  118. }
  119. fn hexDigest(h: *std.crypto.hash.sha2.Sha256) HlValue {
  120. var d: [32]u8 = undefined;
  121. h.final(&d);
  122. const out = allocator.alloc(u8, 64) catch return api.makeNull();
  123. const hex = "0123456789abcdef";
  124. for (d, 0..) |b, i| {
  125. out[i * 2] = hex[b >> 4];
  126. out[i * 2 + 1] = hex[b & 15];
  127. }
  128. return api.makeString(out);
  129. }
  130. /// Resolve a (possibly relative) path against the script dir. Returned slice
  131. /// is allocated with the plugin allocator; caller frees.
  132. fn resolvePath(path: []const u8) ?[]u8 {
  133. if (path.len == 0) return allocator.dupe(u8, path) catch null;
  134. if (path[0] == '/') return allocator.dupe(u8, path) catch null;
  135. if (ship_dir) |sd| {
  136. if (std.fmt.allocPrintSentinel(allocator, "{s}/{s}", .{ sd, path }, 0)) |shipped| {
  137. defer allocator.free(shipped);
  138. if (std.c.access(shipped.ptr, 0) == 0) return allocator.dupe(u8, shipped) catch null;
  139. } else |_| {}
  140. }
  141. if (script_dir) |sd| {
  142. return std.fmt.allocPrint(allocator, "{s}/{s}", .{ sd, path }) catch null;
  143. }
  144. return allocator.dupe(u8, path) catch null;
  145. }
  146. // =========================================================================
  147. // Error values (mission 068): open failures are LOUD — api.makeError with
  148. // the operation, the path as the caller wrote it, and the OS reason. The
  149. // runtime turns a top-level error value into a located runtime error.
  150. // =========================================================================
  151. fn errnoText(errno: usize) []const u8 {
  152. return switch (errno) {
  153. 2 => "no such file or directory",
  154. 13 => "permission denied",
  155. 20 => "not a directory",
  156. 21 => "is a directory",
  157. 1 => "operation not permitted",
  158. 17 => "file exists",
  159. 23 => "too many open files in the system",
  160. 24 => "too many open files",
  161. 28 => "no space left on device",
  162. 30 => "read-only file system",
  163. 36 => "file name too long",
  164. 40 => "too many levels of symbolic links",
  165. else => "I/O error",
  166. };
  167. }
  168. /// What to do about it, for the two descriptor-limit errors (fd403): a docker soft limit of
  169. /// 1024 turned a boot into an unexplained "I/O error (errno 24)".
  170. fn errnoHint(errno: usize) []const u8 {
  171. return switch (errno) {
  172. 23, 24 => "raise the open-file limit (ulimit -n) or close handles",
  173. else => "relative paths resolve against the script's directory",
  174. };
  175. }
  176. fn errDeinit(val: *api.HlValue) callconv(.c) void {
  177. if (val.type == .hl_error) {
  178. const s = val.data.string;
  179. allocator.free(@constCast(s.ptr[0..s.len]));
  180. }
  181. }
  182. fn makeOpenError(op: []const u8, path: []const u8, errno: usize) api.HlValue {
  183. const msg = std.fmt.allocPrint(allocator, "{s}: cannot open '{s}' — {s} (errno {d}); {s}", .{ op, path, errnoText(errno), errno, errnoHint(errno) }) catch
  184. return api.makeError("fs: cannot open file");
  185. var v = api.makeError(msg);
  186. v.deinit_fn = &errDeinit;
  187. return v;
  188. }
  189. fn makeReadError(op: []const u8, path: []const u8, errno: usize) api.HlValue {
  190. const msg = std.fmt.allocPrint(allocator, "{s}: cannot read '{s}' — {s} (errno {d})", .{ op, path, errnoText(errno), errno }) catch
  191. return api.makeError("fs: cannot read file");
  192. var v = api.makeError(msg);
  193. v.deinit_fn = &errDeinit;
  194. return v;
  195. }
  196. // =========================================================================
  197. // hl_fs_file — file descriptor with metadata + line iterator
  198. // =========================================================================
  199. const FileIterState = struct {
  200. fd: i32,
  201. allocated_strings: std.array_list.Managed([]u8),
  202. done: bool,
  203. buf: [4096]u8,
  204. buf_pos: usize,
  205. buf_len: usize,
  206. };
  207. export fn hl_fs_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  208. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.file expects a string path");
  209. const path_str = argv[0].data.string;
  210. const path = path_str.ptr[0..path_str.len];
  211. // Resolve relative paths against the script dir; keep the caller's path
  212. // for the descriptor's name/path fields.
  213. const resolved = resolvePath(path) orelse return api.makeNull();
  214. defer allocator.free(resolved);
  215. traceAccess('r', resolved);
  216. // We need a null-terminated path for the OS
  217. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  218. defer allocator.free(path_z);
  219. // Open file
  220. const rc = linuxOpenRc(path_z, .{}, 0);
  221. if (rc < 0) return makeOpenError("fs.file", path, @intCast(-rc));
  222. const fd: i32 = @intCast(rc);
  223. // Stat for size, chmod, uid, gid
  224. var size: f64 = 0;
  225. var chmod: f64 = 0;
  226. var uid: f64 = 0;
  227. var gid: f64 = 0;
  228. var stat_ok = false;
  229. var statx_buf: std.os.linux.Statx = undefined;
  230. const statx_rc = std.os.linux.statx(
  231. fd,
  232. "",
  233. std.os.linux.AT.EMPTY_PATH,
  234. std.os.linux.STATX.BASIC_STATS,
  235. &statx_buf,
  236. );
  237. if (statx_rc == 0) {
  238. size = @floatFromInt(statx_buf.size);
  239. chmod = @floatFromInt(statx_buf.mode & 0o7777);
  240. uid = @floatFromInt(statx_buf.uid);
  241. gid = @floatFromInt(statx_buf.gid);
  242. stat_ok = true;
  243. }
  244. // Extract name from path
  245. const name = if (std.mem.lastIndexOfScalar(u8, path, '/')) |idx|
  246. path[idx + 1 ..]
  247. else
  248. path;
  249. // Mime from extension
  250. const mime = mimeFromName(name);
  251. // Build fields: name, path, size, mime, chmod, user, group = 7 fields
  252. const field_count: usize = 7;
  253. const fields = allocator.alloc(HlField, field_count) catch return api.makeNull();
  254. fields[0] = .{ .key = hlStr("name"), .value = api.makeString(name) };
  255. fields[1] = .{ .key = hlStr("path"), .value = api.makeString(path) };
  256. fields[2] = .{ .key = hlStr("size"), .value = api.makeNumber(size) };
  257. fields[3] = .{ .key = hlStr("mime"), .value = api.makeString(mime) };
  258. fields[4] = .{ .key = hlStr("chmod"), .value = api.makeNumber(chmod) };
  259. if (stat_ok) {
  260. fields[5] = .{ .key = hlStr("user"), .value = api.makeNumber(uid) };
  261. fields[6] = .{ .key = hlStr("group"), .value = api.makeNumber(gid) };
  262. } else {
  263. fields[5] = .{ .key = hlStr("user"), .value = api.makeNull() };
  264. fields[6] = .{ .key = hlStr("group"), .value = api.makeNull() };
  265. }
  266. const obj = allocator.create(HlObject) catch return api.makeNull();
  267. obj.* = .{
  268. .fields = fields.ptr,
  269. .field_count = field_count,
  270. .deinit_fn = &fileObjDeinit,
  271. };
  272. // Create line iterator
  273. const iter_state = allocator.create(FileIterState) catch return api.makeNull();
  274. iter_state.* = .{
  275. .fd = fd,
  276. .allocated_strings = std.array_list.Managed([]u8).init(allocator),
  277. .done = false,
  278. .buf = undefined,
  279. .buf_pos = 0,
  280. .buf_len = 0,
  281. };
  282. const iter = allocator.create(HlIterator) catch return api.makeNull();
  283. iter.* = .{
  284. .context = @ptrCast(iter_state),
  285. .next_fn = &fileIterNext,
  286. .deinit_fn = &fileIterDeinit,
  287. };
  288. // Return object — runtime will see it has both object fields and an iterator
  289. // We pack the iterator pointer into the object by adding one more field
  290. const full_fields = allocator.alloc(HlField, field_count + 1) catch return api.makeNull();
  291. @memcpy(full_fields[0..field_count], fields);
  292. full_fields[field_count] = .{ .key = hlStr("__iter"), .value = api.makeIterator(iter) };
  293. // Free the original fields, use full_fields
  294. allocator.free(fields);
  295. obj.fields = full_fields.ptr;
  296. obj.field_count = field_count + 1;
  297. return api.makeObject(obj);
  298. }
  299. fn fileIterNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  300. const state: *FileIterState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  301. if (state.done) return api.makeNull();
  302. var line_buf = std.array_list.Managed(u8).init(allocator);
  303. while (true) {
  304. if (state.buf_pos < state.buf_len) {
  305. const remaining = state.buf[state.buf_pos..state.buf_len];
  306. if (std.mem.indexOfScalar(u8, remaining, '\n')) |nl_pos| {
  307. line_buf.appendSlice(remaining[0..nl_pos]) catch return api.makeNull();
  308. state.buf_pos += nl_pos + 1;
  309. break;
  310. } else {
  311. line_buf.appendSlice(remaining) catch return api.makeNull();
  312. state.buf_pos = 0;
  313. state.buf_len = 0;
  314. }
  315. }
  316. // Read from file using posix read
  317. const n = linuxRead(state.fd, &state.buf) orelse {
  318. state.done = true;
  319. break;
  320. };
  321. if (n == 0) {
  322. state.done = true;
  323. break;
  324. }
  325. state.buf_pos = 0;
  326. state.buf_len = n;
  327. }
  328. if (state.done) closeIterFd(state);
  329. if (line_buf.items.len == 0 and state.done) {
  330. line_buf.deinit();
  331. return api.makeNull();
  332. }
  333. const line = line_buf.toOwnedSlice() catch return api.makeNull();
  334. state.allocated_strings.append(line) catch return api.makeNull();
  335. return api.makeString(line);
  336. }
  337. /// An iterator that ran to its end gives its fd back at once (fd403: the compiler's
  338. /// directory walks held one fd per listDir until the GC finalized them: > 1024 at boot).
  339. /// The fd is -1 afterwards; deinit closes only a still-open one.
  340. fn closeIterFd(state: anytype) void {
  341. if (state.fd >= 0) {
  342. _ = linux.close(state.fd);
  343. state.fd = -1;
  344. }
  345. }
  346. fn fileIterDeinit(ctx: ?*anyopaque) callconv(.c) void {
  347. const state: *FileIterState = @ptrCast(@alignCast(ctx orelse return));
  348. closeIterFd(state);
  349. for (state.allocated_strings.items) |s| {
  350. allocator.free(s);
  351. }
  352. state.allocated_strings.deinit();
  353. allocator.destroy(state);
  354. }
  355. fn fileObjDeinit(obj: *HlObject) callconv(.c) void {
  356. const fields = obj.fields[0..obj.field_count];
  357. // Check for iterator field and clean it up (only if not already nulled out by runtime)
  358. for (fields) |field| {
  359. if (field.value.type == .hl_iterator) {
  360. const iter = field.value.data.iterator;
  361. if (iter.deinit_fn) |deinit_fn| {
  362. deinit_fn(iter.context);
  363. }
  364. allocator.destroy(iter);
  365. }
  366. }
  367. allocator.free(fields);
  368. allocator.destroy(obj);
  369. }
  370. // =========================================================================
  371. // hl_fs_read_file — read entire file as string
  372. // =========================================================================
  373. fn readFileDeinit(val: *HlValue) callconv(.c) void {
  374. if (val.type == .hl_string) {
  375. const s = val.data.string;
  376. allocator.free(@constCast(s.ptr[0..s.len]));
  377. }
  378. }
  379. /// exists(path) → Boolean (mission 077, 074 GAP 8). The ONLY hl:fs entry point
  380. /// that never errors: it answers a question, and "no" is an answer, not a
  381. /// failure. Same script-relative resolution as everything else. Without it the
  382. /// only way to test a path was to open it and survive the error — which is why
  383. /// the retired live_server used to index `static/` blind instead of probing it.
  384. export fn hl_fs_exists(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  385. if (argc < 1 or argv[0].type != .hl_string) return api.makeBool(false);
  386. const path_str = argv[0].data.string;
  387. const path = path_str.ptr[0..path_str.len];
  388. const resolved = resolvePath(path) orelse return api.makeBool(false);
  389. defer allocator.free(resolved);
  390. traceAccess('e', resolved);
  391. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeBool(false);
  392. defer allocator.free(path_z);
  393. // statx, not open: a directory, a symlink target, a device — anything the
  394. // OS can name — counts, and nothing is opened (no fd, no side effect).
  395. var statx_buf: std.os.linux.Statx = undefined;
  396. const rc = std.os.linux.statx(
  397. std.os.linux.AT.FDCWD,
  398. path_z,
  399. 0,
  400. std.os.linux.STATX.BASIC_STATS,
  401. &statx_buf,
  402. );
  403. return api.makeBool(@as(isize, @bitCast(rc)) == 0);
  404. }
  405. /// changeTime(path) → the path's last status change (ctime, which no write can set
  406. /// back) as milliseconds since the epoch, or null when it is not there (#195). The
  407. /// build cache asks it of everything a build read: an input changed after the build
  408. /// began (a file edited, a checkout, a file made or removed in a listed directory)
  409. /// makes what the build saw differ from what the record would say. Not traced.
  410. export fn hl_fs_change_time(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  411. if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();
  412. const path_str = argv[0].data.string;
  413. const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();
  414. defer allocator.free(resolved);
  415. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  416. defer allocator.free(path_z);
  417. var statx_buf: std.os.linux.Statx = undefined;
  418. const rc = std.os.linux.statx(
  419. std.os.linux.AT.FDCWD,
  420. path_z,
  421. 0,
  422. std.os.linux.STATX.BASIC_STATS,
  423. &statx_buf,
  424. );
  425. if (@as(isize, @bitCast(rc)) != 0) return api.makeNull();
  426. const sec: f64 = @floatFromInt(statx_buf.ctime.sec);
  427. const nsec: f64 = @floatFromInt(statx_buf.ctime.nsec);
  428. return api.makeNumber(sec * 1000.0 + nsec / 1000000.0);
  429. }
  430. /// stat(path) → { size, mtime, ctime, type } without opening or reading the file, or
  431. /// null when the path is not there (the way changeTime treats a missing path). `size`
  432. /// is in bytes; `mtime` and `ctime` are milliseconds since the epoch, the same form
  433. /// changeTime answers in; `type` is "file", "directory" or "other" (the words listDir
  434. /// uses). Symlinks are followed, so the answer describes what the link points at.
  435. /// Not traced (like changeTime, it reads no content).
  436. export fn hl_fs_stat(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  437. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.stat expects a string path");
  438. const path_str = argv[0].data.string;
  439. const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();
  440. defer allocator.free(resolved);
  441. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  442. defer allocator.free(path_z);
  443. var sx: std.os.linux.Statx = undefined;
  444. const rc = std.os.linux.statx(std.os.linux.AT.FDCWD, path_z, 0, std.os.linux.STATX.BASIC_STATS, &sx);
  445. if (@as(isize, @bitCast(rc)) != 0) return api.makeNull();
  446. const fmt = sx.mode & std.os.linux.S.IFMT;
  447. const kind: []const u8 = if (fmt == std.os.linux.S.IFREG) "file" else if (fmt == std.os.linux.S.IFDIR) "directory" else "other";
  448. const m_ms: f64 = @as(f64, @floatFromInt(sx.mtime.sec)) * 1000.0 + @as(f64, @floatFromInt(sx.mtime.nsec)) / 1000000.0;
  449. const c_ms: f64 = @as(f64, @floatFromInt(sx.ctime.sec)) * 1000.0 + @as(f64, @floatFromInt(sx.ctime.nsec)) / 1000000.0;
  450. const field_count: usize = 4;
  451. const fields = allocator.alloc(HlField, field_count) catch return api.makeNull();
  452. fields[0] = .{ .key = hlStr("size"), .value = api.makeNumber(@floatFromInt(sx.size)) };
  453. fields[1] = .{ .key = hlStr("mtime"), .value = api.makeNumber(m_ms) };
  454. fields[2] = .{ .key = hlStr("ctime"), .value = api.makeNumber(c_ms) };
  455. fields[3] = .{ .key = hlStr("type"), .value = api.makeString(kind) };
  456. const obj = allocator.create(HlObject) catch return api.makeNull();
  457. obj.* = .{ .fields = fields.ptr, .field_count = field_count, .deinit_fn = &entryObjDeinit };
  458. return api.makeObject(obj);
  459. }
  460. /// readRange(path, offset, length) → at most `length` bytes starting at byte `offset`,
  461. /// as a string of raw bytes (the Hybriel side wraps it in Bytes). Only that range is
  462. /// read (pread), never the rest of the file. An offset at or past the end gives an empty
  463. /// result; a length running past the end gives the shorter rest. Offset and length must
  464. /// be whole numbers, zero or more; anything else is an error. A missing file is an error
  465. /// like readFile's.
  466. export fn hl_fs_read_range(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  467. if (argc < 3 or argv[0].type != .hl_string) return api.makeError("fs.readBytes expects a string path, an offset and a length");
  468. if (argv[1].type != .hl_number or argv[2].type != .hl_number) return api.makeError("fs.readBytes: offset and length must both be numbers (or both left out to read the whole file)");
  469. const off_f: f64 = argv[1].data.number;
  470. const len_f: f64 = argv[2].data.number;
  471. if (!(off_f >= 0) or !(len_f >= 0) or off_f != @floor(off_f) or len_f != @floor(len_f) or off_f > 9.0e15 or len_f > 9.0e15)
  472. return api.makeError("fs.readBytes: offset and length must be whole numbers, zero or more");
  473. const offset: u64 = @intFromFloat(off_f);
  474. const want: u64 = @intFromFloat(len_f);
  475. const path_str = argv[0].data.string;
  476. const path = path_str.ptr[0..path_str.len];
  477. const resolved = resolvePath(path) orelse return api.makeNull();
  478. defer allocator.free(resolved);
  479. traceAccess('r', resolved);
  480. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  481. defer allocator.free(path_z);
  482. const rc = linuxOpenRc(path_z, .{}, 0);
  483. if (rc < 0) return makeOpenError("fs.readBytes", path, @intCast(-rc));
  484. const fd: i32 = @intCast(rc);
  485. defer _ = linux.close(fd);
  486. // Never allocate more than the file can still give: a huge length on a small file is cheap.
  487. var cap: u64 = want;
  488. var sx: std.os.linux.Statx = undefined;
  489. const src = std.os.linux.statx(fd, "", std.os.linux.AT.EMPTY_PATH, std.os.linux.STATX.BASIC_STATS, &sx);
  490. if (@as(isize, @bitCast(src)) == 0 and (sx.mode & std.os.linux.S.IFMT) == std.os.linux.S.IFREG) {
  491. cap = if (offset >= sx.size) 0 else @min(want, sx.size - offset);
  492. }
  493. var content = std.array_list.Managed(u8).init(allocator);
  494. defer content.deinit();
  495. var buf: [65536]u8 = undefined;
  496. var got: u64 = 0;
  497. while (got < cap) {
  498. const chunk: usize = @intCast(@min(@as(u64, buf.len), cap - got));
  499. const n_read: isize = @bitCast(linux.pread(fd, &buf, chunk, @intCast(offset + got)));
  500. if (n_read == 0) break;
  501. if (n_read < 0) {
  502. const errno: usize = @intCast(-n_read);
  503. if (errno == @intFromEnum(linux.E.INTR)) continue;
  504. return makeReadError("fs.readBytes", path, errno);
  505. }
  506. content.appendSlice(buf[0..@intCast(n_read)]) catch return api.makeError("fs.readBytes: out of memory reading the range");
  507. got += @intCast(n_read);
  508. }
  509. const result_slice = content.toOwnedSlice() catch return api.makeNull();
  510. var result = api.makeString(result_slice);
  511. result.deinit_fn = &readFileDeinit;
  512. return result;
  513. }
  514. export fn hl_fs_read_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  515. return readWhole(argc, argv, false);
  516. }
  517. /// tryReadFile(path) → the file as a string, or null when the path is not
  518. /// there (ENOENT/ENOTDIR). Any other failure is an error as in readFile. For a
  519. /// file another process may delete between a probe and the read (a shared
  520. /// cache): the vanishing is an answer, not a fault.
  521. export fn hl_fs_try_read_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  522. return readWhole(argc, argv, true);
  523. }
  524. fn readWhole(argc: u32, argv: [*]const HlValue, absent_is_null: bool) HlValue {
  525. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.readFile expects a string path");
  526. const path_str = argv[0].data.string;
  527. const path = path_str.ptr[0..path_str.len];
  528. const resolved = resolvePath(path) orelse return api.makeNull();
  529. defer allocator.free(resolved);
  530. traceAccess('r', resolved);
  531. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  532. defer allocator.free(path_z);
  533. const rc = linuxOpenRc(path_z, .{}, 0);
  534. if (rc < 0) {
  535. const en: usize = @intCast(-rc);
  536. if (absent_is_null and (en == @intFromEnum(linux.E.NOENT) or en == @intFromEnum(linux.E.NOTDIR))) return api.makeNull();
  537. return makeOpenError("fs.readFile", path, en);
  538. }
  539. const fd: i32 = @intCast(rc);
  540. defer _ = linux.close(fd);
  541. // The whole file: no size cap (a 10 MiB cap once truncated silently, ticket #112).
  542. // A failed read is an error naming the path, never a short string.
  543. var content = std.array_list.Managed(u8).init(allocator);
  544. defer content.deinit();
  545. var buf: [65536]u8 = undefined;
  546. while (true) {
  547. const n_read: isize = @bitCast(linux.read(fd, &buf, buf.len));
  548. if (n_read == 0) break;
  549. if (n_read < 0) {
  550. const errno: usize = @intCast(-n_read);
  551. if (errno == @intFromEnum(linux.E.INTR)) continue;
  552. return makeReadError("fs.readFile", path, errno);
  553. }
  554. content.appendSlice(buf[0..@intCast(n_read)]) catch return api.makeError("fs.readFile: out of memory reading the file");
  555. }
  556. const result_slice = content.toOwnedSlice() catch return api.makeNull();
  557. var result = api.makeString(result_slice);
  558. result.deinit_fn = &readFileDeinit;
  559. return result;
  560. }
  561. // =========================================================================
  562. // hl_fs_list_dir — streaming directory iterator with metadata
  563. // =========================================================================
  564. const DirIterState = struct {
  565. fd: i32,
  566. base_path: []const u8,
  567. allocated_strings: std.array_list.Managed([]u8),
  568. // fd403: the WHOLE getdents64 output, read when listDir() is called, so the directory fd
  569. // is closed at once. A for-of that ends with break/return never finalizes its iterator
  570. // before the GC runs, and the compiler's own pathKind() returns from inside one: 1000+
  571. // directory fds open at the tracker's boot (docker nofile 1024). Stat is lazy, by path.
  572. raw: std.array_list.Managed(u8),
  573. dir_resolved: []u8,
  574. dents_pos: usize,
  575. dents_len: usize,
  576. done: bool,
  577. };
  578. export fn hl_fs_list_dir(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  579. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.listDir expects a string path");
  580. const path_str = argv[0].data.string;
  581. const path = path_str.ptr[0..path_str.len];
  582. const resolved = resolvePath(path) orelse return api.makeNull();
  583. defer allocator.free(resolved);
  584. traceAccess('l', resolved);
  585. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  586. defer allocator.free(path_z);
  587. const rc = linuxOpenRc(path_z, .{ .DIRECTORY = true }, 0);
  588. if (rc < 0) return makeOpenError("fs.listDir", path, @intCast(-rc));
  589. const fd: i32 = @intCast(rc);
  590. const path_copy = allocator.dupe(u8, path) catch {
  591. _ = linux.close(fd);
  592. return api.makeNull();
  593. };
  594. var raw = std.array_list.Managed(u8).init(allocator);
  595. var chunk: [4096]u8 align(8) = undefined;
  596. while (true) {
  597. const got = std.os.linux.getdents64(fd, &chunk, chunk.len);
  598. if (@as(isize, @bitCast(got)) <= 0) break;
  599. raw.appendSlice(chunk[0..got]) catch break;
  600. }
  601. _ = linux.close(fd);
  602. const state = allocator.create(DirIterState) catch return api.makeNull();
  603. state.* = .{
  604. .fd = -1,
  605. .base_path = path_copy,
  606. .allocated_strings = std.array_list.Managed([]u8).init(allocator),
  607. .raw = raw,
  608. .dir_resolved = allocator.dupe(u8, resolved) catch @constCast(""),
  609. .dents_pos = 0,
  610. .dents_len = raw.items.len,
  611. .done = false,
  612. };
  613. const iter = allocator.create(HlIterator) catch return api.makeNull();
  614. iter.* = .{
  615. .context = @ptrCast(state),
  616. .next_fn = &dirIterNext,
  617. .deinit_fn = &dirIterDeinit,
  618. };
  619. return api.makeIterator(iter);
  620. }
  621. fn dirIterNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  622. const state: *DirIterState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  623. if (state.done) return api.makeNull();
  624. while (true) {
  625. // Need more directory entries?
  626. if (state.dents_pos >= state.dents_len) {
  627. state.done = true;
  628. return api.makeNull();
  629. }
  630. // Parse next dirent64
  631. const entry_ptr: *align(1) std.os.linux.dirent64 = @ptrCast(&state.raw.items[state.dents_pos]);
  632. state.dents_pos += entry_ptr.reclen;
  633. // Get name
  634. const name_ptr: [*]const u8 = @ptrCast(&entry_ptr.name);
  635. const name_len = std.mem.indexOfScalar(u8, name_ptr[0..256], 0) orelse continue;
  636. const name = name_ptr[0..name_len];
  637. // Skip . and ..
  638. if (std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, "..")) continue;
  639. const name_copy = allocator.dupe(u8, name) catch return api.makeNull();
  640. state.allocated_strings.append(name_copy) catch return api.makeNull();
  641. // Build full path
  642. const full_path = std.fmt.allocPrint(allocator, "{s}/{s}", .{ state.base_path, name }) catch return api.makeNull();
  643. state.allocated_strings.append(full_path) catch return api.makeNull();
  644. // Entry type from d_type
  645. const kind_str: []const u8 = switch (entry_ptr.type) {
  646. std.os.linux.DT.DIR => "directory",
  647. std.os.linux.DT.REG => "file",
  648. std.os.linux.DT.LNK => "symlink",
  649. else => "other",
  650. };
  651. // Stat for size, chmod, uid, gid
  652. var size: f64 = 0;
  653. var chmod: f64 = 0;
  654. var e_uid: f64 = 0;
  655. var e_gid: f64 = 0;
  656. // null-terminate name for statx
  657. var name_z_buf: [256]u8 = undefined;
  658. if (name.len < name_z_buf.len) {
  659. @memcpy(name_z_buf[0..name.len], name);
  660. name_z_buf[name.len] = 0;
  661. var statx_buf: std.os.linux.Statx = undefined;
  662. var stat_path: [4096]u8 = undefined;
  663. const stat_z = std.fmt.bufPrintZ(&stat_path, "{s}/{s}", .{ state.dir_resolved, name }) catch null;
  664. const src = if (stat_z) |sz| std.os.linux.statx(
  665. std.os.linux.AT.FDCWD,
  666. sz.ptr,
  667. 0,
  668. std.os.linux.STATX.BASIC_STATS,
  669. &statx_buf,
  670. ) else @as(usize, 1);
  671. if (src == 0) {
  672. size = @floatFromInt(statx_buf.size);
  673. chmod = @floatFromInt(statx_buf.mode & 0o7777);
  674. e_uid = @floatFromInt(statx_buf.uid);
  675. e_gid = @floatFromInt(statx_buf.gid);
  676. }
  677. }
  678. const mime = mimeFromName(name_copy);
  679. // Build object: name, path, type, size, mime, chmod, user, group
  680. // The runtime's hlObjectToValue will call entryObjDeinit after conversion,
  681. // so these objects are freed immediately upon consumption.
  682. const field_count: usize = 8;
  683. const fields = allocator.alloc(HlField, field_count) catch return api.makeNull();
  684. fields[0] = .{ .key = hlStr("name"), .value = api.makeString(name_copy) };
  685. fields[1] = .{ .key = hlStr("path"), .value = api.makeString(full_path) };
  686. fields[2] = .{ .key = hlStr("type"), .value = api.makeString(kind_str) };
  687. fields[3] = .{ .key = hlStr("size"), .value = api.makeNumber(size) };
  688. fields[4] = .{ .key = hlStr("mime"), .value = api.makeString(mime) };
  689. fields[5] = .{ .key = hlStr("chmod"), .value = api.makeNumber(chmod) };
  690. fields[6] = .{ .key = hlStr("user"), .value = api.makeNumber(e_uid) };
  691. fields[7] = .{ .key = hlStr("group"), .value = api.makeNumber(e_gid) };
  692. const obj = allocator.create(HlObject) catch return api.makeNull();
  693. obj.* = .{
  694. .fields = fields.ptr,
  695. .field_count = field_count,
  696. .deinit_fn = &entryObjDeinit,
  697. };
  698. return api.makeObject(obj);
  699. }
  700. }
  701. fn entryObjDeinit(obj: *HlObject) callconv(.c) void {
  702. allocator.free(obj.fields[0..obj.field_count]);
  703. allocator.destroy(obj);
  704. }
  705. fn dirIterDeinit(ctx: ?*anyopaque) callconv(.c) void {
  706. const state: *DirIterState = @ptrCast(@alignCast(ctx orelse return));
  707. closeIterFd(state);
  708. state.raw.deinit();
  709. if (state.dir_resolved.len > 0) allocator.free(state.dir_resolved);
  710. for (state.allocated_strings.items) |s| {
  711. allocator.free(s);
  712. }
  713. state.allocated_strings.deinit();
  714. allocator.free(@constCast(state.base_path));
  715. allocator.destroy(state);
  716. }
  717. // =========================================================================
  718. // Helpers
  719. // =========================================================================
  720. /// Raw open: >= 0 is the fd, < 0 is -errno.
  721. fn linuxOpenRc(path_z: [*:0]const u8, flags: linux.O, mode: u32) isize {
  722. const rc = linux.open(path_z, flags, mode);
  723. return @bitCast(rc);
  724. }
  725. fn linuxRead(fd: i32, buf: []u8) ?usize {
  726. const rc = linux.read(fd, buf.ptr, buf.len);
  727. if (@as(isize, @bitCast(rc)) <= 0) return null;
  728. return rc;
  729. }
  730. fn hlStr(comptime s: []const u8) HlString {
  731. return .{ .ptr = s.ptr, .len = s.len };
  732. }
  733. fn mimeFromName(name: []const u8) []const u8 {
  734. const ext = if (std.mem.lastIndexOfScalar(u8, name, '.')) |dot|
  735. name[dot..]
  736. else
  737. return "application/octet-stream";
  738. if (std.mem.eql(u8, ext, ".txt")) return "text/plain";
  739. if (std.mem.eql(u8, ext, ".html") or std.mem.eql(u8, ext, ".htm")) return "text/html";
  740. if (std.mem.eql(u8, ext, ".css")) return "text/css";
  741. if (std.mem.eql(u8, ext, ".js")) return "text/javascript";
  742. if (std.mem.eql(u8, ext, ".json")) return "application/json";
  743. if (std.mem.eql(u8, ext, ".xml")) return "application/xml";
  744. if (std.mem.eql(u8, ext, ".png")) return "image/png";
  745. if (std.mem.eql(u8, ext, ".jpg") or std.mem.eql(u8, ext, ".jpeg")) return "image/jpeg";
  746. if (std.mem.eql(u8, ext, ".gif")) return "image/gif";
  747. if (std.mem.eql(u8, ext, ".svg")) return "image/svg+xml";
  748. if (std.mem.eql(u8, ext, ".pdf")) return "application/pdf";
  749. if (std.mem.eql(u8, ext, ".zip")) return "application/zip";
  750. if (std.mem.eql(u8, ext, ".gz")) return "application/gzip";
  751. if (std.mem.eql(u8, ext, ".mp3")) return "audio/mpeg";
  752. if (std.mem.eql(u8, ext, ".mp4")) return "video/mp4";
  753. if (std.mem.eql(u8, ext, ".wasm")) return "application/wasm";
  754. if (std.mem.eql(u8, ext, ".hl")) return "text/x-hybriel";
  755. if (std.mem.eql(u8, ext, ".md")) return "text/markdown";
  756. if (std.mem.eql(u8, ext, ".yml") or std.mem.eql(u8, ext, ".yaml")) return "text/yaml";
  757. if (std.mem.eql(u8, ext, ".toml")) return "application/toml";
  758. if (std.mem.eql(u8, ext, ".csv")) return "text/csv";
  759. if (std.mem.eql(u8, ext, ".ts")) return "text/typescript";
  760. if (std.mem.eql(u8, ext, ".c") or std.mem.eql(u8, ext, ".h")) return "text/x-c";
  761. if (std.mem.eql(u8, ext, ".zig")) return "text/x-zig";
  762. if (std.mem.eql(u8, ext, ".rs")) return "text/x-rust";
  763. if (std.mem.eql(u8, ext, ".py")) return "text/x-python";
  764. if (std.mem.eql(u8, ext, ".sh")) return "text/x-shellscript";
  765. if (std.mem.eql(u8, ext, ".sql")) return "application/sql";
  766. if (std.mem.eql(u8, ext, ".webp")) return "image/webp";
  767. if (std.mem.eql(u8, ext, ".ico")) return "image/x-icon";
  768. if (std.mem.eql(u8, ext, ".woff2")) return "font/woff2";
  769. if (std.mem.eql(u8, ext, ".woff")) return "font/woff";
  770. if (std.mem.eql(u8, ext, ".ttf")) return "font/ttf";
  771. return "application/octet-stream";
  772. }
  773. // ── fs.watch: an inotify LOOP SOURCE (the dev-reload bell) ───────────────────
  774. // `watch(path)` returns an event-loop source whose wake_fd IS the inotify fd,
  775. // so the loop's own epoll_wait wakes on a save — no polling anywhere. Watches
  776. // the directory RECURSIVELY at registration (dot-dirs skipped); directories
  777. // created afterwards are picked up the next time the app is restarted, which
  778. // is the honest v1 for a dev tool.
  779. //
  780. // EXCLUSIONS (mission 266). `watch(path, exclude)` takes a second argument —
  781. // a path STRING or a LIST of them, the same either-shape the plugin surface
  782. // already uses in `hl_proc_spawn` — naming directories the descent must not
  783. // enter. One argument still means "watch everything": the argument is optional
  784. // and a null is the same as absent.
  785. //
  786. // This exists because a program that knows, at startup, about a directory it
  787. // will write to constantly (hl:web's session store is the first) had NO way to
  788. // say so. The only skip the walker possessed was "the name starts with a dot",
  789. // so the framework's advice was to RENAME the directory — a lecture standing
  790. // in for a fix. The dot-dir skip STAYS; `.git` is its reason and it is a good
  791. // one. This is a second, explicit reason to skip, not a replacement.
  792. const WatchState = struct {
  793. ifd: i32,
  794. buf: [4096]u8 align(4) = undefined,
  795. len: usize = 0,
  796. pos: usize = 0,
  797. };
  798. /// LEXICAL path normalisation — collapses `//` and resolves `.` / `..`
  799. /// without touching the filesystem. It must be lexical: an excluded directory
  800. /// need not exist yet at the moment the watch is armed (hl:web resolves its
  801. /// session dir before it creates it), and realpath(2) on a missing path fails.
  802. /// Both the watch root and every exclusion go through this, so the comparison
  803. /// below is between two paths written the same way.
  804. fn normalizePath(path: []const u8) ?[]u8 {
  805. const absolute = path.len > 0 and path[0] == '/';
  806. var parts = std.ArrayListUnmanaged([]const u8).empty;
  807. defer parts.deinit(allocator);
  808. var it = std.mem.tokenizeScalar(u8, path, '/');
  809. while (it.next()) |seg| {
  810. if (std.mem.eql(u8, seg, ".")) continue;
  811. if (std.mem.eql(u8, seg, "..")) {
  812. if (parts.items.len > 0 and !std.mem.eql(u8, parts.items[parts.items.len - 1], "..")) {
  813. _ = parts.pop();
  814. continue;
  815. }
  816. if (absolute) continue; // ".." above "/" is "/"
  817. }
  818. parts.append(allocator, seg) catch return null;
  819. }
  820. var out = std.ArrayListUnmanaged(u8).empty;
  821. defer out.deinit(allocator);
  822. for (parts.items, 0..) |seg, i| {
  823. if (absolute or i > 0) out.append(allocator, '/') catch return null;
  824. out.appendSlice(allocator, seg) catch return null;
  825. }
  826. if (out.items.len == 0) out.appendSlice(allocator, if (absolute) "/" else ".") catch return null;
  827. return allocator.dupe(u8, out.items) catch null;
  828. }
  829. /// Is `child` the directory `root`, or somewhere under it? Both must already
  830. /// be normalised. A bare `startsWith` would call `/a/sessions-old` a child of
  831. /// `/a/sessions`, which is the whole reason this is a function: the byte after
  832. /// the prefix has to BE a separator.
  833. fn pathIsInside(child: []const u8, root: []const u8) bool {
  834. if (root.len == 0) return false;
  835. if (std.mem.eql(u8, child, root)) return true;
  836. if (child.len <= root.len) return false;
  837. if (!std.mem.startsWith(u8, child, root)) return false;
  838. if (root[root.len - 1] == '/') return true; // root is "/" itself
  839. return child[root.len] == '/';
  840. }
  841. fn addWatchesRecursive(ifd: i32, dir_path: []const u8, depth: u32, excludes: []const []const u8) void {
  842. if (depth > 8) return;
  843. // The SECOND reason to skip a directory (mission 266). `dir_path` is
  844. // normalised: the root was normalised before the first call and every
  845. // child below is that root plus one plain name.
  846. for (excludes) |ex| if (pathIsInside(dir_path, ex)) return;
  847. const path_z = allocator.dupeZ(u8, dir_path) catch return;
  848. defer allocator.free(path_z);
  849. const mask: u32 = linux.IN.CLOSE_WRITE | linux.IN.CREATE | linux.IN.DELETE | linux.IN.MOVED_TO | linux.IN.MOVED_FROM;
  850. _ = linux.inotify_add_watch(ifd, path_z, mask);
  851. // The descent walks getdents64 directly, like hl_fs_list_dir does — this
  852. // plugin speaks raw syscalls throughout and never pulls in std.fs.
  853. const rc = linuxOpenRc(path_z, .{ .DIRECTORY = true }, 0);
  854. if (rc < 0) return;
  855. const fd: i32 = @intCast(rc);
  856. defer _ = linux.close(fd);
  857. var dents: [4096]u8 align(8) = undefined;
  858. while (true) {
  859. const got = linux.getdents64(fd, &dents, dents.len);
  860. if (@as(isize, @bitCast(got)) <= 0) break;
  861. var pos: usize = 0;
  862. while (pos < got) {
  863. const entry: *align(1) linux.dirent64 = @ptrCast(&dents[pos]);
  864. pos += entry.reclen;
  865. if (entry.type != linux.DT.DIR) continue;
  866. const name_ptr: [*]const u8 = @ptrCast(&entry.name);
  867. const name_len = std.mem.indexOfScalar(u8, name_ptr[0..256], 0) orelse continue;
  868. const name = name_ptr[0..name_len];
  869. // "." and ".." would recurse forever; every other dot-dir is noise
  870. // for a dev watcher (.git alone would cost thousands of watches).
  871. if (name.len == 0 or name[0] == '.') continue;
  872. const child = std.fmt.allocPrint(allocator, "{s}/{s}", .{ dir_path, name }) catch continue;
  873. defer allocator.free(child);
  874. addWatchesRecursive(ifd, child, depth + 1, excludes);
  875. }
  876. }
  877. }
  878. /// One exclusion, resolved against the script dir like every other hl:fs path
  879. /// and then normalised. Appends nothing on an empty string.
  880. fn appendExclusion(list: *std.ArrayListUnmanaged([]u8), raw: []const u8) bool {
  881. if (raw.len == 0) return true;
  882. const resolved = resolvePath(raw) orelse return false;
  883. defer allocator.free(resolved);
  884. const norm = normalizePath(resolved) orelse return false;
  885. list.append(allocator, norm) catch {
  886. allocator.free(norm);
  887. return false;
  888. };
  889. return true;
  890. }
  891. export fn hl_fs_watch(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  892. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("hl:fs: watch(path) needs a path string");
  893. const raw = argv[0].data.string.ptr[0..argv[0].data.string.len];
  894. const resolved = resolvePath(raw) orelse return api.makeError("hl:fs: watch: could not resolve the path");
  895. defer allocator.free(resolved);
  896. const path = normalizePath(resolved) orelse return api.makeError("hl:fs: watch: could not resolve the path");
  897. defer allocator.free(path);
  898. // THE OPTIONAL SECOND ARGUMENT: absent or null → watch everything, exactly
  899. // as before. A string is one directory; an object with numeric keys is the
  900. // loader's list shape (`hl_proc_spawn` reads its argv list the same way).
  901. var excludes = std.ArrayListUnmanaged([]u8).empty;
  902. defer {
  903. for (excludes.items) |e| allocator.free(e);
  904. excludes.deinit(allocator);
  905. }
  906. if (argc >= 2) {
  907. switch (argv[1].type) {
  908. .hl_null => {},
  909. .hl_string => {
  910. const sv = argv[1].data.string;
  911. if (!appendExclusion(&excludes, sv.ptr[0..sv.len])) return api.makeError("hl:fs: out of memory");
  912. },
  913. .hl_object => {
  914. const obj_in = argv[1].data.object;
  915. for (obj_in.fields[0..obj_in.field_count]) |field| {
  916. if (field.value.type == .hl_null) continue;
  917. if (field.value.type != .hl_string) return api.makeError("hl:fs: watch(path, exclude): every exclusion must be a path string");
  918. const sv = field.value.data.string;
  919. if (!appendExclusion(&excludes, sv.ptr[0..sv.len])) return api.makeError("hl:fs: out of memory");
  920. }
  921. },
  922. else => return api.makeError("hl:fs: watch(path, exclude): exclude is a path string or a list of path strings"),
  923. }
  924. }
  925. const rc = linux.inotify_init1(linux.IN.NONBLOCK);
  926. const ifd: i32 = @intCast(@as(isize, @bitCast(rc)));
  927. if (ifd < 0) return api.makeError("hl:fs: watch: inotify unavailable");
  928. addWatchesRecursive(ifd, path, 0, excludes.items);
  929. const state = allocator.create(WatchState) catch return api.makeError("hl:fs: out of memory");
  930. state.* = .{ .ifd = ifd };
  931. const iter = allocator.create(HlIterator) catch return api.makeError("hl:fs: out of memory");
  932. iter.* = .{
  933. .context = @ptrCast(state),
  934. .next_fn = &watchTryNext, // non-blocking either way — event loop only
  935. .try_next_fn = &watchTryNext,
  936. .deinit_fn = &watchDeinit,
  937. .wake_fd = ifd,
  938. };
  939. return api.makeIterator(iter);
  940. }
  941. fn watchTryNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  942. const st: *WatchState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  943. if (st.pos >= st.len) {
  944. const r = linux.read(st.ifd, &st.buf, st.buf.len);
  945. const n: isize = @bitCast(r);
  946. if (n <= 0) return api.makeNull(); // EAGAIN: drained
  947. st.len = @intCast(n);
  948. st.pos = 0;
  949. }
  950. // one inotify_event: wd(i32) mask(u32) cookie(u32) len(u32) name[len]
  951. const base = st.pos;
  952. if (st.len - base < 16) {
  953. st.pos = st.len;
  954. return api.makeNull();
  955. }
  956. const name_len = std.mem.readInt(u32, st.buf[base + 12 ..][0..4], .little);
  957. const name_start = base + 16;
  958. var name: []const u8 = "";
  959. if (name_len > 0 and name_start + name_len <= st.len) {
  960. const raw_name = st.buf[name_start .. name_start + name_len];
  961. name = std.mem.sliceTo(raw_name, 0);
  962. }
  963. st.pos = name_start + name_len;
  964. const fields = allocator.alloc(api.HlField, 1) catch return api.makeNull();
  965. const name_copy = allocator.dupe(u8, name) catch {
  966. allocator.free(fields);
  967. return api.makeNull();
  968. };
  969. fields[0] = .{ .key = hlStr("name"), .value = api.makeString(name_copy) };
  970. const obj = allocator.create(api.HlObject) catch {
  971. allocator.free(name_copy);
  972. allocator.free(fields);
  973. return api.makeNull();
  974. };
  975. obj.* = .{ .fields = fields.ptr, .field_count = 1, .deinit_fn = &watchEventDeinit };
  976. return api.makeObject(obj);
  977. }
  978. /// An event is the loader's to copy and ours to free (the emit soak, 2026-10-02): with
  979. /// no deinit, every inotify event of the dev watcher — each write a db makes under the
  980. /// watched root — kept its name, its field and its object for good.
  981. fn watchEventDeinit(obj: *api.HlObject) callconv(.c) void {
  982. const sv = obj.fields[0].value.data.string;
  983. allocator.free(@constCast(sv.ptr)[0..sv.len]);
  984. allocator.free(obj.fields[0..obj.field_count]);
  985. allocator.destroy(obj);
  986. }
  987. fn watchDeinit(ctx: ?*anyopaque) callconv(.c) void {
  988. const st: *WatchState = @ptrCast(@alignCast(ctx orelse return));
  989. _ = linux.close(st.ifd);
  990. allocator.destroy(st);
  991. }
  992. // =========================================================================
  993. // THE WRITE SURFACE (2026-08-28)
  994. //
  995. // hl:fs was READ-ONLY until this block: file, readFile, listDir, exists,
  996. // watch. It could report a file's `chmod` and never set one. Session
  997. // persistence is the first thing in this tree that has to put bytes on a
  998. // disk, and the rule when the framework can do something the language
  999. // cannot is that the LANGUAGE is missing it — so the capability lands here,
  1000. // as an ordinary hl:fs surface any program can use, not as a private hook
  1001. // the session store reaches through.
  1002. //
  1003. // Three calls, and the shape of each is a decision:
  1004. //
  1005. // writeFile(path, contents, mode?) ATOMIC. Writes a sibling temp file,
  1006. // fsyncs it, then rename()s it over the target — so a reader sees
  1007. // either the whole previous file or the whole new one, never a torn
  1008. // one. A half-written session file that revives as garbage is a
  1009. // silent logout, and the crash that produces it is exactly the crash
  1010. // nobody can reproduce. rename(2) within one directory is atomic on
  1011. // every filesystem Linux ships; that is the whole reason the temp
  1012. // file is a SIBLING rather than in /tmp (a cross-device rename fails).
  1013. // mkDir(path, mode?) recursive, and succeeds when the
  1014. // directory is already there — the caller wants it to exist, not to
  1015. // be the one who created it.
  1016. // remove(path) IDEMPOTENT: true when the path is
  1017. // gone on return, including when it was already gone. A sweep
  1018. // deleting an expired file must not fail because something else
  1019. // deleted it first.
  1020. //
  1021. // MODES ARE EXPLICIT AND DEFAULT TIGHT. hybrilior passes no mode anywhere,
  1022. // so its session files land at whatever the umask says — 0644 on a shared
  1023. // box, i.e. every session on the machine readable by every other tenant.
  1024. // Here the default is 0600 for a file and 0700 for a directory, and a
  1025. // caller who wants them looser has to say so. This is not the kind of bug
  1026. // that shows up in a test; it shows up in someone else's logs.
  1027. // =========================================================================
  1028. fn makeWriteError(op: []const u8, path: []const u8, errno: usize) api.HlValue {
  1029. const msg = std.fmt.allocPrint(allocator, "{s}: cannot write '{s}' — {s} (errno {d}); {s}", .{ op, path, errnoText(errno), errno, errnoHint(errno) }) catch
  1030. return api.makeError("fs: write failed");
  1031. var v = api.makeError(msg);
  1032. v.deinit_fn = &errDeinit;
  1033. return v;
  1034. }
  1035. /// mkdir every missing component of `path`. Returns 0, or the errno of the
  1036. /// first component that could not be created for a reason other than "it is
  1037. /// already there".
  1038. fn mkdirRecursive(path: []const u8, mode: u32) usize {
  1039. if (path.len == 0) return 0;
  1040. const buf = allocator.dupeZ(u8, path) catch return 12; // ENOMEM
  1041. defer allocator.free(buf);
  1042. // Walk the separators left to right, creating each prefix in turn. Index
  1043. // 0 is skipped so a leading '/' is never itself a component to create.
  1044. var i: usize = 1;
  1045. while (i <= buf.len) : (i += 1) {
  1046. const at_end = i == buf.len;
  1047. if (!at_end and buf[i] != '/') continue;
  1048. if (!at_end) buf[i] = 0;
  1049. const rc: isize = @bitCast(linux.mkdir(buf.ptr, mode));
  1050. if (!at_end) buf[i] = '/';
  1051. if (rc < 0) {
  1052. const errno: usize = @intCast(-rc);
  1053. // EEXIST is the success case: the caller wants it to exist.
  1054. if (errno != 17) return errno;
  1055. }
  1056. }
  1057. return 0;
  1058. }
  1059. export fn hl_fs_mk_dir(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1060. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.mkDir expects a string path");
  1061. const path_str = argv[0].data.string;
  1062. const path = path_str.ptr[0..path_str.len];
  1063. var mode: u32 = 0o700;
  1064. if (argc >= 2 and argv[1].type == .hl_number) mode = @intFromFloat(argv[1].data.number);
  1065. const resolved = resolvePath(path) orelse return api.makeError("fs.mkDir: out of memory");
  1066. defer allocator.free(resolved);
  1067. const errno = mkdirRecursive(resolved, mode);
  1068. if (errno != 0) return makeWriteError("fs.mkDir", path, errno);
  1069. return api.makeBool(true);
  1070. }
  1071. const write_usage = "fs.writeFile expects (String path, String or Bytes contents, Number mode?)";
  1072. export fn hl_fs_write_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1073. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1074. return api.makeError(write_usage);
  1075. }
  1076. const path_str = argv[0].data.string;
  1077. const body_str = argv[1].data.string;
  1078. return writeWhole(path_str.ptr[0..path_str.len], body_str.ptr[0..body_str.len], modeArg(argc, argv));
  1079. }
  1080. /// hl_fs_write_file_hex(path, hex, mode?) — writeFile with a Bytes (ticket
  1081. /// #88): a Bytes crosses the plugin boundary as its hex text (the ABI has no
  1082. /// Bytes, as hl:proc's write_hex says), is decoded here and written raw.
  1083. export fn hl_fs_write_file_hex(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1084. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1085. return api.makeError(write_usage);
  1086. }
  1087. const path_str = argv[0].data.string;
  1088. const hex = argv[1].data.string.ptr[0..argv[1].data.string.len];
  1089. const raw = allocator.alloc(u8, hex.len / 2) catch return api.makeError("fs.writeFile: out of memory");
  1090. defer allocator.free(raw);
  1091. _ = std.fmt.hexToBytes(raw, hex) catch return api.makeError("fs.writeFile: not a Bytes");
  1092. return writeWhole(path_str.ptr[0..path_str.len], raw, modeArg(argc, argv));
  1093. }
  1094. fn modeArg(argc: u32, argv: [*]const HlValue) u32 {
  1095. if (argc >= 3 and argv[2].type == .hl_number) return @intFromFloat(argv[2].data.number);
  1096. return 0o600;
  1097. }
  1098. fn writeWhole(path: []const u8, body: []const u8, mode: u32) HlValue {
  1099. const resolved = resolvePath(path) orelse return api.makeError("fs.writeFile: out of memory");
  1100. defer allocator.free(resolved);
  1101. // The temp name is a SIBLING (see the block comment): rename(2) is only
  1102. // atomic within one filesystem, and /tmp is routinely a different one.
  1103. // The pid keeps two processes writing the same path off each other's temp
  1104. // file; the rename itself settles who wins the target.
  1105. const pid = linux.getpid();
  1106. const tmp = std.fmt.allocPrintSentinel(allocator, "{s}.hltmp{d}", .{ resolved, pid }, 0) catch
  1107. return api.makeError("fs.writeFile: out of memory");
  1108. defer allocator.free(tmp);
  1109. const rc = linuxOpenRc(tmp.ptr, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, mode);
  1110. if (rc < 0) return makeWriteError("fs.writeFile", path, @intCast(-rc));
  1111. const fd: i32 = @intCast(rc);
  1112. var wrote: usize = 0;
  1113. while (wrote < body.len) {
  1114. const n: isize = @bitCast(linux.write(fd, body.ptr + wrote, body.len - wrote));
  1115. if (n <= 0) {
  1116. _ = linux.close(fd);
  1117. _ = linux.unlink(tmp.ptr);
  1118. return makeWriteError("fs.writeFile", path, if (n < 0) @intCast(-n) else 5);
  1119. }
  1120. wrote += @intCast(n);
  1121. }
  1122. // fsync BEFORE the rename, or the rename can land while the bytes are
  1123. // still only in the page cache — a power cut then leaves an EMPTY file
  1124. // where a complete one used to be, which is worse than either outcome.
  1125. _ = linux.fsync(fd);
  1126. _ = linux.close(fd);
  1127. // O_CREAT honours the mode only through the umask; say it outright so a
  1128. // 0600 request is 0600 whatever the process umask happens to be.
  1129. _ = linux.chmod(tmp.ptr, mode);
  1130. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.writeFile: out of memory");
  1131. defer allocator.free(path_z);
  1132. const ren: isize = @bitCast(linux.rename(tmp.ptr, path_z.ptr));
  1133. if (ren < 0) {
  1134. _ = linux.unlink(tmp.ptr);
  1135. return makeWriteError("fs.writeFile", path, @intCast(-ren));
  1136. }
  1137. return api.makeBool(true);
  1138. }
  1139. const append_usage = "fs.appendFile expects (String path, String or Bytes contents, Number mode?)";
  1140. export fn hl_fs_append_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1141. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1142. return api.makeError(append_usage);
  1143. }
  1144. const path_str = argv[0].data.string;
  1145. const body_str = argv[1].data.string;
  1146. return appendWhole(path_str.ptr[0..path_str.len], body_str.ptr[0..body_str.len], modeArg(argc, argv));
  1147. }
  1148. /// hl_fs_append_file_hex(path, hex, mode?) — appendFile with a Bytes (ticket
  1149. /// #88), the same hex-text crossing writeFile's hex sibling uses.
  1150. export fn hl_fs_append_file_hex(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1151. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1152. return api.makeError(append_usage);
  1153. }
  1154. const path_str = argv[0].data.string;
  1155. const hex = argv[1].data.string.ptr[0..argv[1].data.string.len];
  1156. const raw = allocator.alloc(u8, hex.len / 2) catch return api.makeError("fs.appendFile: out of memory");
  1157. defer allocator.free(raw);
  1158. _ = std.fmt.hexToBytes(raw, hex) catch return api.makeError("fs.appendFile: not a Bytes");
  1159. return appendWhole(path_str.ptr[0..path_str.len], raw, modeArg(argc, argv));
  1160. }
  1161. /// APPEND, NOT ATOMIC BY RENAME (writeFile's block comment above): an append
  1162. /// MUTATES the file that is already there, so there is no whole "old" or
  1163. /// "new" version to swap in — O_APPEND gives a narrower guarantee instead.
  1164. /// The kernel positions a single write() at the file's CURRENT end and
  1165. /// performs it as one operation, so two processes each appending a line never
  1166. /// interleave their bytes mid-line and a reader never sees a torn append —
  1167. /// which is why this is ONE write() of the whole body where writeFile's is
  1168. /// (short-write retries aside). The file is created at `mode` (default 0600,
  1169. /// same default as writeFile) if it is not there yet; O_APPEND on an existing
  1170. /// file leaves its mode untouched, same as any other open of it.
  1171. fn appendWhole(path: []const u8, body: []const u8, mode: u32) HlValue {
  1172. const resolved = resolvePath(path) orelse return api.makeError("fs.appendFile: out of memory");
  1173. defer allocator.free(resolved);
  1174. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.appendFile: out of memory");
  1175. defer allocator.free(path_z);
  1176. const rc = linuxOpenRc(path_z.ptr, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true }, mode);
  1177. if (rc < 0) return makeWriteError("fs.appendFile", path, @intCast(-rc));
  1178. const fd: i32 = @intCast(rc);
  1179. defer _ = linux.close(fd);
  1180. var wrote: usize = 0;
  1181. while (wrote < body.len) {
  1182. const n: isize = @bitCast(linux.write(fd, body.ptr + wrote, body.len - wrote));
  1183. if (n <= 0) {
  1184. return makeWriteError("fs.appendFile", path, if (n < 0) @intCast(-n) else 5);
  1185. }
  1186. wrote += @intCast(n);
  1187. }
  1188. return api.makeBool(true);
  1189. }
  1190. export fn hl_fs_remove(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1191. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.remove expects a string path");
  1192. const path_str = argv[0].data.string;
  1193. const path = path_str.ptr[0..path_str.len];
  1194. const resolved = resolvePath(path) orelse return api.makeError("fs.remove: out of memory");
  1195. defer allocator.free(resolved);
  1196. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.remove: out of memory");
  1197. defer allocator.free(path_z);
  1198. var rc: isize = @bitCast(linux.unlink(path_z.ptr));
  1199. // an empty directory goes too (EISDIR): hybriel.hl's scratch directories
  1200. // (mission 326 rung 12), with no `rmdir` to shell out to
  1201. if (rc == -21) rc = @bitCast(linux.rmdir(path_z.ptr));
  1202. if (rc < 0) {
  1203. const errno: usize = @intCast(-rc);
  1204. // ENOENT is success: the caller asked for the path to be gone.
  1205. if (errno == 2) return api.makeBool(true);
  1206. return makeWriteError("fs.remove", path, errno);
  1207. }
  1208. return api.makeBool(true);
  1209. }
  1210. /// realPath(path) → the canonical absolute path (symlinks resolved, `.`/`..`
  1211. /// folded; realpath(3)), or null when the path is not there or cannot be
  1212. /// resolved. `/proc/self/exe` answers the running binary without a shell.
  1213. export fn hl_fs_real_path(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1214. if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();
  1215. const path_str = argv[0].data.string;
  1216. const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();
  1217. defer allocator.free(resolved);
  1218. traceAccess('e', resolved);
  1219. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  1220. defer allocator.free(path_z);
  1221. var buf: [std.posix.PATH_MAX]u8 = undefined;
  1222. const out = std.c.realpath(path_z.ptr, &buf) orelse return api.makeNull();
  1223. const text = allocator.dupe(u8, std.mem.span(out)) catch return api.makeNull();
  1224. var result = api.makeString(text);
  1225. result.deinit_fn = &readFileDeinit;
  1226. return result;
  1227. }

Branches

Latest commits

  • 0ee5a6f2Tickets conductor: T36 resumedmre
  • 9149c165Tickets conductor: T36 diagnosismre
  • 91713313Tickets conductor: T36 report 1mre
  • 756315d2Tickets conductor: T36 startedmre
  • 0814ce6bTickets conductor: brief 025 tickets#36 style formmre
  • 1b6916c4Tickets conductor: Atlas handover tickets#36mre
  • aab95226Tickets conductor: worldapi-conductor paths, deploy blocker = read-only diskmre
  • 6372b06dTickets conductor: worker port slotmre
  • 836af31cTickets conductor: token pathsmre
  • b03f11b6Tickets conductor: CONDUCTOR.md (project part), short STATUS.md, old STATUS to archive/2026-10-31mre
  • a4123831tickets#42: the /connect and /login/callback error pages are app pages: the function routes redirect to /connect/failed/<code> and /login/failed/<code> (components/problem.hl, sentences in lib/problems.hl), htmlPage and its hand-written stylesheet are gone; gate tests/error-pages.mjsmre
  • cefc7b4atickets: a startup error prints its message before exit 1 (hybriel#247)mre
  • 99bd6570tickets: lib/migrate.hl writes no table of another topic any more: projects.hl rewriteSlug / addProjectNamed / hasMembers, tickets.hl moveToProject / ticketRecords / ticketRecordsOf, events.hl renameStates / eventRecords / eventRecordsOf; the migration calls them (tickets#47)mre
  • b57161e3tickets: the markup names its own rules (Style.pMessage, Style.olTickets, ...) instead of hand-written class strings that copy a stylesheet rule; the shared bodies sit in lib/looks.hl (tickets#38)mre
  • f767b24dtickets: 111 needless let became plain declarations (3 in ticket.hl, ticket_list.hl, comments.hl and 108 never-reassigned, not captured loop-body ones); the 212 really reassigned lets stay (tickets#44)mre
  • 16c0d3b5tickets: the modal window is phone first: the full-screen sheet is the base rule, the centred window sits in the min-width 60rem block (tickets#39)mre
  • 090ee809tickets: every component's styles in its own nested Style {} block; styles.hl keeps only the theme inherit, the accent and the site-wide rules (tickets#36)mre
  • d395763ftickets: ident-access gate ports 8769/8768 (8797 is taken on loreana)mre
  • afb9a403tickets: an ident access key (Authorization: Bearer idt_…) works in the API (ident#27 app side): lib/ident-access.hl copied from components, read keys GET only, ident down 503; gate tests/ident-access-tickets.mjsmre
  • 48c1ba79tickets: md-paste-files gate with the file manager casesmre