-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnexadb_binary_server.py
More file actions
executable file
·1867 lines (1528 loc) · 70.5 KB
/
nexadb_binary_server.py
File metadata and controls
executable file
·1867 lines (1528 loc) · 70.5 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 Binary Protocol Server
==============================
High-performance binary protocol server for NexaDB with:
- Custom binary protocol (3-10x faster than HTTP/JSON)
- MessagePack encoding (2-10x faster than JSON)
- Persistent TCP connections
- Connection pooling (1000+ concurrent connections)
- Streaming results for large queries
Protocol Specification:
----------------------
Message Format:
Header (12 bytes):
- Magic (4 bytes): 0x4E455841 ("NEXA")
- Version (1 byte): 0x01
- Message Type (1 byte): 0x01-0xFF
- Flags (2 bytes): Reserved for future use
- Payload Length (4 bytes): uint32
Payload (variable):
- MessagePack encoded data
Message Types:
Client → Server:
0x01 = CONNECT - Handshake + authentication
0x02 = CREATE - Insert document
0x03 = READ - Get document by key
0x04 = UPDATE - Update document
0x05 = DELETE - Delete document
0x06 = QUERY - Query with filters
0x07 = VECTOR_SEARCH - Vector similarity search
0x08 = BATCH_WRITE - Bulk insert
0x09 = PING - Keep-alive
Server → Client:
0x81 = SUCCESS - Operation succeeded
0x82 = ERROR - Operation failed
0x83 = NOT_FOUND - Key doesn't exist
0x84 = DUPLICATE - Key already exists
0x85 = STREAM_START - Beginning of result stream
0x86 = STREAM_CHUNK - Partial results
0x87 = STREAM_END - End of results
0x88 = PONG - Keep-alive response
Usage:
------
python3 nexadb_binary_server.py --host 0.0.0.0 --port 6970
"""
import socket
import struct
import threading
import time
import sys
from concurrent.futures import ThreadPoolExecutor
from typing import Dict, Any, Optional
# MessagePack for binary serialization
try:
import msgpack
except ImportError:
print("[ERROR] msgpack not installed. Installing...")
import subprocess
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'msgpack'])
import msgpack
import hashlib
import json
import os
# Import NexaDB core
sys.path.append('.')
from veloxdb_core import VeloxDB
from toon_format import json_to_toon, toon_to_json
from unified_auth import UnifiedAuthManager
class NexaDBBinaryProtocol:
"""Binary protocol constants and utilities"""
# Protocol magic and version
MAGIC = 0x4E455841 # "NEXA" in hex
VERSION = 0x01
# Client → Server message types
MSG_CONNECT = 0x01
MSG_CREATE = 0x02
MSG_READ = 0x03
MSG_UPDATE = 0x04
MSG_DELETE = 0x05
MSG_QUERY = 0x06
MSG_VECTOR_SEARCH = 0x07
MSG_BATCH_WRITE = 0x08
MSG_PING = 0x09
MSG_DISCONNECT = 0x0A
MSG_QUERY_TOON = 0x0B # Query with TOON format response
MSG_EXPORT_TOON = 0x0C # Export collection to TOON format
MSG_IMPORT_TOON = 0x0D # Import TOON data into collection
MSG_CREATE_USER = 0x0E # Create new user (admin only)
MSG_DELETE_USER = 0x0F # Delete user (admin only)
MSG_LIST_USERS = 0x10 # List all users (admin only)
MSG_CHANGE_PASSWORD = 0x11 # Change user password
MSG_LIST_COLLECTIONS = 0x20 # List all collections
MSG_DROP_COLLECTION = 0x21 # Drop a collection
MSG_GET_VECTORS = 0x23 # Get vector statistics
MSG_SUBSCRIBE_CHANGES = 0x30 # Subscribe to change stream
MSG_UNSUBSCRIBE_CHANGES = 0x31 # Unsubscribe from change stream
# NEW v3.0.0: Database operations
MSG_LIST_DATABASES = 0x40 # List all databases
MSG_DROP_DATABASE = 0x42 # Drop a database
MSG_BUILD_HNSW_INDEX = 0x45 # Build HNSW index for vector collection
# NEW v3.0.0: MongoDB import
MSG_IMPORT_MONGODB_DB = 0x50 # Import entire MongoDB database
MSG_IMPORT_MONGODB_COLLECTION = 0x51 # Import single MongoDB collection
# Server → Client response types
MSG_SUCCESS = 0x81
MSG_ERROR = 0x82
MSG_NOT_FOUND = 0x83
MSG_DUPLICATE = 0x84
MSG_STREAM_START = 0x85
MSG_STREAM_CHUNK = 0x86
MSG_STREAM_END = 0x87
MSG_PONG = 0x88
MSG_CHANGE_EVENT = 0x90 # Server pushes change events
@staticmethod
def pack_message(msg_type: int, data: Any) -> bytes:
"""
Pack message into binary protocol format.
Args:
msg_type: Message type code
data: Data to encode (will be MessagePack encoded)
Returns:
Binary message (header + payload)
"""
# Encode payload with MessagePack
payload = msgpack.packb(data, use_bin_type=True)
# Build header (12 bytes)
header = struct.pack(
'>IBBHI',
NexaDBBinaryProtocol.MAGIC, # Magic (4 bytes)
NexaDBBinaryProtocol.VERSION, # Version (1 byte)
msg_type, # Message type (1 byte)
0, # Flags (2 bytes)
len(payload) # Payload length (4 bytes)
)
return header + payload
@staticmethod
def unpack_header(header_bytes: bytes) -> tuple:
"""
Unpack message header.
Args:
header_bytes: 12 bytes of header
Returns:
(magic, version, msg_type, flags, payload_len)
"""
return struct.unpack('>IBBHI', header_bytes)
class NexaDBBinaryServer:
"""
Binary protocol server for NexaDB.
Features:
- Persistent TCP connections
- Connection pooling (1000+ concurrent)
- Binary protocol (3-10x faster than HTTP)
- Streaming results for large queries
- Automatic reconnection handling
"""
def __init__(
self,
host: str = '0.0.0.0',
port: int = 6970,
data_dir: str = './nexadb_data',
max_connections: int = 1000,
max_workers: int = 100
):
"""
Initialize binary protocol server.
Args:
host: Host to bind to
port: Port to listen on
data_dir: Database data directory
max_connections: Maximum concurrent connections
max_workers: Thread pool size
"""
self.host = host
self.port = port
self.data_dir = data_dir
self.max_connections = max_connections
self.max_workers = max_workers
# Initialize database
print(f"[INIT] Initializing NexaDB at {data_dir}")
self.db = VeloxDB(data_dir)
# NEW v3.0.5: Ensure 'default' database exists for fresh users
self.db.database('default')
print(f"[INIT] Default database initialized")
# Initialize unified authentication (username/password + API keys)
print(f"[SECURITY] Initializing unified authentication")
self.auth = UnifiedAuthManager(data_dir)
# Connection pool
self.executor = ThreadPoolExecutor(max_workers=max_workers)
# Socket
self.socket = None
self.running = False
# Authenticated sessions: address -> {username, role, authenticated_at}
self.sessions = {}
self.sessions_lock = threading.Lock()
# Change stream subscriptions: {address: {socket, collection, operations}}
self.subscriptions = {}
self.subscriptions_lock = threading.Lock()
# Statistics
self.stats = {
'total_connections': 0,
'active_connections': 0,
'total_requests': 0,
'total_errors': 0,
'auth_failures': 0,
'start_time': time.time()
}
self.stats_lock = threading.Lock()
# Register global change stream listener
self._setup_change_stream()
def start(self):
"""Start binary protocol server."""
# Create socket
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Bind and listen
self.socket.bind((self.host, self.port))
self.socket.listen(self.max_connections)
self.running = True
print("=" * 70)
print("NexaDB Binary Protocol Server Started")
print("=" * 70)
print(f"Host: {self.host}")
print(f"Port: {self.port}")
print(f"Data Directory: {self.data_dir}")
print(f"Max Connections: {self.max_connections}")
print(f"Worker Threads: {self.max_workers}")
print(f"\nServer listening on {self.host}:{self.port}")
print("\nProtocol: Binary (MessagePack)")
print("Performance: 3-10x faster than HTTP/REST")
print("\n🔒 SECURITY: Username/Password Authentication")
print(" - Clients must send CONNECT with username + password")
print(" - All operations require authentication")
print(" - Default user: root / nexadb123")
print("\nSupported Operations:")
print(" - CREATE, READ, UPDATE, DELETE")
print(" - QUERY (with filters)")
print(" - BATCH_WRITE (bulk inserts)")
print(" - VECTOR_SEARCH (AI/ML)")
print(" - TOON FORMAT (40-50% token reduction for LLMs) ⭐ NEW!")
print("\n🚀 FIRST DATABASE WITH NATIVE TOON SUPPORT!")
print("=" * 70)
try:
while self.running:
# Accept connection
client_socket, address = self.socket.accept()
# Update stats
with self.stats_lock:
self.stats['total_connections'] += 1
self.stats['active_connections'] += 1
# Handle connection in thread pool
self.executor.submit(self.handle_connection, client_socket, address)
except KeyboardInterrupt:
print("\n[SHUTDOWN] Shutting down server...")
self.stop()
def stop(self):
"""Stop server."""
self.running = False
if self.socket:
self.socket.close()
# Shutdown thread pool
self.executor.shutdown(wait=True)
# Close database
self.db.close()
print("[SHUTDOWN] Server stopped")
def handle_connection(self, client_socket: socket.socket, address: tuple):
"""
Handle persistent client connection.
Args:
client_socket: Client socket
address: Client address (host, port)
"""
print(f"[CONNECT] New connection from {address[0]}:{address[1]}")
try:
while self.running:
# Read message header (12 bytes)
header_bytes = self._recv_exact(client_socket, 12)
if not header_bytes:
break # Connection closed
# Parse header
magic, version, msg_type, flags, payload_len = NexaDBBinaryProtocol.unpack_header(header_bytes)
# Verify magic
if magic != NexaDBBinaryProtocol.MAGIC:
print(f"[ERROR] Invalid magic: {hex(magic)}")
self._send_error(client_socket, f"Invalid protocol magic: {hex(magic)}")
break
# Verify version
if version != NexaDBBinaryProtocol.VERSION:
print(f"[ERROR] Unsupported version: {version}")
self._send_error(client_socket, f"Unsupported protocol version: {version}")
break
# Read payload
payload_bytes = self._recv_exact(client_socket, payload_len)
if not payload_bytes:
break # Connection closed
# Decode MessagePack
try:
data = msgpack.unpackb(payload_bytes, raw=False)
except Exception as e:
print(f"[ERROR] Failed to decode MessagePack: {e}")
self._send_error(client_socket, f"Invalid MessagePack: {e}")
continue
# Update stats
with self.stats_lock:
self.stats['total_requests'] += 1
# Process message
self._process_message(client_socket, msg_type, data, address)
except Exception as e:
print(f"[ERROR] Connection error from {address}: {e}")
with self.stats_lock:
self.stats['total_errors'] += 1
finally:
client_socket.close()
# Remove session
with self.sessions_lock:
if address in self.sessions:
del self.sessions[address]
# Remove subscription
with self.subscriptions_lock:
if address in self.subscriptions:
del self.subscriptions[address]
with self.stats_lock:
self.stats['active_connections'] -= 1
print(f"[DISCONNECT] Connection closed from {address[0]}:{address[1]}")
def _recv_exact(self, sock: socket.socket, n: int) -> Optional[bytes]:
"""
Receive exactly n bytes from socket.
Args:
sock: Socket to read from
n: Number of bytes to read
Returns:
Bytes read, or None if connection closed
"""
data = b''
while len(data) < n:
chunk = sock.recv(n - len(data))
if not chunk:
return None # Connection closed
data += chunk
return data
def _send_message(self, sock: socket.socket, msg_type: int, data: Any):
"""
Send binary message to client.
Args:
sock: Socket to send to
msg_type: Message type code
data: Data to send
"""
message = NexaDBBinaryProtocol.pack_message(msg_type, data)
sock.sendall(message)
def _send_success(self, sock: socket.socket, data: Any):
"""Send success response."""
self._send_message(sock, NexaDBBinaryProtocol.MSG_SUCCESS, data)
def _send_error(self, sock: socket.socket, error: str):
"""Send error response."""
self._send_message(sock, NexaDBBinaryProtocol.MSG_ERROR, {'error': error})
def _send_not_found(self, sock: socket.socket):
"""Send not found response."""
self._send_message(sock, NexaDBBinaryProtocol.MSG_NOT_FOUND, {'error': 'Not found'})
def _check_database_permission(self, address: tuple, database: str, required_permission: str) -> bool:
"""
Check if user has required permission for a database (v3.0.0).
Permission hierarchy: admin > write > read > guest
Args:
address: Client address (to get session)
database: Database name
required_permission: Required permission level (admin, write, read, guest)
Returns:
True if user has permission, False otherwise
"""
with self.sessions_lock:
session = self.sessions.get(address)
if not session:
return False
# Admin role has access to all databases
if session['role'] == 'admin':
return True
# Check database-specific permissions
db_permissions = session.get('database_permissions', {})
# If no specific permission for this database, deny access
if database not in db_permissions:
return False
# Permission hierarchy
permission_levels = {'guest': 1, 'read': 2, 'write': 3, 'admin': 4}
user_level = permission_levels.get(db_permissions[database], 0)
required_level = permission_levels.get(required_permission, 0)
return user_level >= required_level
def _process_message(self, sock: socket.socket, msg_type: int, data: Dict[str, Any], address: tuple):
"""
Process incoming message and send response.
Args:
sock: Client socket
msg_type: Message type code
data: Message data
address: Client address
"""
try:
if msg_type == NexaDBBinaryProtocol.MSG_CONNECT:
# CONNECT - Handshake + Authentication
self._handle_connect(sock, data, address)
return # Don't check auth for CONNECT itself
# Check authentication for all other operations
with self.sessions_lock:
if address not in self.sessions:
self._send_error(sock, "Not authenticated. Send CONNECT message with API key first.")
return
if msg_type == NexaDBBinaryProtocol.MSG_CREATE:
# CREATE - Insert document
self._handle_create(sock, data, address)
elif msg_type == NexaDBBinaryProtocol.MSG_READ:
# READ - Get document by key
self._handle_read(sock, data, address)
elif msg_type == NexaDBBinaryProtocol.MSG_UPDATE:
# UPDATE - Update document
self._handle_update(sock, data, address)
elif msg_type == NexaDBBinaryProtocol.MSG_DELETE:
# DELETE - Delete document
self._handle_delete(sock, data, address)
elif msg_type == NexaDBBinaryProtocol.MSG_QUERY:
# QUERY - Query with filters
self._handle_query(sock, data, address)
elif msg_type == NexaDBBinaryProtocol.MSG_VECTOR_SEARCH:
# VECTOR_SEARCH - Vector similarity search
self._handle_vector_search(sock, data, address)
elif msg_type == NexaDBBinaryProtocol.MSG_BATCH_WRITE:
# BATCH_WRITE - Bulk insert
self._handle_batch_write(sock, data, address)
elif msg_type == NexaDBBinaryProtocol.MSG_PING:
# PING - Keep-alive
self._handle_ping(sock, data)
elif msg_type == NexaDBBinaryProtocol.MSG_DISCONNECT:
# DISCONNECT - Graceful close
self._send_success(sock, {'status': 'goodbye'})
sock.close()
elif msg_type == NexaDBBinaryProtocol.MSG_QUERY_TOON:
# QUERY_TOON - Query with TOON format response
self._handle_query_toon(sock, data)
elif msg_type == NexaDBBinaryProtocol.MSG_EXPORT_TOON:
# EXPORT_TOON - Export collection to TOON format
self._handle_export_toon(sock, data)
elif msg_type == NexaDBBinaryProtocol.MSG_IMPORT_TOON:
# IMPORT_TOON - Import TOON data into collection
self._handle_import_toon(sock, data)
elif msg_type == NexaDBBinaryProtocol.MSG_CREATE_USER:
# CREATE_USER - Create new user (admin only)
self._handle_create_user(sock, data, address)
elif msg_type == NexaDBBinaryProtocol.MSG_DELETE_USER:
# DELETE_USER - Delete user (admin only)
self._handle_delete_user(sock, data, address)
elif msg_type == NexaDBBinaryProtocol.MSG_LIST_USERS:
# LIST_USERS - List all users (admin only)
self._handle_list_users(sock, address)
elif msg_type == NexaDBBinaryProtocol.MSG_CHANGE_PASSWORD:
# CHANGE_PASSWORD - Change user password
self._handle_change_password(sock, data, address)
elif msg_type == NexaDBBinaryProtocol.MSG_LIST_COLLECTIONS:
# LIST_COLLECTIONS - List all collections
self._handle_list_collections(sock, data, address)
elif msg_type == NexaDBBinaryProtocol.MSG_DROP_COLLECTION:
# DROP_COLLECTION - Drop a collection
self._handle_drop_collection(sock, data, address)
elif msg_type == NexaDBBinaryProtocol.MSG_GET_VECTORS:
# GET_VECTORS - Get vector statistics
self._handle_get_vectors(sock, data)
elif msg_type == NexaDBBinaryProtocol.MSG_SUBSCRIBE_CHANGES:
# SUBSCRIBE_CHANGES - Subscribe to change stream
self._handle_subscribe_changes(sock, data, address)
elif msg_type == NexaDBBinaryProtocol.MSG_UNSUBSCRIBE_CHANGES:
# UNSUBSCRIBE_CHANGES - Unsubscribe from change stream
self._handle_unsubscribe_changes(sock, data, address)
elif msg_type == NexaDBBinaryProtocol.MSG_LIST_DATABASES:
# LIST_DATABASES - List all databases (NEW v3.0.0)
self._handle_list_databases(sock)
elif msg_type == NexaDBBinaryProtocol.MSG_DROP_DATABASE:
# DROP_DATABASE - Drop a database (NEW v3.0.0)
self._handle_drop_database(sock, data)
elif msg_type == NexaDBBinaryProtocol.MSG_IMPORT_MONGODB_DB:
# IMPORT_MONGODB_DB - Import entire MongoDB database (NEW v3.0.0)
self._handle_import_mongodb_database(sock, data)
elif msg_type == NexaDBBinaryProtocol.MSG_IMPORT_MONGODB_COLLECTION:
# IMPORT_MONGODB_COLLECTION - Import single collection (NEW v3.0.0)
self._handle_import_mongodb_collection(sock, data)
elif msg_type == NexaDBBinaryProtocol.MSG_BUILD_HNSW_INDEX:
# BUILD_HNSW_INDEX - Build/rebuild HNSW index for vector collection (NEW v3.0.0)
self._handle_build_hnsw_index(sock, data, address)
else:
self._send_error(sock, f"Unknown message type: {msg_type}")
except Exception as e:
print(f"[ERROR] Failed to process message: {e}")
self._send_error(sock, str(e))
with self.stats_lock:
self.stats['total_errors'] += 1
def _handle_connect(self, sock: socket.socket, data: Dict[str, Any], address: tuple):
"""
Handle CONNECT message with username/password authentication.
Args:
sock: Client socket
data: Connection data with 'username' and 'password' fields
address: Client address
"""
username = data.get('username')
password = data.get('password')
if not username or not password:
self._send_error(sock, "Missing 'username' or 'password' field in CONNECT message")
with self.stats_lock:
self.stats['auth_failures'] += 1
return
# Authenticate user
user_info = self.auth.authenticate_password(username, password)
if not user_info:
self._send_error(sock, "Invalid username or password")
with self.stats_lock:
self.stats['auth_failures'] += 1
return
# Get user's full info including database permissions (v3.0.0)
user_full = self.auth.get_user(user_info['username'])
database_permissions = user_full.get('database_permissions', {}) if user_full else {}
# Store session
with self.sessions_lock:
self.sessions[address] = {
'username': user_info['username'],
'role': user_info['role'],
'database_permissions': database_permissions, # NEW v3.0.0
'authenticated_at': time.time()
}
print(f"[AUTH] User '{user_info['username']}' (role: {user_info['role']}) authenticated from {address[0]}:{address[1]}")
self._send_success(sock, {
'status': 'connected',
'server': 'NexaDB Binary Protocol',
'version': '1.0.0',
'authenticated': True,
'username': user_info['username'],
'role': user_info['role']
})
def _handle_create(self, sock: socket.socket, data: Dict[str, Any], address: tuple = None):
"""Handle CREATE message."""
# NEW v3.0.0: Check if this is database creation
if data.get('create_database'):
database_name = data.get('database')
if not database_name:
self._send_error(sock, "Missing 'database' field")
return
# Check if current user is admin
with self.sessions_lock:
session = self.sessions.get(address)
if not session or session['role'] != 'admin':
self._send_error(sock, "Permission denied. Only admins can create databases.")
return
# Database is created implicitly when first accessed
# Just verify it by accessing it
db = self.db.database(database_name)
print(f"[DATABASE] Admin '{session['username']}' created database '{database_name}'")
self._send_success(sock, {
'database': database_name,
'message': 'Database created'
})
return
# Regular document creation
database_name = data.get('database', 'default') # NEW v3.0.0: Database support
collection_name = data.get('collection')
document = data.get('data')
if not collection_name or not document:
self._send_error(sock, "Missing 'collection' or 'data' field")
return
# NEW v3.0.0: Check database permission
if address and not self._check_database_permission(address, database_name, 'write'):
self._send_error(sock, f"Permission denied: You don't have 'write' access to database '{database_name}'")
return
# Get database
db = self.db.database(database_name)
# NEW v3.0.5: Register collection metadata so it appears in list_collections
# Check if document has vector field to determine dimensions
vector_dimensions = None
if 'vector' in document and isinstance(document['vector'], list):
vector_dimensions = len(document['vector'])
db.register_collection(collection_name, vector_dimensions)
# Check if document has vector field for automatic indexing
if 'vector' in document and isinstance(document['vector'], list):
# Auto-index vector for similarity search
vector = document['vector']
dimensions = len(vector)
# Validate vector dimensions against collection metadata
# First check if collection has a marker with dimensions spec
collection = db.collection(collection_name)
all_docs = collection.find({'_nexadb_collection_marker': True}, limit=1)
expected_dimensions = None
if all_docs:
marker = all_docs[0]
if '_vector_dimensions' in marker:
expected_dimensions = marker['_vector_dimensions']
# If no marker dimensions, check against existing vectors
if expected_dimensions is None:
vector_prefix = f"db:{database_name}:vector:{collection_name}:"
existing_vectors_iter = self.db.engine.range_scan(vector_prefix, vector_prefix + '\xff')
# Get first vector if it exists
first_vector = None
try:
for vec in existing_vectors_iter:
first_vector = vec
break # Only get the first one
except:
pass
if first_vector:
# Collection has vectors, use their dimensions
try:
import json
existing_vector = json.loads(first_vector[1].decode('utf-8'))
expected_dimensions = len(existing_vector)
except:
pass # If we can't decode, proceed
# Validate dimensions if we have expected dimensions
if expected_dimensions is not None and dimensions != expected_dimensions:
self._send_error(sock, f"Vector dimension mismatch: collection expects {expected_dimensions} dimensions, got {dimensions}")
return
# Insert via vector collection (indexes vector automatically)
vector_collection = db.vector_collection(collection_name, dimensions)
doc_data = {k: v for k, v in document.items() if k != 'vector'}
doc_id = vector_collection.insert(doc_data, vector)
else:
# Regular insert (no vector)
collection = db.collection(collection_name)
doc_id = collection.insert(document)
self._send_success(sock, {
'database': database_name,
'collection': collection_name,
'document_id': doc_id,
'message': 'Document inserted'
})
def _handle_read(self, sock: socket.socket, data: Dict[str, Any], address: tuple = None):
"""Handle READ message."""
database_name = data.get('database', 'default') # NEW v3.0.0: Database support
collection_name = data.get('collection')
doc_id = data.get('key')
if not collection_name or not doc_id:
self._send_error(sock, "Missing 'collection' or 'key' field")
return
# NEW v3.0.0: Check database permission
if address and not self._check_database_permission(address, database_name, 'read'):
self._send_error(sock, f"Permission denied: You don't have 'read' access to database '{database_name}'")
return
# Get database and collection
db = self.db.database(database_name)
collection = db.collection(collection_name)
document = collection.find_by_id(doc_id)
if document:
self._send_success(sock, {
'database': database_name,
'collection': collection_name,
'document': document
})
else:
self._send_not_found(sock)
def _handle_update(self, sock: socket.socket, data: Dict[str, Any], address: tuple = None):
"""Handle UPDATE message."""
database_name = data.get('database', 'default') # NEW v3.0.0: Database support
collection_name = data.get('collection')
doc_id = data.get('key')
updates = data.get('updates')
if not collection_name or not doc_id or not updates:
self._send_error(sock, "Missing 'collection', 'key', or 'updates' field")
return
# NEW v3.0.0: Check database permission
if address and not self._check_database_permission(address, database_name, 'write'):
self._send_error(sock, f"Permission denied: You don't have 'write' access to database '{database_name}'")
return
# Get database and collection
db = self.db.database(database_name)
collection = db.collection(collection_name)
success = collection.update(doc_id, updates)
if success:
self._send_success(sock, {
'database': database_name,
'collection': collection_name,
'document_id': doc_id,
'message': 'Document updated'
})
else:
self._send_not_found(sock)
def _handle_delete(self, sock: socket.socket, data: Dict[str, Any], address: tuple = None):
"""Handle DELETE message."""
database_name = data.get('database', 'default') # NEW v3.0.0: Database support
collection_name = data.get('collection')
doc_id = data.get('key')
if not collection_name or not doc_id:
self._send_error(sock, "Missing 'collection' or 'key' field")
return
# NEW v3.0.0: Check database permission
if address and not self._check_database_permission(address, database_name, 'write'):
self._send_error(sock, f"Permission denied: You don't have 'write' access to database '{database_name}'")
return
# Get database and collection
db = self.db.database(database_name)
collection = db.collection(collection_name)
success = collection.delete(doc_id)
if success:
self._send_success(sock, {
'database': database_name,
'collection': collection_name,
'document_id': doc_id,
'message': 'Document deleted'
})
else:
self._send_not_found(sock)
def _handle_query(self, sock: socket.socket, data: Dict[str, Any], address: tuple = None):
"""Handle QUERY message."""
database_name = data.get('database', 'default') # NEW v3.0.0: Database support
collection_name = data.get('collection')
filters = data.get('filters', {})
limit = data.get('limit', 100)
if not collection_name:
self._send_error(sock, "Missing 'collection' field")
return
# NEW v3.0.0: Check database permission
if address and not self._check_database_permission(address, database_name, 'read'):
self._send_error(sock, f"Permission denied: You don't have 'read' access to database '{database_name}'")
return
# Get database and collection
db = self.db.database(database_name)
collection = db.collection(collection_name)
documents = collection.find(filters, limit=limit)
self._send_success(sock, {
'database': database_name,
'collection': collection_name,
'documents': documents,
'count': len(documents)
})
def _handle_vector_search(self, sock: socket.socket, data: Dict[str, Any], address: tuple = None):
"""Handle VECTOR_SEARCH message."""
database_name = data.get('database', 'default') # NEW v3.0.0: Database support
collection_name = data.get('collection')
vector = data.get('vector')
limit = data.get('limit', 10)
dimensions = data.get('dimensions', 768)
filters = data.get('filters') # Optional metadata filters
if not collection_name or not vector:
self._send_error(sock, "Missing 'collection' or 'vector' field")
return
# NEW v3.0.0: Check database permission
if address and not self._check_database_permission(address, database_name, 'read'):
self._send_error(sock, f"Permission denied: You don't have 'read' access to database '{database_name}'")
return
# Get database and vector collection
db = self.db.database(database_name)
vector_collection = db.vector_collection(collection_name, dimensions)
results = vector_collection.search(vector, limit=limit)
# Format results
formatted_results = []
for doc_id, similarity, doc in results:
# Apply metadata filters if provided
if filters:
# Check if document matches all filters
matches = True
for field, condition in filters.items():
doc_value = doc.get(field)
if isinstance(condition, dict):
# Handle operators like {'$gte': 100}
for operator, operand in condition.items():
if operator == '$gte' and not (doc_value >= operand):
matches = False
break
elif operator == '$lte' and not (doc_value <= operand):
matches = False
break
elif operator == '$gt' and not (doc_value > operand):
matches = False
break
elif operator == '$lt' and not (doc_value < operand):
matches = False
break
else:
# Simple equality check
if doc_value != condition:
matches = False
break
if not matches:
continue
formatted_results.append({
'document_id': doc_id,
'similarity': float(similarity),
'document': doc
})
self._send_success(sock, {
'database': database_name,
'collection': collection_name,
'results': formatted_results,
'count': len(formatted_results)
})
def _handle_batch_write(self, sock: socket.socket, data: Dict[str, Any], address: tuple = None):
"""Handle BATCH_WRITE message."""
database_name = data.get('database', 'default') # NEW v3.0.0: Database support
collection_name = data.get('collection')
documents = data.get('documents', [])
if not collection_name or not documents:
self._send_error(sock, "Missing 'collection' or 'documents' field")
return
# NEW v3.0.0: Check database permission
if address and not self._check_database_permission(address, database_name, 'write'):
self._send_error(sock, f"Permission denied: You don't have 'write' access to database '{database_name}'")
return
# Get database
db = self.db.database(database_name)
# Check if documents have vector fields for automatic indexing
has_vectors = any('vector' in doc and isinstance(doc.get('vector'), list) for doc in documents)
if has_vectors:
# Use vector collection for automatic indexing with BATCH operations (100x faster!)
# Get dimensions from first document with vector
dimensions = None
for doc in documents:
if 'vector' in doc and isinstance(doc['vector'], list):
dimensions = len(doc['vector'])
break
vector_collection = db.vector_collection(collection_name, dimensions)
# Separate vector documents from regular documents
vector_docs = []
regular_docs = []
for doc in documents:
if 'vector' in doc and isinstance(doc['vector'], list):
vector = doc['vector']