-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph_server.cpp
More file actions
288 lines (247 loc) · 7.99 KB
/
Copy pathgraph_server.cpp
File metadata and controls
288 lines (247 loc) · 7.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
#include "AdjacencyContainer.h"
#include "httplib.h"
#include "json.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <unordered_map>
using json = nlohmann::json;
using namespace std;
struct Node {
int id;
json props;
Node(int id_= 0, const json &p=json{}) : id(id_), props(p) {}
};
AdjacencyContainer graph;
unordered_map<int, Node> nodes;
string addNode(int id, const json &props) {
if (nodes.count(id)) {
return "Node already exists\n";
}
nodes[id] = Node(id, props);
return "Added node " + to_string(id) + "\n";
}
string addEdge(int u, int v, double w, const json &props) {
if (!nodes.count(u) || !nodes.count(v)) {
return "Node(s) missing\n";
}
graph.insert_edge({v, w});
return "Added edge " + to_string(u) + " -> " + to_string(v) + "\n";
}
string findNodeWhere(const string &key, const string &value) {
ostringstream oss;
for (auto &[id, node] : nodes) {
if (node.props.contains(key) && node.props[key].get<string>() == value) {
oss << "Node " << id << " matches\n";
}
}
return oss.str().empty() ? "No matching nodes\n" : oss.str();
}
string neighbors(int id) {
ostringstream oss;
for (auto &e : graph.neighbors()) {
oss << id << " -> " << e.to << " weight: " << e.weight << "\n";
}
return oss.str().empty() ? "No neighbors\n" : oss.str();
}
string printGraph() {
ostringstream oss;
oss << "Nodes:\n";
for (auto &[id, node] : nodes) {
oss << " " << id << " " << node.props.dump() << "\n";
}
oss << "Edges:\n";
for (auto &e : graph.neighbors()) {
oss << " " << e.to << " weight: " << e.weight << "\n";
}
return oss.str();
}
string saveGraph(const string &filename) {
json j;
j["nodes"] = json::array();
for (auto &[id, node] : nodes) {
json n;
n["id"] = node.id;
n["props"] = node.props;
j["nodes"].push_back(n);
}
j["edges"] = json::array();
for (auto &e : graph.neighbors()) {
json edge;
edge["to"] = e.to;
edge["weight"] = e.weight;
j["edges"].push_back(edge);
}
ofstream ofs(filename);
if (!ofs.is_open()) return "Failed to open file\n";
ofs << j.dump(4);
return "Graph saved to " + filename + "\n";
}
string loadGraph(const string &filename) {
ifstream ifs(filename);
if (!ifs.is_open()) return "Failed to open file\n";
json j;
ifs >> j;
nodes.clear();
graph.edges_list.clear();
graph.edges_cache.clear();
graph.cache_valid = false;
for (auto &n : j["nodes"]) {
nodes[n["id"].get<int>()] = Node(n["id"].get<int>(), n["props"]);
}
for (auto &e : j["edges"]) {
graph.insert_edge({e["to"].get<int>(), e["weight"].get<double>()});
}
return "Graph loaded from " + filename + "\n";
}
string clearGraph() {
nodes.clear();
graph.edges_list.clear();
graph.edges_cache.clear();
graph.cache_valid = false;
return "Graph cleared\n";
}
string deleteNode(int id) {
// 1. Check if node exists
if (nodes.find(id) == nodes.end())
return "Node not found\n";
// 2. Remove node from nodes map
nodes.erase(id);
// 3. Remove all edges pointing to or from this node
int removed = 0;
// Remove outgoing edges (from node `id`)
removed += graph.remove_edge_to(id);
// Remove incoming edges (edges that lead to `id`)
for (auto it = graph.edges_list.begin(); it != graph.edges_list.end(); ) {
if (it->to == id) {
it = graph.edges_list.erase(it);
removed++;
} else {
++it;
}
}
graph.cache_valid = false;
ostringstream oss;
oss << "Deleted Node " << id << " and " << removed << " edges\n";
return oss.str();
}
string deleteEdge(int from, int to) {
// Ensure 'from' node exists
if (nodes.find(from) == nodes.end())
return "Source node not found\n";
// Remove edges from `from` → `to`
int removed = graph.remove_edge_to(to);
if (removed == 0)
return "No edge found from " + to_string(from) + " to " + to_string(to) + "\n";
ostringstream oss;
oss << "Deleted " << removed << " edge(s) from " << from << " to " << to << "\n";
return oss.str();
}
// --- Main query parser ---
string executeQuery(const string &query) {
istringstream ss(query);
istringstream iss(query);
string cmd;
ostringstream output;
iss >> cmd;
while (ss >> cmd) {
if (cmd == "ADD") {
string type;
ss >> type;
if (type == "NODE") {
int id;
ss >> id;
string rest;
getline(ss, rest); // PROPS JSON
json props = json::object();
auto pos = rest.find("PROPS");
if (pos != string::npos) {
string jsonStr = rest.substr(pos + 5);
try { props = json::parse(jsonStr); } catch (...) {}
}
output << addNode(id, props);
} else if (type == "EDGE") {
int u, v;
double w;
ss >> u >> v >> w;
string rest;
getline(ss, rest); // PROPS (optional)
json props = json::object();
auto pos = rest.find("PROPS");
if (pos != string::npos) {
string jsonStr = rest.substr(pos + 5);
try { props = json::parse(jsonStr); } catch (...) {}
}
output << addEdge(u, v, w, props);
}
} else if (cmd == "FIND") {
string node, where, condition;
ss >> node >> where;
getline(ss, condition);
auto eqPos = condition.find('=');
if (eqPos != string::npos) {
string key = condition.substr(0, eqPos);
string value = condition.substr(eqPos + 1);
output << findNodeWhere(key, value);
}
} else if (cmd == "NEIGHBORS") {
int id;
ss >> id;
output << neighbors(id);
} else if (cmd == "PRINT") {
output << printGraph();
} else if (cmd == "SAVE") {
string filename;
ss >> filename;
output << saveGraph(filename);
} else if (cmd == "LOAD") {
string filename;
ss >> filename;
output << loadGraph(filename);
output << clearGraph();
} else if (cmd == "CLEAR") {
}
else if (cmd == "DELETE") {
string type;
iss >> type;
if (type == "NODE") {
int id;
iss >> id;
return deleteNode(id);
} else if (type == "EDGE") {
int from, to;
iss >> from >> to;
return deleteEdge(from, to);
} else {
return "Unknown DELETE command\n";
}
}
else {
output << "Unknown command: " << cmd << "\n";
}
}
return output.str();
}
int main() {
httplib::Server svr;
svr.Post("/query", [](const httplib::Request &req, httplib::Response &res){
string result = executeQuery(req.body);
res.set_content(result, "text/plain");
});
cout << "Server running at http://localhost:8080\n";
// Handle CORS preflight requests
svr.Options("/query", [](const httplib::Request& req, httplib::Response& res) {
res.set_header("Access-Control-Allow-Origin", "*");
res.set_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
res.set_header("Access-Control-Allow-Headers", "Content-Type");
res.status = 200;
});
// Automatically add CORS headers to all responses
svr.set_default_headers({
{"Access-Control-Allow-Origin", "*"},
{"Access-Control-Allow-Methods", "POST, GET, OPTIONS"},
{"Access-Control-Allow-Headers", "Content-Type"}
});
svr.listen("0.0.0.0", 8080);
}