8#include "absl/status/status.h"
9#include "absl/status/statusor.h"
10#include "absl/strings/str_cat.h"
19void Send(
const absl::StatusOr<std::string>& json,
20 httplib::Response& response) {
22 response.status = absl::IsNotFound(json.status()) ? 404 : 400;
23 response.set_content(
ErrorJson(json.status().message()),
27 response.set_content(*json,
"application/json");
32absl::Status
Serve(
const Graph& graph,
const std::string& address,
int port) {
33 httplib::Server server;
37 server.set_socket_options([](socket_t fd) {
38 httplib::set_socket_opt(fd, SOL_SOCKET, SO_REUSEADDR, 1);
43 if (!server.set_mount_point(
"/", SMOLLERGRAPH_UI,
44 {{
"Cache-Control",
"no-cache"}})) {
45 return absl::NotFoundError(
46 absl::StrCat(
"there's no folder ", SMOLLERGRAPH_UI));
51 server.Get(
"/api/names", [&graph](
const httplib::Request& request,
52 httplib::Response& response) {
53 response.set_content(
NamesJson(graph, request.get_param_value(
"prefix")),
56 server.Get(
"/api/query", [&graph](
const httplib::Request& request,
57 httplib::Response& response) {
58 Send(
QueryJson(graph, request.get_param_value(
"q")), response);
60 server.Get(R
"(/api/node/(\d+))", [&graph](const httplib::Request& request,
61 httplib::Response& response) {
62 Send(
NodeJson(graph, request.matches[1].str()), response);
64 server.Get(R
"(/api/similar/(\d+))", [&graph](const httplib::Request& request,
65 httplib::Response& response) {
66 Send(
SimilarJson(graph, request.matches[1].str()), response);
68 if (!server.bind_to_port(address, port)) {
69 return absl::UnavailableError(
70 absl::StrCat(
"can't listen on ", address,
" port ", port));
73 std::cout <<
"Serving the graph on http://localhost:" << port << std::endl;
74 if (!server.listen_after_bind()) {
75 return absl::InternalError(
"stopped listening");
77 return absl::OkStatus();
A graph kept in three files of records, one for nodes, one for relationships and one for their proper...
absl::StatusOr< std::string > SimilarJson(const Graph &graph, std::string_view id)
Returns the kSimilar nodes whose embeddings are most like node id's, the most alike first,...
absl::StatusOr< std::string > QueryJson(const Graph &graph, std::string_view text)
absl::StatusOr< std::string > NodeJson(const Graph &graph, std::string_view id)
Returns node id's record as it's kept on disk: its label, its page, its offset in the page and its by...
std::string ErrorJson(std::string_view message)
Returns an error's message as JSON, for the UI to show.
std::string NamesJson(const Graph &graph, std::string_view prefix)
Returns a few of the graph's names that start with prefix, in order, for the UI to suggest.
absl::Status Serve(const Graph &graph, const std::string &address, int port)
Answers HTTP requests for the graph on address and port, until the process is stopped.