-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsimple_db_server.py
More file actions
222 lines (209 loc) · 9.22 KB
/
Copy pathsimple_db_server.py
File metadata and controls
222 lines (209 loc) · 9.22 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
#
################################################################################
# The MIT License (MIT)
#
# Copyright (c) 2025 Curt Timmerman
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
################################################################################
#
import json
# Run the following with micropython
from simple_db import SimpleDB, simpledb_available
# Run the following with python
#from simple_db_btrees import SimpleDBBtrees as SimpleDB, simpledb_available
'''
From json-rpc documentation
-32700 Parse error, Invalid JSON was received by the server.
An error occurred on the server while parsing the JSON text.
-32600 Invalid Request, The JSON sent is not a valid Request object.
-32601 Method not found, The method does not exist / is not available.
-32602 Invalid params, Invalid method parameter(s).
-32603 Internal error, Internal JSON-RPC error.
-32000 to -32099 Server error, Reserved for implementation-defined server-errors.
'''
RPC_GENERIC_ERROR = -32000
RPC_DB_CALL_ERROR = -32001
RPC_METHOD_ERROR = -32601
RPC_PARSE_ERROR = -32700
RPC_REQUEST_ERROR = -32600
RPC_PARAMETER_ERROR = -32602
RPC_INTERNAL_ERROR = -32603
RPC_ERRORS = {
RPC_METHOD_ERROR : "Method not found" ,
RPC_PARSE_ERROR : "Parse error" ,
RPC_REQUEST_ERROR : "Invalid request" ,
RPC_PARAMETER_ERROR : "Invalid method parameter(s)" ,
RPC_INTERNAL_ERROR : "Internal JSON-RPC error" ,
RPC_GENERIC_ERROR : "Unknown Error" ,
RPC_DB_CALL_ERROR : "SimpleDB client call error"
}
DEFAULT_METHODS = "readonly"
DEFAULT_METHODS = "open"
METHODS = {
"readonly" : {
"get_configuration" : {"allowed" : True,"method" : None} ,
"write_row" : {"allowed" : False,"method" : None} ,
"rewrite_row" : {"allowed" : False,"method" : None} ,
"row_exists" : {"allowed" : True ,"method" : None} ,
"read_row" : {"allowed" : True ,"method" : None} ,
"read_columns" : {"allowed" : True ,"method" : None} ,
"first_row" : {"allowed" : True ,"method" : None} ,
"next_row" : {"allowed" : True ,"method" : None} ,
"get_table_keys" : {"allowed" : True ,"limit_max" : 500 ,"method" : None} ,
"get_table_rows" : {"allowed" : True ,"limit_max" : 200 ,"method" : None} ,
"get_table_items" : {"allowed" : True ,"limit_max" : 100 ,"method" : None} ,
"delete_row" : {"allowed" : False,"method" : None} ,
"commit" : {"allowed" : True ,"method" : None} ,
"dump_all" : {"allowed" : False ,"method" : None} ,
"load" : {"allowed" : False ,"method" : None} ,
"get_date_time" : {"allowed" : True ,"method" : None} ,
"get_date" : {"allowed" : True ,"method" : None} ,
"get_time" : {"allowed" : True ,"method" : None}
} ,
"restricted" : {
"get_configuration" : {"allowed" : True,"method" : None} ,
"row_exists" : {"allowed" : True ,"method" : None} ,
"read_row" : {"allowed" : True ,"method" : None} ,
"read_columns" : {"allowed" : True ,"method" : None} ,
"first_row" : {"allowed" : True ,"method" : None} ,
"next_row" : {"allowed" : True ,"method" : None} ,
"get_table_rows" : {"allowed" : True ,"limit_max" : 20 ,"method" : None} ,
"commit" : {"allowed" : True ,"method" : None} ,
"get_date_time" : {"allowed" : True ,"method" : None} ,
"get_date" : {"allowed" : True ,"method" : None} ,
"get_time" : {"allowed" : True ,"method" : None}
} ,
"open" : {
"get_configuration" : {"allowed" : True,"method" : None} ,
"write_row" : {"allowed" : True,"method" : None} ,
"rewrite_row" : {"allowed" : True,"method" : None} ,
"row_exists" : {"allowed" : True ,"method" : None} ,
"read_row" : {"allowed" : True ,"method" : None} ,
"read_columns" : {"allowed" : True ,"method" : None} ,
"first_row" : {"allowed" : True ,"method" : None} ,
"next_row" : {"allowed" : True ,"method" : None} ,
"get_table_keys" : {"allowed" : True ,"limit_max" : 1000 ,"method" : None} ,
"get_table_rows" : {"allowed" : True ,"limit_max" : 500 ,"method" : None} ,
"get_table_items" : {"allowed" : True ,"limit_max" : 200 ,"method" : None} ,
"delete_row" : {"allowed" : True,"method" : None} ,
"commit" : {"allowed" : True ,"method" : None} ,
"dump_all" : {"allowed" : True ,"method" : None} ,
"load" : {"allowed" : True ,"method" : None} ,
"get_date_time" : {"allowed" : True ,"method" : None} ,
"get_date" : {"allowed" : True ,"method" : None} ,
"get_time" : {"allowed" : True ,"method" : None}
}
}
## For handling GET parameters
SCALAR_PARAMETERS = [
"epoch_seconds" ,
"file_path" ,
"limit" ,
"row_data" ,
"table_name"
]
ARRAY_PARAMETERS = [
"end_key" ,
"key" ,
"pk_id" ,
"column_list" ,
"start_key"
]
class SimpleDBServer :
def __init__ (self ,
db_file_name = "server_test.db") :
## Set up database methods
self.db = SimpleDB (db_file_name)
for _, (method_type, methods) in enumerate (METHODS.items ()) :
for _, (method_id, method_data) in enumerate (methods.items ()) :
if method_data ["allowed"] :
try :
method_data ["method"] = getattr (self.db, method_id, None)
except Exception :
method_data ["allowed"] = False
## Set up server
self.rpc_reply = None
self.methods = None
def process_request (self, rpc_request, methods = None) :
#print ("process_request:", rpc_request)
self.rpc_reply = {
"jsonrpc" : "2.0" ,
"id" : None
}
if methods is None :
self.methods = METHODS [DEFAULT_METHODS]
elif methods in METHODS :
self.methods = METHODS [methods]
else :
self.methods = METHODS [DEFAULT_METHODS]
self.process_message (rpc_request)
return self.rpc_reply
def process_message (self, rpc_request) :
db_reply = None
try :
self.rpc_dict = json.loads (rpc_request)
except :
self.rpc_error (RPC_PARSE_ERROR)
return None
## test for valid json rpc message
if "jsonrpc" not in self.rpc_dict \
or "method" not in self.rpc_dict \
or "params" not in self.rpc_dict :
self.rpc_error (RPC_REQUEST_ERROR)
return None
if "id" in self.rpc_dict :
self.rpc_reply ["id"] = self.rpc_dict ["id"] # don't care about "id"
if self.rpc_dict["method"] not in self.methods :
self.rpc_error (RPC_METHOD_ERROR) # Not a valid method
return
## Test for valid/allowed method
method_data = self.methods [self.rpc_dict["method"]]
if not method_data ["allowed"] :
self.rpc_error (RPC_METHOD_ERROR) # method not allowed
return
if "limit_max" in method_data :
if "limit" in self.rpc_dict["params"] :
if self.rpc_dict["params"]["limit"] > method_data["limit_max"] :
self.rpc_dict["params"]["limit"] = method_data["limit_max"]
else :
self.rpc_dict["params"]["limit"] = method_data["limit_max"]
#print ("rpc: params", self.rpc_dict["params"])
try :
## simple db function call
db_reply = self.methods [self.rpc_dict["method"]]["method"] (**self.rpc_dict["params"])
except Exception as e :
self.rpc_error_message (RPC_DB_CALL_ERROR, str(e))
return
self.rpc_reply ["result"] = db_reply # reply message
def rpc_error_message (self, error_number, error_message) :
message_save = RPC_ERRORS [error_number]
RPC_ERRORS [error_number] = error_message
self.rpc_error (error_number)
RPC_ERRORS [error_number] = message_save
def rpc_error (self, error_number) :
#print ("rpc_error:", error_number)
self.rpc_reply ["error"] = {
"code" : error_number ,
"message" : RPC_ERRORS [error_number]
}
## Shut down server and database
def shutdown (self) :
print ("Stopping Server")
self.db.close () # database