11"""Integration of Dispatch functions with http."""
22
3+ from datetime import datetime
4+
35import logging
46import os
57from datetime import timedelta
@@ -61,10 +63,12 @@ def __init__(
6163 registry : Registry ,
6264 verification_key : Optional [Ed25519PublicKey ] = None ,
6365 ):
64- super ().__init__ (request , client_address , server )
6566 self .registry = registry
6667 self .verification_key = verification_key
6768 self .error_content_type = "application/json"
69+ print (datetime .now (), "INITIALIZING FUNCTION SERVICE" )
70+ super ().__init__ (request , client_address , server )
71+ print (datetime .now (), "DONE HANDLING REQUEST" )
6872
6973 def send_error_response_invalid_argument (self , message : str ):
7074 self .send_error_response (400 , "invalid_argument" , message )
@@ -82,17 +86,33 @@ def send_error_response_internal(self, message: str):
8286 self .send_error_response (500 , "internal" , message )
8387
8488 def send_error_response (self , status : int , code : str , message : str ):
89+ body = f'{{"code":"{ code } ","message":"{ message } "}}' .encode ()
8590 self .send_response (status )
8691 self .send_header ("Content-Type" , self .error_content_type )
92+ self .send_header ("Content-Length" , str (len (body )))
8793 self .end_headers ()
88- self .wfile .write (f'{{"code":"{ code } ","message":"{ message } "}}' .encode ())
94+ print (datetime .now (), "SENDING ERROR RESPONSE" )
95+ self .wfile .write (body )
96+ print (datetime .now (), f"SERVER IS DONE { len (body )} " )
8997
9098 def do_POST (self ):
9199 if self .path != "/dispatch.sdk.v1.FunctionService/Run" :
92100 self .send_error_response_not_found ("path not found" )
93101 return
94102
95- data : bytes = self .rfile .read ()
103+ content_length = int (self .headers .get ("Content-Length" , 0 ))
104+ if content_length == 0 :
105+ self .send_error_response_invalid_argument ("content length is required" )
106+ return
107+ if content_length < 0 :
108+ self .send_error_response_invalid_argument ("content length is negative" )
109+ return
110+ if content_length > 16_000_000 :
111+ self .send_error_response_invalid_argument ("content length is too large" )
112+ return
113+
114+ data : bytes = self .rfile .read (content_length )
115+ print (datetime .now (), f"RECEIVED POST REQUEST: { self .path } { len (data )} { self .request_version } { self .headers } " )
96116 logger .debug ("handling run request with %d byte body" , len (data ))
97117
98118 if self .verification_key is not None :
@@ -130,7 +150,7 @@ def do_POST(self):
130150 )
131151 return
132152
133- logger . info ( "running function '%s'" , req .function )
153+ print ( datetime . now (), "running function '%s'" , req .function )
134154 try :
135155 output = func ._primitive_call (Input (req ))
136156 except Exception :
0 commit comments