<commit_before>
import copy
import urllib2
import uuid
import sys
try:
    import json
except: 
    import simplejson as json

# JSON-RPC standard error codes
ERR_PARSE = -32700
ERR_INVALID_REQ = -32600
ERR_METHOD_NOT_FOUND = -32601
ERR_INVALID_PARAMS = -32602
ERR_INTERNAL = -32603

# Our extensions
ERR_UNKNOWN = -32000
ERR_INVALID_RESP = -32001

def contract_from_file(fname):
    f = open(fname)
    j = f.read()
    f.close()
    return Contract(json.loads(j))

def unpack_method(method):
    pos = method.find(".")
    if pos == -1:
        raise RpcException(ERR_METHOD_NOT_FOUND, "Method not found: %s" % method)

    iface_name = method[:pos]
    func_name  = method[pos+1:]
    return iface_name, func_name

class RpcException(Exception, json.JSONEncoder):

    def __init__(self, code, msg="", data=None):
        self.code = code
        self.msg = msg
        self.data = data

    def __str__(self):
        s = "RpcException: code=%d msg=%s" % (self.code, self.msg)
        if self.data:
            s += "%s data=%s" % (s, str(self.data))
        return s

class Server(object):

    def __init__(self, contract, validate_request=True, validate_response=True):
        self.validate_req  = validate_request
        self.validate_resp = validate_response
        self.contract = contract
        self.handlers = { }

    def add_handler(self, iface_name, handler):
        if self.contract.has_interface(iface_name):
            self.handlers[iface_name] = handler
        else:
            raise RpcException(ERR_INVALID_REQ, "Unknown interface: '%s'", iface_name)

    def call(self, req):
        if isinstance(req, list):
            if len(req) < 1:
                return self._err(None, ERR_INVALID_REQ, "Invalid Request. Empty batch.")

            resp = [ ]
            for r in req:
                resp.append(self._call_and_format(r))
            return resp
        else:
            return self._call_and_format(req)

    def _err(self, reqid, code, msg, data=None):
        err = { "code": code, "message": msg }
        if data:
            err["data"] = data
        return { "jsonrpc": "2.0", "id": reqid, "error": err }
    
    def _call_and_format(self, req):
        if not isinstance(req, dict):
            return self._err(None, ERR_INVALID_REQ, 
                             "Invalid Request. %s is not an object." % str(req))

        reqid = None
        if req.has_key("id"):
            reqid = req["id"]

        try:
            resp = self._call(req)
            return { "jsonrpc": "2.0", "id": reqid, "result": resp }
        except RpcException as e:
            return self._err(reqid, e.code, e.msg, e.data)
        except:
            return self._err(reqid, ERR_UNKNOWN, str(sys.exc_info()))
        

    def _call(self, req):
        if not req.has_key("method"):
            raise RpcException(ERR_INVALID_REQ, "Invalid Request. No 'method'.")

        method = req["method"]

        if method == "barrister-idl":
            return self.contract.idl_parsed

        iface_name, func_name = unpack_method(method)

        if self.handlers.has_key(iface_name):
            iface_impl = self.handlers[iface_name]
            func = getattr(iface_impl, func_name)
            if func:
                if req.has_key("params"):
                    params = req["params"]
                else:
                    params = [ ]

                if self.validate_req:
                    self.contract.validate_request(iface_name, func_name, params)

                if params and len(params) > 0:
                    result = func(*params)
                else:
                    result = func()

                if self.validate_resp:
                    self.contract.validate_response(iface_name, func_name, result)
                return result
            else:
                msg = "Method '%s' not found" % (method)
                raise RpcException(ERR_METHOD_NOT_FOUND, msg)
        else:
            msg = "No implementation of '%s' found" % (iface_name)
            raise RpcException(ERR_METHOD_NOT_FOUND, msg)        

class HttpTransport(object):

    def __init__(self, url, handlers=None, headers=None):
        if not headers:
            headers = { }
        headers['Content-Type'] = 'application/json'
        self.url = url
        self.headers = headers
        if handlers:
            self.opener = urllib2.build_opener(*handlers)
        else:
            self.opener = urllib2.build_opener()
        
    def request(self, req):
        data = json.dumps(req)
        req = urllib2.Request(self.url, data, self.headers)
        f = urllib2.urlopen(req)
        resp = f.read()
        f.close()
        return json.loads(resp)

class InProcTransport(object):

    def __init__(self, server):
        self.server = server

    def request(self, req):
        return self.server.call(req)

class Client(object):
    
    def __init__(self, transport, validate_request=True, validate_response=True,
                 id_gen=None):
        self.transport = transport
        self.validate_req  = validate_request
        self.validate_resp = validate_response
        if not id_gen:
            id_gen = lambda: uuid.uuid4().hex
        self.id_gen = id_gen
        req = {"jsonrpc": "2.0", "method": "barrister-idl", "id": "1"}
        resp = transport.request(req)
        self.contract = Contract(resp["result"])
        for k, v in self.contract.interfaces.items():
            setattr(self, k, InterfaceClientProxy(self, v))
<commit_msg>Add a counter based id generator.  Replace lambda in Client with module level function.<commit_after>
import urllib2
import uuid
import sys
import itertools
try:
    import json
except: 
    import simplejson as json

# JSON-RPC standard error codes
ERR_PARSE = -32700
ERR_INVALID_REQ = -32600
ERR_METHOD_NOT_FOUND = -32601
ERR_INVALID_PARAMS = -32602
ERR_INTERNAL = -32603

# Our extensions
ERR_UNKNOWN = -32000
ERR_INVALID_RESP = -32001

def contract_from_file(fname):
    f = open(fname)
    j = f.read()
    f.close()
    return Contract(json.loads(j))

def unpack_method(method):
    pos = method.find(".")
    if pos == -1:
        raise RpcException(ERR_METHOD_NOT_FOUND, "Method not found: %s" % method)

    iface_name = method[:pos]
    func_name  = method[pos+1:]
    return iface_name, func_name

def idgen_uuid():
    return uuid.uuid4()

idgen_seq_counter = itertools.count()
def idgen_seq():
    return str(idgen_seq_counter.next())

class RpcException(Exception, json.JSONEncoder):

    def __init__(self, code, msg="", data=None):
        self.code = code
        self.msg = msg
        self.data = data

    def __str__(self):
        s = "RpcException: code=%d msg=%s" % (self.code, self.msg)
        if self.data:
            s += "%s data=%s" % (s, str(self.data))
        return s

class Server(object):

    def __init__(self, contract, validate_request=True, validate_response=True):
        self.validate_req  = validate_request
        self.validate_resp = validate_response
        self.contract = contract
        self.handlers = { }

    def add_handler(self, iface_name, handler):
        if self.contract.has_interface(iface_name):
            self.handlers[iface_name] = handler
        else:
            raise RpcException(ERR_INVALID_REQ, "Unknown interface: '%s'", iface_name)

    def call(self, req):
        if isinstance(req, list):
            if len(req) < 1:
                return self._err(None, ERR_INVALID_REQ, "Invalid Request. Empty batch.")

            resp = [ ]
            for r in req:
                resp.append(self._call_and_format(r))
            return resp
        else:
            return self._call_and_format(req)

    def _err(self, reqid, code, msg, data=None):
        err = { "code": code, "message": msg }
        if data:
            err["data"] = data
        return { "jsonrpc": "2.0", "id": reqid, "error": err }
    
    def _call_and_format(self, req):
        if not isinstance(req, dict):
            return self._err(None, ERR_INVALID_REQ, 
                             "Invalid Request. %s is not an object." % str(req))

        reqid = None
        if req.has_key("id"):
            reqid = req["id"]

        try:
            resp = self._call(req)
            return { "jsonrpc": "2.0", "id": reqid, "result": resp }
        except RpcException as e:
            return self._err(reqid, e.code, e.msg, e.data)
        except:
            return self._err(reqid, ERR_UNKNOWN, str(sys.exc_info()))
        

    def _call(self, req):
        if not req.has_key("method"):
            raise RpcException(ERR_INVALID_REQ, "Invalid Request. No 'method'.")

        method = req["method"]

        if method == "barrister-idl":
            return self.contract.idl_parsed

        iface_name, func_name = unpack_method(method)

        if self.handlers.has_key(iface_name):
            iface_impl = self.handlers[iface_name]
            func = getattr(iface_impl, func_name)
            if func:
                if req.has_key("params"):
                    params = req["params"]
                else:
                    params = [ ]

                if self.validate_req:
                    self.contract.validate_request(iface_name, func_name, params)

                if params and len(params) > 0:
                    result = func(*params)
                else:
                    result = func()

                if self.validate_resp:
                    self.contract.validate_response(iface_name, func_name, result)
                return result
            else:
                msg = "Method '%s' not found" % (method)
                raise RpcException(ERR_METHOD_NOT_FOUND, msg)
        else:
            msg = "No implementation of '%s' found" % (iface_name)
            raise RpcException(ERR_METHOD_NOT_FOUND, msg)        

class HttpTransport(object):

    def __init__(self, url, handlers=None, headers=None):
        if not headers:
            headers = { }
        headers['Content-Type'] = 'application/json'
        self.url = url
        self.headers = headers
        if handlers:
            self.opener = urllib2.build_opener(*handlers)
        else:
            self.opener = urllib2.build_opener()
        
    def request(self, req):
        data = json.dumps(req)
        req = urllib2.Request(self.url, data, self.headers)
        f = urllib2.urlopen(req)
        resp = f.read()
        f.close()
        return json.loads(resp)

class InProcTransport(object):

    def __init__(self, server):
        self.server = server

    def request(self, req):
        return self.server.call(req)

class Client(object):
    
    def __init__(self, transport, validate_request=True, validate_response=True,
                 id_gen=idgen_uuid):
        self.transport = transport
        self.validate_req  = validate_request
        self.validate_resp = validate_response
        self.id_gen = id_gen
        req = {"jsonrpc": "2.0", "method": "barrister-idl", "id": "1"}
        resp = transport.request(req)
        self.contract = Contract(resp["result"])
        for k, v in self.contract.interfaces.items():
            setattr(self, k, InterfaceClientProxy(self, v))

{'fraction_non_alphanumeric': 0.10919642857142857, 'fraction_numerical': 0.009285714285714286, 'mean_word_length': 2.02402807775378, 'pattern_counts': {'":': 24, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2579473', 'n_tokens_mistral': 3476, 'n_tokens_neox': 3374, 'n_words': 813}