summaryrefslogtreecommitdiff
path: root/web/catalog.zig
diff options
context:
space:
mode:
Diffstat (limited to 'web/catalog.zig')
-rw-r--r--web/catalog.zig91
1 files changed, 69 insertions, 22 deletions
diff --git a/web/catalog.zig b/web/catalog.zig
index 87349bb..d375973 100644
--- a/web/catalog.zig
+++ b/web/catalog.zig
@@ -17,7 +17,8 @@ pub const Site = struct {
title: []const u8,
cwd: []const u8,
root: []const u8,
- port: u16,
+ // Optional compatibility listener. New routes can share the gateway port.
+ port: ?u16 = null,
build: []const []const u8 = &.{},
watch: []const []const u8 = &.{},
// Poll only these source paths for a managed rebuild watcher.
@@ -57,6 +58,9 @@ pub const Catalog = struct {
runner: *Runner,
http_port: u16 = 0,
host_filesystem: bool = false,
+ export_host: bool = false,
+ namespace: []const u8 = "",
+ host_export: ?*Catalog = null,
files: [16][512]?Io.File = @splat(@splat(null)),
reads: [16][32]u64 = @splat(@splat(0)),
read_handles: [16][32]u32 = @splat(@splat(0)),
@@ -82,26 +86,40 @@ pub const Catalog = struct {
for (s.name) |ch| if (!std.ascii.isAlphanumeric(ch) and ch != '-' and ch != '_') return error.InvalidSiteName;
if (names.contains(s.name)) return error.DuplicateSite;
try names.put(s.name, {});
- for (parsed.value.sites[0..i]) |other| if (other.port == s.port) return error.DuplicatePort;
+ for (parsed.value.sites[0..i]) |other| if (s.port != null and other.port == s.port) return error.DuplicatePort;
for (s.inputs) |input| if (!std.fs.path.isAbsolute(input) and !safeRelative(input)) return error.InvalidWatchInput;
}
try Io.Dir.cwd().createDirPath(io, state_dir);
const cat = try A.create(Catalog);
cat.* = .{ .io = io, .sites = parsed.value.sites, .states = try A.alloc(State, parsed.value.sites.len), .state_dir = state_dir, .runner = try A.create(Runner) };
- cat.host_filesystem = parsed.value.filesystem != null;
+ cat.export_host = parsed.value.filesystem != null;
@memset(cat.states, .{});
try cat.nodes.append(A, "");
cat.runner.init(.{ .io = io, .root = 1, .handler = .{ .ctx = cat, .serve = serve, .closed = closed } });
return cat;
}
- pub fn start(cat: *Catalog, socket: [:0]const u8) !void {
- _ = try cat.runner.listen(.{ .unix = socket }, 16);
+ pub fn start(cat: *Catalog, socket: [:0]const u8, env: c9.post.Env, post_name: []const u8) !void {
+ if (cat.export_host) {
+ // Only the pure service is posted. The host adapter has its own
+ // runner, lock and fid/read tables, and NO supervision tasks.
+ cat.namespace = try std.fmt.allocPrint(A, "/mnt/9p/{s}", .{post_name});
+ try cat.runner.listenPosted(env, post_name, 16);
+ const host = try A.create(Catalog);
+ host.* = .{ .io = cat.io, .sites = &.{}, .states = &.{}, .state_dir = "", .runner = try A.create(Runner), .host_filesystem = true, .namespace = cat.namespace };
+ try host.nodes.append(A, "");
+ host.runner.init(.{ .io = cat.io, .root = 1, .handler = .{ .ctx = host, .serve = serve, .closed = closed } });
+ cat.host_export = host;
+ _ = try host.runner.listen(.{ .unix = socket }, 16);
+ } else {
+ _ = try cat.runner.listen(.{ .unix = socket }, 16);
+ }
try cat.group.concurrent(cat.io, discoverLoop, .{cat});
for (cat.sites, 0..) |_, i| try cat.group.concurrent(cat.io, siteLoop, .{ cat, i });
}
pub fn stop(cat: *Catalog) void {
+ if (cat.host_export) |host| host.stop();
cat.group.cancel(cat.io);
cat.runner.stop();
}
@@ -140,11 +158,14 @@ pub const Catalog = struct {
pub fn snapshot(cat: *Catalog, a: std.mem.Allocator) ![]const u8 {
cat.mutex.lockUncancelable(cat.io);
defer cat.mutex.unlock(cat.io);
- const Row = struct { name: []const u8, title: []const u8, root: []const u8, port: u16, build: bool, watch: bool, status: State };
+ return cat.snapshotLocked(a);
+ }
+ fn snapshotLocked(cat: *Catalog, a: std.mem.Allocator) ![]const u8 {
+ const Row = struct { name: []const u8, title: []const u8, root: []const u8, port: ?u16, build: bool, watch: bool, status: State };
const rows = try a.alloc(Row, cat.sites.len);
for (cat.sites, 0..) |s, i| rows[i] = .{ .name = s.name, .title = s.title, .root = s.root, .port = s.port, .build = s.build.len != 0, .watch = s.watch.len != 0 or s.inputs.len != 0, .status = cat.states[i] };
const listeners = try std.json.parseFromSlice(std.json.Value, a, cat.listeners, .{});
- return std.json.Stringify.valueAlloc(a, .{ .sites = rows, .listeners = listeners.value, .discovery_error = cat.discovery_error, .namespace = if (cat.host_filesystem) "/_9web" else "" }, .{});
+ return std.json.Stringify.valueAlloc(a, .{ .sites = rows, .listeners = listeners.value, .discovery_error = cat.discovery_error, .namespace = cat.namespace }, .{});
}
fn discoverLoop(cat: *Catalog) void {
@@ -155,7 +176,9 @@ pub const Catalog = struct {
const pid = std.fmt.allocPrint(a, "{d}", .{std.os.linux.getpid()}) catch return;
var ports: std.Io.Writer.Allocating = .init(a);
ports.writer.print("{d}", .{cat.http_port}) catch return;
- for (cat.sites) |site| ports.writer.print(",{d}", .{site.port}) catch return;
+ for (cat.sites) |site| if (site.port) |port| {
+ ports.writer.print(",{d}", .{port}) catch return;
+ };
const result = std.process.run(A, cat.io, .{ .argv = &.{ "python3", "-c", @embedFile("discover.py"), pid, ports.written() }, .stdout_limit = .limited(2 * 1024 * 1024), .stderr_limit = .limited(8192), .timeout = .{ .duration = .{ .raw = .fromSeconds(15), .clock = .awake } } }) catch |err| {
if (err == error.Canceled) return;
cat.mutex.lockUncancelable(cat.io);
@@ -320,8 +343,6 @@ pub const Catalog = struct {
}
fn virtualPath(cat: *Catalog, path: []const u8) ?[]const u8 {
if (!cat.host_filesystem) return path;
- if (std.mem.eql(u8, path, "_9web")) return "";
- if (std.mem.startsWith(u8, path, "_9web/")) return path[6..];
return null;
}
fn sitePath(cat: *Catalog, raw: []const u8) ?struct { i: usize, rest: []const u8 } {
@@ -373,6 +394,7 @@ pub const Catalog = struct {
fn content(cat: *Catalog, a: std.mem.Allocator, raw: []const u8) ![]const u8 {
const path = cat.virtualPath(raw) orelse return error.FileNotFound;
if (std.mem.eql(u8, path, "index.html")) return @embedFile("static/index.html");
+ if (std.mem.eql(u8, path, "index.json")) return cat.snapshotLocked(a);
if (std.mem.eql(u8, path, "listeners/index.json")) return cat.listeners;
if (std.mem.eql(u8, path, "services/index.json")) {
const parsed = try std.json.parseFromSlice([]std.json.Value, a, cat.listeners, .{});
@@ -399,7 +421,7 @@ pub const Catalog = struct {
fn children(cat: *Catalog, a: std.mem.Allocator, raw: []const u8) ![][]const u8 {
var names: std.ArrayList([]const u8) = .empty;
const path = cat.virtualPath(raw) orelse {
- var dir = try Io.Dir.cwd().openDir(cat.io, try hostPath(a, raw), .{ .iterate = true });
+ var dir = try Io.Dir.cwd().openDir(cat.io, try cat.hostPath(a, raw), .{ .iterate = true });
defer dir.close(cat.io);
var it = dir.iterate();
while (try it.next(cat.io)) |entry| try names.append(a, try a.dupe(u8, entry.name));
@@ -407,7 +429,7 @@ pub const Catalog = struct {
sortNames(names.items);
return names.items;
};
- if (path.len == 0) try names.appendSlice(a, &.{ "index.html", "sites", "services", "listeners" }) else if (std.mem.eql(u8, path, "sites")) {
+ if (path.len == 0) try names.appendSlice(a, &.{ "index.html", "index.json", "sites", "services", "listeners" }) else if (std.mem.eql(u8, path, "sites")) {
for (cat.sites) |s| try names.append(a, s.name);
} else if (std.mem.eql(u8, path, "services") or std.mem.eql(u8, path, "listeners")) try names.append(a, "index.json") else if (cat.sitePath(raw)) |p| {
if (p.rest.len == 0) try names.appendSlice(a, &.{ "public", "ctl", "status", "log", "events" }) else if (std.mem.eql(u8, p.rest, "public") or std.mem.startsWith(u8, p.rest, "public/")) {
@@ -548,12 +570,15 @@ pub const Catalog = struct {
};
conn.reply(&.{ .tag = tag, .status = .err, .ename = message }, "");
}
- fn hostPath(a: std.mem.Allocator, path: []const u8) ![]const u8 {
+ fn hostPath(cat: *Catalog, a: std.mem.Allocator, path: []const u8) ![]const u8 {
if (!safeRelative(path)) return error.AccessDenied;
+ // Compatibility alias is a namespace mapping, never a second service.
+ if (std.mem.eql(u8, path, "_9web")) return a.dupe(u8, cat.namespace);
+ if (std.mem.startsWith(u8, path, "_9web/")) return std.fmt.allocPrint(a, "{s}/{s}", .{ cat.namespace, path[6..] });
return std.fmt.allocPrint(a, "/{s}", .{path});
}
fn hostAttr(cat: *Catalog, a: std.mem.Allocator, path: []const u8) !fs.Attr {
- const full = try hostPath(a, path);
+ const full = try cat.hostPath(a, path);
const st = Io.Dir.cwd().statFile(cat.io, full, .{}) catch |err| blk: {
// Keep dangling symlinks visible; an attempt to open reports the error.
if (err != error.FileNotFound) return err;
@@ -572,7 +597,7 @@ pub const Catalog = struct {
fn hostOpen(cat: *Catalog, a: std.mem.Allocator, path: []const u8, mode: u8, truncate: bool) !Io.File {
// Pin the inode with O_PATH, inspect it without opening a device/FIFO,
// then reopen that exact inode. Symlinks and mount points are followed.
- const ref = try Io.Dir.cwd().openFile(cat.io, try hostPath(a, path), .{ .path_only = true });
+ const ref = try Io.Dir.cwd().openFile(cat.io, try cat.hostPath(a, path), .{ .path_only = true });
defer ref.close(cat.io);
const st = try ref.stat(cat.io);
if (st.kind != .file and st.kind != .directory) return error.SpecialFileNotSupported;
@@ -609,7 +634,7 @@ pub const Catalog = struct {
}
}
fn hostOperation(cat: *Catalog, a: std.mem.Allocator, conn: *Runner.Conn, req: fs.Req, path: []const u8, reply: *fs.Reply) !void {
- const full = try hostPath(a, path);
+ const full = try cat.hostPath(a, path);
switch (req.op) {
.open => {
var slot: usize = 0;
@@ -620,7 +645,7 @@ pub const Catalog = struct {
if (!safeName(req.data)) return error.AccessDenied;
next = try std.fs.path.join(a, &.{ path, req.data });
if (cat.virtualPath(next) != null) return error.PermissionDenied;
- const dest = try hostPath(a, next);
+ const dest = try cat.hostPath(a, next);
if (req.perm & c9.dmdir != 0) {
try Io.Dir.cwd().createDir(cat.io, dest, .fromMode(req.perm & 0o777));
break :blk try cat.hostOpen(a, next, req.omode, false);
@@ -659,7 +684,7 @@ pub const Catalog = struct {
errdefer if (!renamed) {
for (replacements.items) |r| A.free(r.name);
};
- try Io.Dir.cwd().renamePreserve(full, .cwd(), try hostPath(a, next), cat.io);
+ try Io.Dir.cwd().renamePreserve(full, .cwd(), try cat.hostPath(a, next), cat.io);
for (replacements.items) |r| {
A.free(cat.nodes.items[r.index]);
cat.nodes.items[r.index] = r.name;
@@ -706,7 +731,23 @@ pub const Catalog = struct {
.open => {
if (req.create) return error.PermissionDenied;
if ((req.omode & 3) != 0 and !std.mem.endsWith(u8, path, "/ctl")) return error.PermissionDenied;
- if (std.mem.endsWith(u8, path, "/events")) {
+ const site_path = cat.sitePath(path);
+ if (site_path) |p| if (std.mem.startsWith(u8, p.rest, "public/")) {
+ const f = try openBeneath(cat.io, cat.sites[p.i].root, p.rest[7..]);
+ errdefer f.close(cat.io);
+ const st = try f.stat(cat.io);
+ if (st.kind == .directory) {
+ f.close(cat.io);
+ } else {
+ if (st.kind != .file) return error.PermissionDenied;
+ var slot: usize = 0;
+ while (slot < 512 and cat.files[conn.index][slot] != null) : (slot += 1) {}
+ if (slot == 512) return error.TooManyOpenFiles;
+ cat.files[conn.index][slot] = f;
+ reply.handle = @intCast(slot + 1);
+ }
+ };
+ if (site_path != null and std.mem.eql(u8, site_path.?.rest, "events")) {
var found = false;
for (&cat.cursors[conn.index], 0..) |*cursor, ci| if (!cursor.used) {
cursor.* = .{ .used = true };
@@ -719,7 +760,13 @@ pub const Catalog = struct {
},
.release => {
if (req.remove) return error.PermissionDenied;
- if (req.opened and req.handle != 0) cat.cursors[conn.index][req.handle - 1].used = false;
+ if (req.opened and req.handle != 0) {
+ const p = cat.sitePath(path);
+ if (p != null and std.mem.startsWith(u8, p.?.rest, "public/")) {
+ if (cat.files[conn.index][req.handle - 1]) |f| f.close(cat.io);
+ cat.files[conn.index][req.handle - 1] = null;
+ } else cat.cursors[conn.index][req.handle - 1].used = false;
+ }
},
.write => unreachable,
.read => {
@@ -746,8 +793,8 @@ pub const Catalog = struct {
return;
}
if (std.mem.startsWith(u8, p.rest, "public/")) {
- const f = try openBeneath(cat.io, cat.sites[p.i].root, p.rest[7..]);
- defer f.close(cat.io);
+ if (req.handle == 0) return error.FileNotOpen;
+ const f = cat.files[conn.index][req.handle - 1] orelse return error.FileNotOpen;
const b = try a.alloc(u8, req.size);
bytes = b[0..try f.readPositionalAll(cat.io, b, req.off)];
conn.reply(&reply, bytes);