TASK
Implementation
Build a gRPC interceptor pipeline. Interceptors are middleware that wrap gRPC handler calls, running logic before and after the actual service method.
Interceptor chain: logging -> auth -> rate_limit -> handler
Implement handlers:
Request: {"type": "grpc_call", "msg_id": 1, "service": "KeyValue", "method": "Get", "request": {"key": "k1"}, "metadata": {"authorization": "Bearer valid_token"}}
Response: {"type": "grpc_call_ok", "in_reply_to": 1, "status": "OK", "interceptors_applied": ["logging", "auth", "rate_limit"], "response": {"key": "k1", "value": "v1", "found": true}}
Request: {"type": "grpc_call", "msg_id": 2, "service": "KeyValue", "method": "Get", "request": {"key": "k1"}, "metadata": {}}
Response: {"type": "grpc_call_ok", "in_reply_to": 2, "status": "UNAUTHENTICATED", "interceptor_failed": "auth"}
Request: {"type": "grpc_interceptor_stats", "msg_id": 3}
Response: {"type": "grpc_interceptor_stats_ok", "in_reply_to": 3, "stats": {
"total_requests": 2, "auth_failures": 1, "rate_limited": 0
}}Sample Test Cases
Authenticated request passes all interceptorsTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"grpc_call","msg_id":2,"service":"KeyValue","method":"Put","request":{"key":"k1","value":"v1"},"metadata":{"authorization":"Bearer valid_token"}}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
Missing auth token fails at auth interceptorTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"grpc_call","msg_id":2,"service":"KeyValue","method":"Get","request":{"key":"k1"},"metadata":{}}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
{"src": "n1", "dest": "c1", "body": {"type": "grpc_call_ok", "in_reply_to": 2, "status": "UNAUTHENTICATED", "interceptor_failed": "auth", "msg_id": 1}}
Hints
Hint 1▾
Interceptors are middleware for gRPC calls, similar to HTTP middleware
Hint 2▾
They run before and after the actual handler
Hint 3▾
Chain multiple interceptors: logging -> auth -> rate_limit -> handler
Hint 4▾
Auth interceptor checks metadata for a valid token
Hint 5▾
Rate limiter uses a token bucket per client IP
OVERVIEW
Theoretical Hub
Concept overview coming soon
Key Concepts
interceptormiddlewareauthenticationrate limitingrequest pipeline
main.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env python3
import sys
import json
def main():
# Your implementation here
for line in sys.stdin:
msg = json.loads(line)
print(json.dumps(msg), flush=True)
if __name__ == "__main__":
main()