gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitad529ac1ad529ac1log: m572 verdictmread529ac1/plugins/fs/fs.zig

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

Branches

Latest commits

  • ad529ac1log: m572 verdictmre
  • 1b37d404RV39 on hold: hybriel#308mre
  • f9127c68Revert "Merge branch 'rv39'"mre
  • cd39f3d3log: hybriel#308mre
  • 51341d6elog: RV39 deploy startedmre
  • c9e29e06Merge branch 'rv39'mre
  • 0f8d1fdclog: RV39 report, browser 387/2mre
  • 50249b0bRV39: reportmre
  • 10ed9581compose: HL_GC_STATS=1mre
  • 955da19bRV39: re-vendor Hybriel set day39 (source 51e921d7, bin 6b481aa7)mre
  • 64b8d1dclog: RV39 startedmre
  • 1f2df72amission RV39mre
  • 6c1936f9log+status: GC planmre
  • 2846a840log: m569 result, GC hypothesismre
  • b24cd2d5log: Anton on hl:fetch, mission 569mre
  • 7d42cac1log+status: SL1 measured, fetch stalls remainmre
  • 8e5f2ceflog: SL1 deployedmre
  • 29f34212log: SL1 deploy startedmre
  • 529dd741Merge sl1-slices: slice details repair and person fill (SL1)mre
  • 8a83316blog: SL1 result, session drain slowermre