Package: noneapi
NoneAPI (alpha)This mini-framework (RPC like) allows you to easily build microservices that can communicate with each other like modules in a monolith. This project was inspired by thenameko framework.🎯 PhilosophyJust call your microservices like you would any other function.The goal of this framework is to simplify microservice interactions, eliminating the need for middleware. To send parameters like 'user' or anything else, include them in the method arguments. This ensures clarity in the data sent to and received from the service.Performance:
~ 35000 requests per second on one worker📜 Table of ContentsPhilosophyWhy Not Nameko or Others?FeaturesInstallationQuick StartTutorialsAPI ReferenceFAQChangelogContributingLicense❓ Why Not Nameko or Others?We leverageZeroMQto eliminate broker intermediaries.🌟 FeaturesFast and reliable with ZeroMQEasy integrationDecoupled architectureEvent-driven designMulti-subscriber supportNo broker neededZero learning curveAuto-generated documentation⚙️ InstallationInstall via pip:pipinstallnoneapiQuick StartHere's how to get started with MyLibrary:Install:pipinstallnoneapiCreate order service:# services.pyfromnoneapiimportrpcfromnoneapiimportContainer,ContainerRunnerfrom.dbimportorder_sessionfrom.modelsimportOrderclassOrderService:name='order_service'@rpcdefget_order(self,order_id:int):order=order_session.query(Order).get(order_id)ifnotorder:returnNonereturnorder.to_dict()@rpcdefsave_order(self,order:dict):order=Order(**order)order_session.add(order)order_session.commit()returnorder.to_dict()# containers.pycontainer=Container(OrderService)runner=ContainerRunner(is_document_server=False)runner.register("order",container,host="*",port=5555)# app.pyfrom.containersimportrunnerif__name__=='__main__':runner.run()Use by client:fromnoneapiimportClusterProxyfromexceptionsimportRemoteErrorfrom.usecasesimportOrderUsecaseconfig=[{"name":"order_service","host":"127.0.0.1","port":5555}]...# some other codewithClusterProxy(config)ascluster:order=cluster.order_service.get_order(1)order_usecase=OrderUsecase(order)updated_order=order_usecase.do_something()cluster.order_service.save_order.async_call(updated_order)...# A lot of codetry:result=cluster.order_service.save_order.result()exceptRemoteErrorase:print(e)# do somethingelse:# do somethingTutorialsInstall:pipinstallnoneapiRPC:fromnoneapiimportrpcclassOrderService:name='order_service'@rpcdefadd_order(self,order:dict):# some codereturnorderIn this scenario, any service usingnoneapican communicate directly with this service by invoking theadd_ordermethod.name: Identifier for the service. This is used for service discovery and is mandatory for each service.@rpc: A decorator that makes the method available for remote procedure calls. Only methods tagged with this decorator can be remotely invoked.Event handlingfromnoneapiimportrpc,event_handler,EventDispatcher,ServiceProxyclassOrderService:name='order_service'payment_service=ServiceProxy(event_host="127.0.0.1",event_port=5556)@rpcdefadd_order(self,order:dict):# some codereturnorder@event_handler(service_name='payment_service',topic='payment_success')defon_payment_success(self,order_id:int):# some codereturnorder_idclassPaymentService:name='payment_service'dispatch=EventDispatcher(port=5556,host='*')@rpcdefpay(self,order_id:int):self.dispatch('payment_success',order_id)returnorder_idIn this setup, we add anevent_handlertoOrderServiceand establishPaymentServicewith anEventDispatcher. Whenever a 'payment_success' event is dispatched byPaymentService, theon_payment_successmethod inOrderServicewill be triggered. Essentially, this mimics the publish/subscribe (pub/sub) pattern where you can subscribe to different topics.@event_handler: A decorator used for methods that will be invoked when a specific event is dispatched. Only methods with this decorator respond to the event.EventDispatcher: A class responsible for sending out events to all services that are listening viaevent_handler. The parametersportandhostspecify where theEventDispatcherwill be available for dispatching events.ServiceProxy: A class offering access to remote services. The optional parametersevent_hostandevent_portdefine where the service listens for events. Because there are no message brokers, it's essential to know the publisher's location for event reception.Containers:fromnoneapiimportContainer,ContainerRunnerfrom.servicesimportOrderServicecontainer=Container(OrderService)runner=ContainerRunner(is_document_server=False)runner.register(container,host="*",port=5555)runner.run()In this case, we create a container with one service and run it.Container: A class that holds all services that will be available for remote calls.ContainerRunner: A class responsible for running all registered containers and facilitating service discovery.register: A method to register a container within the runner. It acceptscontainer,host, andportas arguments. Bothhostandportare optional. By default,hostis set to"*"andportto5555.run: A method that starts all the containers and the documentation service if applicable.ClusterProxy:fromnoneapiimportClusterProxyfromexceptionsimportRemoteErrorconfig=[{"name":"order_service","host":"127.0.0.1","port":5555,}]defmain():withClusterProxy(config)ascluster:order=cluster.order_service.add_order({"id":1})In this example, we create aClusterProxywith a configuration that points to theorder_service. TheClusterProxyis a context manager that allows us to access the service viacluster.order_service. Theadd_ordermethod is invoked with a dictionary as an argument.ClusterProxy: A class that allows access to remote services. It accepts a configuration as an argument. The configuration is a list of dictionaries with the following keys:name,host, andport. Thenameis the identifier of the service. Thehostandportare the location of the service. Bothhostandportare optional. By default,hostis set to `"Async call:fromnoneapiimportClusterProxyfromexceptionsimportRemoteErrorconfig=[{"name":"order_service","host":"127.0.0.1","port":5555,}]defmain():withClusterProxy(config)ascluster:cluster.order_service.add_order.async_call({"id":1})# a lot of codetry:result=cluster.order_service.result()exceptRemoteErrorase:print(e)# do somethingelse:# do somethingIn this example, we create aClusterProxywith a configuration that points to theorder_service. TheClusterProxyis a context manager that allows us to access the service viacluster.order_servicelike in the previous example but withasync_callthat allow us to call method asynchronously. Theresultmethod is invoked without arguments and returned result.Validation with pydanticfromnoneapiimportrpcclassOrderService:name='order_service'@rpcdefadd_order(self,order_id:int,name:str):# some codereturnorderIn this scenario, we can validate input. NoneAPI will validate input data and return error if data is not valid.
Onlyint,float,str,boolandNonetypes are supported.If you want validate complex data, you can usepydanticmodels for that:fromnoneapiimportrpcfrompydanticimportBaseModelclassOrder(BaseModel):id:intname:strclassOrderService:name='order_service'@rpcdefadd_order(self,order:Order):# some codereturnorderIn this case NoneAPI will validate input data withOrdermodel and return error if data is not valid.DocsfromnoneapiimportContainer,ContainerRunnerfrom.servicesimportOrderServicecontainer=Container(OrderService)runner=ContainerRunner(is_document_server=True)runner.register(container,host="*",port=5555)runner.run()In this case, we create a container with one service and run it with documentation server.
It will be always available onhttp://localhost:8081/Custom serializationfromnoneapiimportBaseSerializerfromnoneapiimportProtocolfrommsgpackimportpackb,unpackbclassMsgPackSerializer(BaseSerializer):def_serialize(self,data:dict)->bytes:returnpackb(data)def_deserialize(self,data:bytes)->dict:returnunpackb(data)classOrderService:name='order_service'protocol:Protocol[MsgPackSerializer]=Protocol(MsgPackSerializer())@rpcdefadd_order(self,order:dict):# some codereturnorderIn this case, we're creating a custom serializer for the service, applicable to all its methods. By default, NoneAPI employs a clean JSON serializer, powered by the ultra-fast orjson library. Feel free to use any serializer—just inherit from BaseSerializer and pass it to the Protocol class.IMPORTANT: If you change the serializer, you must change it on all services that will communicate with each other. Otherwise, you will get an error.ChangelogVersion 0.1.3 (2023-10-29)(alpha)Initial releaseVersion 0.1.4 (2023-10-29)(alpha)Add custom serializerAdd custom serializer documentationContributingTo contribute, please fork the repository, make your changes, and submit a pull request.LicenseThis project is licensed under the MIT License. See the LICENSE.md file for details.If you like this project, please give it a star! 🌟