slow_server.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """Deliberately slow HTTP endpoint that mimics the HIS bdhealth REST gateway.
  4. Accepts a POST, swallows the body, waits SLEEP_SEC, then answers 200 JSON.
  5. Used to measure the real client-side timeout of UppPay's RestClient.Post.
  6. """
  7. import json
  8. import sys
  9. import time
  10. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  11. SLEEP_SEC = int(sys.argv[1]) if len(sys.argv) > 1 else 60
  12. PORT = int(sys.argv[2]) if len(sys.argv) > 2 else 8099
  13. if hasattr(sys.stdout, "reconfigure"):
  14. sys.stdout.reconfigure(encoding="utf-8", errors="replace")
  15. class Handler(BaseHTTPRequestHandler):
  16. protocol_version = "HTTP/1.1"
  17. def do_POST(self):
  18. length = int(self.headers.get("Content-Length", 0))
  19. self.rfile.read(length)
  20. print("[slow-server] got POST %s (%d bytes) -> sleeping %ds"
  21. % (self.path, length, SLEEP_SEC), flush=True)
  22. time.sleep(SLEEP_SEC)
  23. body = json.dumps({"errorCode": "0", "errorMessage": "slow-ok"}).encode()
  24. try:
  25. self.send_response(200)
  26. self.send_header("Content-Type", "application/json")
  27. self.send_header("Content-Length", str(len(body)))
  28. self.end_headers()
  29. self.wfile.write(body)
  30. print("[slow-server] responded after %ds" % SLEEP_SEC, flush=True)
  31. except Exception as e:
  32. print("[slow-server] client already gone: %s" % e, flush=True)
  33. def log_message(self, *a):
  34. pass
  35. if __name__ == "__main__":
  36. print("[slow-server] listening on 127.0.0.1:%d, will stall %ds"
  37. % (PORT, SLEEP_SEC), flush=True)
  38. ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()