Repository navigation
Expand file tree
/
Copy pathadmin_server.py
More file actions
1826 lines (1549 loc) · 70.4 KB
/
Copy pathadmin_server.py
File metadata and controls
1826 lines (1549 loc) · 70.4 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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
NexaDB Admin Server
===================
Serves the admin panel on HTTP with TOON export functionality.
Usage:
python3 admin_server.py --port 9999
"""
import http.server
import socketserver
import json
import os
import sys
from urllib.parse import urlparse, parse_qs
import socket as sock
import struct
import msgpack
import uuid
import time
from http.cookies import SimpleCookie
# Binary protocol constants
MAGIC = 0x4E455841
VERSION = 0x01
MSG_CONNECT = 0x01
MSG_QUERY_TOON = 0x0B
MSG_EXPORT_TOON = 0x0C
MSG_SUCCESS = 0x81
# Import TOON module and auth
sys.path.append(os.path.dirname(__file__))
# Add nexadb-python to path to import NEW client (same as tests use)
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'nexadb-python'))
from toon_format import json_to_toon
from unified_auth import UnifiedAuthManager
# Session storage (in-memory for now)
SESSIONS = {}
SESSION_TIMEOUT = 24 * 60 * 60 # 24 hours
def pack_message(msg_type, data):
"""Pack message for binary protocol."""
payload = msgpack.packb(data, use_bin_type=True)
header = struct.pack('>IBBHI', MAGIC, VERSION, msg_type, 0, len(payload))
return header + payload
def unpack_message(socket):
"""Unpack message from binary protocol."""
header_bytes = socket.recv(12)
magic, version, msg_type, flags, payload_len = struct.unpack('>IBBHI', header_bytes)
payload_bytes = b''
while len(payload_bytes) < payload_len:
chunk = socket.recv(payload_len - len(payload_bytes))
payload_bytes += chunk
payload = msgpack.unpackb(payload_bytes, raw=False)
return msg_type, payload
def create_session(username, role, api_key):
"""Create a new session."""
session_id = str(uuid.uuid4())
SESSIONS[session_id] = {
'username': username,
'role': role,
'api_key': api_key,
'created_at': time.time(),
'last_access': time.time()
}
return session_id
def get_session(session_id):
"""Get session data if valid."""
if not session_id or session_id not in SESSIONS:
return None
session = SESSIONS[session_id]
# Check if session expired
if time.time() - session['last_access'] > SESSION_TIMEOUT:
del SESSIONS[session_id]
return None
# Update last access time
session['last_access'] = time.time()
return session
def delete_session(session_id):
"""Delete a session."""
if session_id in SESSIONS:
del SESSIONS[session_id]
class AdminRequestHandler(http.server.SimpleHTTPRequestHandler):
"""HTTP request handler with TOON API endpoints and authentication."""
auth = None # Will be set in run_server
data_dir = None # Will be set in run_server
def end_headers(self):
# Add cache-control headers to prevent caching
self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
self.send_header('Pragma', 'no-cache')
self.send_header('Expires', '0')
super().end_headers()
def get_session_from_cookie(self):
"""Extract session ID from cookie."""
cookie_header = self.headers.get('Cookie')
if not cookie_header:
return None
cookie = SimpleCookie()
cookie.load(cookie_header)
if 'nexadb_session' in cookie:
return cookie['nexadb_session'].value
return None
def is_authenticated(self):
"""Check if request is authenticated."""
session_id = self.get_session_from_cookie()
session = get_session(session_id)
return session is not None
def do_GET(self):
"""Handle GET requests."""
parsed_path = urlparse(self.path)
# Serve admin panel - redirect root to login or dashboard
if parsed_path.path == '/':
if self.is_authenticated():
self.send_response(302)
self.send_header('Location', '/admin_panel/index.html')
self.end_headers()
else:
self.send_response(302)
self.send_header('Location', '/admin_panel/login.html')
self.end_headers()
return
# Public paths that don't require authentication
public_paths = [
'/admin_panel/login.html',
'/admin_panel/css/styles.css',
'/admin_panel/js/auth.js'
]
# Check if this is a public path
is_public = any(parsed_path.path == p for p in public_paths)
# Check if this is a JS/CSS asset that requires authentication
is_protected_asset = (
parsed_path.path.startswith('/admin_panel/js/') and
parsed_path.path != '/admin_panel/js/auth.js'
) or (
parsed_path.path == '/admin_panel/index.html'
)
# Also support legacy /js/ path
if parsed_path.path.startswith('/js/'):
is_protected_asset = True
# If /admin_panel/ without index.html, redirect to index.html if authenticated, else login
if parsed_path.path == '/admin_panel/' or parsed_path.path == '/admin_panel':
if self.is_authenticated():
self.send_response(302)
self.send_header('Location', '/admin_panel/index.html')
self.end_headers()
else:
self.send_response(302)
self.send_header('Location', '/admin_panel/login.html')
self.end_headers()
return
# If it's a protected asset and not authenticated, redirect to login
if is_protected_asset and not is_public and not self.is_authenticated():
self.send_response(302)
self.send_header('Location', '/admin_panel/login.html')
self.end_headers()
return
# Block access to old admin panel
if 'admin_modern' in parsed_path.path:
self.send_error(404, "File not found")
return
# API endpoint for TOON export
if parsed_path.path == '/api/toon/export':
self.handle_toon_export(parsed_path)
# Collections endpoint
elif parsed_path.path == '/api/collections':
self.handle_get_collections()
# Vectors endpoint
elif parsed_path.path == '/api/vectors':
self.handle_get_vectors()
# Storage endpoint (NEW v2.3.1 fix)
elif parsed_path.path == '/api/storage':
self.handle_get_storage()
# Monitoring stats endpoint (NEW v3.0.0 - aggregated stats for monitoring)
elif parsed_path.path == '/api/stats/monitoring':
self.handle_get_monitoring_stats()
# API endpoints that require authentication
elif parsed_path.path == '/api/databases':
# Protected endpoint - check authentication
if not self.is_authenticated():
self.send_response(401)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({'error': 'Unauthorized'}).encode())
return
self.handle_get_databases()
# User management endpoints (GET)
elif parsed_path.path == '/api/users/list':
self.handle_list_users()
# Database endpoints (NEW v3.0.0)
elif parsed_path.path.startswith('/api/databases/') and parsed_path.path.endswith('/collections'):
# GET /api/databases/{name}/collections
database_name = parsed_path.path.split('/')[3]
self.handle_get_database_collections(database_name)
elif parsed_path.path.startswith('/api/databases/') and parsed_path.path.endswith('/stats'):
# GET /api/databases/{name}/stats
database_name = parsed_path.path.split('/')[3]
self.handle_get_database_stats(database_name)
elif parsed_path.path.startswith('/api/users/') and not parsed_path.path.endswith('/database-access'):
# GET /api/users/{username}
username = parsed_path.path.split('/')[3]
self.handle_get_user(username)
# Status endpoint (REST API compatible) - NEW v3.0.5
elif parsed_path.path == '/status':
self.handle_rest_status()
# REST API compatible routes (proxy to binary server) - NEW v3.0.5
# These allow admin panel to use same paths as REST API
elif parsed_path.path.startswith('/collections/'):
# GET /collections/{name} - list documents
parts = parsed_path.path.strip('/').split('/')
if len(parts) >= 2:
collection_name = parts[1]
query_params = parse_qs(parsed_path.query)
database = query_params.get('database', ['default'])[0]
self.handle_rest_get_documents(collection_name, database, query_params)
else:
self.send_error_response(400, 'Invalid collection path')
elif parsed_path.path == '/collections':
# GET /collections - list all collections
query_params = parse_qs(parsed_path.query)
database = query_params.get('database', ['default'])[0]
self.handle_rest_list_collections(database)
else:
# Handle .js files explicitly to ensure correct Content-Type
if parsed_path.path.endswith('.js'):
try:
# Get file path relative to current directory
file_path = parsed_path.path.lstrip('/')
# Support legacy /js/ path by redirecting to /admin_panel/js/
if file_path.startswith('js/'):
file_path = 'admin_panel/' + file_path
with open(file_path, 'r') as f:
content = f.read()
self.send_response(200)
self.send_header('Content-Type', 'application/javascript')
self.end_headers()
self.wfile.write(content.encode('utf-8'))
except FileNotFoundError:
self.send_error(404, "File not found")
except Exception as e:
self.send_error(500, f"Server error: {str(e)}")
else:
# Serve other static files
super().do_GET()
def do_POST(self):
"""Handle POST requests."""
parsed_path = urlparse(self.path)
# Login endpoint
if parsed_path.path == '/api/auth/login':
self.handle_login()
# Logout endpoint
elif parsed_path.path == '/api/auth/logout':
self.handle_logout()
# Vector search endpoint
elif parsed_path.path == '/api/search':
self.handle_vector_search()
# Database creation (NEW v3.0.0)
elif parsed_path.path == '/api/databases':
self.handle_create_database()
# Collection creation
elif parsed_path.path.startswith('/api/databases/') and '/collections' in parsed_path.path and not parsed_path.path.endswith('/documents'):
database_name = parsed_path.path.split('/')[3]
self.handle_create_collection(database_name)
# Document insertion
elif parsed_path.path.startswith('/api/databases/') and '/collections/' in parsed_path.path and parsed_path.path.endswith('/documents'):
parts = parsed_path.path.split('/')
database_name = parts[3]
collection_name = parts[5]
self.handle_insert_document(database_name, collection_name)
# Query documents
elif parsed_path.path == '/api/query':
self.handle_query_documents()
# User management endpoints
elif parsed_path.path == '/api/users/create':
self.handle_create_user()
elif parsed_path.path == '/api/users/delete':
self.handle_delete_user()
elif parsed_path.path == '/api/users/update-password':
self.handle_update_password()
elif parsed_path.path == '/api/users/regenerate-api-key':
self.handle_regenerate_api_key()
elif parsed_path.path == '/api/users/grant-database-permission':
self.handle_grant_database_permission()
# REST API compatible route for collection creation - NEW v3.0.5
elif parsed_path.path.startswith('/collections/'):
parts = parsed_path.path.strip('/').split('/')
if len(parts) >= 2:
collection_name = parts[1]
query_params = parse_qs(parsed_path.query)
database = query_params.get('database', ['default'])[0]
self.handle_rest_insert_document(collection_name, database)
else:
self.send_error(400, "Invalid collection path")
else:
self.send_error(404, "Endpoint not found")
def do_DELETE(self):
"""Handle DELETE requests."""
parsed_path = urlparse(self.path)
# Delete document - /api/databases/{db}/collections/{collection}/documents/{id}
if parsed_path.path.startswith('/api/databases/') and '/documents/' in parsed_path.path:
parts = parsed_path.path.split('/')
database_name = parts[3]
collection_name = parts[5]
document_id = parts[7]
self.handle_delete_document(database_name, collection_name, document_id)
# Delete document - /databases/{db}/collections/{collection}/documents/{id} (without /api prefix) - NEW v3.0.5
elif parsed_path.path.startswith('/databases/') and '/documents/' in parsed_path.path:
parts = parsed_path.path.split('/')
database_name = parts[2]
collection_name = parts[4]
document_id = parts[6]
self.handle_delete_document(database_name, collection_name, document_id)
# Delete collection
elif parsed_path.path.startswith('/api/databases/') and '/collections/' in parsed_path.path:
parts = parsed_path.path.split('/')
database_name = parts[3]
collection_name = parts[5]
self.handle_drop_collection(database_name, collection_name)
# Delete database (NEW v3.0.0)
elif parsed_path.path.startswith('/api/databases/'):
database_name = parsed_path.path.split('/')[3]
self.handle_delete_database(database_name)
# REST API compatible route for document deletion - NEW v3.0.5
elif parsed_path.path.startswith('/collections/'):
parts = parsed_path.path.strip('/').split('/')
if len(parts) >= 3:
collection_name = parts[1]
document_id = parts[2]
query_params = parse_qs(parsed_path.query)
database = query_params.get('database', ['default'])[0]
self.handle_rest_delete_document(collection_name, document_id, database)
else:
self.send_error(400, "Invalid path - expected /collections/{name}/{id}")
else:
self.send_error(404, "Endpoint not found")
def do_PUT(self):
"""Handle PUT requests."""
parsed_path = urlparse(self.path)
# Update document
if parsed_path.path.startswith('/api/databases/') and '/documents/' in parsed_path.path:
parts = parsed_path.path.split('/')
database_name = parts[3]
collection_name = parts[5]
document_id = parts[7]
self.handle_update_document(database_name, collection_name, document_id)
# Grant/revoke database access (NEW v3.0.0)
elif parsed_path.path.endswith('/database-access'):
username = parsed_path.path.split('/')[3]
self.handle_update_database_access(username)
else:
self.send_error(404, "Endpoint not found")
def handle_login(self):
"""Handle login request."""
try:
# Read request body
content_length = int(self.headers.get('Content-Length', 0))
body = self.rfile.read(content_length).decode('utf-8')
data = json.loads(body)
username = data.get('username')
password = data.get('password')
if not username or not password:
self.send_response(400)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'error': 'Missing username or password'
}).encode())
return
# Authenticate with unified auth manager
user_info = self.auth.authenticate_password(username, password)
if not user_info:
self.send_response(401)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'status': 'error', # Match test expectations
'error': 'Invalid username or password'
}).encode())
return
# Create session
session_id = create_session(
user_info['username'],
user_info['role'],
user_info['api_key']
)
# Set session cookie
cookie = SimpleCookie()
cookie['nexadb_session'] = session_id
cookie['nexadb_session']['path'] = '/'
cookie['nexadb_session']['max-age'] = SESSION_TIMEOUT
cookie['nexadb_session']['httponly'] = True
# Send response
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Set-Cookie', cookie['nexadb_session'].OutputString())
self.end_headers()
self.wfile.write(json.dumps({
'status': 'success', # Match test expectations
'success': True, # Keep for backward compatibility
'username': user_info['username'],
'role': user_info['role'],
'api_key': user_info['api_key']
}).encode())
except Exception as e:
self.send_response(500)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'error': f'Server error: {str(e)}'
}).encode())
def handle_logout(self):
"""Handle logout request."""
try:
session_id = self.get_session_from_cookie()
if session_id:
delete_session(session_id)
# Clear cookie
cookie = SimpleCookie()
cookie['nexadb_session'] = ''
cookie['nexadb_session']['path'] = '/'
cookie['nexadb_session']['max-age'] = 0
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Set-Cookie', cookie['nexadb_session'].OutputString())
self.end_headers()
self.wfile.write(json.dumps({
'status': 'success', # Match test expectations
'success': True, # Keep for backward compatibility
'message': 'Logged out successfully'
}).encode())
except Exception as e:
self.send_response(500)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'error': f'Server error: {str(e)}'
}).encode())
def handle_get_collections(self):
"""Handle GET /api/collections - fetch all collections from binary server."""
try:
from nexaclient import NexaClient
# Connect to binary server (THE SINGLE SOURCE OF TRUTH)
with NexaClient(host='localhost', port=6970) as db:
collections = db.list_collections()
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps({
'collections': collections,
'count': len(collections)
}).encode())
except Exception as e:
self.send_response(500)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'error': f'Server error: {str(e)}'
}).encode())
def handle_get_vectors(self):
"""Handle GET /api/vectors - get vector index statistics from binary server."""
try:
from nexaclient import NexaClient
# Connect to binary server (THE SINGLE SOURCE OF TRUTH)
with NexaClient(host='localhost', port=6970) as db:
result = db.get_vectors()
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps(result).encode())
except Exception as e:
self.send_response(500)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'error': f'Server error: {str(e)}'
}).encode())
def handle_get_storage(self):
"""Handle GET /api/storage - calculate actual storage size (NEW v2.3.1 fix)."""
try:
total_size = 0
# Calculate actual directory size
if self.data_dir and os.path.exists(self.data_dir):
for dirpath, dirnames, filenames in os.walk(self.data_dir):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
try:
total_size += os.path.getsize(filepath)
except OSError:
pass # Skip files that can't be accessed
# Convert bytes to KB
size_kb = total_size / 1024
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps({
'storage_bytes': total_size,
'storage_kb': round(size_kb, 2),
'storage_mb': round(size_kb / 1024, 2)
}).encode())
except Exception as e:
self.send_response(500)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'error': f'Server error: {str(e)}'
}).encode())
def handle_get_monitoring_stats(self):
"""Handle GET /api/stats/monitoring - get aggregated monitoring stats (NEW v3.0.0)."""
try:
from nexaclient import NexaClient
# Connect to binary server (THE SINGLE SOURCE OF TRUTH)
with NexaClient(host='localhost', port=6970) as db:
# Get all databases
databases = db.list_databases()
total_databases = len(databases)
# Get total collections across all databases
total_collections = 0
for database in databases:
collections = db.list_collections(database=database)
total_collections += len(collections)
# Get total users
total_users = 0
if self.auth:
users_dict = self.auth.list_users()
total_users = len(users_dict)
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps({
'databases': total_databases,
'collections': total_collections,
'users': total_users
}).encode())
except Exception as e:
self.send_response(500)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'error': f'Server error: {str(e)}'
}).encode())
def handle_vector_search(self):
"""Handle POST /api/search - perform vector search."""
try:
from nexaclient import NexaClient
# Read request body
content_length = int(self.headers.get('Content-Length', 0))
body = self.rfile.read(content_length).decode('utf-8')
data = json.loads(body)
collection = data.get('collection')
query_vector = data.get('query_vector')
k = data.get('k', 10)
dimensions = data.get('dimensions', 768) # Default to 768
database = data.get('database') # v3.0.0: Extract database parameter
if not collection:
self.send_response(400)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'error': 'Missing collection parameter'
}).encode())
return
if not query_vector:
self.send_response(400)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'error': 'Missing query_vector parameter'
}).encode())
return
# Validate vector dimensions
if len(query_vector) != dimensions:
self.send_response(400)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'error': f'Query vector must have {dimensions} dimensions, got {len(query_vector)}'
}).encode())
return
# Connect to binary server (THE SINGLE SOURCE OF TRUTH)
with NexaClient(host='localhost', port=6970) as db:
results = db.vector_search(collection, query_vector, limit=k, dimensions=dimensions, database=database)
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps({
'success': True,
'results': results,
'count': len(results)
}).encode())
except Exception as e:
self.send_response(500)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'error': f'Server error: {str(e)}'
}).encode())
def handle_toon_export(self, parsed_path):
"""Handle TOON export API request."""
try:
from nexaclient import NexaClient
# Parse query parameters
params = parse_qs(parsed_path.query)
collection = params.get('collection', [''])[0]
if not collection:
self.send_error(400, "Missing collection parameter")
return
# Connect to binary server (THE SINGLE SOURCE OF TRUTH)
with NexaClient(host='localhost', port=6970) as db:
response = db.export_toon(collection)
# Return TOON data as JSON response
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
result = {
'success': True,
'toon_data': response.get('data', ''),
'token_stats': response.get('token_stats', {}),
'count': response.get('count', 0)
}
self.wfile.write(json.dumps(result).encode())
except Exception as e:
self.send_error(500, f"Server error: {str(e)}")
def handle_get_databases(self):
"""Handle GET /api/databases - list all databases (NEW v3.0.0)."""
try:
from nexaclient import NexaClient
# Connect to binary server
with NexaClient(host='localhost', port=6970) as db:
databases = db.list_databases()
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps({
'databases': databases,
'count': len(databases)
}).encode())
except Exception as e:
self.send_response(500)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'error': f'Server error: {str(e)}'
}).encode())
def handle_create_database(self):
"""Handle POST /api/databases - create new database (NEW v3.0.0)."""
try:
from nexaclient import NexaClient
# Read request body
content_length = int(self.headers.get('Content-Length', 0))
body = self.rfile.read(content_length).decode('utf-8')
data = json.loads(body)
database_name = data.get('name')
if not database_name:
self.send_response(400)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'error': 'Missing database name'
}).encode())
return
# Connect to binary server
with NexaClient(host='localhost', port=6970) as db:
result = db.create_database(database_name)
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps({
'status': 'success',
'database': database_name,
'message': f"Database '{database_name}' created successfully"
}).encode())
except Exception as e:
self.send_response(500)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'status': 'error',
'error': f'Server error: {str(e)}'
}).encode())
def handle_delete_database(self, database_name):
"""Handle DELETE /api/databases/{name} - drop database (NEW v3.0.0)."""
try:
from nexaclient import NexaClient
# Connect to binary server
with NexaClient(host='localhost', port=6970) as db:
result = db.drop_database(database_name)
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps({
'status': 'success',
'message': f"Database '{database_name}' deleted successfully"
}).encode())
except Exception as e:
self.send_response(500)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'status': 'error',
'error': f'Server error: {str(e)}'
}).encode())
def handle_get_database_collections(self, database_name):
"""Handle GET /api/databases/{name}/collections - list collections in database (NEW v3.0.0)."""
try:
from nexaclient import NexaClient
# Connect to binary server
with NexaClient(host='localhost', port=6970) as db:
collections = db.list_collections(database=database_name)
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps({
'database': database_name,
'collections': collections,
'count': len(collections)
}).encode())
except Exception as e:
self.send_response(500)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'error': f'Server error: {str(e)}'
}).encode())
def handle_get_database_stats(self, database_name):
"""Handle GET /api/databases/{name}/stats - get database statistics (NEW v3.0.0)."""
try:
from nexaclient import NexaClient
# Connect to binary server and get real stats
with NexaClient(host='localhost', port=6970) as db:
collections = db.list_collections(database=database_name)
collections_count = len(collections)
# Count documents in each collection
documents_count = 0
for collection in collections:
try:
docs = db.query(collection, {}, database=database_name, limit=0)
# Query with limit=0 should return count or empty list
# Let's count manually with a high limit
docs = db.query(collection, {}, database=database_name, limit=100000)
documents_count += len(docs)
except:
pass
stats = {
'database': database_name,
'collections_count': collections_count,
'documents_count': documents_count
}
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps({
'database': database_name,
'collections_count': stats.get('collections_count', 0),
'documents_count': stats.get('documents_count', 0),
'stats': stats
}).encode())
except Exception as e:
self.send_response(500)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'error': f'Server error: {str(e)}'
}).encode())
def handle_get_user(self, username):
"""Handle GET /api/users/{username} - get user with database permissions (NEW v3.0.0)."""
try:
if not self.auth:
self.send_response(500)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'error': 'Authentication system not initialized'
}).encode())
return
user_data = self.auth.get_user(username)
if not user_data:
self.send_response(404)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'error': f"User '{username}' not found"
}).encode())
return
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps({
'username': username,
'role': user_data.get('role', 'guest'),
'database_permissions': user_data.get('database_permissions', {}),
'created_at': user_data.get('created_at', 0)
}).encode())
except Exception as e:
self.send_response(500)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'error': f'Server error: {str(e)}'
}).encode())
def handle_update_database_access(self, username):
"""Handle PUT /api/users/{username}/database-access - grant/revoke database access (NEW v3.0.0)."""
try:
if not self.auth:
self.send_response(500)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'error': 'Authentication system not initialized'
}).encode())
return
# Read request body
content_length = int(self.headers.get('Content-Length', 0))
body = self.rfile.read(content_length).decode('utf-8')
data = json.loads(body)
database_name = data.get('database')
permission = data.get('permission') # Can be null to revoke
if not database_name:
self.send_response(400)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'error': 'Missing database name'
}).encode())
return
if permission:
# Grant access
self.auth.grant_database_access(username, database_name, permission)
message = f"Granted '{permission}' access to database '{database_name}' for user '{username}'"
else:
# Revoke access
self.auth.revoke_database_access(username, database_name)
message = f"Revoked access to database '{database_name}' for user '{username}'"
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps({
'success': True,
'message': message
}).encode())
except Exception as e:
self.send_response(500)
self.send_header('Content-Type', 'application/json')
self.end_headers()