Repository navigation
Expand file tree
/
Copy path23_server_mode_http_access.py
More file actions
471 lines (414 loc) · 16.2 KB
/
Copy path23_server_mode_http_access.py
File metadata and controls
471 lines (414 loc) · 16.2 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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
#!/usr/bin/env python3
"""Example 23: Server Mode And HTTP Access.
This example shows the narrow client-server story that already works in the
Python bindings today without adding a new remote client abstraction.
Workflow covered:
- start ArcadeDB server mode from the embedded Python package
- inspect server metadata over HTTP
- create a database through the server-managed Java API
- create schema through the HTTP command endpoint
- insert records through embedded access in the same Python process
- log in to the HTTP API and switch to bearer-token authentication
- query and update the same data over HTTP
- verify HTTP-side changes back through embedded access
Notes:
- This repo remains embedded-first. Server mode is an optional access pattern
for multi-process or remote HTTP use.
- The example intentionally uses Python's standard library for HTTP instead of
introducing a dedicated remote client layer.
"""
from __future__ import annotations
import argparse
import base64
import json
import shutil
import socket
import time
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
import arcadedb
ROOT_PASSWORD = "example23pass"
ITEMS = [
{
"sku": "SKU-001",
"name": "Arcade Notebook",
"category": "office",
"stock": 12,
"warehouse": "north",
},
{
"sku": "SKU-002",
"name": "Graph Whiteboard",
"category": "office",
"stock": 4,
"warehouse": "north",
},
{
"sku": "SKU-003",
"name": "Vector GPU Crate",
"category": "hardware",
"stock": 2,
"warehouse": "south",
},
]
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Example 23: server mode and HTTP access workflow"
)
parser.add_argument(
"--server-root",
default="./my_test_databases/server_mode_demo_root",
help=(
"Server root directory "
"(default: ./my_test_databases/server_mode_demo_root)"
),
)
parser.add_argument(
"--db-name",
default="example23_server_demo",
help="Database name to create inside the server root",
)
parser.add_argument(
"--host",
default="127.0.0.1",
help="HTTP host to bind the embedded server to (default: 127.0.0.1)",
)
parser.add_argument(
"--http-port",
type=int,
default=2481,
help="HTTP port for the embedded server (default: 2481)",
)
parser.add_argument(
"--wait-for-enter",
action="store_true",
help=(
"Keep the server running after the scripted steps finish until you "
"press Enter"
),
)
return parser.parse_args()
def require(condition: bool, message: str) -> None:
if not condition:
raise RuntimeError(message)
def reset_server_root(server_root: Path) -> None:
if server_root.exists():
shutil.rmtree(server_root)
server_root.parent.mkdir(parents=True, exist_ok=True)
def choose_http_port(host: str, requested_port: int) -> tuple[int, bool]:
"""Return a usable HTTP port for the example.
Tries the requested port first. If it is unavailable, fall back to an
ephemeral free port chosen by the OS.
"""
def _can_bind(port: int) -> bool:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.bind((host, port))
except OSError:
return False
return True
if requested_port > 0 and _can_bind(requested_port):
return requested_port, False
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind((host, 0))
fallback_port = int(sock.getsockname()[1])
return fallback_port, True
def basic_auth_header(username: str, password: str) -> dict[str, str]:
token = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
return {"Authorization": f"Basic {token}"}
def bearer_auth_header(token: str) -> dict[str, str]:
return {"Authorization": f"Bearer {token}"}
def http_json_request(
url: str,
*,
method: str = "GET",
payload: dict | None = None,
headers: dict[str, str] | None = None,
timeout: float = 30.0,
) -> dict:
request_headers = {"Accept": "application/json"}
if headers:
request_headers.update(headers)
data = None
if payload is not None:
data = json.dumps(payload).encode("utf-8")
request_headers["Content-Type"] = "application/json"
request = Request(url, data=data, headers=request_headers, method=method)
if not request.full_url.startswith(
("http://localhost", "http://127.0.0.1", "https://")
):
raise ValueError(f"Refusing to call unexpected URL: {request.full_url!r}")
try:
with urlopen(request, timeout=timeout) as response: # nosec B310
body = response.read().decode("utf-8")
except HTTPError as exc:
detail = exc.read().decode("utf-8", errors="replace")
raise RuntimeError(f"HTTP {exc.code} for {method} {url}: {detail}") from exc
except URLError as exc:
raise RuntimeError(f"HTTP request failed for {method} {url}: {exc}") from exc
except OSError as exc:
# A socket timeout raises TimeoutError, which is an OSError but NOT a
# URLError, so it escapes the clause above. wait_for_server() retries on
# RuntimeError, so leaving this uncaught turned a slow first request into
# a hard failure instead of one more poll. Same for ConnectionRefusedError
# when the listener is not accepting yet.
raise RuntimeError(f"HTTP request failed for {method} {url}: {exc!r}") from exc
if not body.strip():
return {}
try:
return json.loads(body)
except json.JSONDecodeError as exc:
raise RuntimeError(f"Expected JSON from {url}, got: {body}") from exc
def wait_for_server(base_url: str, headers: dict[str, str], timeout_sec: float) -> dict:
"""Poll /api/v1/server?mode=basic until it answers.
The first HTTP request after start_up is much slower than the rest: measured
on one developer machine it took 5.6s, the second 0.7s, and every one after
that under 10ms. Undertow and the REST handlers class-load lazily and the
root password is verified with a deliberately expensive KDF, and both happen
on request one. So the per-attempt timeout here is generous on purpose; a
tight one just converts warmup into a failure.
``mode=basic`` returns the version, server name, and languages this example
prints without the full form's metrics section; on 26.9.1 and earlier that
section made the first full call take about 20 s (ArcadeData/arcadedb#8909).
"""
start = time.perf_counter()
while True:
try:
return http_json_request(
f"{base_url}/api/v1/server?mode=basic",
headers=headers,
timeout=30.0,
)
except RuntimeError:
if time.perf_counter() - start > timeout_sec:
raise
time.sleep(0.25)
def print_rows(title: str, rows: list[dict]) -> None:
print(title)
if not rows:
print(" (no rows)")
print()
return
for row in rows:
print(f" - {row}")
print()
def main() -> int:
args = parse_args()
server_root = Path(args.server_root)
reset_server_root(server_root)
http_port, used_fallback_port = choose_http_port(args.host, args.http_port)
base_url = f"http://{args.host}:{http_port}"
basic_headers = basic_auth_header("root", ROOT_PASSWORD)
print("=" * 72)
print("ArcadeDB Python - Example 23: Server Mode And HTTP Access")
print("=" * 72)
print()
print("Positioning: embedded-first package, optional server mode when HTTP helps")
print(f"Server root: {server_root}")
print(f"Database name: {args.db_name}")
print(f"Base URL: {base_url}")
if used_fallback_port:
print(
f"Requested HTTP port {args.http_port} was unavailable; "
f"using {http_port} instead."
)
print()
with arcadedb.create_server(
str(server_root),
root_password=ROOT_PASSWORD,
config={
"host": args.host,
"http_port": http_port,
"mode": "development",
},
) as server:
print(f"Studio URL: {server.get_studio_url()}")
server_info = wait_for_server(base_url, basic_headers, timeout_sec=90.0)
print_rows(
"Server metadata:",
[
{
"version": server_info.get("version"),
"serverName": server_info.get("serverName"),
"languages": server_info.get("languages"),
}
],
)
login_payload = http_json_request(
f"{base_url}/api/v1/login",
method="POST",
headers=basic_headers,
)
token = login_payload.get("token")
require(bool(token), "Expected /api/v1/login to return a bearer token")
bearer_headers = bearer_auth_header(token)
print("Acquired bearer token via HTTP login.")
print()
db = server.create_database(args.db_name)
print("Created database through server-managed Java API.")
print()
for statement in (
"CREATE DOCUMENT TYPE InventoryItem",
"CREATE PROPERTY InventoryItem.sku STRING",
"CREATE PROPERTY InventoryItem.name STRING",
"CREATE PROPERTY InventoryItem.category STRING",
"CREATE PROPERTY InventoryItem.stock INTEGER",
"CREATE PROPERTY InventoryItem.warehouse STRING",
"CREATE INDEX ON InventoryItem (sku) UNIQUE_HASH",
):
http_json_request(
f"{base_url}/api/v1/command/{args.db_name}",
method="POST",
payload={"language": "sql", "command": statement},
headers=bearer_headers,
)
print("Created schema through the HTTP command endpoint.")
print()
with db.transaction():
for item in ITEMS:
db.command(
"sql",
"INSERT INTO InventoryItem SET sku = ?, name = ?, category = ?, "
"stock = ?, warehouse = ?",
item["sku"],
item["name"],
item["category"],
item["stock"],
item["warehouse"],
)
print_rows("Inserted through embedded access:", ITEMS)
http_list = http_json_request(
f"{base_url}/api/v1/query/{args.db_name}",
method="POST",
payload={
"language": "sql",
"command": (
"SELECT sku, name, category, stock, warehouse "
"FROM InventoryItem ORDER BY sku"
),
},
headers=bearer_headers,
)
remote_rows = http_list.get("result", [])
require(len(remote_rows) == len(ITEMS), "Expected HTTP query to see all items")
print_rows("Queried through HTTP:", remote_rows)
http_json_request(
f"{base_url}/api/v1/command/{args.db_name}",
method="POST",
payload={
"language": "sql",
"command": ("UPDATE InventoryItem SET stock = 9 WHERE sku = 'SKU-002'"),
},
headers=bearer_headers,
)
http_json_request(
f"{base_url}/api/v1/command/{args.db_name}",
method="POST",
payload={
"language": "sql",
"command": (
"INSERT INTO InventoryItem SET sku = 'SKU-004', "
"name = 'Remote Rack', category = 'hardware', "
"stock = 7, warehouse = 'west'"
),
},
headers=bearer_headers,
)
print("Applied one HTTP-side update and one HTTP-side insert.")
print()
embedded_rows = [
{
"sku": row.get("sku"),
"name": row.get("name"),
"category": row.get("category"),
"stock": row.get("stock"),
"warehouse": row.get("warehouse"),
}
for row in db.query(
"sql",
"SELECT sku, name, category, stock, warehouse "
"FROM InventoryItem ORDER BY sku",
)
]
require(
[row["sku"] for row in embedded_rows]
== ["SKU-001", "SKU-002", "SKU-003", "SKU-004"],
"Expected embedded verification to see all four SKUs",
)
require(
next(row for row in embedded_rows if row["sku"] == "SKU-002")["stock"] == 9,
"Expected embedded verification to see the HTTP-side stock update",
)
print_rows("Verified back through embedded access:", embedded_rows)
aggregate_payload = http_json_request(
f"{base_url}/api/v1/query/{args.db_name}",
method="POST",
payload={
"language": "sql",
"command": (
"SELECT category, sum(stock) AS total_stock, count(*) AS items "
"FROM InventoryItem GROUP BY category ORDER BY category"
),
},
headers=bearer_headers,
)
aggregate_rows = aggregate_payload.get("result", [])
require(len(aggregate_rows) == 2, "Expected two category aggregates")
print_rows("HTTP aggregate query:", aggregate_rows)
# Where the client/server cost lives. The same projection, answered by
# the embedded handle (materialised to a list of dicts, the shape an
# HTTP client receives) and by the HTTP endpoint of the server in THIS
# process. The gap between them is the wire format alone: same JVM,
# same heap, same page cache. The project page adds a third arm, a
# separate container, to price the process boundary on top.
print()
print("Where the client/server cost lives (same process, two paths):")
db.command("sql", "CREATE DOCUMENT TYPE DecompRow")
db.command("sql", "CREATE PROPERTY DecompRow.id LONG")
db.command("sql", "CREATE PROPERTY DecompRow.amount DOUBLE")
db.command("sql", "CREATE PROPERTY DecompRow.region STRING")
db.insert_many(
"DecompRow",
[
{"id": i, "amount": (i * 37 % 100000) / 100.0, "region": f"r{i % 8}"}
for i in range(20_000)
],
commit_every=5_000,
)
import statistics as _st
import time as _time
for n in (10, 1000, 10000):
sql = f"SELECT id, amount, region FROM DecompRow LIMIT {n}"
emb, http = [], []
for _ in range(5):
t0 = _time.perf_counter()
rows_emb = db.query("sql", sql).to_list()
emb.append((_time.perf_counter() - t0) * 1000)
t0 = _time.perf_counter()
rows_http = http_json_request(
f"{base_url}/api/v1/query/{args.db_name}",
method="POST",
payload={"language": "sql", "command": sql, "limit": -1},
headers=bearer_headers,
timeout=120.0,
).get("result", [])
http.append((_time.perf_counter() - t0) * 1000)
require(len(rows_emb) == len(rows_http) == n, f"row count mismatch at {n}")
print(
f" {n:>6} rows embedded {_st.median(emb):8.2f} ms in-process HTTP {_st.median(http):8.2f} ms"
f" wire format costs {_st.median(http) - _st.median(emb):+.2f} ms"
)
if args.wait_for_enter:
print(
"Server is still running. Open Studio in your browser now if you "
"want to inspect the database."
)
print(f"Studio URL: {server.get_studio_url()}")
input("Press Enter to stop the server and exit the example...")
db.close()
print("Example 23 completed.")
return 0
if __name__ == "__main__":
raise SystemExit(main())