#!/usr/bin/env python3
"""SageMaker serving contract: GET /ping and POST /invocations on port 8080.
/invocations echoes a JSON request body back as {"echo": <body>}.
"""
import json
import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def _send(self, status, body, content_type="application/json"):
payload = body if isinstance(body, bytes) else json.dumps(body).encode()
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def do_GET(self):
if self.path == "/ping":
self._send(200, {"status": "healthy"})
else:
self._send(404, {"error": "not found"})
def do_POST(self):
if self.path != "/invocations":
self._send(404, {"error": "not found"})
return
length = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(length) if length > 0 else b""
try:
request = json.loads(raw) if raw else None
except ValueError:
self._send(400, {"error": "request body must be JSON"})
return
self._send(200, {"echo": request})
def log_message(self, format, *args):
pass
if __name__ == "__main__":
port = int(os.environ.get("SAGEMAKER_BIND_TO_PORT", "8080"))
ThreadingHTTPServer(("0.0.0.0", port), Handler).serve_forever()