grpc_server.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. import grpc
  2. from concurrent import futures
  3. import time
  4. import threading
  5. import hr_pb2
  6. import hr_pb2_grpc
  7. # ========== IAM Service ==========
  8. class IAMService(hr_pb2_grpc.IAMServiceServicer):
  9. def GetUser(self, request, context):
  10. print(f"[IAM] GetUser called with id={request.id}")
  11. return hr_pb2.UserResponse(id=request.id, name="Alice", role="Engineer")
  12. def Login(self, request, context):
  13. print(f"[IAM] Login attempt: {request.username}")
  14. if request.username == "admin" and request.password == "1234":
  15. return hr_pb2.LoginResponse(success=True, message="Login successful")
  16. else:
  17. return hr_pb2.LoginResponse(success=False, message="Invalid credentials")
  18. # ========== Personality Test Service ==========
  19. class PersonalityTestService(hr_pb2_grpc.PersonalityTestServiceServicer):
  20. def __init__(self, channel):
  21. self.iam_stub = hr_pb2_grpc.IAMServiceStub(channel)
  22. def GetTestResult(self, request, context):
  23. print(f"[PersonalityTest] GetTestResult for user {request.user_id}")
  24. # Call IAM service to verify user exists
  25. try:
  26. user = self.iam_stub.GetUser(hr_pb2.UserRequest(id=request.user_id))
  27. print(f"[PersonalityTest] User verified: {user.name}")
  28. except grpc.RpcError as e:
  29. print(f"[PersonalityTest] Failed to verify user: {e}")
  30. return hr_pb2.TestResponse(user_id=request.user_id, result="INTJ - The Architect")
  31. # ========== Interview Service ==========
  32. class InterviewService(hr_pb2_grpc.InterviewServiceServicer):
  33. def __init__(self, channel):
  34. self.data = {}
  35. self.iam_stub = hr_pb2_grpc.IAMServiceStub(channel)
  36. self.workspace_stub = hr_pb2_grpc.WorkspaceServiceStub(channel)
  37. def ScheduleInterview(self, request, context):
  38. print(f"[Interview] Scheduling interview for user {request.user_id} on {request.date}")
  39. # Call IAM to get user info
  40. try:
  41. user = self.iam_stub.GetUser(hr_pb2.UserRequest(id=request.user_id))
  42. print(f"[Interview] Scheduling for: {user.name} ({user.role})")
  43. except grpc.RpcError as e:
  44. print(f"[Interview] Could not get user info: {e}")
  45. # Call Workspace to get user profile
  46. try:
  47. profile = self.workspace_stub.GetProfile(hr_pb2.GetProfileRequest(user_id=request.user_id))
  48. if profile.success:
  49. print(f"[Interview] Candidate skills: {profile.skills}")
  50. except grpc.RpcError as e:
  51. print(f"[Interview] Could not get profile: {e}")
  52. self.data.setdefault(request.user_id, []).append(request.date)
  53. return hr_pb2.InterviewResponse(success=True, message="Interview scheduled")
  54. def GetInterviews(self, request, context):
  55. print(f"[Interview] Getting interviews for user {request.user_id}")
  56. interviews = self.data.get(request.user_id, [])
  57. return hr_pb2.InterviewListResponse(interviews=interviews)
  58. # ========== Workspace Service ==========
  59. class WorkspaceService(hr_pb2_grpc.WorkspaceServiceServicer):
  60. def __init__(self, channel):
  61. self.profiles = {}
  62. self.job_descriptions = {}
  63. self.iam_stub = hr_pb2_grpc.IAMServiceStub(channel)
  64. self.test_stub = hr_pb2_grpc.PersonalityTestServiceStub(channel)
  65. def CreateProfile(self, request, context):
  66. print(f"[Workspace] Creating profile for user {request.user_id}")
  67. # Call IAM to verify user
  68. try:
  69. user = self.iam_stub.GetUser(hr_pb2.UserRequest(id=request.user_id))
  70. print(f"[Workspace] Creating profile for verified user: {user.name}")
  71. except grpc.RpcError as e:
  72. print(f"[Workspace] Could not verify user: {e}")
  73. # Get personality test result
  74. try:
  75. test_result = self.test_stub.GetTestResult(hr_pb2.TestRequest(user_id=request.user_id))
  76. print(f"[Workspace] User personality: {test_result.result}")
  77. except grpc.RpcError as e:
  78. print(f"[Workspace] Could not get personality test: {e}")
  79. self.profiles[request.user_id] = {
  80. 'name': request.name,
  81. 'skills': request.skills,
  82. 'experience': request.experience
  83. }
  84. return hr_pb2.ProfileResponse(
  85. user_id=request.user_id,
  86. name=request.name,
  87. skills=request.skills,
  88. experience=request.experience,
  89. success=True,
  90. message="Profile created successfully"
  91. )
  92. def GetProfile(self, request, context):
  93. print(f"[Workspace] Getting profile for user {request.user_id}")
  94. profile = self.profiles.get(request.user_id)
  95. if profile:
  96. return hr_pb2.ProfileResponse(
  97. user_id=request.user_id,
  98. name=profile['name'],
  99. skills=profile['skills'],
  100. experience=profile['experience'],
  101. success=True,
  102. message="Profile retrieved"
  103. )
  104. else:
  105. return hr_pb2.ProfileResponse(
  106. user_id=request.user_id,
  107. success=False,
  108. message="Profile not found"
  109. )
  110. def CreateJobDescription(self, request, context):
  111. print(f"[Workspace] Creating job description {request.job_id}")
  112. self.job_descriptions[request.job_id] = {
  113. 'title': request.title,
  114. 'description': request.description,
  115. 'requirements': request.requirements
  116. }
  117. return hr_pb2.JobDescriptionResponse(
  118. job_id=request.job_id,
  119. title=request.title,
  120. description=request.description,
  121. requirements=request.requirements,
  122. success=True,
  123. message="Job description created successfully"
  124. )
  125. def GetJobDescription(self, request, context):
  126. print(f"[Workspace] Getting job description {request.job_id}")
  127. job = self.job_descriptions.get(request.job_id)
  128. if job:
  129. return hr_pb2.JobDescriptionResponse(
  130. job_id=request.job_id,
  131. title=job['title'],
  132. description=job['description'],
  133. requirements=job['requirements'],
  134. success=True,
  135. message="Job description retrieved"
  136. )
  137. else:
  138. return hr_pb2.JobDescriptionResponse(
  139. job_id=request.job_id,
  140. success=False,
  141. message="Job description not found"
  142. )
  143. # ========== Server Function ==========
  144. def serve():
  145. # Create internal channel for inter-service communication
  146. internal_channel = grpc.insecure_channel('localhost:50051')
  147. server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
  148. hr_pb2_grpc.add_IAMServiceServicer_to_server(IAMService(), server)
  149. hr_pb2_grpc.add_PersonalityTestServiceServicer_to_server(PersonalityTestService(internal_channel), server)
  150. hr_pb2_grpc.add_InterviewServiceServicer_to_server(InterviewService(internal_channel), server)
  151. hr_pb2_grpc.add_WorkspaceServiceServicer_to_server(WorkspaceService(internal_channel), server)
  152. server.add_insecure_port('[::]:50051')
  153. server.start()
  154. print("🚀 gRPC server running on port 50051 with inter-service communication enabled")
  155. server.wait_for_termination()
  156. # ========== Client Function ==========
  157. def run_client():
  158. time.sleep(2) # Wait for server to fully start
  159. with grpc.insecure_channel('localhost:50051') as channel:
  160. iam = hr_pb2_grpc.IAMServiceStub(channel)
  161. test = hr_pb2_grpc.PersonalityTestServiceStub(channel)
  162. interview = hr_pb2_grpc.InterviewServiceStub(channel)
  163. workspace = hr_pb2_grpc.WorkspaceServiceStub(channel)
  164. print("\n=== Testing IAM ===")
  165. user = iam.GetUser(hr_pb2.UserRequest(id=1))
  166. print(f"✅ User: {user.name}, Role: {user.role}")
  167. login = iam.Login(hr_pb2.LoginRequest(username="admin", password="1234"))
  168. print(f"✅ Login: {login.message}")
  169. print("\n=== Testing Personality Test (calls IAM) ===")
  170. result = test.GetTestResult(hr_pb2.TestRequest(user_id=1))
  171. print(f"✅ Personality result: {result.result}")
  172. print("\n=== Testing Workspace - Profile (calls IAM & PersonalityTest) ===")
  173. profile = workspace.CreateProfile(hr_pb2.ProfileRequest(
  174. user_id=1,
  175. name="Alice Johnson",
  176. skills="Python, gRPC, Microservices",
  177. experience="5 years"
  178. ))
  179. print(f"✅ Profile created: {profile.message}")
  180. print("\n=== Testing Interview Scheduling (calls IAM & Workspace) ===")
  181. interview.ScheduleInterview(hr_pb2.InterviewRequest(user_id=1, date="2025-10-25"))
  182. interview.ScheduleInterview(hr_pb2.InterviewRequest(user_id=1, date="2025-10-30"))
  183. interviews = interview.GetInterviews(hr_pb2.InterviewListRequest(user_id=1))
  184. print(f"✅ Interview dates: {list(interviews.interviews)}")
  185. print("\n=== Testing Workspace - Job Description ===")
  186. job = workspace.CreateJobDescription(hr_pb2.JobDescriptionRequest(
  187. job_id=101,
  188. title="Senior Backend Engineer",
  189. description="Build scalable microservices",
  190. requirements="5+ years Python, gRPC experience"
  191. ))
  192. print(f"✅ Job description created: {job.message}")
  193. # ========== Run Both ==========
  194. if __name__ == "__main__":
  195. t = threading.Thread(target=serve, daemon=True)
  196. t.start()
  197. run_client()