navid/veins / commit
12773c30368c
Navid M <navidmomtahen@gmail.com> · 2026-11-28
parents: c3f1d72b5216
Browse files at this commit · Download source
--- a/veins/src/cli/help_cmd.sx+++ b/veins/src/cli/help_cmd.sx@@ -440,10 +440,11 @@ } fn show_serve() void = trust {- stdio.puts("usage: vn serve -stdio <repo>")- stdio.puts(" vn serve -listen <addr:port> -root <dir> -tls-cert <file> -tls-key <file>")+ stdio.puts("usage: vn serve -stdio <repo> [-quota <bytes>]")+ stdio.puts(" vn serve -listen <addr:port> -root <dir> -tls-cert <file> -tls-key <file> [-quota <bytes>]") stdio.puts("") stdio.puts("run the native server over standard input/output or TLS 1.3")+ stdio.puts("-quota limits stored pack and index bytes per top-level namespace") } fn show_key() void = trust {--- a/veins/src/cli/serve_cmd.sx+++ b/veins/src/cli/serve_cmd.sx@@ -6,6 +6,23 @@ val layout = use("../store/layout.sx") val server = use("../server/serve.sx") val cmsg = use("../core/msg.sx")++fn parse_u64(text: bytes.Bytes) option[u64] = trust {+ if text.len == 0 {+ return none+ }+ val value: mut u64 = 0+ val i: mut usize = 0+ for i < text.len {+ val c: u8 = bytes.Bytes.at(text, i)+ if c < 48 || c > 57 {+ return none+ }+ value = value * 10 + (c - 48) as u64+ i+++ }+ return some value+} pub fn run(args: list[ref u8], start: usize) i32 = trust { val stdio_mode: mut bool = false@@ -14,6 +31,7 @@ val cert: mut bytes.Bytes = bytes.empty() val key: mut bytes.Bytes = bytes.empty() val repo_path: mut str.StringView = str.from_cstr(c".")+ val quota_bytes: mut u64 = 0 val i: mut usize = start for i < @len(args) { val o = @get(args, i)@@ -58,7 +76,30 @@ if v is some r { key = bytes.Bytes.dup(bytes.from_cstr(r)) i+++ }+ }+ } elif bytes.Bytes.eql(av, bytes.bytes(c"-quota", 6)) {+ val v = @get(args, i + 1)+ if v is some r {+ val parsed = parse_u64(bytes.from_cstr(r))+ if parsed is none {+ cmsg.error_prefix()+ stdio.eprint("-quota requires a byte count\n", {})+ return 1+ }+ match parsed {+ some n => {+ quota_bytes = n+ }+ none => {+ return 1+ } }+ i+++ } else {+ cmsg.error_prefix()+ stdio.eprint("-quota requires a byte count\n", {})+ return 1 } } else { cmsg.error_prefix()@@ -84,7 +125,7 @@ return 1 } }- return server.serve_stdio(repo)+ return server.serve_stdio(repo, quota_bytes) } if listen.ptr == none { cmsg.error_prefix()@@ -99,7 +140,7 @@ val root_repo: layout.Repo = layout.Repo{ root: bytes.Bytes.dup(bytes.bytes(root.ptr, root.len)) }- val code: i32 = server.serve_listen(listen, root_repo, cert, key)+ val code: i32 = server.serve_listen(listen, root_repo, cert, key, quota_bytes) layout.free_repo(root_repo) bytes.free_owned(listen) bytes.free_owned(cert)--- a/veins/src/git/import.sx+++ b/veins/src/git/import.sx@@ -1437,7 +1437,7 @@ @free(up) } - val wrote: bool = writer.finish(ctx.writer)+ val wrote: bool = writer.finish(ctx.writer) == 0 if !wrote { msg.error_prefix() stdio.eprint("failed to write object pack\n", {})--- a/veins/src/protocol/client.sx+++ b/veins/src/protocol/client.sx@@ -541,6 +541,12 @@ } if code == wire.ERR_AUTH_FAILED { return bytes.bytes(c"authentication failed", 21)+ }+ if code == wire.ERR_QUOTA {+ return bytes.bytes(c"storage quota exceeded", 23)+ }+ if code == wire.ERR_TOO_LARGE {+ return bytes.bytes(c"push too large", 14) } return bytes.bytes(c"unknown server error", 20) }@@ -789,7 +795,7 @@ writer.abort(w) return false }- return writer.finish(w)+ return writer.finish(w) == 0 } pub fn get_chunks(c: mut ref Client, repo: layout.Repo, ids: list[bytes.Bytes]) bool = trust {@@ -818,7 +824,7 @@ writer.abort(w) return false }- return writer.finish(w)+ return writer.finish(w) == 0 } pub fn have_query(c: mut ref Client, ids: list[bytes.Bytes]) option[list[u64]] = trust {--- a/veins/src/protocol/wire.sx+++ b/veins/src/protocol/wire.sx@@ -42,6 +42,8 @@ pub val ERR_UNAUTHENTICATED: u8 = 10 pub val ERR_FORBIDDEN: u8 = 11 pub val ERR_AUTH_FAILED: u8 = 12+pub val ERR_QUOTA: u8 = 13+pub val ERR_TOO_LARGE: u8 = 14 pub type Frame = { kind: mut u8--- /dev/null+++ b/veins/src/server/quota.sx@@ -0,0 +1,113 @@+/// Per-namespace storage accounting for `vn serve -quota`.++val fs = use("std/fs")+val str = use("std/string")+val time = use("std/time")+val bytes = use("../core/bytes.sx")+val files = use("../io/files.sx")++fn first_component(name: bytes.Bytes) bytes.Bytes = trust {+ val i: mut usize = 0+ for i < name.len {+ if bytes.Bytes.at(name, i) == 47 {+ return bytes.Bytes.slice(name, 0, i)+ }+ i+++ }+ return name+}++/// `root/<first path component of the repository name>`.+pub fn namespace_path(root: str.StringView, repo_name: bytes.Bytes) str.StringView = trust {+ val ns: bytes.Bytes = first_component(repo_name)+ return files.join(root, str.view(ns.ptr, ns.len as i64))+}++fn tree_size(dir: str.StringView) u64 = trust {+ val total: mut u64 = 0+ val names: list[ref u8] = files.list_dir(dir)+ for n in names {+ val child: str.StringView = files.join(dir, str.from_cstr(n))+ if files.exists_dir(child) {+ total = total + tree_size(child)+ } else {+ val size = fs.file_size(child)+ if size is some nbytes {+ if nbytes > 0 {+ total = total + nbytes as u64+ }+ }+ }+ files.free_path(child)+ }+ files.free_names(names)+ return total+}++fn repo_size(dir: str.StringView) u64 = trust {+ val packs: str.StringView = files.join(dir, str.from_cstr(c".veins/store/packs"))+ val total: mut u64 = 0+ if files.exists_dir(packs) {+ total = tree_size(packs)+ }+ files.free_path(packs)+ return total+}++/// Sum the persistent pack and index bytes for a repository or for every+/// immediate repository under a namespace directory.+pub fn used(dir: str.StringView) u64 = trust {+ if !files.exists_dir(dir) {+ return 0+ }+ val own: u64 = repo_size(dir)+ if own > 0 {+ return own+ }+ val total: mut u64 = 0+ val names: list[ref u8] = files.list_dir(dir)+ for n in names {+ val child: str.StringView = files.join(dir, str.from_cstr(n))+ if files.exists_dir(child) {+ total = total + repo_size(child)+ }+ files.free_path(child)+ }+ files.free_names(names)+ return total+}++test "storage usage sums namespace repositories" {+ trust {+ val base: str.StringView = str.from_cstr(fs.temp_dir_cstr())+ val name_c: ref u8 = @fmtalloc("veins-quota-{d}", {time.now_ns()})+ val name: str.StringView = str.from_cstr(name_c)+ val root: str.StringView = files.join(base, name)+ @free(name_c as ref void)+ assert files.mkdir_all(root)+ val owner: str.StringView = files.join(root, str.from_cstr(c"alice"))+ assert files.mkdir_all(owner)+ val repo: str.StringView = files.join(owner, str.from_cstr(c"repo"))+ assert files.mkdir_all(repo)+ val veins: str.StringView = files.join(repo, str.from_cstr(c".veins"))+ assert files.mkdir_all(veins)+ val store: str.StringView = files.join(veins, str.from_cstr(c"store"))+ assert files.mkdir_all(store)+ val packs: str.StringView = files.join(store, str.from_cstr(c"packs"))+ assert files.mkdir_all(packs)+ val pack: str.StringView = files.join(packs, str.from_cstr(c"a.vpack"))+ val index: str.StringView = files.join(packs, str.from_cstr(c"a.vidx"))+ assert files.write_all(pack, bytes.bytes(c"abc", 3))+ assert files.write_all(index, bytes.bytes(c"defgh", 5))+ assert used(owner) == 8+ files.free_path(index)+ files.free_path(pack)+ files.free_path(packs)+ files.free_path(store)+ files.free_path(veins)+ files.free_path(repo)+ files.free_path(owner)+ val _ = fs.remove_dir_all(root)+ files.free_path(root)+ }+}--- a/veins/src/server/serve.sx+++ b/veins/src/server/serve.sx@@ -37,8 +37,12 @@ val access = use("../auth/access.sx") val handshake = use("../auth/handshake.sx") val b3 = use("../crypto/blake3.sx")+val quota = use("quota.sx") val MAX_CHUNKS_PER_REQUEST: usize = 4096+val MAX_PUSH_RECORDS: usize = 100000+val QUOTA_RESERVE: u64 = 1048576+val DRAIN_BYTES: usize = 67108864 type Session = { s: mut stream.Stream@@ -57,6 +61,8 @@ public_key: mut bytes.Bytes fingerprint: mut bytes.Bytes haves: mut list[bytes.Bytes]+ quota_bytes: mut u64+ quota_dir: mut str.StringView failed_auth: mut i32 closing: mut bool }@@ -215,6 +221,10 @@ if found is some repo { s.repo = repo s.repo_present = true+ if s.quota_bytes > 0 {+ files.free_path(s.quota_dir)+ s.quota_dir = quota.namespace_path(layout.root_view(r), s.hello_repo)+ } } } }@@ -1005,6 +1015,38 @@ } files.free_buffer(body) return fine+}++fn drain_push(s: ref Session, max_bytes: usize) bool = trust {+ val seen: mut usize = 0+ for seen <= max_bytes {+ val nf = wire.read_frame(s.s)+ val fr: mut wire.Frame = wire.Frame{+ kind: 0,+ request_id: 0,+ payload: bytes.empty(),+ base: bytes.empty()+ }+ match nf {+ some x => {+ fr = x+ }+ none => {+ return false+ }+ }+ val kind: u8 = fr.kind+ val size: usize = fr.payload.len+ wire.free_frame(fr)+ if kind == wire.END {+ return true+ }+ if kind != wire.RECORDS {+ return false+ }+ seen = seen + size+ }+ return false } fn handle_put_records(s: mut ref Session, f: wire.Frame) bool = trust {@@ -1011,7 +1053,23 @@ if deny(s, f.request_id, true) { return true }- val w_opt = writer.open(s.repo)+ val limit: mut u64 = 0+ if s.quota_bytes > 0 {+ val used: u64 = quota.used(s.quota_dir)+ if used + QUOTA_RESERVE >= s.quota_bytes {+ if !drain_push(s, DRAIN_BYTES) {+ s.closing = true+ }+ return wire.write_error(+ s.s,+ f.request_id,+ wire.ERR_QUOTA,+ bytes.bytes(c"storage quota exceeded", 23)+ )+ }+ limit = s.quota_bytes - used - QUOTA_RESERVE+ }+ val w_opt = writer.open_limited(s.repo, limit) val w: mut ref writer.Writer = none match w_opt { some x => {@@ -1025,6 +1083,9 @@ val hash: ref void = @alloc(b3.hasher_state_size()) as ref void b3.hasher_init(hash) val failed: mut bool = false+ val too_large: mut bool = false+ val quota_hit: mut bool = false+ val records: mut usize = 0 val accepted: mut list[objid.Id] = lists.new[objid.Id]() for { val nf = wire.read_frame(s.s)@@ -1056,7 +1117,14 @@ } if fr.kind != wire.RECORDS { wire.free_frame(fr)+ failed = true+ break+ }+ records+++ if records > MAX_PUSH_RECORDS {+ too_large = true failed = true+ wire.free_frame(fr) break } b3.hasher_update(hash, fr.payload.ptr, fr.payload.len)@@ -1068,6 +1136,10 @@ } else { writer.add_known(w, rec.kind, objid.id(rec.id.ptr), rec.body) @append(accepted, copy_id(objid.id(rec.id.ptr)))+ if w.failed {+ quota_hit = w.quota_hit+ failed = true+ } } bytes.free_ptr(computed.ptr) bytes.free_ptr(rec.id.ptr)@@ -1081,24 +1153,62 @@ } @free(hash as ref void) if failed {+ val was_quota: bool = quota_hit writer.abort(w)- wire.write_error(+ if !drain_push(s, DRAIN_BYTES) {+ s.closing = true+ }+ for id in accepted {+ if id.ptr != none {+ bytes.free_ptr(id.ptr)+ }+ }+ @listfree(accepted)+ if too_large {+ return wire.write_error(+ s.s,+ f.request_id,+ wire.ERR_TOO_LARGE,+ bytes.bytes(c"too many objects in one push", 29)+ )+ }+ if was_quota {+ return wire.write_error(+ s.s,+ f.request_id,+ wire.ERR_QUOTA,+ bytes.bytes(c"storage quota exceeded", 23)+ )+ }+ return wire.write_error( s.s, f.request_id, wire.ERR_HASH_MISMATCH, bytes.bytes(c"record rejected", 15) )- return true }- val passed: bool = writer.finish(w)- if !passed {- wire.write_error(+ val status: i32 = writer.finish(w)+ if status != 0 {+ for id in accepted {+ if id.ptr != none {+ bytes.free_ptr(id.ptr)+ }+ }+ @listfree(accepted)+ if status == 2 {+ return wire.write_error(+ s.s,+ f.request_id,+ wire.ERR_QUOTA,+ bytes.bytes(c"storage quota exceeded", 23)+ )+ }+ return wire.write_error( s.s, f.request_id, wire.ERR_INTERNAL, bytes.bytes(c"pack write failed", 17) )- return true } open_session_store(s) val closure_ok: mut bool = true@@ -1247,6 +1357,14 @@ fn handle_update_refs(s: mut ref Session, f: wire.Frame) bool = trust { if deny(s, f.request_id, true) { return true+ }+ if s.quota_bytes > 0 && quota.used(s.quota_dir) + QUOTA_RESERVE >= s.quota_bytes {+ return wire.write_error(+ s.s,+ f.request_id,+ wire.ERR_QUOTA,+ bytes.bytes(c"storage quota exceeded", 23)+ ) } val dec = msg.decode_update_refs(f.payload) val updates: mut list[msg.UpdateRef] = lists.new[msg.UpdateRef]()@@ -1380,6 +1498,7 @@ layout.free_repo(s.repo) } free_bytes_list(s.haves)+ files.free_path(s.quota_dir) if s.hello_repo.ptr != none { bytes.free_ptr(s.hello_repo.ptr) }@@ -1406,7 +1525,8 @@ st: stream.Stream, fixed: option[layout.Repo], root: option[layout.Repo],- binding: bytes.Bytes+ binding: bytes.Bytes,+ quota_bytes: u64 ) void = trust { val s: mut ref Session = @alloc(@sizeof(Session)) as ref Session s.s = st@@ -1425,11 +1545,14 @@ s.public_key = bytes.empty() s.fingerprint = bytes.empty() s.haves = lists.new[bytes.Bytes]()+ s.quota_bytes = quota_bytes+ s.quota_dir = str.view(none, 0) s.failed_auth = 0 s.closing = false if fixed is some repo { s.repo = repo s.repo_present = true+ s.quota_dir = files.join(layout.root_view(repo), str.from_cstr(c"")) s.access = access.load(repo) if s.access.valid { open_session_store(s)@@ -1462,9 +1585,9 @@ free_session(s) } -pub fn serve_stdio(repo: layout.Repo) i32 = trust {+pub fn serve_stdio(repo: layout.Repo, quota_bytes: u64) i32 = trust { val st: stream.Stream = stream.stdio_stream()- session(st, some repo, none, bytes.empty())+ session(st, some repo, none, bytes.empty(), quota_bytes) return 0 } @@ -1497,7 +1620,8 @@ addr: bytes.Bytes, root: layout.Repo, cert: bytes.Bytes,- key: bytes.Bytes+ key: bytes.Bytes,+ quota_bytes: u64 ) i32 = trust { when linux { val _ = runtime.signal(13, ignore_sigpipe)@@ -1555,7 +1679,7 @@ bind = bytes.bytes(binding, 32) } val no_repo: option[layout.Repo] = none- session(st, no_repo, some root, bind)+ session(st, no_repo, some root, bind, quota_bytes) @free(binding as ref void) } net.TcpServer.close[allocators.HeapAllocator](ac, server)--- a/veins/src/store/txn.sx+++ b/veins/src/store/txn.sx@@ -551,7 +551,7 @@ val op_id: objid.Id = writer.add(tx.writer, types.OPERATION, op_body) operation.free_operation(op) - val wrote: bool = writer.finish(tx.writer)+ val wrote: bool = writer.finish(tx.writer) == 0 if !wrote { msg.error_prefix() stdio.eprint("failed to write object pack\n", {})--- a/veins/src/store/writer.sx+++ b/veins/src/store/writer.sx@@ -54,6 +54,8 @@ items: mut list[ref PendingRecord] pending_bytes: mut usize failed: mut bool+ quota_hit: mut bool+ limit: mut u64 seen: mut idmap.IdSet cache: mut list[ref CachedObj] cache_chunks: mut bool@@ -210,6 +212,12 @@ } pub fn open(repo: layout.Repo) option[ref Writer] = trust {+ return open_limited(repo, 0)+}++/// Open a pack writer that refuses to write more than `limit` bytes of pack and+/// index data. A zero limit means unlimited.+pub fn open_limited(repo: layout.Repo, limit: u64) option[ref Writer] = trust { val tmpdir: str.StringView = layout.tmp_dir(repo) val packs: str.StringView = layout.packs_dir(repo) val name_c: ref u8 = @fmtalloc("import-{d}.vpack", {time.now_ns()})@@ -249,6 +257,8 @@ w.pending_bytes = 0 buf.Buf.free(header) w.failed = false+ w.quota_hit = false+ w.limit = limit w.seen = idmap.new(1024) w.cache = lists.new[ref CachedObj]() w.cache_chunks = false@@ -290,7 +300,11 @@ r.comp = 0 @append(w.items, r) w.pending_bytes = w.pending_bytes + body.len- if w.pending_bytes >= 268435456 {+ val flush_at: mut usize = 268435456+ if w.limit > 0 && w.limit < flush_at as u64 {+ flush_at = w.limit as usize+ }+ if w.pending_bytes >= flush_at { if !write_pending(w) { w.failed = true }@@ -359,6 +373,12 @@ buf.Buf.put_varint(header, r.body.len as u64) buf.Buf.put_varint(header, r.stored.len as u64) val start: u64 = w.offset+ val record_bytes: u64 = header.len as u64 + r.stored.len as u64+ if w.limit > 0 && start + record_bytes + 32 > w.limit {+ w.quota_hit = true+ w.failed = true+ break+ } buf.Buf.put_bytes(out, buf.Buf.view(header)) buf.Buf.put_bytes(out, r.stored) @append(w.metas, records.record_meta(copy_id(r.id), start, r.kind, r.body.len as u64))@@ -405,15 +425,24 @@ return none } -/// Finish the pack and write its index. `w` is consumed.-pub fn finish(w: mut ref Writer) bool = trust {+/// Finish the pack and write its index. `w` is consumed. Returns 0 on success,+/// 1 on a write failure, and 2 when the configured byte limit was reached.+pub fn finish(w: mut ref Writer) i32 = trust { if w.failed {+ val quota_hit: bool = w.quota_hit abort(w)- return false+ if quota_hit {+ return 2+ }+ return 1 } if !write_pending(w) {+ val quota_hit: bool = w.quota_hit abort(w)- return false+ if quota_hit {+ return 2+ }+ return 1 } val count_buf: mut buf.Buf = buf.new(8)@@ -422,12 +451,12 @@ buf.Buf.free(count_buf) if !patched { abort(w)- return false+ return 1 } if !native.seek_set(w.fd, 0) { abort(w)- return false+ return 1 } val state: ref void = @alloc(b3.hasher_state_size()) b3.hasher_init(state)@@ -451,7 +480,7 @@ if !hashed { @free(digest as ref void) abort(w)- return false+ return 1 } val trailer: bytes.Bytes = bytes.bytes(digest, 32) val wrote_trailer: bool = native.pwrite_fd_all(w.fd, w.offset as i64, trailer)@@ -462,7 +491,17 @@ @free(digest as ref void) val _ = native.delete_file(w.tmp_path) free_writer(w)- return false+ return 1+ }++ records.sort_by_id(w.metas)+ val index_bytes: bytes.Bytes = index.encode(w.metas, trailer)+ if w.limit > 0 && w.offset + 32 + index_bytes.len as u64 > w.limit {+ val idx_buf: mut ref void = index_bytes.ptr as ref void+ @free(idx_buf)+ @free(digest as ref void)+ abort(w)+ return 2 } val hex: ref u8 = @alloc(65) as ref u8@@ -475,6 +514,8 @@ val idx_final: str.StringView = files.join(w.packs_dir, idx_file) val renamed: bool = native.rename_file(w.tmp_path, pack_final) if !renamed {+ val idx_buf: mut ref void = index_bytes.ptr as ref void+ @free(idx_buf) @free(hex as ref void) @free(digest as ref void) files.free_path(pack_file)@@ -483,12 +524,10 @@ files.free_path(idx_final) val _ = native.delete_file(w.tmp_path) free_writer(w)- return false+ return 1 } val _ = native.sync_dir_path(w.packs_dir) - records.sort_by_id(w.metas)- val index_bytes: bytes.Bytes = index.encode(w.metas, trailer) val idx_tmp_name: str.StringView = files.with_suffix(pack_name, str.from_cstr(c".vidx.tmp")) val idx_tmp: str.StringView = files.join(w.tmp_dir, idx_tmp_name) val wrote_index: bool = native.write_atomic(@@ -509,5 +548,8 @@ @free(hex as ref void) @free(digest as ref void) free_writer(w)- return wrote_index+ if wrote_index {+ return 0+ }+ return 1 }--- a/xveins/src/net_commands.cpp+++ b/xveins/src/net_commands.cpp@@ -9,6 +9,7 @@ #include "worktree.h" #include <algorithm>+#include <charconv> #include <cstddef> #include <cstring> #include <iostream>@@ -901,6 +902,7 @@ std::string cert; std::string key; std::string repo_path = ".";+ std::uint64_t quota_bytes = 0; for (std::size_t i = 2; i < args.size(); ++i) { const std::string &arg = args[i]; if (arg == "-stdio") {@@ -919,6 +921,23 @@ } else if (arg == "-tls-key") { if (i + 1 < args.size()) key = args[++i];+ } else if (arg == "-quota") {+ if (i + 1 >= args.size()) {+ error_prefix();+ std::cout << "-quota requires a byte count\n";+ return 1;+ }+ const std::string &value = args[++i];+ std::uint64_t parsed = 0;+ const auto result =+ std::from_chars(value.data(), value.data() + value.size(), parsed);+ if (result.ec != std::errc() ||+ result.ptr != value.data() + value.size()) {+ error_prefix();+ std::cout << "-quota requires a byte count\n";+ return 1;+ }+ quota_bytes = parsed; } else { error_prefix(); std::cout << "unknown serve option: " << arg << "\n";@@ -932,7 +951,7 @@ std::cout << "not a veins repository\n"; return 1; }- return server::serve_stdio(*repo);+ return server::serve_stdio(*repo, quota_bytes); } if (listen.empty()) { error_prefix();@@ -944,7 +963,8 @@ std::cout << "TLS requires -tls-cert and -tls-key\n"; return 1; }- return server::serve_listen(listen, path_from_bytes(root), cert, key);+ return server::serve_listen(listen, path_from_bytes(root), cert, key,+ quota_bytes); } // ---------------------------------------------------------------------------@@ -1289,10 +1309,12 @@ return true; } if (command == "serve") {- std::cout << "usage: vn serve -stdio <repo>\n";+ std::cout << "usage: vn serve -stdio <repo> [-quota <bytes>]\n"; std::cout << " vn serve -listen <addr:port> -root <dir> -tls-cert "- "<file> -tls-key <file>\n\n";+ "<file> -tls-key <file> [-quota <bytes>]\n\n"; std::cout << "run the native server over standard input/output or TLS 1.3\n";+ std::cout << "-quota limits stored pack and index bytes per top-level "+ "namespace\n"; return true; } if (command == "key") {--- a/xveins/src/protocol.cpp+++ b/xveins/src/protocol.cpp@@ -762,7 +762,7 @@ return false; } - if (!writer.finish(repo)) {+ if (writer.finish(repo) != 0) { set_error("cannot write incoming objects to the store"); return false; }--- a/xveins/src/server.cpp+++ b/xveins/src/server.cpp@@ -22,6 +22,9 @@ namespace { constexpr std::size_t MAX_CHUNKS_PER_REQUEST = 4096;+constexpr std::size_t MAX_PUSH_RECORDS = 100000;+constexpr std::uint64_t QUOTA_RESERVE = 1u << 20;+constexpr std::size_t DRAIN_BYTES = 64u << 20; struct Session { net::Stream stream;@@ -41,10 +44,23 @@ bool has_public_key = false; std::string fingerprint; std::vector<Id> haves;+ std::uint64_t quota_bytes = 0; int failed_auth = 0; bool closing = false; fs::path root; };++fs::path quota_dir(const Session &session) {+ if (session.root.empty())+ return session.repo_root;+ std::string_view repo = session.hello_repo;+ const auto slash = repo.find('/');+ if (slash != std::string_view::npos)+ repo = repo.substr(0, slash);+ if (repo.empty())+ return session.root;+ return session.root / path_from_bytes(repo);+} std::uint8_t effective_role(const Session &session) { if (session.authed)@@ -617,15 +633,46 @@ } } return fine;+}++bool drain_push(Session &session, std::size_t max_bytes) {+ std::size_t seen = 0;+ while (seen <= max_bytes) {+ auto frame = wire::read_frame(session.stream);+ if (!frame)+ return false;+ if (frame->kind == wire::END)+ return true;+ if (frame->kind != wire::RECORDS)+ return false;+ seen += frame->payload.size();+ }+ return false; } bool handle_put_records(Session &session, const wire::Frame &frame) { if (deny(session, frame.request_id, true)) return true;+ std::uint64_t limit = 0;+ if (session.quota_bytes > 0) {+ const std::uint64_t used = storage_usage(quota_dir(session));+ if (used + QUOTA_RESERVE >= session.quota_bytes) {+ if (!drain_push(session, DRAIN_BYTES))+ session.closing = true;+ wire::write_error(session.stream, frame.request_id, wire::ERR_QUOTA,+ "storage quota exceeded");+ return true;+ }+ limit = session.quota_bytes - used - QUOTA_RESERVE;+ } Writer writer;+ writer.set_limit(limit); blake3_hasher hasher; blake3_hasher_init(&hasher); bool failed = false;+ bool too_large = false;+ bool quota_hit = false;+ std::size_t records = 0; std::vector<Id> accepted; for (;;) {@@ -646,6 +693,11 @@ break; } if (incoming.kind != wire::RECORDS) {+ failed = true;+ break;+ }+ if (++records > MAX_PUSH_RECORDS) {+ too_large = true; failed = true; break; }@@ -663,16 +715,33 @@ } writer.add_known(record->kind, record->id, std::move(record->body)); accepted.push_back(record->id);+ if (writer.quota_hit()) {+ quota_hit = true;+ failed = true;+ break;+ } } if (failed) {- wire::write_error(session.stream, frame.request_id,- wire::ERR_HASH_MISMATCH, "record rejected");+ if (!drain_push(session, DRAIN_BYTES))+ session.closing = true;+ if (too_large) {+ wire::write_error(session.stream, frame.request_id, wire::ERR_TOO_LARGE,+ "too many objects in one push");+ } else if (quota_hit) {+ wire::write_error(session.stream, frame.request_id, wire::ERR_QUOTA,+ "storage quota exceeded");+ } else {+ wire::write_error(session.stream, frame.request_id,+ wire::ERR_HASH_MISMATCH, "record rejected");+ } return true; }- if (!writer.finish(session.repo_root)) {- wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,- "pack write failed");+ const int status = writer.finish(session.repo_root);+ if (status != 0) {+ wire::write_error(session.stream, frame.request_id,+ status == 2 ? wire::ERR_QUOTA : wire::ERR_INTERNAL,+ status == 2 ? "storage quota exceeded" : "pack write failed"); return true; } open_session_store(session);@@ -747,7 +816,14 @@ bool handle_update_refs(Session &session, const wire::Frame &frame) { if (deny(session, frame.request_id, true))+ return true;+ if (session.quota_bytes > 0 &&+ storage_usage(quota_dir(session)) + QUOTA_RESERVE >=+ session.quota_bytes) {+ wire::write_error(session.stream, frame.request_id, wire::ERR_QUOTA,+ "storage quota exceeded"); return true;+ } auto updates = proto::decode_update_refs(bytes_of(frame.payload)); if (!updates) { wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,@@ -817,10 +893,12 @@ } void run_session(net::Stream stream, std::optional<fs::path> fixed,- std::optional<fs::path> root, std::string binding) {+ std::optional<fs::path> root, std::string binding,+ std::uint64_t quota_bytes) { Session session; session.stream = std::move(stream); session.binding = std::move(binding);+ session.quota_bytes = quota_bytes; if (root) session.root = *root; if (fixed) {@@ -859,13 +937,14 @@ } // namespace -int serve_stdio(const fs::path &repo) {- run_session(net::Stream::stdio_stream(), repo, std::nullopt, {});+int serve_stdio(const fs::path &repo, std::uint64_t quota_bytes) {+ run_session(net::Stream::stdio_stream(), repo, std::nullopt, {}, quota_bytes); return 0; } int serve_listen(std::string_view address, const fs::path &root,- std::string_view cert_path, std::string_view key_path) {+ std::string_view cert_path, std::string_view key_path,+ std::uint64_t quota_bytes) { net::ignore_sigpipe(); auto port = parse_port(address); if (!port) {@@ -904,7 +983,7 @@ exported.size()); } run_session(net::Stream::tls_stream(*accepted, ssl), std::nullopt, root,- std::move(binding));+ std::move(binding), quota_bytes); } net::close_socket(listener); net::tls_ctx_free(ctx);--- a/xveins/src/server.h+++ b/xveins/src/server.h@@ -6,8 +6,9 @@ namespace vn::server { -int serve_stdio(const fs::path &repo);+int serve_stdio(const fs::path &repo, std::uint64_t quota_bytes); int serve_listen(std::string_view address, const fs::path &root,- std::string_view cert_path, std::string_view key_path);+ std::string_view cert_path, std::string_view key_path,+ std::uint64_t quota_bytes); } // namespace vn::server--- a/xveins/src/store.cpp+++ b/xveins/src/store.cpp@@ -50,6 +50,33 @@ } fs::path format_path(const fs::path &root) { return veins_dir(root) / "format";+}++static std::uint64_t repo_storage_usage(const fs::path &root) {+ std::uint64_t total = 0;+ for (const auto &name : list_directory(packs_dir(root))) {+ const auto info = stat_path(packs_dir(root) / path_from_bytes(name));+ if (info && info->kind == 1)+ total += info->size;+ }+ return total;+}++std::uint64_t storage_usage(const fs::path &dir) {+ if (!stat_path(dir)) {+ return 0;+ }+ if (stat_path(format_path(dir))) {+ return repo_storage_usage(dir);+ }+ std::uint64_t total = 0;+ for (const auto &name : list_directory(dir)) {+ const fs::path child = dir / path_from_bytes(name);+ const auto info = stat_path(child);+ if (info && info->kind == 2)+ total += repo_storage_usage(child);+ }+ return total; } std::optional<fs::path> discover_repo(const fs::path &start) {@@ -501,21 +528,24 @@ return output; } -bool write_pack(const fs::path &root, const std::vector<RawObject> &objects) {+int write_pack(const fs::path &root, const std::vector<RawObject> &objects,+ std::uint64_t limit) { PackOutput output = encode_pack(objects); if (output.count == 0)- return true;+ return 0;+ if (limit > 0 && output.pack.size() + output.index.size() > limit)+ return 2; const fs::path pfinal = packs_dir(root) / (output.name + ".vpack"); const fs::path ifinal = packs_dir(root) / (output.name + ".vidx"); const fs::path ptmp = tmp_dir(root) / (output.name + ".vpack.tmp"); const fs::path itmp = tmp_dir(root) / (output.name + ".vidx.tmp"); if (!write_atomic(ptmp, pfinal, bytes_of(output.pack)))- return false;+ return 1; if (!write_atomic(itmp, ifinal, bytes_of(output.index))) { (void)remove_file(pfinal);- return false;+ return 1; }- return true;+ return 0; } // ---------------------------------------------------------------------------@@ -704,8 +734,13 @@ Id Writer::add(std::uint8_t type, const std::vector<std::uint8_t> &body) { const Id id = object_id(type, bytes_of(body));- if (!seen_.insert(id).second)+ if (quota_hit_ || !seen_.insert(id).second)+ return id;+ if (limit_ > 0 && raw_bytes_ + body.size() > limit_) {+ quota_hit_ = true; return id;+ }+ raw_bytes_ += body.size(); objects_.push_back(RawObject{type, body, id}); if (type != TYPE_CHUNK || cache_chunks_) cache_.push_back(RawObject{type, body, id});@@ -714,8 +749,13 @@ Id Writer::add(std::uint8_t type, std::vector<std::uint8_t> &&body) { const Id id = object_id(type, bytes_of(body));- if (!seen_.insert(id).second)+ if (quota_hit_ || !seen_.insert(id).second)+ return id;+ if (limit_ > 0 && raw_bytes_ + body.size() > limit_) {+ quota_hit_ = true; return id;+ }+ raw_bytes_ += body.size(); if (type != TYPE_CHUNK || cache_chunks_) cache_.push_back(RawObject{type, body, id}); objects_.push_back(RawObject{type, std::move(body), id});@@ -724,8 +764,13 @@ Id Writer::add_known(std::uint8_t type, const Id &id, const std::vector<std::uint8_t> &body) {- if (!seen_.insert(id).second)+ if (quota_hit_ || !seen_.insert(id).second)+ return id;+ if (limit_ > 0 && raw_bytes_ + body.size() > limit_) {+ quota_hit_ = true; return id;+ }+ raw_bytes_ += body.size(); objects_.push_back(RawObject{type, body, id}); if (type != TYPE_CHUNK || cache_chunks_) cache_.push_back(RawObject{type, body, id});@@ -734,8 +779,13 @@ Id Writer::add_known(std::uint8_t type, const Id &id, std::vector<std::uint8_t> &&body) {- if (!seen_.insert(id).second)+ if (quota_hit_ || !seen_.insert(id).second)+ return id;+ if (limit_ > 0 && raw_bytes_ + body.size() > limit_) {+ quota_hit_ = true; return id;+ }+ raw_bytes_ += body.size(); if (type != TYPE_CHUNK || cache_chunks_) cache_.push_back(RawObject{type, body, id}); objects_.push_back(RawObject{type, std::move(body), id});@@ -754,7 +804,11 @@ return std::nullopt; } -bool Writer::finish(const fs::path &root) { return write_pack(root, objects_); }+int Writer::finish(const fs::path &root) {+ if (quota_hit_)+ return 2;+ return write_pack(root, objects_, limit_);+} // --------------------------------------------------------------------------- // View helpers@@ -1100,7 +1154,7 @@ const auto op_body = encode_operation(op); const Id op_id = writer_.add(TYPE_OPERATION, op_body); - if (!writer_.finish(root_)) {+ if (writer_.finish(root_) != 0) { error_prefix(); std::cout << "failed to write object pack\n"; return fail_io("failed to write object pack");--- a/xveins/src/store.h+++ b/xveins/src/store.h@@ -30,6 +30,7 @@ fs::path resolutions_dir(const fs::path &root); fs::path config_path(const fs::path &root); fs::path format_path(const fs::path &root);+std::uint64_t storage_usage(const fs::path &dir); std::optional<fs::path> discover_repo(const fs::path &start); Result<fs::path> init_repo(const fs::path &path);@@ -90,7 +91,8 @@ encode_index(const std::vector<RecordMeta> &records, const std::array<std::uint8_t, 32> &trailer); -bool write_pack(const fs::path &root, const std::vector<RawObject> &objects);+int write_pack(const fs::path &root, const std::vector<RawObject> &objects,+ std::uint64_t limit); // --------------------------------------------------------------------------- // Store@@ -155,10 +157,12 @@ Id add_known(std::uint8_t type, const Id &id, std::vector<std::uint8_t> &&body); void enable_chunk_cache() { cache_chunks_ = true; }+ void set_limit(std::uint64_t limit) { limit_ = limit; }+ bool quota_hit() const { return quota_hit_; } std::optional<std::vector<std::uint8_t>> find_cached(std::uint8_t type, const Id &id) const; - bool finish(const fs::path &root);+ int finish(const fs::path &root); std::vector<RawObject> &objects() { return objects_; } private:@@ -166,6 +170,9 @@ std::vector<RawObject> cache_; std::set<Id> seen_; bool cache_chunks_ = false;+ std::uint64_t limit_ = 0;+ std::uint64_t raw_bytes_ = 0;+ bool quota_hit_ = false; }; class Txn {--- a/xveins/src/wire.cpp+++ b/xveins/src/wire.cpp@@ -120,6 +120,10 @@ return "permission denied"; case ERR_AUTH_FAILED: return "authentication failed";+ case ERR_QUOTA:+ return "storage quota exceeded";+ case ERR_TOO_LARGE:+ return "push too large"; default: return "unknown server error"; }--- a/xveins/src/wire.h+++ b/xveins/src/wire.h@@ -47,6 +47,8 @@ ERR_UNAUTHENTICATED = 10, ERR_FORBIDDEN = 11, ERR_AUTH_FAILED = 12,+ ERR_QUOTA = 13,+ ERR_TOO_LARGE = 14, }; struct Frame {