# python/01-service-architecture.py"""Microservices architecture patterns and service discovery"""fromtypingimportList,Dict,Any,Optional,Callablefromdataclassesimportdataclass,asdictfromenumimportEnumimportasyncioimportjsonimporttimefromdatetimeimportdatetimeimportuuidclassServiceStatus(Enum):"""Service status enumeration"""HEALTHY="healthy"UNHEALTHY="unhealthy"STARTING="starting"STOPPING="stopping"UNKNOWN="unknown"@dataclassclassServiceInfo:"""Service information"""service_id:strname:strversion:strhost:strport:intstatus:ServiceStatushealth_check_url:strmetadata:Dict[str,Any]registered_at:datetimelast_heartbeat:datetimeclassServiceRegistry:"""Service registry for service discovery"""def__init__(self):self.services:Dict[str,ServiceInfo]={}self.health_checkers:Dict[str,Callable]={}self.heartbeat_interval=30# secondsself.health_check_interval=10# secondsdefregister_service(self,service_info:ServiceInfo)->bool:"""Register service in registry"""try:self.services[service_info.service_id]=service_infoprint(f"Service {service_info.name} registered with ID {service_info.service_id}")returnTrueexceptExceptionase:print(f"Failed to register service: {e}")returnFalsedefunregister_service(self,service_id:str)->bool:"""Unregister service from registry"""ifservice_idinself.services:delself.services[service_id]print(f"Service {service_id} unregistered")returnTruereturnFalsedefget_service(self,service_id:str)->Optional[ServiceInfo]:"""Get service by ID"""returnself.services.get(service_id)defget_services_by_name(self,name:str)->List[ServiceInfo]:"""Get services by name"""return[serviceforserviceinself.services.values()ifservice.name==name]defget_healthy_services(self)->List[ServiceInfo]:"""Get all healthy services"""return[serviceforserviceinself.services.values()ifservice.status==ServiceStatus.HEALTHY]defupdate_service_status(self,service_id:str,status:ServiceStatus)->bool:"""Update service status"""ifservice_idinself.services:self.services[service_id].status=statusself.services[service_id].last_heartbeat=datetime.utcnow()returnTruereturnFalsedefregister_health_checker(self,service_id:str,checker:Callable)->None:"""Register health checker for service"""self.health_checkers[service_id]=checkerasyncdefperform_health_check(self,service_id:str)->bool:"""Perform health check for service"""ifservice_idnotinself.services:returnFalseservice=self.services[service_id]checker=self.health_checkers.get(service_id)ifchecker:try:result=awaitchecker()ifresult:self.update_service_status(service_id,ServiceStatus.HEALTHY)else:self.update_service_status(service_id,ServiceStatus.UNHEALTHY)returnresultexceptExceptionase:print(f"Health check failed for {service_id}: {e}")self.update_service_status(service_id,ServiceStatus.UNHEALTHY)returnFalsereturnTrueasyncdefstart_health_monitoring(self)->None:"""Start health monitoring for all services"""whileTrue:forservice_idinlist(self.services.keys()):awaitself.perform_health_check(service_id)awaitasyncio.sleep(self.health_check_interval)classServiceClient:"""Service client for inter-service communication"""def__init__(self,service_registry:ServiceRegistry):self.registry=service_registryself.http_client=None# Would be aiohttp.ClientSession in real implementationasyncdefdiscover_service(self,service_name:str)->Optional[ServiceInfo]:"""Discover service by name"""services=self.registry.get_services_by_name(service_name)healthy_services=[sforsinservicesifs.status==ServiceStatus.HEALTHY]ifnothealthy_services:returnNone# Simple round-robin load balancingreturnhealthy_services[0]asyncdefcall_service(self,service_name:str,endpoint:str,method:str="GET",data:Dict[str,Any]=None)->Dict[str,Any]:"""Call service endpoint"""service=awaitself.discover_service(service_name)ifnotservice:raiseException(f"Service {service_name} not found or unhealthy")# In real implementation, this would make HTTP requesturl=f"http://{service.host}:{service.port}{endpoint}"print(f"Calling {method}{url}")# Simulate service callreturn{"status":"success","service":service.name,"endpoint":endpoint,"data":data}# Usage examplesasyncdefexample_service_discovery():"""Example service discovery usage"""# Create service registryregistry=ServiceRegistry()# Register servicesuser_service=ServiceInfo(service_id=str(uuid.uuid4()),name="user-service",version="1.0.0",host="localhost",port=8001,status=ServiceStatus.HEALTHY,health_check_url="/health",metadata={"environment":"production"},registered_at=datetime.utcnow(),last_heartbeat=datetime.utcnow())order_service=ServiceInfo(service_id=str(uuid.uuid4()),name="order-service",version="1.0.0",host="localhost",port=8002,status=ServiceStatus.HEALTHY,health_check_url="/health",metadata={"environment":"production"},registered_at=datetime.utcnow(),last_heartbeat=datetime.utcnow())registry.register_service(user_service)registry.register_service(order_service)# Create service clientclient=ServiceClient(registry)# Call servicestry:result=awaitclient.call_service("user-service","/users","GET")print(f"User service result: {result}")exceptExceptionase:print(f"Service call failed: {e}")# Start health monitoringasyncio.create_task(registry.start_health_monitoring())
# python/02-service-communication.py"""Service communication patterns including synchronous and asynchronous communication"""fromtypingimportList,Dict,Any,Optional,Callable,Coroutinefromdataclassesimportdataclass,asdictfromenumimportEnumimportasyncioimportjsonimporttimefromdatetimeimportdatetimeimportuuidclassMessageType(Enum):"""Message type enumeration"""REQUEST="request"RESPONSE="response"EVENT="event"COMMAND="command"@dataclassclassMessage:"""Message for service communication"""message_id:strmessage_type:MessageTypesource_service:strtarget_service:strpayload:Dict[str,Any]timestamp:datetimecorrelation_id:Optional[str]=Nonereply_to:Optional[str]=NoneclassMessageBus:"""Message bus for service communication"""def__init__(self):self.subscribers:Dict[str,List[Callable]]={}self.message_queue:List[Message]=[]self.message_handlers:Dict[str,Callable]={}defsubscribe(self,topic:str,handler:Callable)->None:"""Subscribe to topic"""iftopicnotinself.subscribers:self.subscribers[topic]=[]self.subscribers[topic].append(handler)defunsubscribe(self,topic:str,handler:Callable)->None:"""Unsubscribe from topic"""iftopicinself.subscribers:ifhandlerinself.subscribers[topic]:self.subscribers[topic].remove(handler)asyncdefpublish(self,topic:str,message:Message)->None:"""Publish message to topic"""iftopicinself.subscribers:forhandlerinself.subscribers[topic]:try:ifasyncio.iscoroutinefunction(handler):awaithandler(message)else:handler(message)exceptExceptionase:print(f"Error handling message: {e}")asyncdefsend_message(self,message:Message)->None:"""Send message to target service"""topic=f"service.{message.target_service}"awaitself.publish(topic,message)asyncdefsend_request(self,source_service:str,target_service:str,payload:Dict[str,Any],reply_to:str=None)->str:"""Send request message"""message_id=str(uuid.uuid4())message=Message(message_id=message_id,message_type=MessageType.REQUEST,source_service=source_service,target_service=target_service,payload=payload,timestamp=datetime.utcnow(),reply_to=reply_to)awaitself.send_message(message)returnmessage_idasyncdefsend_response(self,request_message:Message,payload:Dict[str,Any])->None:"""Send response message"""response_message=Message(message_id=str(uuid.uuid4()),message_type=MessageType.RESPONSE,source_service=request_message.target_service,target_service=request_message.source_service,payload=payload,timestamp=datetime.utcnow(),correlation_id=request_message.message_id)awaitself.send_message(response_message)asyncdefsend_event(self,source_service:str,event_type:str,payload:Dict[str,Any])->None:"""Send event message"""message=Message(message_id=str(uuid.uuid4()),message_type=MessageType.EVENT,source_service=source_service,target_service="*",# Broadcast to allpayload={"event_type":event_type,"data":payload},timestamp=datetime.utcnow())# Publish to all servicesfortopicinself.subscribers.keys():awaitself.publish(topic,message)classServiceGateway:"""Service gateway for routing and load balancing"""def__init__(self,service_registry:ServiceRegistry,message_bus:MessageBus):self.registry=service_registryself.message_bus=message_busself.routing_rules:Dict[str,str]={}self.load_balancers:Dict[str,List[str]]={}defadd_route(self,path:str,service_name:str)->None:"""Add routing rule"""self.routing_rules[path]=service_namedefadd_load_balancer(self,service_name:str,service_ids:List[str])->None:"""Add load balancer for service"""self.load_balancers[service_name]=service_idsasyncdefroute_request(self,path:str,method:str,data:Dict[str,Any])->Dict[str,Any]:"""Route request to appropriate service"""ifpathnotinself.routing_rules:raiseException(f"No route found for {path}")service_name=self.routing_rules[path]# Get available servicesservices=self.registry.get_services_by_name(service_name)healthy_services=[sforsinservicesifs.status==ServiceStatus.HEALTHY]ifnothealthy_services:raiseException(f"No healthy services found for {service_name}")# Simple round-robin load balancingservice=healthy_services[0]# Send request to servicerequest_id=awaitself.message_bus.send_request(source_service="gateway",target_service=service.name,payload={"path":path,"method":method,"data":data})return{"request_id":request_id,"service":service.name,"status":"routed"}classCircuitBreaker:"""Circuit breaker for service resilience"""def__init__(self,failure_threshold:int=5,timeout:float=60.0):self.failure_threshold=failure_thresholdself.timeout=timeoutself.failure_count=0self.last_failure_time=Noneself.state="closed"# closed, open, half-opendefcan_execute(self)->bool:"""Check if circuit breaker allows execution"""ifself.state=="closed":returnTrueelifself.state=="open":iftime.time()-self.last_failure_time>=self.timeout:self.state="half-open"returnTruereturnFalseelse:# half-openreturnTruedefrecord_success(self)->None:"""Record successful execution"""self.failure_count=0self.state="closed"defrecord_failure(self)->None:"""Record failed execution"""self.failure_count+=1self.last_failure_time=time.time()ifself.failure_count>=self.failure_threshold:self.state="open"defget_state(self)->Dict[str,Any]:"""Get circuit breaker state"""return{"state":self.state,"failure_count":self.failure_count,"last_failure_time":self.last_failure_time,"failure_threshold":self.failure_threshold,"timeout":self.timeout}# Usage examplesasyncdefexample_service_communication():"""Example service communication usage"""# Create message busmessage_bus=MessageBus()# Create service registryregistry=ServiceRegistry()# Create service gatewaygateway=ServiceGateway(registry,message_bus)# Add routing rulesgateway.add_route("/users","user-service")gateway.add_route("/orders","order-service")# Subscribe to messagesasyncdefhandle_user_request(message:Message):print(f"Handling user request: {message.payload}")# Process request and send responseawaitmessage_bus.send_response(message,{"result":"success"})message_bus.subscribe("service.user-service",handle_user_request)# Send request through gatewaytry:result=awaitgateway.route_request("/users","GET",{})print(f"Gateway result: {result}")exceptExceptionase:print(f"Gateway error: {e}")# Send eventawaitmessage_bus.send_event(source_service="user-service",event_type="user_created",payload={"user_id":"123","name":"John Doe"})
# python/03-data-consistency.py"""Data consistency patterns for microservices including saga pattern and event sourcing"""fromtypingimportList,Dict,Any,Optional,Callablefromdataclassesimportdataclass,asdictfromenumimportEnumimportasyncioimportjsonimporttimefromdatetimeimportdatetimeimportuuidclassSagaStatus(Enum):"""Saga status enumeration"""STARTED="started"COMPLETED="completed"FAILED="failed"COMPENSATING="compensating"COMPENSATED="compensated"classSagaStepStatus(Enum):"""Saga step status enumeration"""PENDING="pending"EXECUTING="executing"COMPLETED="completed"FAILED="failed"COMPENSATING="compensating"COMPENSATED="compensated"@dataclassclassSagaStep:"""Saga step definition"""step_id:strservice_name:straction:strcompensate_action:strpayload:Dict[str,Any]status:SagaStepStatusexecuted_at:Optional[datetime]=Nonecompensated_at:Optional[datetime]=Noneerror:Optional[str]=None@dataclassclassSaga:"""Saga definition"""saga_id:strstatus:SagaStatussteps:List[SagaStep]created_at:datetimecompleted_at:Optional[datetime]=Noneerror:Optional[str]=NoneclassSagaOrchestrator:"""Saga orchestrator for managing distributed transactions"""def__init__(self):self.sagas:Dict[str,Saga]={}self.step_handlers:Dict[str,Callable]={}self.compensation_handlers:Dict[str,Callable]={}defregister_step_handler(self,service_name:str,action:str,handler:Callable)->None:"""Register step handler"""key=f"{service_name}.{action}"self.step_handlers[key]=handlerdefregister_compensation_handler(self,service_name:str,action:str,handler:Callable)->None:"""Register compensation handler"""key=f"{service_name}.{action}"self.compensation_handlers[key]=handlerasyncdefcreate_saga(self,steps:List[Dict[str,Any]])->str:"""Create new saga"""saga_id=str(uuid.uuid4())saga_steps=[]forstep_datainsteps:step=SagaStep(step_id=str(uuid.uuid4()),service_name=step_data["service_name"],action=step_data["action"],compensate_action=step_data["compensate_action"],payload=step_data["payload"],status=SagaStepStatus.PENDING)saga_steps.append(step)saga=Saga(saga_id=saga_id,status=SagaStatus.STARTED,steps=saga_steps,created_at=datetime.utcnow())self.sagas[saga_id]=sagareturnsaga_idasyncdefexecute_saga(self,saga_id:str)->bool:"""Execute saga"""ifsaga_idnotinself.sagas:returnFalsesaga=self.sagas[saga_id]try:# Execute steps in orderforstepinsaga.steps:awaitself.execute_step(step)# Mark saga as completedsaga.status=SagaStatus.COMPLETEDsaga.completed_at=datetime.utcnow()returnTrueexceptExceptionase:# Start compensationsaga.status=SagaStatus.FAILEDsaga.error=str(e)awaitself.compensate_saga(saga_id)returnFalseasyncdefexecute_step(self,step:SagaStep)->None:"""Execute saga step"""step.status=SagaStepStatus.EXECUTINGstep.executed_at=datetime.utcnow()try:key=f"{step.service_name}.{step.action}"handler=self.step_handlers.get(key)ifhandler:ifasyncio.iscoroutinefunction(handler):awaithandler(step.payload)else:handler(step.payload)step.status=SagaStepStatus.COMPLETEDelse:raiseException(f"No handler found for {key}")exceptExceptionase:step.status=SagaStepStatus.FAILEDstep.error=str(e)raiseeasyncdefcompensate_saga(self,saga_id:str)->None:"""Compensate saga"""ifsaga_idnotinself.sagas:returnsaga=self.sagas[saga_id]saga.status=SagaStatus.COMPENSATING# Compensate steps in reverse orderforstepinreversed(saga.steps):ifstep.status==SagaStepStatus.COMPLETED:awaitself.compensate_step(step)saga.status=SagaStatus.COMPENSATEDasyncdefcompensate_step(self,step:SagaStep)->None:"""Compensate saga step"""step.status=SagaStepStatus.COMPENSATINGstep.compensated_at=datetime.utcnow()try:key=f"{step.service_name}.{step.compensate_action}"handler=self.compensation_handlers.get(key)ifhandler:ifasyncio.iscoroutinefunction(handler):awaithandler(step.payload)else:handler(step.payload)step.status=SagaStepStatus.COMPENSATEDelse:raiseException(f"No compensation handler found for {key}")exceptExceptionase:step.error=str(e)raiseedefget_saga(self,saga_id:str)->Optional[Saga]:"""Get saga by ID"""returnself.sagas.get(saga_id)defget_saga_status(self,saga_id:str)->Optional[Dict[str,Any]]:"""Get saga status"""saga=self.get_saga(saga_id)ifnotsaga:returnNonereturn{"saga_id":saga.saga_id,"status":saga.status.value,"steps":[{"step_id":step.step_id,"service_name":step.service_name,"action":step.action,"status":step.status.value,"executed_at":step.executed_at.isoformat()ifstep.executed_atelseNone,"compensated_at":step.compensated_at.isoformat()ifstep.compensated_atelseNone,"error":step.error}forstepinsaga.steps],"created_at":saga.created_at.isoformat(),"completed_at":saga.completed_at.isoformat()ifsaga.completed_atelseNone,"error":saga.error}classEventStore:"""Event store for event sourcing"""def__init__(self):self.events:List[Dict[str,Any]]=[]self.aggregates:Dict[str,List[str]]={}defappend_event(self,aggregate_id:str,event_type:str,payload:Dict[str,Any],version:int)->str:"""Append event to store"""event_id=str(uuid.uuid4())event={"event_id":event_id,"aggregate_id":aggregate_id,"event_type":event_type,"payload":payload,"version":version,"timestamp":datetime.utcnow().isoformat()}self.events.append(event)ifaggregate_idnotinself.aggregates:self.aggregates[aggregate_id]=[]self.aggregates[aggregate_id].append(event_id)returnevent_iddefget_events(self,aggregate_id:str)->List[Dict[str,Any]]:"""Get events for aggregate"""ifaggregate_idnotinself.aggregates:return[]event_ids=self.aggregates[aggregate_id]return[eventforeventinself.eventsifevent["event_id"]inevent_ids]defget_events_by_type(self,event_type:str)->List[Dict[str,Any]]:"""Get events by type"""return[eventforeventinself.eventsifevent["event_type"]==event_type]defget_all_events(self)->List[Dict[str,Any]]:"""Get all events"""returnself.events.copy()# Usage examplesasyncdefexample_data_consistency():"""Example data consistency usage"""# Create saga orchestratororchestrator=SagaOrchestrator()# Register step handlersasyncdefcreate_user(payload:Dict[str,Any]):print(f"Creating user: {payload}")# Simulate user creationawaitasyncio.sleep(0.1)asyncdefcreate_order(payload:Dict[str,Any]):print(f"Creating order: {payload}")# Simulate order creationawaitasyncio.sleep(0.1)asyncdefsend_notification(payload:Dict[str,Any]):print(f"Sending notification: {payload}")# Simulate notificationawaitasyncio.sleep(0.1)# Register compensation handlersasyncdefdelete_user(payload:Dict[str,Any]):print(f"Deleting user: {payload}")# Simulate user deletionawaitasyncio.sleep(0.1)asyncdefcancel_order(payload:Dict[str,Any]):print(f"Cancelling order: {payload}")# Simulate order cancellationawaitasyncio.sleep(0.1)# Register handlersorchestrator.register_step_handler("user-service","create",create_user)orchestrator.register_step_handler("order-service","create",create_order)orchestrator.register_step_handler("notification-service","send",send_notification)orchestrator.register_compensation_handler("user-service","create",delete_user)orchestrator.register_compensation_handler("order-service","create",cancel_order)# Create sagasteps=[{"service_name":"user-service","action":"create","compensate_action":"delete","payload":{"name":"John Doe","email":"john@example.com"}},{"service_name":"order-service","action":"create","compensate_action":"cancel","payload":{"user_id":"123","items":["item1","item2"]}},{"service_name":"notification-service","action":"send","compensate_action":"cancel","payload":{"user_id":"123","message":"Order created"}}]saga_id=awaitorchestrator.create_saga(steps)print(f"Created saga: {saga_id}")# Execute sagasuccess=awaitorchestrator.execute_saga(saga_id)print(f"Saga execution success: {success}")# Get saga statusstatus=orchestrator.get_saga_status(saga_id)print(f"Saga status: {status}")# Event store exampleevent_store=EventStore()# Append eventsevent_store.append_event("user-123","user_created",{"name":"John Doe"},1)event_store.append_event("user-123","user_updated",{"email":"john@example.com"},2)event_store.append_event("order-456","order_created",{"user_id":"user-123"},1)# Get eventsuser_events=event_store.get_events("user-123")print(f"User events: {user_events}")order_events=event_store.get_events("order-456")print(f"Order events: {order_events}")