The Python service
The service is a hundred and fifty lines of Python with nothing outside the standard library: http.server for the socket, subprocess for the core and json for the edge. It starts the core once per request, writes the thirty bytes to its standard input and reads the fifty back. Everything the client sees, including every error, is decided here.
The service
#!/usr/bin/env python3
"""A small HTTP service in front of the COBOL pricing core."""
import json
import os
import subprocess
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
HOST = os.environ.get("PRICE_HOST", "127.0.0.1")
CORE = os.environ.get("PRICE_CORE", "./price")
TIMEOUT = float(os.environ.get("PRICE_TIMEOUT", "5"))
REQUEST_SIZE = 30
ANSWER_SIZE = 50
REGIONS = {"N1", "S2", "E3", "W4"}
def run_core(payload: bytes):
"""Run the core with one request on stdin and return (status, stdout)."""
process = subprocess.run(
[CORE],
input=payload,
capture_output=True,
timeout=TIMEOUT,
check=False,
)
return process.returncode, process.stdout, process.stderr
def answer_fields(line: str):
return {
"order_id": line[0:6].strip(),
"status": line[6:8],
"net_cents": int(line[8:19]),
"tax_cents": int(line[19:30]),
"message": line[30:50].strip(),
}
def request_from_json(body):
order_id = str(body.get("order_id", ""))[:6].ljust(6)
sku = str(body.get("sku", ""))[:8].ljust(8)
qty = int(body.get("qty", 0))
price_cents = int(body.get("price_cents", 0))
region = str(body.get("region", ""))[:2].ljust(2)
if region.strip() and region.strip() not in REGIONS:
raise ValueError(f"unknown region {region.strip()}")
if qty < 0 or qty > 99999 or price_cents < 0 or price_cents > 999999999:
raise ValueError("quantity or price out of range")
return f"{order_id}{sku}{qty:05d}{price_cents:09d}{region}".encode()
class Handler(BaseHTTPRequestHandler):
server_version = "price-service/1.0"
def send_json(self, status, document):
payload = (json.dumps(document) + "\n").encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def send_text(self, status, text):
payload = text.encode()
self.send_response(status)
self.send_header("Content-Type", "text/plain; charset=ascii")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def do_GET(self):
if self.path == "/health":
self.send_json(200, {"status": "ok", "core": CORE,
"core_exists": os.path.exists(CORE)})
return
self.send_json(404, {"error": "not found", "path": self.path})
def do_POST(self):
length = int(self.headers.get("Content-Length", "0"))
body = self.rfile.read(length)
if self.path == "/price":
self.handle_fixed(body)
elif self.path == "/price/json":
self.handle_json(body)
else:
self.send_json(404, {"error": "not found", "path": self.path})
def handle_fixed(self, body):
if len(body) != REQUEST_SIZE:
self.send_json(400, {"error": f"request must be {REQUEST_SIZE} bytes",
"got": len(body)})
return
try:
status, stdout, stderr = run_core(body)
except subprocess.TimeoutExpired:
self.send_json(504, {"error": "core timed out", "timeout": TIMEOUT})
return
except OSError as error:
self.send_json(500, {"error": "core could not start", "detail": str(error)})
return
if len(stdout) < ANSWER_SIZE:
self.send_json(500, {"error": "core answered nothing",
"status": status, "stderr": stderr.decode()[-200:]})
return
line = stdout[:ANSWER_SIZE].decode("ascii")
if status == 0:
self.send_text(200, line + "\n")
elif status == 4:
self.send_text(422, line + "\n")
else:
self.send_json(500, {"error": "core failed", "status": status,
"stderr": stderr.decode()[-200:]})
def handle_json(self, body):
try:
request = json.loads(body or b"{}")
if not isinstance(request, dict):
raise ValueError("body must be a JSON object")
payload = request_from_json(request)
except (ValueError, TypeError, json.JSONDecodeError) as error:
self.send_json(400, {"error": str(error)})
return
try:
status, stdout, stderr = run_core(payload)
except subprocess.TimeoutExpired:
self.send_json(504, {"error": "core timed out", "timeout": TIMEOUT})
return
except OSError as error:
self.send_json(500, {"error": "core could not start", "detail": str(error)})
return
if len(stdout) < ANSWER_SIZE:
self.send_json(500, {"error": "core answered nothing", "status": status})
return
answer = answer_fields(stdout[:ANSWER_SIZE].decode("ascii"))
answer["http_status"] = 200 if status == 0 else 422
self.send_json(answer["http_status"], answer)
def log_message(self, fmt, *args):
sys.stderr.write(f"{self.address_string()} {fmt % args}\n")
def main():
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8765
server = ThreadingHTTPServer((HOST, port), Handler)
print(f"listening on {HOST}:{port}, core {CORE}", flush=True)
server.serve_forever()
if __name__ == "__main__":
main()
Four decisions in that file are the whole design. The core is a subprocess.run with input, a timeout of five seconds by default and no shell, so a request cannot become a command. The exit status is the protocol: 0 is 200, 4 is 422 and anything else is 500, and a timeout is caught before either. The JSON endpoint converts to the fixed record and back, so the core never sees a document. And /health reports whether the core file exists, which is the first thing a deployment check asks.
Starting it
The service expects price in its working folder; PRICE_CORE and PRICE_TIMEOUT change the core and the limit, and PRICE_HOST the address it binds to. The default is 127.0.0.1, which is what a test on one machine wants; a container sets it to 0.0.0.0 so a published port reaches the service. Started on port 8765 in the background:
cobc -x -free -Wall -O2 -o price price.cob
python3 -I server.py 8765 &
listening on 127.0.0.1:8765, core ./price
Real requests
A health check and a priced order, with the body of the answer and the HTTP status printed by curl:
curl -s http://127.0.0.1:8765/health
printf 'C00001WIDGET0100002000123456N1' | curl -s -w '\n%{http_code}\n' \
-X POST --data-binary @- http://127.0.0.1:8765/price
{"status": "ok", "core": "./price", "core_exists": true}
C00001000000024691200000032099PRICED
200
A rejected order is a 422 with the fifty-byte answer, so a client that speaks the protocol gets the reason in the message field and a client that speaks HTTP gets the status:
printf 'C00002WIDGET0200000000100000N1' | curl -s -w '\n%{http_code}\n' \
-X POST --data-binary @- http://127.0.0.1:8765/price
C00002040000000000000000000000QUANTITY IS ZERO
422
The answer is fifty bytes and the message is padded to twenty, so it reaches a log unbroken. A client that wants a sentence parses the message; a client that wants a number reads the net field.
The JSON endpoint
curl -s -X POST -H 'Content-Type: application/json' \
-d '{"order_id":"C00007","sku":"WIDGET07","qty":4,"price_cents":2500,"region":"S2"}' \
http://127.0.0.1:8765/price/json
{"order_id": "C00007", "status": "00", "net_cents": 10000, "tax_cents": 1300, "message": "PRICED", "http_status": 200}
The same order through the fixed endpoint is the same five fields in thirty bytes; the only difference is where the conversion happens. A request that breaks the contract is answered by Python and never reaches the core:
curl -s -w '\n%{http_code}\n' -X POST -d '{"order_id":"C00009","sku":"WIDGET09","qty":1,"price_cents":100,"region":"Q7"}' \
http://127.0.0.1:8765/price/json
{"error": "unknown region Q7"}
400
The log
One line per request on standard error, in the format http.server gives, which is enough to see the status of every call without a logging library:
listening on 127.0.0.1:8765, core ./price
127.0.0.1 "GET /health HTTP/1.1" 200 -
127.0.0.1 "POST /price HTTP/1.1" 200 -
127.0.0.1 "POST /price HTTP/1.1" 422 -
127.0.0.1 "POST /price HTTP/1.1" 200 -
127.0.0.1 "POST /price HTTP/1.1" 422 -
Stopping it is kill %1 in the shell that started it. The next page takes the same server through the failures a client can cause, and then a timeout that the client cannot.
The COBOL was built with cobc (GnuCOBOL) 3.2.0 with -O2, the service runs on Python 3.14.10 with the standard library only, and both ran on Alpine Linux 3.24.3 (x86_64) in a Docker container with nproc 4.
Article author: Arthur Isaev