diff --git a/CMakeLists.txt b/CMakeLists.txt index 1f6bedd..5624d2d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -169,6 +169,9 @@ if(VISP_INSTALL_MODELS) endif() install(TARGETS vision-cli RUNTIME DESTINATION ${VISP_BIN_INSTALL_DIR}) +if(UNIX) + install(TARGETS vision-server RUNTIME DESTINATION ${VISP_BIN_INSTALL_DIR}) +endif() if(VISP_CI OR VISP_DEV) set_target_properties(vision-cli PROPERTIES INSTALL_RPATH "\$ORIGIN/../${VISP_LIB_INSTALL_DIR}") diff --git a/src/cli/CMakeLists.txt b/src/cli/CMakeLists.txt index d139103..746ce77 100644 --- a/src/cli/CMakeLists.txt +++ b/src/cli/CMakeLists.txt @@ -14,3 +14,15 @@ if(VISP_INSTALL_MODELS) endif() endif() target_compile_definitions(vision-cli PRIVATE VISP_MODEL_INSTALL_DIR="${MODEL_DIR}") + +# HTTP server (POSIX only - uses BSD sockets) + +if(UNIX) + add_executable(vision-server) + target_sources(vision-server PRIVATE server.cpp) + target_include_directories(vision-server PRIVATE ..) + target_compile_definitions(vision-server PRIVATE ${VISP_ASSERT} ${VISP_DEFINITIONS}) + target_compile_options(vision-server PRIVATE ${VISP_WARNINGS} ${VISP_COMP_OPTIONS}) + target_link_options(vision-server PRIVATE ${VISP_LINK_OPTIONS}) + target_link_libraries(vision-server PRIVATE ggml visioncpp stb ${VISP_FMT_LINK}) +endif() diff --git a/src/cli/server.cpp b/src/cli/server.cpp new file mode 100644 index 0000000..25f5be3 --- /dev/null +++ b/src/cli/server.cpp @@ -0,0 +1,1043 @@ +// +// vision-server - a small HTTP server for running vision.cpp models +// +// Serves one or more GGUF models over HTTP with a minimal JSON API. +// Designed to run on the same machine as the models (127.0.0.1 by default) +// and to be cheap enough to live next to other GPU tenants: on a Vulkan +// backend the requested arena is probed against the device before the +// server starts, so it fails at boot instead of stealing memory later. +// +// POSIX only for now (Linux, macOS). A Windows port is a follow-up. + +#include "util/json.h" +#include "util/math.h" +#include "util/string.h" +#include "visp/vision.h" + +#include "stb_image.h" +#include "stb_image_write.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace visp { + +// +// Limits and defaults + +constexpr size_t MAX_HEADER_BYTES = 64 * 1024; +constexpr size_t MAX_BODY_BYTES = 64 * 1024 * 1024; +constexpr int DEFAULT_PORT = 8080; +constexpr size_t DEFAULT_MAX_ARENA_MB = 4096; + +struct timer { + int64_t start; + + timer() : start(ggml_time_us()) {} + + float elapsed_ms() const { return float(ggml_time_us() - start) / 1000.0f; } + + // Formats into a caller-provided buffer - returning a pointer to a local + // string would dangle the moment this function returns. + void elapsed_str(fixed_string<16>& s) const { format(s, "{:.1f} ms", elapsed_ms()); } +}; + +// Accepts plain base64 and data: URL prefixes (eg. from browser clients) +std::string_view base64_of(std::string_view in) { + if (in.starts_with("data:")) { + size_t comma = in.find(','); + if (comma == std::string_view::npos) { + throw except("Malformed data: URL"); + } + return in.substr(comma + 1); + } + return in; +} + +// +// HTTP + +struct http_request { + std::string method; + std::string path; + std::vector> headers; + std::string body; + + std::string const* header(char const* name) const { + for (auto const& [k, v] : headers) { + if (k == name) { + return &v; + } + } + return nullptr; + } +}; + +ssize_t write_all(int fd, void const* data, size_t size) { + size_t sent = 0; + while (sent < size) { + ssize_t n = ::write(fd, static_cast(data) + sent, size - sent); + if (n <= 0) { + return -1; + } + sent += size_t(n); + } + return ssize_t(sent); +} + +bool read_all(int fd, void* data, size_t size) { + size_t got = 0; + while (got < size) { + ssize_t n = ::read(fd, static_cast(data) + got, size - got); + if (n <= 0) { + return false; + } + got += size_t(n); + } + return true; +} + +// Reads one HTTP request. If the client sends "Expect: 100-continue", a +// "100 Continue" response is sent before the body is read, so large uploads +// (base64 images) don't stall behind clients that wait for the signal. +http_request http_read(int fd) { + http_request req; + + std::string head; + head.reserve(1024); + char buf[4096]; + bool complete = false; + while (!complete && head.size() < MAX_HEADER_BYTES) { + ssize_t n = ::read(fd, buf, sizeof(buf)); + if (n <= 0) { + throw except("Connection closed while reading request"); + } + head.append(buf, size_t(n)); + complete = head.find("\r\n\r\n") != std::string::npos; + } + if (!complete) { + throw except("Request header too large"); + } + size_t head_end = head.find("\r\n\r\n"); + std::string_view head_sv = std::string_view(head).substr(0, head_end); + + // Request line + size_t line_end = head_sv.find("\r\n"); + std::string_view line = head_sv.substr( + 0, line_end == std::string_view::npos ? head_sv.size() : line_end); + { + size_t sp1 = line.find(' '); + size_t sp2 = line.rfind(' '); + if (sp1 == std::string_view::npos || sp2 == sp1) { + throw except("Malformed request line"); + } + req.method = std::string(line.substr(0, sp1)); + req.path = std::string(line.substr(sp1 + 1, sp2 - sp1 - 1)); + } + + // Headers + size_t pos = line_end + 2; + while (pos < head_sv.size()) { + size_t eol = head_sv.find("\r\n", pos); + std::string_view h = head_sv.substr( + pos, eol == std::string_view::npos ? head_sv.size() - pos : eol - pos); + size_t colon = h.find(':'); + if (colon != std::string_view::npos) { + std::string name; + for (size_t i = 0; i < colon; ++i) { + name += char(std::tolower(uint8_t(h[i]))); + } + size_t vs = colon + 1; + while (vs < h.size() && h[vs] == ' ') { + ++vs; + } + req.headers.emplace_back(std::move(name), std::string(h.substr(vs))); + } + if (eol == std::string_view::npos) { + break; + } + pos = eol + 2; + } + + // Body + size_t content_length = 0; + if (std::string const* cl = req.header("content-length")) { + char* end = nullptr; + unsigned long v = std::strtoul(cl->c_str(), &end, 10); + if (end == cl->c_str() || *end != '\0' || v > MAX_BODY_BYTES) { + throw except("Invalid Content-Length: {}", *cl); + } + content_length = v; + } + + if (std::string const* expect = req.header("expect")) { + if (*expect == "100-continue") { + char const* cont = "HTTP/1.1 100 Continue\r\n\r\n"; + if (write_all(fd, cont, strlen(cont)) < 0) { + throw except("Failed to send 100-continue"); + } + } + } + + // The reads above may have captured part of the body already - seed with + // it, then read the rest. + req.body.assign(head, head_end + 4); + if (req.body.size() > content_length) { + throw except("Request body larger than Content-Length"); + } + while (req.body.size() < content_length) { + ssize_t n = ::read(fd, buf, sizeof(buf)); + if (n <= 0) { + throw except("Connection closed while reading body"); + } + req.body.append(buf, size_t(n)); + if (req.body.size() > MAX_BODY_BYTES) { + throw except("Request body too large"); + } + } + req.body.resize(content_length); + return req; +} + +char const* http_status_text(int status) { + switch (status) { + case 200: return "OK"; + case 400: return "Bad Request"; + case 404: return "Not Found"; + case 405: return "Method Not Allowed"; + case 500: return "Internal Server Error"; + default: return "Error"; + } +} + +struct http_response { + int status = 200; + std::string body; + + void json(json_value const& v) { json_write(body, v); } + + void error(int status_, char const* msg) { + status = status_; + json_value v; + v.set("error", std::string(msg)); + json(v); + } +}; + +void http_write(int fd, http_response const& r) { + std::string head = "HTTP/1.1 " + std::to_string(r.status) + " " + http_status_text(r.status) + + "\r\nContent-Type: application/json\r\nContent-Length: " + std::to_string(r.body.size()) + + "\r\nConnection: close\r\n\r\n"; + if (write_all(fd, head.data(), head.size()) < 0) { + return; + } + if (!r.body.empty()) { + write_all(fd, r.body.data(), r.body.size()); + } +} + +// Error with an HTTP status - thrown for client errors (4xx) and inference +// failures (5xx) alike; everything else (unexpected) stays a plain except. +struct http_error : exception { + int status = 500; + + template + http_error(int status_, char const* fmt, Args&&... args) + : exception(format>(fmt, std::forward(args)...)), status(status_) {} +}; + +// +// Images in memory (stb) + +image_data image_decode_rgb(std::span bytes) { + int w = 0, h = 0, ch = 0; + unsigned char* pixels = stbi_load_from_memory( + reinterpret_cast(bytes.data()), int(bytes.size()), &w, &h, &ch, 3); + if (!pixels) { + throw except("Could not decode image ({} bytes)", bytes.size()); + } + image_data img{.extent = {w, h}, .format = image_format::rgb_u8}; + img.data.reset(new unsigned char[size_t(w) * h * 3]); + std::memcpy(img.data.get(), pixels, size_t(w) * h * 3); + stbi_image_free(pixels); + return img; +} + +image_data image_decode_alpha(std::span bytes) { + int w = 0, h = 0, ch = 0; + unsigned char* pixels = stbi_load_from_memory( + reinterpret_cast(bytes.data()), int(bytes.size()), &w, &h, &ch, 0); + if (!pixels) { + throw except("Could not decode mask image ({} bytes)", bytes.size()); + } + image_data img{.extent = {w, h}, .format = image_format::alpha_u8}; + img.data.reset(new unsigned char[size_t(w) * h]); + if (ch == 1) { + std::memcpy(img.data.get(), pixels, size_t(w) * h); + } else if (ch == 4) { + for (int i = 0; i < w * h; ++i) { + img.data[i] = pixels[i * 4 + 3]; + } + } else { + throw except("Mask image must be grayscale or have an alpha channel (got {} channels)", ch); + } + stbi_image_free(pixels); + return img; +} + +std::vector image_encode_png(image_view const& img) { + std::vector out; + auto write_cb = [](void* ctx, void* data, int size) { + auto& vec = *static_cast*>(ctx); + vec.insert( + vec.end(), static_cast(data), static_cast(data) + size); + }; + if (!stbi_write_png_to_func( + write_cb, &out, img.extent[0], img.extent[1], n_channels(img.format), img.data, + img.extent[0] * n_bytes(img.format))) { + throw except("PNG encoding failed"); + } + return out; +} + +json_value image_to_json(image_view const& img) { + json_value v; + v.set("width", int(img.extent[0])); + v.set("height", int(img.extent[1])); + v.set("image", base64_encode(image_encode_png(img))); + return v; +} + +// +// Models + +char const* to_string(model_family f) { + switch (f) { + case model_family::sam: return "sam"; + case model_family::birefnet: return "birefnet"; + case model_family::depth_anything: return "depth"; + case model_family::migan: return "migan"; + case model_family::esrgan: return "esrgan"; + default: return "unknown"; + } +} + +// FNV-1a, for the SAM embedding cache key +uint64_t hash_bytes(std::span data) { + uint64_t h = 0xcbf29ce484222325ULL; + for (unsigned char b : data) { + h ^= uint64_t(b); + h *= 0x100000001b3ULL; + } + return h; +} + +struct sam_embed_cache { + bool valid = false; + uint64_t key = 0; + ggml_type embed_type = GGML_TYPE_F32; + i64x4 embed_ne = {}; + std::optional embed_host; +}; + +struct model_entry { + model_family family = model_family::sam; + std::string path; + bool loaded = false; + + model_file file; + model_weights weights; + + // SAM: the image encoder (TinyViT) is the expensive half of a predict. + // The most recent encoder output is kept on the host and re-uploaded on + // cache hits, so repeated prompts on the same image skip the encode. + sam_params sam_p; + sam_embed_cache sam_cache; + + migan_params migan_p; + esrgan_params esrgan_p; +}; + +struct server_config { + std::string listen = "127.0.0.1"; + int port = DEFAULT_PORT; + std::optional backend; + std::vector models; + size_t max_arena_mb = DEFAULT_MAX_ARENA_MB; +}; + +struct server { + server_config cfg; + backend_device backend{}; + std::vector models; + std::mutex infer_mutex; + std::atomic running{false}; + int listen_fd = -1; +}; + +// Proves the backend can hand out an arena of the requested size right now, +// and gives it back. On Vulkan this is a real device-memory check, so the +// server refuses to start on a card already committed to other tenants +// (eg. a big LLM server) instead of failing mid-request later. +void reserve_arena(backend_device const& b, size_t bytes) { + if (bytes == 0 || b.type() != backend_type::vulkan) { + return; // CPU memory is not the shared resource this protects + } + printf("Checking %zu MB can be reserved on the GPU... ", size_t(bytes) / (1024 * 1024)); + timer t; + ggml_backend_buffer_t buf = ggml_backend_alloc_buffer(b, bytes); + if (!buf) { + throw except( + "Cannot reserve an arena of {} MB on {} - not enough free memory " + "(in use by another client?). Lower --max-arena, free memory, or use --backend cpu.", + size_t(bytes) / (1024 * 1024), ggml_backend_dev_name(ggml_backend_get_device(b))); + } + ggml_backend_buffer_free(buf); + fixed_string<16> ts; + t.elapsed_str(ts); + printf("done (%s)\n", ts.c_str()); +} + +// The device budget for one request. This ggml-vulkan allocates per tensor +// (there is no arena to clamp), so the budget is checked *before* the graph +// allocates: a dry run of the graph allocator (no_alloc) reports exactly the +// buffer the real allocation would create - in-place ops included, which is +// why summing tensor sizes would overcount - and an over-budget request is +// refused with its measured figure instead of dying mid-allocation inside +// another client's headroom. +void check_device_budget(compute_graph const& g, server& s) { + ggml_gallocr_t tmp = ggml_gallocr_new(ggml_backend_get_default_buffer_type(s.backend)); + size_t need = 0; + ggml_gallocr_reserve_n_size(tmp, g.graph, nullptr, nullptr, &need); + ggml_gallocr_free(tmp); + + size_t const cap = s.cfg.max_arena_mb * 1024 * 1024; + if (need > cap) { + throw http_error( + 503, + "this request would use ~{} MB of {} memory, more than the {} MB cap ({}); use a " + "smaller image or raise the cap", + need / (1024 * 1024), ggml_backend_dev_name(ggml_backend_get_device(s.backend)), + s.cfg.max_arena_mb, + s.cfg.max_arena_mb == DEFAULT_MAX_ARENA_MB ? "the default" : "--max-arena"); + } +} + +model_entry& server_find_model(server& s, model_family family) { + for (auto& m : s.models) { + if (m.loaded && m.family == family) { + return m; + } + } + throw http_error(404, "No {} model loaded", to_string(family)); +} + +void server_load_models(server& s) { + for (auto& m : s.models) { + timer t; + printf("Loading model weights from '%s'... ", m.path.c_str()); + m.file = model_load(m.path.c_str()); + m.family = model_detect_family(m.file); + m.weights = model_init(m.file.n_tensors()); + model_transfer( + m.file, m.weights, s.backend, s.backend.preferred_float_type(), + s.backend.preferred_layout()); + m.loaded = true; + + switch (m.family) { + case model_family::sam: m.sam_p = {}; break; + case model_family::migan: + m.migan_p = migan_detect_params(m.file); + m.migan_p.invert_mask = true; // -> inpaint opaque areas + break; + case model_family::esrgan: m.esrgan_p = esrgan_detect_params(m.file); break; + default: + // sam/birefnet/depth params are detected per request so + // dynamic-size variants work with any input resolution + break; + } + fixed_string<16> ts; + t.elapsed_str(ts); + printf("done (%s)\n", ts.c_str()); + ggml_type ftype = m.file.float_type() != GGML_TYPE_COUNT ? m.file.float_type() + : m.weights.float_type(); + printf("- family: %s - float type: %s\n", to_string(m.family), ggml_type_name(ftype)); + } +} + +// +// Request handlers + +json_value sam_predict(server& s, model_entry& m, image_data const& image, json_value const& req) { + bool has_point = req.find("point") != nullptr; + bool has_box = req.find("box") != nullptr; + if (has_point == has_box) { + throw http_error(400, "Provide exactly one of 'point' or 'box'"); + } + + f32x4 prompt_data; + bool is_box = false; + if (has_point) { + json_value const& p = *req.find("point"); + i32x2 point{p.get_int("x"), p.get_int("y")}; + if (point[0] < 0 || point[1] < 0 || point[0] >= image.extent[0] || + point[1] >= image.extent[1]) { + throw http_error(400, "Invalid image coordinates: ({}, {})", point[0], point[1]); + } + prompt_data = sam_process_point(point, image.extent, m.sam_p); + } else { + json_value const& b = *req.find("box"); + i32x2 a{b.get_int("x1"), b.get_int("y1")}; + i32x2 c{b.get_int("x2"), b.get_int("y2")}; + if (a[0] < 0 || a[1] < 0 || c[0] > image.extent[0] || c[1] > image.extent[1] || + a[0] >= c[0] || a[1] >= c[1]) { + throw http_error( + 400, "Invalid box coordinates: ({}, {}) to ({}, {})", a[0], a[1], c[0], c[1]); + } + prompt_data = sam_process_box({a, c}, image.extent, m.sam_p); + is_box = true; + } + + uint64_t key = hash_bytes( + std::span( + image.data.get(), size_t(image.extent[0]) * image.extent[1] * 3)); + + // Phase 1 — the encoder, in a graph of its own. Its output buffer + // cannot be reused by any later op of the same graph, so the + // post-compute host copy is the true encoder output. If the encoder + // ran inside the combined encode+predict graph, a later in-place op + // could write into that buffer and the cached "embedding" would be + // stale intermediate data - the next cache-hit request then predicts + // from garbage (measured: the first request of a server was correct, + // every cache hit drifted). + bool cache_hit = m.sam_cache.valid && m.sam_cache.key == key; + if (!cache_hit) { + compute_graph graph1 = compute_graph_init(); + model_ref model1(m.weights, graph1); + image_data input_data = sam_process_input(image, m.sam_p); + tensor image_tensor = compute_graph_input( + model1, GGML_TYPE_F32, {3, m.sam_p.image_size, m.sam_p.image_size, 1}, "image"); + tensor image_embed = sam_encode_image(model1, image_tensor, m.sam_p); + // The encoder chain only exists in the context until something + // expands the graph (the predict path does it for the combined + // graph). Mark the encoder output as this graph's output, which + // registers the whole chain - including the image input - so the + // allocator can give them buffers. + compute_graph_output(model1, image_embed, "image_embed"); + + check_device_budget(graph1, s); + compute_graph_allocate(graph1, s.backend); + transfer_to_backend(image_tensor, input_data); + compute(graph1, s.backend); + + auto ne = nelements(image_embed); + m.sam_cache.valid = true; + m.sam_cache.key = key; + m.sam_cache.embed_type = image_embed->type; + m.sam_cache.embed_ne = {ne[0], ne[1], ne[2], ne[3]}; + m.sam_cache.embed_host = transfer_from_backend(image_embed); + } + + // Phase 2 — the predictor. The embedding is always an input tensor + // filled from the host copy (a few MB - trivial on either backend); + // the prompt is encoded in this same graph. + compute_graph graph = compute_graph_init(); + model_ref model(m.weights, graph); + tensor image_embed = compute_graph_input( + model, m.sam_cache.embed_type, m.sam_cache.embed_ne, "image_embed"); + tensor point_tensor = compute_graph_input(model, GGML_TYPE_F32, {2, 2, 1, 1}, "points"); + tensor prompt_embed = is_box ? sam_encode_box(model, point_tensor) + : sam_encode_points(model, point_tensor); + + sam_prediction output = sam_predict_mask(model, image_embed, prompt_embed); + + // Allocate before the transfers: input tensors have no buffer until the + // graph allocation runs (this is why the CLI allocates first). + check_device_budget(graph, s); + compute_graph_allocate(graph, s.backend); + + // The cached host buffer outlives the graph that produced it, so the + // tensor it came from is gone - size the span from the cached shape + // and type instead of asking the (freed) tensor. + int64_t const ne = m.sam_cache.embed_ne[0] * m.sam_cache.embed_ne[1] * m.sam_cache.embed_ne[2] * + m.sam_cache.embed_ne[3]; + std::span embed_bytes{ + m.sam_cache.embed_host->data.get(), size_t(ne) * ggml_type_size(m.sam_cache.embed_type)}; + transfer_to_backend(image_embed, embed_bytes); + transfer_to_backend(point_tensor, span(prompt_data.v, 4)); + + compute(graph, s.backend); + + tensor_data iou_data = transfer_from_backend(output.iou); + tensor_data mask_data = transfer_from_backend(output.masks); + + auto ious = iou_data.as_f32(); + json_value result; + result.set("width", int(image.extent[0])); + result.set("height", int(image.extent[1])); + + json_value iou_arr; + iou_arr.t = json_value::type::array; + for (float iou : ious) { + iou_arr.array.push_back(iou); + } + result.set("iou", std::move(iou_arr)); + + json_value masks_arr; + masks_arr.t = json_value::type::array; + for (size_t i = 0; i < 4; ++i) { + image_data mask = sam_process_mask(mask_data.as_f32(), int(i), image.extent, m.sam_p); + masks_arr.array.push_back(base64_encode(image_encode_png(mask))); + } + result.set("masks", std::move(masks_arr)); + return result; +} + +json_value birefnet_predict(server& s, model_entry& m, image_data const& image) { + size_t max_alloc = std::min(size_t(4096) * 1024 * 1024, s.cfg.max_arena_mb * 1024 * 1024); + birefnet_params p = birefnet_detect_params(m.file, image.extent, max_alloc); + image_data input_data = birefnet_process_input(image, p); + + compute_graph graph = compute_graph_init(6 * 1024); + model_ref model(m.weights, graph); + + // The precomputed buffers live in this request's graph context, so they + // are rebuilt per request (cheap, host-side work). + birefnet_buffers buffers = birefnet_precompute(model, p); + + tensor input = compute_graph_input( + model, GGML_TYPE_F32, {3, p.image_extent[0], p.image_extent[1], 1}); + tensor output = birefnet_predict(model, input, p); + + check_device_budget(graph, s); + compute_graph_allocate(graph, s.backend); + transfer_to_backend(input, input_data); + for (tensor_data const& buf : buffers) { + transfer_to_backend(buf); + } + compute(graph, s.backend); + + tensor_data output_data = transfer_from_backend(output); + image_data mask = birefnet_process_output(output_data.as_f32(), image.extent, p); + return image_to_json(mask); +} + +json_value depthany_predict(server& s, model_entry& m, image_data const& image) { + depthany_params p = depthany_detect_params(m.file, image.extent); + image_data input_data = depthany_process_input(image, p); + + compute_graph graph = compute_graph_init(); + model_ref model(m.weights, graph); + tensor input = compute_graph_input( + model, GGML_TYPE_F32, {3, p.image_extent[0], p.image_extent[1], 1}); + tensor output = depthany_predict(model, input, p); + + check_device_budget(graph, s); + compute_graph_allocate(graph, s.backend); + transfer_to_backend(input, input_data); + compute(graph, s.backend); + + tensor_data output_data = transfer_from_backend(output); + image_data depth_raw = depthany_process_output(output_data.as_f32(), image.extent, p); + return image_to_json(image_f32_to_u8(depth_raw, image_format::alpha_u8)); +} + +json_value migan_predict( + server& s, model_entry& m, image_data const& image, image_data const& mask) { + image_data input_data = migan_process_input(image, mask, m.migan_p); + + compute_graph graph = compute_graph_init(); + model_ref model(m.weights, graph); + i64x4 input_shape = {4, m.migan_p.resolution, m.migan_p.resolution, 1}; + tensor input = compute_graph_input(model, GGML_TYPE_F32, input_shape); + tensor output = migan_generate(model, input, m.migan_p); + + check_device_budget(graph, s); + compute_graph_allocate(graph, s.backend); + transfer_to_backend(input, input_data); + compute(graph, s.backend); + + tensor_data output_data = transfer_from_backend(output); + image_data output_image = migan_process_output(output_data.as_f32(), image.extent, m.migan_p); + image_data mask_resized = image_scale(mask, image.extent); + image_data composited = image_alpha_composite(output_image, image, mask_resized); + return image_to_json(composited); +} + +json_value esrgan_predict(server& s, model_entry& m, image_data const& image, int tile_size) { + if (tile_size <= 0) { + throw http_error(400, "Invalid tile size: {}", tile_size); + } + + tile_layout tiles = tile_layout(image.extent, tile_size, 16); + tile_layout tiles_out = tile_scale(tiles, m.esrgan_p.scale); + image_data input_tile = image_alloc(tiles.tile_size, image_format::rgb_f32); + image_data output_tile = image_alloc(tiles_out.tile_size, image_format::rgb_f32); + image_data output_image = image_alloc(image.extent * m.esrgan_p.scale, image_format::rgb_f32); + image_clear(output_image); + + compute_graph graph = compute_graph_init(esrgan_estimate_graph_size(m.esrgan_p)); + model_ref model(m.weights, graph); + i64x4 input_shape = {3, tiles.tile_size[0], tiles.tile_size[1], 1}; + tensor input = compute_graph_input(model, GGML_TYPE_F32, input_shape); + tensor output = esrgan_generate(model, input, m.esrgan_p); + check_device_budget(graph, s); + compute_graph_allocate(graph, s.backend); + + for (int t = 0; t < tiles.total(); ++t) { + i32x2 tile_coord = tiles.coord(t); + i32x2 tile_offset = tiles.start(tile_coord); + image_u8_to_f32(image, input_tile, f32x4(0), f32x4(1), tile_offset); + transfer_to_backend(input, input_tile); + compute(graph, s.backend); + transfer_from_backend(output, output_tile); + tile_merge(output_tile, output_image, tile_coord, tiles_out); + } + + return image_to_json(image_f32_to_u8(output_image, image_format::rgba_u8)); +} + +json_value server_health(server& s) { + json_value v; + v.set("status", std::string("ok")); + v.set("backend", std::string(to_string(s.backend.type()))); + + json_value models; + models.t = json_value::type::array; + for (auto const& m : s.models) { + if (!m.loaded) { + continue; + } + json_value e; + e.set("family", to_string(m.family)); + e.set("path", m.path); + models.array.push_back(std::move(e)); + } + v.set("models", std::move(models)); + return v; +} + +// Routes one parsed request. Throws http_error for client errors and +// except for everything unexpected. +json_value server_handle(server& s, http_request const& req) { + std::string method = req.method; + std::string path = req.path; + + if (path == "/health") { + if (method != "GET" && method != "POST") { + throw http_error(405, "Method not allowed: {} {}", method, path); + } + return server_health(s); + } + + bool known = path == "/sam" || path == "/birefnet" || path == "/depth" || + path == "/depth_anything" || path == "/migan" || path == "/esrgan"; + if (method != "POST") { + // Known routes only accept POST; unknown paths 404 regardless of method. + if (known) { + throw http_error(405, "Method not allowed: {} {}", method, path); + } + throw http_error(404, "Unknown route: {} {}", method, path); + } + if (!known) { + throw http_error(404, "Unknown route: {} {}", method, path); + } + + json_value req_json; + try { + req_json = json_parse(req.body); + } catch (std::exception const& e) { + throw http_error(400, "Invalid JSON: {}", e.what()); + } + if (!req_json.is_object()) { + throw http_error(400, "Request body must be a JSON object"); + } + + auto get_image = [&](char const* field) { + try { + std::string const& b64 = req_json.get_string(field); + return image_decode_rgb(base64_decode(base64_of(b64))); + } catch (std::exception const& e) { + throw http_error(400, "Invalid '{}' image: {}", field, e.what()); + } + }; + + if (path == "/sam") { + model_entry& m = server_find_model(s, model_family::sam); + image_data image = get_image("image"); + return sam_predict(s, m, image, req_json); + } + + if (path == "/birefnet") { + model_entry& m = server_find_model(s, model_family::birefnet); + return birefnet_predict(s, m, get_image("image")); + } + + if (path == "/depth" || path == "/depth_anything") { + model_entry& m = server_find_model(s, model_family::depth_anything); + return depthany_predict(s, m, get_image("image")); + } + + if (path == "/migan") { + model_entry& m = server_find_model(s, model_family::migan); + image_data image = get_image("image"); + image_data mask; + try { + mask = image_decode_alpha(base64_decode(base64_of(req_json.get_string("mask")))); + } catch (std::exception const& e) { + throw http_error(400, "Invalid 'mask' image: {}", e.what()); + } + return migan_predict(s, m, image, mask); + } + + if (path == "/esrgan") { + model_entry& m = server_find_model(s, model_family::esrgan); + int tile_size = 224; + if (json_value const* t = req_json.find("tile")) { + if (t->is_number()) { + tile_size = int(t->number); + } else { + throw http_error(400, "'tile' must be a number"); + } + } + return esrgan_predict(s, m, get_image("image"), tile_size); + } + + throw http_error(404, "Unknown route: {} {}", method, path); +} + +// +// Server lifecycle + +void handle_connection(server& s, int fd) { + timer t; + int status = 500; + std::string method = "?"; + std::string path = "?"; + try { + http_request req = http_read(fd); + method = req.method; + path = req.path; + std::lock_guard lock(s.infer_mutex); + http_response resp; + resp.json(server_handle(s, req)); + http_write(fd, resp); + status = resp.status; + } catch (std::exception const& e) { + http_response resp; + resp.error(500, e.what()); + if (auto const* he = dynamic_cast(&e)) { + resp.status = he->status; + } + http_write(fd, resp); + status = resp.status; + } catch (...) { + http_response resp; + resp.error(500, "Internal error"); + http_write(fd, resp); + } + ::close(fd); + fixed_string<16> ts; + t.elapsed_str(ts); + fprintf( + stderr, "[vision-server] %s %s -> %d (%s)\n", method.c_str(), path.c_str(), status, + ts.c_str()); +} + +void server_start(server& s) { + timer t; + printf("Initializing backend... "); + if (s.cfg.backend) { + s.backend = backend_init(*s.cfg.backend); + } else { + s.backend = backend_init(); + } + fixed_string<16> ts; + t.elapsed_str(ts); + printf("done (%s)\n", ts.c_str()); + + ggml_backend_dev_t dev = ggml_backend_get_device(s.backend); + printf("- device: %s - %s\n", ggml_backend_dev_name(dev), ggml_backend_dev_description(dev)); + + reserve_arena(s.backend, s.cfg.max_arena_mb * 1024 * 1024); + + s.models.resize(s.cfg.models.size()); + for (size_t i = 0; i < s.cfg.models.size(); ++i) { + s.models[i].path = s.cfg.models[i]; + } + server_load_models(s); + + s.listen_fd = ::socket(AF_INET, SOCK_STREAM, 0); + if (s.listen_fd < 0) { + throw except("socket() failed"); + } + int on = 1; + setsockopt(s.listen_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); + + sockaddr_in addr{}; + addr.sin_family = AF_INET; + addr.sin_port = htons(uint16_t(s.cfg.port)); + if (inet_pton(AF_INET, s.cfg.listen.c_str(), &addr.sin_addr) != 1) { + throw except("Invalid listen address: {}", s.cfg.listen); + } + if (::bind(s.listen_fd, (sockaddr*)&addr, sizeof(addr)) < 0) { + throw except("bind() failed for {}:{}", s.cfg.listen, s.cfg.port); + } + if (::listen(s.listen_fd, 16) < 0) { + throw except("listen() failed"); + } + printf("Serving on http://%s:%d (Ctrl+C to stop)\n", s.cfg.listen.c_str(), s.cfg.port); +} + +// +// CLI + +char const* const short_usage = R"( +Usage: vision-server [options] +See 'vision-server --help' for more details. +)"; + +void print_usage() { + char const* const usage = R"( +Usage: vision-server [options] + +Options: + -l, --listen Address to listen on (default: 127.0.0.1) + -p, --port Port to listen on (default: 8080) + -m, --model Model file (.gguf), repeatable + -b, --backend Backend type (default: auto) + --max-arena Device-memory budget per request (default: 4096) - probed at boot + and enforced before each graph allocation, so the server fails + loudly instead of starving other GPU tenants + -h, --help Print usage and exit + +Routes (images are PNG or JPEG, base64-encoded; data: URLs accepted): + GET /health Server and model status + POST /sam {"image": "", "point": {"x","y"} | "box": {"x1","y1","x2","y2"}} + -> {"width","height","iou":[4],"masks":[4 b64 PNGs]} + POST /birefnet {"image": ""} + -> {"width","height","image": ""} + POST /depth {"image": ""} + -> {"width","height","image": ""} + POST /migan {"image": "", "mask": ""} + -> {"width","height","image": ""} + POST /esrgan {"image": "", "tile"?: } + -> {"width","height","image": ""} +)"; + printf("%s", usage); +} + +char const* next_arg(int argc, char** argv, int& i) { + if (++i < argc) { + return argv[i]; + } else { + throw except("Missing argument after {}", argv[i - 1]); + } +} + +int parse_int(std::string_view arg) { + int value = 0; + auto [ptr, ec] = std::from_chars(arg.data(), arg.data() + arg.size(), value); + if (ec != std::errc()) { + throw except("Invalid integer argument: {}", arg); + } + return value; +} + +void parse_args(int argc, char** argv, server_config& cfg) { + for (int i = 1; i < argc; ++i) { + std::string_view arg = argv[i]; + if (arg == "-l" || arg == "--listen") { + cfg.listen = next_arg(argc, argv, i); + } else if (arg == "-p" || arg == "--port") { + cfg.port = parse_int(next_arg(argc, argv, i)); + } else if (arg == "-m" || arg == "--model") { + cfg.models.push_back(next_arg(argc, argv, i)); + } else if (arg == "-b" || arg == "--backend") { + std::string_view b = next_arg(argc, argv, i); + if (b == "auto") { + cfg.backend = std::nullopt; + } else if (b == "cpu") { + cfg.backend = backend_type::cpu; + } else if (b == "gpu") { + cfg.backend = backend_type::gpu; + } else { + throw except("Unknown backend type '{}', must be one of: auto, cpu, gpu", b); + } + } else if (arg == "--max-arena") { + cfg.max_arena_mb = size_t(parse_int(next_arg(argc, argv, i))); + } else if (arg == "-h" || arg == "--help") { + print_usage(); + std::exit(0); + } else { + throw except("Unknown argument: {}\n{}", arg, short_usage); + } + } +} + +std::atomic g_stop{false}; + +} // namespace visp + +// +// main + +int main(int argc, char** argv) { + using namespace visp; + try { + ggml_time_init(); + + server_config cfg; + parse_args(argc, argv, cfg); + + server s; + s.cfg = cfg; + + auto on_signal = [](int) { + g_stop = true; + }; + signal(SIGINT, on_signal); + signal(SIGTERM, on_signal); + + server_start(s); + s.running = true; + while (s.running && !g_stop) { + timeval tv{.tv_sec = 0, .tv_usec = 200 * 1000}; + setsockopt(s.listen_fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + sockaddr_in client{}; + socklen_t len = sizeof(client); + int fd = ::accept(s.listen_fd, (sockaddr*)&client, &len); + if (fd >= 0) { + std::thread(handle_connection, std::ref(s), fd).detach(); + } + } + s.running = false; + ::shutdown(s.listen_fd, SHUT_RDWR); + ::close(s.listen_fd); + } catch (std::exception const& e) { + printf("Error: %s\n", e.what()); + return 1; + } catch (...) { + printf("Error: unknown\n"); + return 1; + } + return 0; +} diff --git a/src/util/json.h b/src/util/json.h new file mode 100644 index 0000000..beab754 --- /dev/null +++ b/src/util/json.h @@ -0,0 +1,482 @@ +#pragma once + +#include "string.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace visp { + +// +// JSON value - minimal, ordered tree +// +// A small self-contained implementation (no external dependency) for the +// HTTP server. Object keys keep insertion order and duplicate keys are +// allowed in parsed values (the last one wins on lookup). + +struct json_value { + enum class type { null, boolean, number, string, array, object }; + + type t = type::null; + bool boolean = false; + double number = 0.0; + std::string string; + std::vector array; + std::vector> object; + + json_value() = default; + + json_value(bool v) : t(type::boolean), boolean(v) {} + json_value(int v) : t(type::number), number(v) {} + json_value(int64_t v) : t(type::number), number(double(v)) {} + json_value(size_t v) : t(type::number), number(double(v)) {} + json_value(float v) : t(type::number), number(v) {} + json_value(double v) : t(type::number), number(v) {} + json_value(char const* v) : t(type::string), string(v) {} + json_value(std::string const& v) : t(type::string), string(v) {} + json_value(std::string&& v) : t(type::string), string(std::move(v)) {} + json_value(std::string_view v) : t(type::string), string(v) {} + + bool is_null() const { return t == type::null; } + bool is_bool() const { return t == type::boolean; } + bool is_number() const { return t == type::number; } + bool is_string() const { return t == type::string; } + bool is_array() const { return t == type::array; } + bool is_object() const { return t == type::object; } + + // Find a member of an object. Returns nullptr when absent or not an object. + json_value* find(char const* key) { + if (t != type::object) { + return nullptr; + } + for (auto& [k, v] : object) { + if (k == key) { + return &v; + } + } + return nullptr; + } + + json_value const* find(char const* key) const { + return const_cast(this)->find(key); + } + + // Typed getters. Throw `except` (a user-recoverable error) when the + // member is absent or has a different type, so callers can be written + // without null checks. + int get_int(char const* key) const { + json_value const* v = find(key); + if (!v) { + throw except("Missing JSON member: {}", key); + } + if (!v->is_number()) { + throw except("JSON member '{}' is not a number", key); + } + return int(v->number); + } + + int64_t get_int64(char const* key) const { + json_value const* v = find(key); + if (!v) { + throw except("Missing JSON member: {}", key); + } + if (!v->is_number()) { + throw except("JSON member '{}' is not a number", key); + } + return int64_t(v->number); + } + + double get_double(char const* key) const { + json_value const* v = find(key); + if (!v) { + throw except("Missing JSON member: {}", key); + } + if (!v->is_number()) { + throw except("JSON member '{}' is not a number", key); + } + return v->number; + } + + bool get_bool(char const* key) const { + json_value const* v = find(key); + if (!v) { + throw except("Missing JSON member: {}", key); + } + if (v->t != type::boolean) { + throw except("JSON member '{}' is not a boolean", key); + } + return v->boolean; + } + + std::string const& get_string(char const* key) const { + json_value const* v = find(key); + if (!v) { + throw except("Missing JSON member: {}", key); + } + if (!v->is_string()) { + throw except("JSON member '{}' is not a string", key); + } + return v->string; + } + + // Add or replace a member of an object. + json_value& set(char const* key, json_value&& value) { + if (t != type::object) { + *this = json_value(); + t = type::object; + } + if (json_value* v = find(key)) { + *v = std::move(value); + return *v; + } + object.emplace_back(key, std::move(value)); + return object.back().second; + } +}; + +// +// Parser + +namespace json_detail { + +struct parser { + std::string_view in; + size_t pos = 0; + int depth = 0; + + static constexpr int max_depth = 32; + + void skip_ws() { + while (pos < in.size() && + (in[pos] == ' ' || in[pos] == '\t' || in[pos] == '\n' || in[pos] == '\r')) { + ++pos; + } + } + + char peek() { + if (pos >= in.size()) { + throw except("Unexpected end of JSON input"); + } + return in[pos]; + } + + void expect(char c) { + if (peek() != c) { + throw except("Expected '{}' in JSON, found '{}'", c, peek()); + } + ++pos; + } + + json_value parse() { + skip_ws(); + json_value v = parse_value(); + skip_ws(); + if (pos != in.size()) { + throw except("Trailing data after JSON value"); + } + return v; + } + + json_value parse_value() { + if (++depth > max_depth) { + throw except("JSON nesting too deep (max {})"); + } + skip_ws(); + json_value v = [this]() { + switch (peek()) { + case 'n': expect_literal("null"); return json_value(); + case 't': expect_literal("true"); return json_value(true); + case 'f': expect_literal("false"); return json_value(false); + case '"': return json_value(parse_string()); + case '[': return parse_array(); + case '{': return parse_object(); + default: return parse_number(); + } + }(); + --depth; + return v; + } + + void expect_literal(char const* lit) { + size_t len = std::char_traits::length(lit); + if (in.substr(pos, len) != lit) { + throw except("Invalid JSON literal"); + } + pos += len; + } + + std::string parse_string() { + expect('"'); + std::string out; + for (;;) { + if (pos >= in.size()) { + throw except("Unterminated JSON string"); + } + char c = in[pos++]; + if (c == '"') { + break; + } + if (c == '\\') { + if (pos >= in.size()) { + throw except("Unterminated JSON escape"); + } + char e = in[pos++]; + switch (e) { + case '"': out += '"'; break; + case '\\': out += '\\'; break; + case '/': out += '/'; break; + case 'b': out += '\b'; break; + case 'f': out += '\f'; break; + case 'n': out += '\n'; break; + case 'r': out += '\r'; break; + case 't': out += '\t'; break; + case 'u': { + uint32_t cp = parse_hex4(); + // A high surrogate must be followed by a low surrogate. + if (cp >= 0xD800 && cp <= 0xDBFF) { + if (pos + 1 < in.size() && in[pos] == '\\' && in[pos + 1] == 'u') { + pos += 2; + uint32_t lo = parse_hex4(); + if (lo < 0xDC00 || lo > 0xDFFF) { + throw except("Invalid UTF-16 surrogate pair"); + } + cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00); + } else { + throw except("Unpaired UTF-16 surrogate"); + } + } + append_utf8(out, cp); + break; + } + default: throw except("Invalid JSON escape: \\{}", e); + } + } else if (uint8_t(c) < 0x20) { + throw except("Unescaped control character in JSON string"); + } else { + out += c; + } + } + return out; + } + + uint32_t parse_hex4() { + if (pos + 4 > in.size()) { + throw except("Truncated \\u escape"); + } + uint32_t v = 0; + for (int i = 0; i < 4; ++i) { + char c = in[pos++]; + v <<= 4; + if (c >= '0' && c <= '9') { + v |= uint32_t(c - '0'); + } else if (c >= 'a' && c <= 'f') { + v |= uint32_t(c - 'a' + 10); + } else if (c >= 'A' && c <= 'F') { + v |= uint32_t(c - 'A' + 10); + } else { + throw except("Invalid \\u escape: {}", c); + } + } + return v; + } + + static void append_utf8(std::string& out, uint32_t cp) { + if (cp < 0x80) { + out += char(cp); + } else if (cp < 0x800) { + out += char(0xC0 | (cp >> 6)); + out += char(0x80 | (cp & 0x3F)); + } else if (cp < 0x10000) { + out += char(0xE0 | (cp >> 12)); + out += char(0x80 | ((cp >> 6) & 0x3F)); + out += char(0x80 | (cp & 0x3F)); + } else { + out += char(0xF0 | (cp >> 18)); + out += char(0x80 | ((cp >> 12) & 0x3F)); + out += char(0x80 | ((cp >> 6) & 0x3F)); + out += char(0x80 | (cp & 0x3F)); + } + } + + json_value parse_number() { + size_t start = pos; + if (peek() == '-') { + ++pos; + } + while (pos < in.size() && + (std::isdigit(uint8_t(in[pos])) || in[pos] == '.' || in[pos] == 'e' || + in[pos] == 'E' || in[pos] == '+' || in[pos] == '-')) { + ++pos; + } + if (start == pos) { + throw except("Invalid JSON value at byte {}", pos); + } + std::string_view num = in.substr(start, pos - start); + // Reject forms that strtod would silently accept but JSON does not + // (eg. "01", "1e", "-"). A leading zero before a decimal point is + // required for fractions below one ("0.5") and is valid. + if (num.size() > 1 && num[0] == '0' && std::isdigit(uint8_t(num[1]))) { + throw except("Invalid JSON number: {}", num); + } + char const* digits = num.data(); + char* end = nullptr; + double v = std::strtod(digits, &end); + if (end != digits + num.size() || !std::isfinite(v)) { + throw except("Invalid JSON number: {}", num); + } + return json_value(v); + } + + json_value parse_array() { + expect('['); + json_value v; + v.t = json_value::type::array; + skip_ws(); + if (peek() == ']') { + ++pos; + return v; + } + for (;;) { + v.array.push_back(parse_value()); + skip_ws(); + char c = peek(); + if (c == ',') { + ++pos; + } else if (c == ']') { + ++pos; + return v; + } else { + throw except("Expected ',' or ']' in JSON array"); + } + } + } + + json_value parse_object() { + expect('{'); + json_value v; + v.t = json_value::type::object; + skip_ws(); + if (peek() == '}') { + ++pos; + return v; + } + for (;;) { + skip_ws(); + std::string key = parse_string(); + skip_ws(); + expect(':'); + v.object.emplace_back(std::move(key), parse_value()); + skip_ws(); + char c = peek(); + if (c == ',') { + ++pos; + } else if (c == '}') { + ++pos; + return v; + } else { + throw except("Expected ',' or '}' in JSON object"); + } + } + } +}; + +} // namespace json_detail + +inline json_value json_parse(std::string_view text) { + json_detail::parser p; + p.in = text; + return p.parse(); +} + +// +// Writer + +namespace json_detail { + +inline void escape_into(std::string& out, std::string_view s) { + out += '"'; + for (char c : s) { + switch (c) { + case '"': out += "\\\""; break; + case '\\': out += "\\\\"; break; + case '\b': out += "\\b"; break; + case '\f': out += "\\f"; break; + case '\n': out += "\\n"; break; + case '\r': out += "\\r"; break; + case '\t': out += "\\t"; break; + default: + if (uint8_t(c) < 0x20) { + char buf[8]; + std::snprintf(buf, sizeof(buf), "\\u%04x", c); + out += buf; + } else { + out += c; + } + } + } + out += '"'; +} + +inline void number_into(std::string& out, double v) { + if (std::isfinite(v) && v == std::floor(v) && std::abs(v) <= 9007199254740992.0) { + out += std::to_string(int64_t(v)); + } else { + char buf[32]; + std::snprintf(buf, sizeof(buf), "%.17g", v); + out += buf; + } +} + +inline void write_value(std::string& out, json_value const& v) { + switch (v.t) { + case json_value::type::null: out += "null"; break; + case json_value::type::boolean: out += v.boolean ? "true" : "false"; break; + case json_value::type::number: number_into(out, v.number); break; + case json_value::type::string: escape_into(out, v.string); break; + case json_value::type::array: { + out += '['; + for (size_t i = 0; i < v.array.size(); ++i) { + if (i) { + out += ','; + } + write_value(out, v.array[i]); + } + out += ']'; + break; + } + case json_value::type::object: { + out += '{'; + for (size_t i = 0; i < v.object.size(); ++i) { + if (i) { + out += ','; + } + escape_into(out, v.object[i].first); + out += ':'; + write_value(out, v.object[i].second); + } + out += '}'; + break; + } + } +} + +} // namespace json_detail + +inline void json_write(std::string& out, json_value const& v) { + json_detail::write_value(out, v); +} + +inline std::string json_write(json_value const& v) { + std::string out; + json_write(out, v); + return out; +} + +} // namespace visp diff --git a/src/util/string.h b/src/util/string.h index 220b751..e186b50 100644 --- a/src/util/string.h +++ b/src/util/string.h @@ -2,8 +2,14 @@ #include "visp/util.h" +#include +#include #include +#include +#include +#include #include +#include #ifdef VISP_FMT_LIB # include @@ -83,6 +89,87 @@ exception except(char const* fmt, Args&&... args) { return exception(format>(fmt, std::forward(args)...)); } +// +// Base64 + +inline std::string base64_encode(std::span data) { + static char const alphabet[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + std::string out; + out.reserve((data.size() + 2) / 3 * 4); + size_t i = 0; + while (i + 3 <= data.size()) { + uint32_t v = (uint32_t(uint8_t(data[i])) << 16) | (uint32_t(uint8_t(data[i + 1])) << 8) | + uint32_t(uint8_t(data[i + 2])); + out += alphabet[(v >> 18) & 63]; + out += alphabet[(v >> 12) & 63]; + out += alphabet[(v >> 6) & 63]; + out += alphabet[v & 63]; + i += 3; + } + if (i < data.size()) { + uint32_t v = uint32_t(uint8_t(data[i])) << 16; + bool two = i + 1 < data.size(); + if (two) { + v |= uint32_t(uint8_t(data[i + 1])) << 8; + } + out += alphabet[(v >> 18) & 63]; + out += alphabet[(v >> 12) & 63]; + out += two ? alphabet[(v >> 6) & 63] : '='; + out += '='; + } + return out; +} + +inline std::vector base64_decode(std::string_view in) { + auto value = [](char c) -> int { + if (c >= 'A' && c <= 'Z') + return c - 'A'; + if (c >= 'a' && c <= 'z') + return c - 'a' + 26; + if (c >= '0' && c <= '9') + return c - '0' + 52; + if (c == '+') + return 62; + if (c == '/') + return 63; + throw except("Invalid base64 character: {}", c); + }; + std::string_view s = in; + size_t pad = 0; + while (!s.empty() && (s.back() == '=' || s.back() == '\n' || s.back() == '\r')) { + if (s.back() == '=') { + ++pad; + } + s.remove_suffix(1); + } + // A valid stream is a multiple of four including padding; the stripped + // tail (2 or 3 chars) is the final partial group. + if (in.size() % 4 != 0) { + throw except("Invalid base64 length: {}", in.size()); + } + if (pad > 2) { + throw except("Too much base64 padding"); + } + std::vector out; + out.reserve(s.size() / 4 * 3); + size_t i = 0; + while (i < s.size()) { + size_t chunk = std::min(size_t(4), s.size() - i); + uint32_t v = 0; + for (size_t j = 0; j < chunk; ++j) { + v = (v << 6) | uint32_t(value(s[i + j])); + } + v <<= (4 - chunk) * 6; // align a short final group to the top + size_t nbytes = (chunk * 3) / 4; + for (size_t b = 0; b < nbytes; ++b) { + out.push_back(std::byte((v >> (16 - 8 * b)) & 0xFF)); + } + i += chunk; + } + return out; +} + inline void assertion_failure(char const* file, int line, char const* expr) { auto msg = format>("Assertion failed at {}:{}: {}\n", file, line, expr); fwrite(msg.data, 1, msg.length, stderr); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index f31792d..a3b6414 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -59,6 +59,24 @@ add_test(NAME python WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} COMMAND uv run pytest -vs tests ${PYTHON_TESTS_ARGS}) +# +# HTTP server tests (POSIX only) + +if(UNIX) + add_executable(test-server) + target_sources(test-server PRIVATE + testing.cpp + test-json.cpp + test-server.cpp + ) + target_include_directories(test-server PRIVATE . ../src) + target_compile_definitions(test-server PRIVATE ${VISP_ASSERT} ${VISP_DEFINITIONS}) + target_compile_options(test-server PRIVATE ${VISP_WARNINGS} ${VISP_COMP_OPTIONS}) + target_link_options(test-server PRIVATE ${VISP_LINK_OPTIONS}) + target_link_libraries(test-server PRIVATE visioncpp ${VISP_FMT_LINK}) + add_test(NAME server COMMAND test-server -v) +endif() + # # Benchmarks diff --git a/tests/test-json.cpp b/tests/test-json.cpp new file mode 100644 index 0000000..3724f3f --- /dev/null +++ b/tests/test-json.cpp @@ -0,0 +1,188 @@ +#include "testing.h" +#include "util/json.h" + +namespace visp { + +VISP_TEST(json_null) { + json_value v = json_parse("null"); + CHECK(v.is_null()); +} + +VISP_TEST(json_bool) { + json_value v = json_parse("{\"b\": true}"); + CHECK(v.get_bool("b")); +} + +VISP_TEST(json_number) { + json_value v = json_parse("-12.5e+2"); + CHECK(v.is_number()); + CHECK_EQUAL(v.number, -1250.0); +} + +VISP_TEST(json_number_rejects_leading_zero) { + bool failed = false; + try { + json_parse("012"); + } catch (std::exception const&) { + failed = true; + } + CHECK(failed); +} + +VISP_TEST(json_string_escapes) { + json_value v = json_parse("\"a\\\"b\\\\c\\n\\ud83d\\ude00\""); + CHECK(v.is_string()); + CHECK_EQUAL(v.string, std::string("a\"b\\c\n") + "\xF0\x9F\x98\x80"); +} + +VISP_TEST(json_string_rejects_control) { + bool failed = false; + try { + json_parse("\"a\nb\""); + } catch (std::exception const&) { + failed = true; + } + CHECK(failed); +} + +VISP_TEST(json_array) { + json_value v = json_parse("[1, 2.5, \"three\", [4], {}]"); + CHECK(v.is_array()); + CHECK_EQUAL(v.array.size(), size_t(5)); + CHECK(v.array[3].is_array()); + CHECK(v.array[4].is_object()); +} + +VISP_TEST(json_object) { + json_value v = json_parse("{ \"b\": 2, \"a\": 1 }"); + CHECK(v.is_object()); + CHECK_EQUAL(v.object.size(), size_t(2)); + // insertion order is preserved + CHECK_EQUAL(v.object[0].first, std::string("b")); + CHECK_EQUAL(v.find("a")->number, 1.0); + CHECK(v.find("missing") == nullptr); +} + +VISP_TEST(json_nested) { + json_value v = json_parse("{\"a\": {\"b\": [{\"c\": true}]}}"); + json_value const* c = v.find("a")->find("b")->array[0].find("c"); + CHECK(c != nullptr); + CHECK(c->is_bool() && c->boolean); +} + +VISP_TEST(json_getters) { + json_value v = json_parse("{\"i\": 42, \"d\": 1.5, \"s\": \"x\", \"b\": false}"); + CHECK_EQUAL(v.get_int("i"), 42); + CHECK_EQUAL(v.get_double("d"), 1.5); + CHECK_EQUAL(v.get_string("s"), std::string("x")); + CHECK(v.get_bool("b") == false); +} + +VISP_TEST(json_getter_missing) { + json_value v = json_parse("{}"); + bool failed = false; + try { + v.get_int("nope"); + } catch (std::exception const&) { + failed = true; + } + CHECK(failed); +} + +VISP_TEST(json_getter_wrong_type) { + json_value v = json_parse("{\"n\": \"not a number\"}"); + bool failed = false; + try { + v.get_int("n"); + } catch (std::exception const&) { + failed = true; + } + CHECK(failed); +} + +VISP_TEST(json_set) { + json_value v; + v.set("a", 1); + v.set("b", std::string("two")); + v.set("a", 3); // replace + CHECK_EQUAL(v.object.size(), size_t(2)); + CHECK_EQUAL(v.find("a")->number, 3.0); +} + +VISP_TEST(json_write_roundtrip) { + json_value v; + v.set("name", std::string("he said \"hi\" \n")); + v.set("count", 3); + json_value arr; + arr.t = json_value::type::array; + arr.array.push_back(1.5); + arr.array.push_back(json_value()); // null + v.set("items", std::move(arr)); + + std::string text = json_write(v); + json_value r = json_parse(text); + CHECK_EQUAL(r.get_string("name"), std::string("he said \"hi\" \n")); + CHECK_EQUAL(r.get_int("count"), 3); + CHECK_EQUAL(r.find("items")->array.size(), size_t(2)); + CHECK(r.find("items")->array[1].is_null()); +} + +VISP_TEST(json_write_integers_stay_integers) { + json_value v; + v.set("a", 42); + v.set("b", 0.5); + std::string text = json_write(v); + CHECK(text.find("42,") != std::string::npos); + CHECK(text.find("42.0") == std::string::npos); +} + +VISP_TEST(json_trailing_data_rejected) { + bool failed = false; + try { + json_parse("1 2"); + } catch (std::exception const&) { + failed = true; + } + CHECK(failed); +} + +VISP_TEST(json_depth_limit) { + std::string deep(100, '['); + bool failed = false; + try { + json_parse(deep); + } catch (std::exception const&) { + failed = true; + } + CHECK(failed); +} + +VISP_TEST(json_base64_roundtrip) { + std::vector data{ + std::byte(0), std::byte(1), std::byte(2), std::byte(255), std::byte(128), std::byte(64)}; + std::string enc = base64_encode(data); + auto dec = base64_decode(enc); + CHECK_EQUAL(dec.size(), data.size()); + for (size_t i = 0; i < data.size(); ++i) { + CHECK_EQUAL(uint8_t(dec[i]), uint8_t(data[i])); + } + // single and double remainder + CHECK( + base64_decode(base64_encode(std::vector{std::byte(7)})) == + std::vector{std::byte(7)}); + CHECK( + base64_decode(base64_encode(std::vector{std::byte(1), std::byte(2)})) == + std::vector{std::byte(1), std::byte(2)}); +} + +VISP_TEST(json_base64_rejects_garbage) { + bool failed = false; + try { + base64_decode("!!!!"); + } catch (std::exception const&) { + failed = true; + } + CHECK(failed); +} + +} // namespace visp diff --git a/tests/test-server.cpp b/tests/test-server.cpp new file mode 100644 index 0000000..d971a66 --- /dev/null +++ b/tests/test-server.cpp @@ -0,0 +1,369 @@ +// +// Functional tests for the vision-server binary: spawns a local server with +// the MobileSAM model, then exercises the HTTP API (including the +// Expect: 100-continue path that stalls naive HTTP/1.0-style servers). +// +// POSIX only - see the UNIX guard in CMake. + +#include "testing.h" +#include "util/json.h" +#include "util/string.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace visp { +using std::filesystem::path; + +static int connect_to(int port) { + int fd = ::socket(AF_INET, SOCK_STREAM, 0); + if (fd < 0) { + throw std::runtime_error("socket() failed"); + } + sockaddr_in addr{}; + addr.sin_family = AF_INET; + addr.sin_port = htons(uint16_t(port)); + if (inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr) != 1) { + throw std::runtime_error("inet_pton failed"); + } + if (::connect(fd, (sockaddr*)&addr, sizeof(addr)) < 0) { + ::close(fd); + throw std::runtime_error("connect() failed"); + } + return fd; +} + +static void send_all(int fd, std::string_view data) { + size_t sent = 0; + while (sent < data.size()) { + ssize_t n = ::send(fd, data.data() + sent, data.size() - sent, 0); + if (n <= 0) { + throw std::runtime_error("send() failed"); + } + sent += size_t(n); + } +} + +static std::string recv_until(int fd, char const* pattern) { + std::string out; + timeval tv{10, 0}; + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + char buf[4096]; + for (;;) { + ssize_t n = ::recv(fd, buf, sizeof(buf), 0); + if (n <= 0) { + throw std::runtime_error("timed out waiting for: " + std::string(pattern)); + } + out.append(buf, size_t(n)); + if (out.find(pattern) != std::string::npos) { + return out; + } + } +} + +// The server closes the connection after each response, so the remainder of +// the stream is the complete response. +static std::string read_rest(int fd) { + std::string out; + timeval tv{120, 0}; + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + char buf[65536]; + for (;;) { + ssize_t n = ::recv(fd, buf, sizeof(buf), 0); + if (n == 0) { + return out; + } + if (n < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { + continue; // keep waiting; the server closes after the response + } + throw std::runtime_error("recv() failed"); + } + out.append(buf, size_t(n)); + } +} + +struct test_server { + int pid = -1; + int port = 0; + + explicit test_server(std::vector extra_args = {}) + { + // Pick a free port + int probe = ::socket(AF_INET, SOCK_STREAM, 0); + if (probe < 0) { + throw std::runtime_error("socket() failed"); + } + sockaddr_in a{}; + a.sin_family = AF_INET; + a.sin_port = 0; + a.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + socklen_t len = sizeof(a); + if (::bind(probe, (sockaddr*)&a, sizeof(a)) < 0 || + ::getsockname(probe, (sockaddr*)&a, &len) < 0) { + throw std::runtime_error("port discovery failed"); + } + port = ntohs(a.sin_port); + ::close(probe); + + path server_path = test_dir().root / "build" / "bin" / "vision-server"; + if (!std::filesystem::exists(server_path)) { + throw std::runtime_error("vision-server binary not found at " + server_path.string()); + } + path model = test_dir().models / "MobileSAM-F16.gguf"; + + pid = fork(); + if (pid == 0) { + // Child + std::vector storage; + storage.push_back(server_path.string()); + storage.push_back("-l"); + storage.push_back("127.0.0.1"); + storage.push_back("-p"); + storage.push_back(std::to_string(port)); + storage.push_back("-b"); + storage.push_back("cpu"); + storage.push_back("-m"); + storage.push_back(model.string()); + // MobileSAM's CPU graph wants ~5.6 GB of live tensors; the default + // 4 GB budget would refuse it. Tests run where that is cheap. + if (extra_args.empty()) { + storage.push_back("--max-arena"); + storage.push_back("16384"); + } + for (auto& a : extra_args) { + storage.push_back(a); + } + std::vector argv; + for (auto& s : storage) { + argv.push_back(const_cast(s.c_str())); + } + argv.push_back(nullptr); + execv(server_path.c_str(), argv.data()); + _exit(127); + } + + // Wait for /health + for (int i = 0; i < 120; ++i) { + try { + int fd = connect_to(port); + send_all(fd, "GET /health HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"); + read_rest(fd); + ::close(fd); + return; + } catch (...) { + if (i % 5 == 4) { + // Check the child is still alive - a crash should fail the test, + // not wait out the whole timeout. + int st = 0; + if (::waitpid(pid, &st, WNOHANG) == pid) { + throw std::runtime_error("vision-server exited during startup"); + } + } + usleep(500 * 1000); + } + } + throw std::runtime_error("vision-server did not come up"); + } + + ~test_server() { + if (pid > 0) { + ::kill(pid, SIGTERM); + int st = 0; + ::waitpid(pid, &st, 0); + } + } +}; + +test_server& server() { + static test_server s; + return s; +} + +static std::string image_b64() { + path p = test_dir().input / "cat-and-hat.jpg"; + std::ifstream f(p, std::ios::binary); + std::vector raw((std::istreambuf_iterator(f)), std::istreambuf_iterator()); + if (raw.empty()) { + throw std::runtime_error("test image missing: " + p.string()); + } + std::vector data; + data.resize(raw.size()); + std::memcpy(data.data(), raw.data(), raw.size()); + return base64_encode(data); +} + +static int http_status(std::string const& response) { + if (response.size() < 12 || response.substr(0, 5) != "HTTP/") { + throw std::runtime_error("bad response: " + response.substr(0, 64)); + } + return std::atoi(response.substr(9, 3).c_str()); +} + +static json_value post_json(char const* route, std::string const& body) { + int fd = connect_to(server().port); + std::string req = std::string("POST ") + route + + " HTTP/1.1\r\nHost: 127.0.0.1\r\n" + "Content-Type: application/json\r\nContent-Length: " + + std::to_string(body.size()) + "\r\nConnection: close\r\n\r\n" + body; + send_all(fd, req); + std::string resp = read_rest(fd); + ::close(fd); + size_t sep = resp.find("\r\n\r\n"); + if (sep == std::string::npos) { + throw std::runtime_error("no response body"); + } + CHECK(http_status(resp) == 200); + return json_parse(resp.substr(sep + 4)); +} + +static json_value post_json_expect_status( + char const* route, std::string const& body, int expected) { + int fd = connect_to(server().port); + std::string req = std::string("POST ") + route + + " HTTP/1.1\r\nHost: 127.0.0.1\r\n" + "Content-Type: application/json\r\nContent-Length: " + + std::to_string(body.size()) + "\r\nConnection: close\r\n\r\n" + body; + send_all(fd, req); + std::string resp = read_rest(fd); + ::close(fd); + CHECK(http_status(resp) == expected); + size_t sep = resp.find("\r\n\r\n"); + if (sep == std::string::npos) { + return json_value(); + } + try { + return json_parse(resp.substr(sep + 4)); + } catch (...) { + return json_value(); // error bodies may be non-JSON on the worst path + } +} + +// The first eight bytes must be the PNG signature; width/height come from the +// IHDR chunk (big-endian u32s at offsets 16 and 20). +static void check_png(std::string const& b64, int expect_w, int expect_h) { + auto bytes = base64_decode(b64); + CHECK_EQUAL(bytes.size() > 33, true); + char const* sig = "\x89PNG\r\n\x1a\n"; + CHECK(std::memcmp(bytes.data(), sig, 8) == 0); + auto be32 = [&](size_t off) { + return (int)((uint32_t(uint8_t(bytes[off])) << 24) | + (uint32_t(uint8_t(bytes[off + 1])) << 16) | + (uint32_t(uint8_t(bytes[off + 2])) << 8) | uint32_t(uint8_t(bytes[off + 3]))); + }; + CHECK_EQUAL(be32(16), expect_w); + CHECK_EQUAL(be32(20), expect_h); +} + +VISP_TEST(server_health) { + int fd = connect_to(server().port); + send_all(fd, "GET /health HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"); + std::string resp = read_rest(fd); + ::close(fd); + CHECK(http_status(resp) == 200); + size_t sep = resp.find("\r\n\r\n"); + json_value v = json_parse(resp.substr(sep + 4)); + CHECK_EQUAL(v.get_string("status"), std::string("ok")); + CHECK_EQUAL(v.find("models")->array.size(), size_t(1)); + CHECK_EQUAL(v.find("models")->array[0].get_string("family"), std::string("sam")); +} + +VISP_TEST(server_sam_point) { + std::string body = "{\"image\": \"" + image_b64() + "\", \"point\": {\"x\": 100, \"y\": 100}}"; + json_value v = post_json("/sam", body); + int w = v.get_int("width"); + int h = v.get_int("height"); + CHECK(w > 0 && h > 0); + CHECK_EQUAL(v.find("iou")->array.size(), size_t(4)); + CHECK_EQUAL(v.find("masks")->array.size(), size_t(4)); + for (auto const& m : v.find("masks")->array) { + check_png(m.string, w, h); + } +} + +VISP_TEST(server_sam_box) { + std::string body = "{\"image\": \"" + image_b64() + + "\", \"box\": {\"x1\": 10, \"y1\": 10, \"x2\": 200, \"y2\": 200}}"; + json_value v = post_json("/sam", body); + CHECK_EQUAL(v.find("masks")->array.size(), size_t(4)); +} + +VISP_TEST(server_sam_box_rejects_inverted) { + std::string body = "{\"image\": \"" + image_b64() + + "\", \"box\": {\"x1\": 300, \"y1\": 300, \"x2\": 100, \"y2\": 100}}"; + post_json_expect_status("/sam", body, 400); +} + +VISP_TEST(server_rejects_over_budget) { + // A 16 MB device budget cannot hold MobileSAM's graph; the server must + // refuse before allocating, with the measured figure, not mid-alloc OOM. + test_server s({"--max-arena", "16"}); + std::string body = "{\"image\": \"" + image_b64() + "\", \"point\": {\"x\": 300, \"y\": 200}}"; + int fd = connect_to(s.port); + std::string head = "POST /sam HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: " + "application/json\r\nContent-Length: " + + std::to_string(body.size()) + "\r\n\r\n"; + send_all(fd, head); + send_all(fd, body); + std::string resp = read_rest(fd); + ::close(fd); + CHECK_EQUAL(http_status(resp), 503); + CHECK(resp.find("more than the 16 MB cap") != std::string::npos); +} + +VISP_TEST(server_expect_100_continue) { + std::string body = "{\"image\": \"" + image_b64() + "\", \"point\": {\"x\": 100, \"y\": 100}}"; + int fd = connect_to(server().port); + std::string head = "POST /sam HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: " + "application/json\r\nContent-Length: " + + std::to_string(body.size()) + "\r\nExpect: 100-continue\r\n\r\n"; + send_all(fd, head); + std::string interim = recv_until(fd, "100 Continue"); + CHECK(interim.find("HTTP/1.1 100 Continue") != std::string::npos); + send_all(fd, body); + std::string resp = read_rest(fd); + ::close(fd); + CHECK(http_status(resp) == 200); + size_t sep = resp.find("\r\n\r\n"); + json_value v = json_parse(resp.substr(sep + 4)); + CHECK_EQUAL(v.find("masks")->array.size(), size_t(4)); +} + +VISP_TEST(server_bad_json) { + post_json_expect_status("/sam", "{not json at all", 400); +} + +VISP_TEST(server_bad_image) { + std::string body = "{\"image\": \"!!!!\", \"point\": {\"x\": 1, \"y\": 1}}"; + post_json_expect_status("/sam", body, 400); +} + +VISP_TEST(server_unknown_route) { + int fd = connect_to(server().port); + send_all(fd, "GET /nope HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"); + std::string resp = read_rest(fd); + ::close(fd); + CHECK(http_status(resp) == 404); +} + +VISP_TEST(server_unloaded_model_404) { + std::string body = "{\"image\": \"" + image_b64() + "\"}"; + post_json_expect_status("/birefnet", body, 404); +} + +} // namespace visp