From 0e5a0ca1b99743a2624ceb9c9e7f2aff2eb4bf85 Mon Sep 17 00:00:00 2001
From: Chris Shucksmith
Date: Fri, 20 Nov 2026 10:58:30 +0000
Subject: [PATCH 1/8] Run the LPD receiver and the web server on asyncio and
aiohttp
asyncore and asynchat are gone from python 3.12, and the hand-written HTTP server was the
largest part of what depended on them. lpdserver.py is now an asyncio stream protocol and
httpserver.py serves the same path handlers (and the static files) with aiohttp. Both run
on one event loop, as before, so handlers still see a single thread and the job list needs
no locking; main.py starts them with asyncio.run, writes the print history every ten
seconds and on SIGTERM as well as Ctrl+C.
LPD behaviour is unchanged, including senders that close the connection to mark the end
of the data (even by reset), the trailing null on a sized data file and ignoring unknown
commands. 1,089 production jobs replayed through it with tools/replay_corpus.py arrive
byte for byte. Directory listings from the static file server are gone.
Co-Authored-By: Claude Sonnet 5.5
Claude-Session: https://claude.ai/code/session_01DKcyxWnp9B7ZMfow73wHmP
---
Dockerfile | 2 +-
README.md | 8 +-
httpserver.py | 860 +++++++----------------------------------
init.d/printerface | 2 +-
lpdserver.py | 255 +++++++-----
main.py | 48 ++-
requirements.txt | 1 +
test_integration.py | 36 +-
test_servers.py | 250 ++++++++++++
tools/replay_corpus.py | 16 +-
10 files changed, 615 insertions(+), 863 deletions(-)
create mode 100644 test_servers.py
diff --git a/Dockerfile b/Dockerfile
index 7eb9964..956a472 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,4 +1,4 @@
-# asyncore/asynchat (used by lpdserver.py and httpserver.py) were removed in python 3.12
+# the LPD receiver and web server run on asyncio and aiohttp, so any python from 3.9 will do
FROM python:3.11-slim
MAINTAINER chris@shucksmith.co.uk
diff --git a/README.md b/README.md
index ba00282..e94b3ea 100644
--- a/README.md
+++ b/README.md
@@ -22,8 +22,8 @@ The following will checkout the source code, build a docker image and start an i
## Source code & implementation notes
-* `lpdserver.py` implements a UNIX LPD daemon for recieving print jobs
-* `httpserver.py` simple http server using asynchat
+* `lpdserver.py` implements a UNIX LPD daemon for recieving print jobs, on asyncio
+* `httpserver.py` the web server: path handlers and static files on aiohttp, handlers run on the event loop one at a time
* `mailer.py` asynchronous mail queue to Gmail
* `docparser` recognise and parse some plain-text formats from 1990 to JSON
* `stationary.py` format JSON to nice PDF files
@@ -35,13 +35,13 @@ template are POSTs, and their handlers return `httpserver.Redirect(...)` (a 303)
carrying at most a harmless note in the query string ("queued=1"). A POST that is refused re-renders the form
instead, with what was typed. New actions should follow the same pattern.
-Requires **python 3.11** (3.9+ for the dependencies, but `asyncore`/`asynchat` were removed from the standard library in 3.12).
+Requires **python 3.11** or later. The LPD receiver and the web server share one asyncio event loop (so the job list needs no locking); mail is sent from a thread of its own.
Requirements are specified in requirements.txt
Unit tests run during `docker build` or with:
$ python3.11 -m unittest discover --pattern=*.py
-Uses python asyncore/smtp, bootstrap web framework
+Uses python asyncio/aiohttp/smtplib, bootstrap web framework
Jobs, rendered PDFs, the email address book and `email.cfg` overrides live in `~/printerface`. Set the
`PRINTERFACE_HOME` environment variable to use a different directory, for example to run a second instance
diff --git a/httpserver.py b/httpserver.py
index 46b023b..50b7d12 100644
--- a/httpserver.py
+++ b/httpserver.py
@@ -1,88 +1,36 @@
"""
-Simple HTTP server build on the asyncore/asynchat module.
+The web server, on aiohttp.
-Python's built-in SimpleHTTPServer is mixed up with SocketServer blocking/
-threading semantics in the classes it inherits. The various adapters to make
-it work with asynchat are pretty auful. This file class strips it back to
-work only with asynchat.
+Pages are plain functions registered by path (`pathhandlers`), the same ones the asyncore server called:
+`handler(query_string=..., resp=...)` for GET and HEAD and `handler(query_string=..., postreq=...)` for POST,
+where the query string and the form fields arrive as {name: [values]}. A handler returns `(body, content type)`,
+with body a str, bytes or binary file object, or a `Redirect`. Anything else is served as a file from the
+web root.
-Incorporates basic support for dynamic pages, simple logging, connection re-use,
-and allows http root to be specified.
-
-There are plenty of capable web servers for python, absoutely nobody should use
-this class. _Except_ in the rare case you need a co-operative single
-threaded HTTP to mix inline with other protocol handlers to avoid locking a
-datamodel.
+Handlers run on the event loop, one at a time, exactly as before: they and the LPD receiver share one thread, so
+the job list and the other data they touch need no locking. A handler that blocks (printing, rendering a big
+PDF) holds up everything else for its duration, and that is deliberate, not an oversight.
"""
-import asynchat, asyncore, socket
-import posixpath, sys, io, os, traceback
-import html
+import asyncio
+import io
+import mimetypes
+import os
+import posixpath
+import sys
import time
+import traceback
import urllib.parse
-import mimetypes
-
-# HTTP headers and the request line are latin-1 on the wire; bodies we generate are utf-8
-HEADER_ENCODING = 'latin-1'
-BODY_ENCODING = 'utf-8'
+from email.utils import formatdate
-"""HTTP server base class.
+from aiohttp import web
-Note: the class in this module doesn't implement any HTTP request; see
-SimpleHTTPServer for simple implementations of GET, HEAD and POST
-(including CGI scripts). It does, however, optionally implement HTTP/1.1
-persistent connections, as of version 0.3.
-
-Contents:
-
-- BaseHTTPRequestHandler: HTTP request handler base class
-"""
-__version__ = "0.3"
-
-class CaseInsensitiveDict(dict):
- """Dictionary with case-insensitive keys
- Replacement for the deprecated mimetools.Message class. infile is a binary file of header lines.
- """
- def __init__(self, infile, *args):
- self._ci_dict = {}
- lines = infile.readlines()
- for line in lines:
- line = line.decode(HEADER_ENCODING)
- if ':' not in line:
- continue
- k,v=line.split(":",1)
- self._ci_dict[k.lower()] = self[k] = v.strip()
- self.headers = list(self.keys())
-
- def getheader(self,key,default=""):
- return self._ci_dict.get(key.lower(),default)
-
- def get(self,key,default=""):
- return self._ci_dict.get(key.lower(),default)
-
- def __getitem__(self,key):
- return self._ci_dict[key.lower()]
-
- def __contains__(self,key):
- return key.lower() in self._ci_dict
-
-# Default error message template
-DEFAULT_ERROR_MESSAGE = """\
-
-Error response
-
-
-Error response
-Error code %(code)d.
-
Message: %(message)s.
-
Error code explanation: %(code)s = %(explain)s.
-
-"""
+# bodies we generate are utf-8
+BODY_ENCODING = 'utf-8'
-DEFAULT_ERROR_CONTENT_TYPE = "text/html"
+# a form post (an email body, a template) is small; this only stops a runaway client
+MAX_REQUEST_BYTES = 16 * 1024 * 1024
-def _quote_html(text):
- return text.replace("&", "&").replace("<", "<").replace(">", ">")
class Redirect(object):
"""A path handler returns this instead of (body, content type) to answer with a redirect. It is a 303 See
@@ -91,6 +39,7 @@ class Redirect(object):
def __init__(self, location):
self.location = location
+
def _body_file(f, ctype):
"""Normalise whatever a path handler returned into (binary file object, content type).
Handlers return str (json, plain), bytes (mako output, pdf) or a binary file object."""
@@ -102,670 +51,153 @@ def _body_file(f, ctype):
ctype += '; charset=' + BODY_ENCODING
return f, ctype
-class BaseHTTPRequestHandler(asynchat.async_chat):
-
- # The Python system version, truncated to its first component.
- sys_version = "Python/" + sys.version.split()[0]
-
- # The server software version. You may want to override this.
- # The format is multiple whitespace-separated strings,
- # where each string is of the form name[/version].
- server_version = "BaseHTTP/" + __version__
-
- # The default request version. This only affects responses up until
- # the point where the request line is parsed, so it mainly decides what
- # the client gets back when sending a malformed request line.
- # Most web servers default to HTTP 0.9, i.e. don't send a status line.
- default_request_version = "HTTP/0.9"
-
- def parse_request(self, requestline):
- """Parse a request (internal).
- the results are in self.command, self.path, self.request_version,
- self.headers and self.close_connection.
-
- Return True for success, False for failure; on failure a call to
- send_error is made before returning.
-
- """
- self.command = None # set in case of error on the first line
- self.request_version = version = self.default_request_version
- self.close_connection = 1
-
- requestline = requestline.decode(HEADER_ENCODING).rstrip('\r\n')
- self.requestline = requestline
- words = requestline.split()
- if len(words) == 3:
- command, path, version = words
- if version[:5] != 'HTTP/':
- self.send_error(400, "Bad request version (%r)" % version)
- return False
- try:
- base_version_number = version.split('/', 1)[1]
- version_number = base_version_number.split(".")
- # RFC 2145 section 3.1 says there can be only one "." and
- # - major and minor numbers MUST be treated as
- # separate integers;
- # - HTTP/2.4 is a lower version than HTTP/2.13, which in
- # turn is lower than HTTP/12.3;
- # - Leading zeros MUST be ignored by recipients.
- if len(version_number) != 2:
- raise ValueError
- version_number = int(version_number[0]), int(version_number[1])
- except (ValueError, IndexError):
- self.send_error(400, "Bad request version (%r)" % version)
- return False
- if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1":
- self.close_connection = 0
- if version_number >= (2, 0):
- self.send_error(505, "Invalid HTTP Version (%s)" % base_version_number)
- return False
- elif len(words) == 2:
- command, path = words
- self.close_connection = 1
- if command != 'GET':
- self.send_error(400, "Bad HTTP/0.9 request type (%r)" % command)
- return False
- elif not words:
- return False
- else:
- self.send_error(400, "Bad request syntax (%r)" % requestline)
- return False
-
- querystring = dict()
- qparts = path.split('?', 1)
- if len(qparts) > 1:
- path = qparts[0]
- querystring = urllib.parse.parse_qs(qparts[1])
- self.command, self.path, self.request_version, self.query_string = command, path, version, querystring
-
- # Examine the headers and look for a Connection directive
- self.headers = CaseInsensitiveDict(self.rfile, 0)
-
- conntype = self.headers.get('Connection', "")
- if conntype.lower() == 'close':
- self.close_connection = 1
- elif (conntype.lower() == 'keep-alive' and
- self.protocol_version >= "HTTP/1.1"):
- self.close_connection = 0
- return True
-
- def send_error(self, code, message=None):
- """Send and log an error reply.
-
- Arguments are the error code, and a detailed message.
- The detailed message defaults to the short entry matching the
- response code.
-
- This sends an error response (so it must be called before any
- output has been generated), logs the error, and finally sends
- a piece of HTML explaining the error to the user.
-
- """
-
- try:
- short, long = self.responses[code]
- except KeyError:
- short, long = '???', '???'
- if message is None:
- message = short
- explain = long
- self.log_error("code %d, message %s", code, message)
- # using _quote_html to prevent Cross Site Scripting attacks (see bug #1100201)
- content = (self.error_message_format %
- {'code': code, 'message': _quote_html(message), 'explain': explain})
- self.send_response(code, message)
- self.send_header("Content-Type", self.error_content_type)
- self.send_header('Connection', 'close')
- self.end_headers()
- if self.command != 'HEAD' and code >= 200 and code not in (204, 304):
- self.push(content.encode(BODY_ENCODING))
-
- error_message_format = DEFAULT_ERROR_MESSAGE
- error_content_type = DEFAULT_ERROR_CONTENT_TYPE
-
- def send_response(self, code, message=None):
- """Send the response header and log the response code.
-
- Also send two standard headers with the server software
- version and the current date.
-
- """
- self.log_request(code)
- if message is None:
- if code in self.responses:
- message = self.responses[code][0]
- else:
- message = ''
- if self.request_version != 'HTTP/0.9':
- self.push(("%s %d %s\r\n" % (self.protocol_version, code, message)).encode(HEADER_ENCODING, 'replace'))
- self.send_header('Server', self.version_string())
- self.send_header('Date', self.date_time_string())
- def send_header(self, keyword, value):
- """Send a MIME header."""
- if self.request_version != 'HTTP/0.9':
- self.push(("%s: %s\r\n" % (keyword, value)).encode(HEADER_ENCODING, 'replace'))
+if not mimetypes.inited:
+ mimetypes.init() # try to read system mime.types
+extensions_map = mimetypes.types_map.copy()
+extensions_map.update({
+ '': 'application/octet-stream', # Default
+ '.py': 'text/plain',
+ '.c': 'text/plain',
+ '.h': 'text/plain',
+})
- if keyword.lower() == 'connection':
- if value.lower() == 'close':
- self.close_connection = 1
- elif value.lower() == 'keep-alive':
- self.close_connection = 0
- def end_headers(self):
- """Send the blank line ending the MIME headers."""
- if self.request_version != 'HTTP/0.9':
- self.push(b"\r\n")
-
- def log_request(self, code='-', size='-'):
- """Log requests, called by send_response(). """
- self.log_message('"%s" %s %s', self.requestline, str(code), str(size))
-
- def log_error(self, format, *args):
- """Log an error.
-
- This is called when a request cannot be fulfilled. By
- default it passes the message on to log_message().
-
- Arguments are the same as for log_message().
-
- XXX This should go to the separate error log.
-
- """
-
- self.log_message(format, *args)
-
- def log_message(self, format, *args):
- """Log an arbitrary message.
-
- This is used by all other logging functions. Override
- it if you have specific logging wishes.
-
- The first argument, FORMAT, is a format string for the
- message to be logged. If the format string contains
- any % escapes requiring parameters, they should be
- specified as subsequent arguments (it's just like
- printf!).
-
- The client host and current date/time are prefixed to
- every message.
-
- """
-
- sys.stderr.write("%s - - [%s] %s\n" %
- (self.address_string(),
- self.log_date_time_string(),
- format%args))
-
- def version_string(self):
- """Return the server software version string."""
- return self.server_version + ' ' + self.sys_version
-
- def date_time_string(self, timestamp=None):
- """Return the current date and time formatted for a message header."""
- if timestamp is None:
- timestamp = time.time()
- year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
- s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
- self.weekdayname[wd],
- day, self.monthname[month], year,
- hh, mm, ss)
- return s
-
- def log_date_time_string(self):
- """Return the current time formatted for logging."""
- now = time.time()
- year, month, day, hh, mm, ss, x, y, z = time.localtime(now)
- s = "%02d/%3s/%04d %02d:%02d:%02d" % (
- day, self.monthname[month], year, hh, mm, ss)
- return s
-
- weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
-
- monthname = [None,
- 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
- 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
-
- def address_string(self):
- """Return the client address formatted for logging.
-
- This version looks up the full hostname using gethostbyaddr(),
- and tries to find a name that contains at least one dot.
-
- """
-
- host, port = self.client_address[:2]
- # return socket.getfqdn(host)
- return host
-
- # Essentially static class variables
-
- # The version of the HTTP protocol we support.
- # Set this to HTTP/1.1 to enable automatic keepalive
- protocol_version = "HTTP/1.1"
-
- # Table mapping response codes to messages; entries have the
- # form {code: (shortmessage, longmessage)}.
- # See RFC 2616.
- responses = {
- 100: ('Continue', 'Request received, please continue'),
- 101: ('Switching Protocols',
- 'Switching to new protocol; obey Upgrade header'),
-
- 200: ('OK', 'Request fulfilled, document follows'),
- 201: ('Created', 'Document created, URL follows'),
- 202: ('Accepted',
- 'Request accepted, processing continues off-line'),
- 203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
- 204: ('No Content', 'Request fulfilled, nothing follows'),
- 205: ('Reset Content', 'Clear input form for further input.'),
- 206: ('Partial Content', 'Partial content follows.'),
-
- 300: ('Multiple Choices',
- 'Object has several resources -- see URI list'),
- 301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
- 302: ('Found', 'Object moved temporarily -- see URI list'),
- 303: ('See Other', 'Object moved -- see Method and URL list'),
- 304: ('Not Modified',
- 'Document has not changed since given time'),
- 305: ('Use Proxy',
- 'You must use proxy specified in Location to access this '
- 'resource.'),
- 307: ('Temporary Redirect',
- 'Object moved temporarily -- see URI list'),
-
- 400: ('Bad Request',
- 'Bad request syntax or unsupported method'),
- 401: ('Unauthorized',
- 'No permission -- see authorization schemes'),
- 402: ('Payment Required',
- 'No payment -- see charging schemes'),
- 403: ('Forbidden',
- 'Request forbidden -- authorization will not help'),
- 404: ('Not Found', 'Nothing matches the given URI'),
- 405: ('Method Not Allowed',
- 'Specified method is invalid for this resource.'),
- 406: ('Not Acceptable', 'URI not available in preferred format.'),
- 407: ('Proxy Authentication Required', 'You must authenticate with '
- 'this proxy before proceeding.'),
- 408: ('Request Timeout', 'Request timed out; try again later.'),
- 409: ('Conflict', 'Request conflict.'),
- 410: ('Gone',
- 'URI no longer exists and has been permanently removed.'),
- 411: ('Length Required', 'Client must specify Content-Length.'),
- 412: ('Precondition Failed', 'Precondition in headers is false.'),
- 413: ('Request Entity Too Large', 'Entity is too large.'),
- 414: ('Request-URI Too Long', 'URI is too long.'),
- 415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
- 416: ('Requested Range Not Satisfiable',
- 'Cannot satisfy request range.'),
- 417: ('Expectation Failed',
- 'Expect condition could not be satisfied.'),
-
- 500: ('Internal Server Error', 'Server got itself in trouble'),
- 501: ('Not Implemented',
- 'Server does not support this operation'),
- 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
- 503: ('Service Unavailable',
- 'The server cannot process the request due to a high load'),
- 504: ('Gateway Timeout',
- 'The gateway server did not receive a timely response'),
- 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
- }
-
-
-"""Simple HTTP Server.
-
-This module builds on BaseHTTPServer by implementing the standard GET
-and HEAD requests in a fairly straightforward manner.
-
-"""
-class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
+def guess_type(path):
+ base, ext = posixpath.splitext(path)
+ return extensions_map.get(ext) or extensions_map.get(ext.lower()) or extensions_map['']
- """Simple HTTP request handler with GET and HEAD commands.
- This serves files from the current directory and any of its
- subdirectories. The MIME type for files is determined by
- calling the .guess_type() method.
+class ResponseGatherer(object):
+ """What a GET handler is given to add response headers to (a download's Content-Disposition)."""
+ def __init__(self):
+ self.headers = []
- The GET and HEAD requests are identical except that the HEAD
- request omits the actual contents of the file.
+ def add_header(self, key, value):
+ self.headers.append((key, value))
- """
- server_version = "SimpleHTTP/" + __version__
+class HttpServer(object):
+ """Serves pathhandlers and the files under webroot. Use as `await server.start()`; `server.port` is the
+ port actually bound (pass port=0 to be given one)."""
- def do_GET(self):
- """Serve a GET request."""
- f = self.send_head()
- if f:
- self.push(f.read())
+ def __init__(self, pathhandlers, webroot, ip='', port=8081):
+ self.handlers = pathhandlers
+ self.webroot = webroot
+ self.ip = ip
+ self.port = port
+ self.runner = None
+
+ async def start(self):
+ app = web.Application(client_max_size=MAX_REQUEST_BYTES)
+ app.router.add_route('*', '/{tail:.*}', self._handle)
+ self.runner = web.AppRunner(app, access_log=None)
+ await self.runner.setup()
+ site = web.TCPSite(self.runner, self.ip or None, self.port, backlog=100)
+ await site.start()
+ self.port = self.runner.addresses[0][1]
+ print("[httpd] aiohttp running on port %s, serving from %s" % (self.port, self.webroot))
+ return self
+
+ async def close(self):
+ if self.runner:
+ await self.runner.cleanup()
+
+ def log(self, request, status, size):
+ peer = request.transport.get_extra_info('peername') if request.transport else None
+ peer = peer or ('-', 0)
+ print('[httpd-%d] %s %s "%s %s HTTP/%d.%d" %s %s' % (peer[1], time.strftime('%d/%b/%Y %H:%M:%S'), peer[0],
+ request.method, request.raw_path, request.version.major, request.version.minor, status, size))
+
+ def reply(self, request, status, body=b'', headers=None):
+ response = web.Response(status=status, body=body, headers=headers)
+ self.log(request, status, len(body) if body else '-')
+ return response
+
+ def error(self, request, status, message):
+ page = ('
%d %s%d %s
' % (
+ status, message, status, message)).encode(BODY_ENCODING)
+ return self.reply(request, status, page, {'Content-Type': 'text/html; charset=' + BODY_ENCODING})
+
+ async def _handle(self, request):
+ path = request.path
+ query_string = urllib.parse.parse_qs(request.rel_url.raw_query_string)
+ handler = self.handlers.get(path)
+ if request.method == 'POST':
+ if not handler:
+ return self.error(request, 404, 'Not Found')
+ # only urlencoded form bodies are understood; fields arrive as {name: [values]}, like query_string
+ body = (await request.read()).decode(BODY_ENCODING, 'replace')
+ postreq = urllib.parse.parse_qs(body, keep_blank_values=True)
+ return self.run_handler(request, handler, dict(query_string=query_string, postreq=postreq))
+ if request.method not in ('GET', 'HEAD'):
+ return self.error(request, 501, 'Unsupported method (%r)' % request.method)
+ if handler:
+ gatherer = ResponseGatherer()
+ return self.run_handler(request, handler, dict(query_string=query_string, resp=gatherer), gatherer)
+ return self.static(request, path)
+
+ def run_handler(self, request, handler, kwargs, gatherer=None):
+ try:
+ result = handler(**kwargs)
+ if isinstance(result, Redirect):
+ return self.reply(request, 303, b'', {'Location': result.location})
+ (f, ctype) = _body_file(*result)
+ headers = dict(gatherer.headers) if gatherer else {}
+ headers['Content-Type'] = ctype
+ body = f.read()
f.close()
+ return self.reply(request, 200, body, headers)
+ except Exception:
+ print(traceback.format_exc())
+ return self.error(request, 500, 'Internal Server Error')
- def do_HEAD(self):
- """Serve a HEAD request."""
- f = self.send_head()
- if f:
- f.close()
+ def translate_path(self, path):
+ """The file under the web root for a /-separated URL path. Components that mean something to the
+ file system (drives, '..') are ignored, so a request can't leave the web root."""
+ path = posixpath.normpath(urllib.parse.unquote(path))
+ result = self.webroot
+ for word in [w for w in path.split('/') if w]:
+ drive, word = os.path.splitdrive(word)
+ head, word = os.path.split(word)
+ if word in (os.curdir, os.pardir):
+ continue
+ result = os.path.join(result, word)
+ return result
- def send_head(self):
- """Common code for GET and HEAD commands.
-
- This sends the response code and MIME headers.
-
- Return value is either a file object (which has to be copied
- to the outputfile by the caller unless the command was HEAD,
- and must be closed by the caller under all circumstances), or
- None, in which case the caller has nothing further to do.
-
- """
- class ResponseGatherer():
- def __init__(self):
- self.headers = []
- def add_header(self, key, value):
- self.headers.append((key, value))
- def write_headers(self, connection):
- for (k,v) in self.headers:
- connection.send_header(k,v)
-
- handler = self.handlers.get(self.path)
- if (handler):
- try:
- resp = ResponseGatherer()
- result = handler(query_string=self.query_string, resp=resp)
- if isinstance(result, Redirect):
- self.send_redirect(result)
- return None
- (f, ctype) = _body_file(*result)
- self.send_response(200)
- resp.write_headers(self)
- self.send_header("Content-type", ctype)
- f.seek(0, os.SEEK_END)
- self.send_header("Content-Length", str(f.tell()))
- # self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
- self.end_headers()
- f.seek(0)
- return f
- except:
- tb = traceback.format_exc()
- print(tb)
- self.send_error(500, "File not found")
- return None
-
- path = self.translate_path(self.path)
- f = None
+ def static(self, request, urlpath):
+ path = self.translate_path(urlpath)
if os.path.isdir(path):
- if not self.path.endswith('/'):
+ if not urlpath.endswith('/'):
# redirect browser - doing basically what apache does
- self.send_response(301)
- self.send_header("Location", self.path + "/")
- self.end_headers()
- return None
- for index in "index.html", "index.htm":
- index = os.path.join(path, index)
- if os.path.exists(index):
- path = index
+ return self.reply(request, 301, b'', {'Location': urlpath + '/'})
+ for index in ('index.html', 'index.htm'):
+ if os.path.exists(os.path.join(path, index)):
+ path = os.path.join(path, index)
break
else:
- return self.list_directory(path)
- ctype = self.guess_type(path)
- try:
- # Always read in binary mode. Opening files in text mode may cause
- # newline translations, making the actual size of the content
- # transmitted *less* than the content-length!
- f = open(path, 'rb')
- except IOError:
- tb = traceback.format_exc()
- print(tb)
- self.send_error(404, "File not found")
- return None
- self.send_response(200)
- self.send_header("Content-type", ctype)
- fs = os.fstat(f.fileno())
- self.send_header("Content-Length", str(fs[6]))
- self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
- self.end_headers()
- return f
-
- def send_redirect(self, redirect):
- self.send_response(303)
- self.send_header("Location", redirect.location)
- self.send_header("Content-Length", "0")
- self.end_headers()
-
- def list_directory(self, path):
- """Helper to produce a directory listing (absent index.html).
-
- Return value is either a file object, or None (indicating an
- error). In either case, the headers are sent, making the
- interface the same as for send_head().
-
- """
+ return self.error(request, 404, 'Not Found')
try:
- list = os.listdir(path)
- except os.error:
- self.send_error(404, "No permission to list directory")
- return None
- list.sort(key=lambda a: a.lower())
- f = io.StringIO()
- displaypath = html.escape(urllib.parse.unquote(self.path))
- f.write('')
- f.write("\nDirectory listing for %s\n" % displaypath)
- f.write("\nDirectory listing for %s
\n" % displaypath)
- f.write("
\n\n")
- for name in list:
- fullname = os.path.join(path, name)
- displayname = linkname = name
- # Append / for directories or @ for symbolic links
- if os.path.isdir(fullname):
- displayname = name + "/"
- linkname = name + "/"
- if os.path.islink(fullname):
- displayname = name + "@"
- # Note: a link to a directory displays with @ and links with /
- f.write('- %s\n'
- % (urllib.parse.quote(linkname), html.escape(displayname)))
- f.write("
\n
\n\n\n")
- f = io.BytesIO(f.getvalue().encode(sys.getfilesystemencoding(), 'replace'))
- length = len(f.getvalue())
- self.send_response(200)
- encoding = sys.getfilesystemencoding()
- self.send_header("Content-type", "text/html; charset=%s" % encoding)
- self.send_header("Content-Length", str(length))
- self.end_headers()
- return f
+ # binary, so that newline translation can't change the size of what is sent
+ with open(path, 'rb') as f:
+ body = f.read()
+ mtime = os.fstat(f.fileno()).st_mtime
+ except OSError:
+ return self.error(request, 404, 'Not Found')
+ return self.reply(request, 200, body, {'Content-Type': guess_type(path), 'Last-Modified': formatdate(mtime, usegmt=True)})
- def translate_path(self, path):
- """Translate a /-separated PATH to the local filename syntax.
-
- Components that mean special things to the local file system
- (e.g. drive or directory names) are ignored. (XXX They should
- probably be diagnosed.)
-
- """
- # abandon query parameters
- path = path.split('?',1)[0]
- path = path.split('#',1)[0]
- path = posixpath.normpath(urllib.parse.unquote(path))
- words = path.split('/')
- words = [w for w in words if w]
- path = self.webroot
- for word in words:
- drive, word = os.path.splitdrive(word)
- head, word = os.path.split(word)
- if word in (os.curdir, os.pardir): continue
- path = os.path.join(path, word)
- return path
-
- def guess_type(self, path):
- """Guess the type of a file.
-
- Argument is a PATH (a filename).
-
- Return value is a string of the form type/subtype,
- usable for a MIME Content-type header.
-
- The default implementation looks the file's extension
- up in the table self.extensions_map, using application/octet-stream
- as a default; however it would be permissible (if
- slow) to look inside the data to make a better guess.
-
- """
-
- base, ext = posixpath.splitext(path)
- if ext in self.extensions_map:
- return self.extensions_map[ext]
- ext = ext.lower()
- if ext in self.extensions_map:
- return self.extensions_map[ext]
- else:
- return self.extensions_map['']
-
- if not mimetypes.inited:
- mimetypes.init() # try to read system mime.types
- extensions_map = mimetypes.types_map.copy()
- extensions_map.update({
- '': 'application/octet-stream', # Default
- '.py': 'text/plain',
- '.c': 'text/plain',
- '.h': 'text/plain',
- })
-
-class RequestHandler(SimpleHTTPRequestHandler):
-
- def __init__(self,conn,addr, webroot=os.getcwd(), path_handlers={}):
- asynchat.async_chat.__init__(self,conn)
-
- self.client_address = addr
- self.id = "[httpd-%d]" % addr[1]
- self.webroot = webroot
- self.handlers = path_handlers
-
- # set the terminator : when it is received, this means that the
- # http request is complete ; control will be passed to
- # self.found_terminator
- self.reset_terminator();
-
- def reset_terminator(self):
- self.set_terminator (b'\r\n\r\n')
- self.found_terminator = self.handle_request_line
- self.rfile = io.BytesIO()
-
- def collect_incoming_data(self,data):
- self.rfile.write(data)
-
- def do_POST(self):
- """Begins serving a POST request. The request data must be readable
- on a file-like object called self.rfile"""
- # only urlencoded form bodies are understood; fields arrive as {name: [values]}, like query_string
- body = self.rfile.getvalue().decode(BODY_ENCODING, 'replace')
- postreq = urllib.parse.parse_qs(body, keep_blank_values=True)
-
- handler = self.handlers.get(self.path)
- if (handler):
- try:
- result = handler(query_string=self.query_string, postreq=postreq)
- if isinstance(result, Redirect):
- self.send_redirect(result)
- return None
- (f, ctype) = _body_file(*result)
- self.send_response(200)
- self.send_header("Content-type", ctype)
- f.seek(0, os.SEEK_END)
- self.send_header("Content-Length", str(f.tell()))
- # self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
- self.end_headers()
- f.seek(0)
- self.push(f.read())
- f.close()
- return None
- except:
- tb = traceback.format_exc()
- print(tb)
- self.send_error(500, "File not found")
- return None
- else:
- self.send_error(404, "File not found")
- return None
-
- def handle_request_line(self):
- """Called when the http request line and headers have been received"""
- # prepare attributes needed in parse_request()
- self.rfile.seek(0)
- requestline = self.rfile.readline()
- self.parse_request( requestline )
-
- # if browser indicates POST data follows, read it before generating the response
- bytesToRead = int(self.headers.getheader('content-length', '0'))
- if bytesToRead > 0:
- self.set_terminator(bytesToRead)
- self.rfile = io.BytesIO()
- # control will be passed to a new found_terminator
- self.found_terminator = self.dispatch_handler
-
- else:
- # no content from brower - generate response now
- self.dispatch_handler()
-
- def dispatch_handler(self):
- mname = 'do_' + self.command
- if not hasattr(self, mname):
- self.send_error(501, "Unsupported method (%r)" % self.command)
- return
- getattr(self, mname)()
-
- if self.close_connection:
- """Send data, then close"""
- self.log_message("close_connection set, closing connection")
- self.close_when_done()
-
- self.reset_terminator()
-
- def handle_error(self):
- traceback.print_exc(sys.stderr)
- self.close()
-
- def log_message(self, format, *args):
- sys.stdout.write("%s %s %s %s\n" %
- (self.id, self.log_date_time_string(), self.address_string(), format%args))
-
-class ToyHttpServer(asyncore.dispatcher):
-
- def __init__ (self, ip='', port=8081, webroot=os.getcwd(), handler=RequestHandler, pathhandlers={}):
-
- self.webroot=webroot
- self.path_handlers = pathhandlers
- self.handler = handler
- asyncore.dispatcher.__init__ (self)
- self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
-
- self.set_reuse_addr()
- self.bind ((ip, port))
- self.listen (100)
-
- print("[httpd] ToyHTTPServer running on port %s, serving from %s" % (port, self.webroot))
-
- def handle_accept (self):
- try:
- pair = self.accept()
- if pair is not None:
- sock, addr = pair
- self.handler(sock,addr,webroot=self.webroot, path_handlers=self.path_handlers)
- except socket.error:
- self.log_info ('[https] warning: server accept() threw an exception', 'warning')
- return
if __name__=="__main__":
- def about(query_string=''):
+ def about(query_string='', resp=None):
return ("hi %s" % query_string, 'text/plain')
- # launch the server on the specified port
- s = ToyHttpServer(port=8081, pathhandlers={'/about': about})
+ async def main():
+ # launch the server on the specified port
+ await HttpServer({'/about': about}, os.getcwd(), port=8081).start()
+ await asyncio.Event().wait()
try:
- while True:
- asyncore.loop(timeout=2, count=10)
- print('[control] poll')
+ asyncio.run(main())
except KeyboardInterrupt:
print("Crtl+C pressed. Shutting down.")
diff --git a/init.d/printerface b/init.d/printerface
index b631965..931b85d 100755
--- a/init.d/printerface
+++ b/init.d/printerface
@@ -29,7 +29,7 @@
# Location of printerface binary
printerface=~/repos/printerface/main.py
-# Interpreter to run it with. Needs python 3.11 (asyncore was removed in 3.12) plus the packages from
+# Interpreter to run it with. Needs python 3.11 or later plus the packages from
# requirements.txt, so default to a venv made from /opt/python311/bin/python3.11:
# /opt/python311/bin/python3.11 -m venv ~/.venv311 && ~/.venv311/bin/pip install -r requirements.txt
# Set PRINTERFACE_PYTHON to use another one.
diff --git a/lpdserver.py b/lpdserver.py
index d3c9319..c434ded 100644
--- a/lpdserver.py
+++ b/lpdserver.py
@@ -1,130 +1,173 @@
-# Line Printer Daemon implementation, using asynchat
+# Line Printer Daemon implementation (RFC 1179 receive side), using asyncio
# Chris Shucksmith 2013
-import asynchat, asyncore, socket, os
+import asyncio
+import os
import sys
+import traceback
# LPD is a byte protocol and print data is 8-bit. Decode everything as latin-1 so that one byte is
# always one character (columns in the fixed-width documents must not shift) and so it round-trips.
ENCODING = 'latin-1'
-(AwaitingCommand, NewJob, NewJobControl, NewJobData, EndOfFile ) = range(0,5)
+# a client that goes quiet in the middle of a job is dropped after this many seconds
+IDLE_TIMEOUT = 120
-class LpdHandler(asynchat.async_chat):
+ACK = b'\x00'
- def __init__(self, sock, addr, controller):
- asynchat.async_chat.__init__(self, sock=sock)
- self.ibuffer = []
- self.sm = AwaitingCommand
- self.set_terminator(b"\n")
- self.sock = sock
+
+class LpdHandler(object):
+ """One connection. The conversation is: a receive-job command naming the queue, then a control file and a
+ data file, each announced by a subcommand giving its size and acknowledged with a zero byte, and each
+ followed by a zero byte of its own. Many senders close the connection after the data file."""
+
+ def __init__(self, reader, writer, controller):
+ self.reader = reader
+ self.writer = writer
self.controller = controller
- self.id = "[lpd-%d]" % addr[1]
+ peer = writer.get_extra_info('peername') or ('?', 0)
+ self.id = "[lpd-%d]" % peer[1]
+
+ async def _read(self, coro):
+ return await asyncio.wait_for(coro, IDLE_TIMEOUT)
+
+ async def _line(self):
+ """The next command line without its newline, or None if the client has gone."""
+ try:
+ return (await self._read(self.reader.readuntil(b'\n')))[:-1]
+ except asyncio.IncompleteReadError:
+ return None
+
+ async def _ack(self):
+ self.writer.write(ACK)
+ await self.writer.drain()
+
+ async def run(self):
print('%s installed LpdHandler' % self.id)
+ try:
+ await self._conversation()
+ except (asyncio.TimeoutError, ConnectionError):
+ print('%s connection lost' % self.id)
+ except Exception:
+ traceback.print_exc(file=sys.stdout)
+ finally:
+ print('%s handle_close' % self.id)
+ try:
+ self.writer.close()
+ await self.writer.wait_closed()
+ except Exception:
+ pass
- def collect_incoming_data(self, data):
- self.ibuffer.append(data)
- print('%s collect_data - %d bytes' % (self.id, len(data)))
-
- def found_terminator(self):
- # the terminator can arrive split over several recv()s, so gather every fragment
- chunk = b''.join(self.ibuffer)
- self.ibuffer = []
- cmd = chunk[:1]
- if self.sm == AwaitingCommand: # Main command verb
- if cmd == b'\x02':
+ async def _conversation(self):
+ # main command verb: 02 LF
+ while True:
+ chunk = await self._line()
+ if chunk is None:
+ return
+ if chunk[:1] == b'\x02':
self.queue = chunk[1:].decode(ENCODING)
print('%s Incoming job to queue \'%s\'' % (self.id, self.queue))
- self.push(b'\x00')
- self.sm = NewJob
- else:
- print('%s unknown message type %r' % (self.id, cmd))
- elif self.sm == NewJob: # Recieve Job
- if cmd == b'\x02': # Subcommand - Control filename
- sz,name = chunk[1:].decode(ENCODING).split(' ', 1)
- rdlength = int(sz)
- print('%s Incoming header: control file sz %d filename %s' % (self.id, rdlength,name))
- self.sm = NewJobControl
- self.set_terminator(rdlength+1) # include the trailing null
- self.push(b'\x00')
- elif cmd == b'\x03': # Subcommand - Data filename
- sz,name = chunk[1:].decode(ENCODING).split(' ', 1)
- rdlength = int(sz)
- print('%s incoming header: data file sz %d filename %s' % (self.id, rdlength,name))
- self.sm = NewJobData
- # windows seems to set a stupidly large length here and kill the socket to
- # indicate eof. Handle either
- self.set_terminator(rdlength+1) # include the trailing null
- # self.set_terminator(None) # terminated by close of socket
- self.push(b'\x00')
+ await self._ack()
+ break
+ print('%s unknown message type %r' % (self.id, chunk[:1]))
+
+ self.control = {}
+ while True:
+ chunk = await self._line()
+ if chunk is None:
+ print('%s unexpected close of stream' % self.id)
+ return
+ cmd = chunk[:1]
+ if cmd == b'\x02': # subcommand: control file, 02 LF
+ size, name = chunk[1:].decode(ENCODING).split(' ', 1)
+ length = int(size)
+ print('%s Incoming header: control file sz %d filename %s' % (self.id, length, name))
+ await self._ack()
+ try:
+ body = await self._read(self.reader.readexactly(length + 1)) # include the trailing null
+ except asyncio.IncompleteReadError:
+ print('%s unexpected close of stream' % self.id)
+ return
+ self.control = dict([(x[0], x[1:]) for x in body[:-1].decode(ENCODING).split('\n') if len(x) > 1])
+ print('%s control file: %s' % (self.id, repr(self.control)))
+ await self._ack()
+ elif cmd == b'\x03': # subcommand: data file, 03 LF
+ size, name = chunk[1:].decode(ENCODING).split(' ', 1)
+ length = int(size)
+ print('%s incoming header: data file sz %d filename %s' % (self.id, length, name))
+ await self._ack()
+ # Windows sends a stupidly large size and closes the connection to mark the end of the data;
+ # either way we dispatch what arrived. A well formed file keeps its trailing null, as it always has.
+ data, complete = await self._data_file(length + 1)
+ if complete:
+ print('%s end of data file' % self.id)
+ await self._ack()
+ self.dispatch(data)
+ else:
+ # the sender has closed: the job must still be kept even if it can no longer hear the ack
+ print('%s data file: %s' % (self.id, repr(data)[:100]))
+ self.dispatch(data)
+ try:
+ await self._ack()
+ except ConnectionError:
+ pass
+ return
else:
print('%s recieve job unknown subcommand: %r' % (self.id, cmd))
- elif self.sm == NewJobControl: # Recieve - Job Control file (null terminated)
- self.controldata = dict([ (x[0], x[1:]) for x in chunk[:-1].decode(ENCODING).split('\n') if len(x) > 1])
- print('%s control file: %s' % (self.id, repr(self.controldata)))
- self.push(b'\x00')
- self.sm = NewJob
- self.set_terminator(b"\n")
- elif self.sm == NewJobData: # Recieve - Job Data file (terminated by close)
- # Windows NT4 lpr sends a well formed size, hits this code
- print('%s end of data file' % self.id)
- # put the chunk back on the ibuffer for dispatch()
- self.ibuffer.insert(0, chunk)
- self.sm = EndOfFile
- self.push(b'\x00')
- self.close_when_done()
- self.dispatch()
- else:
- print('%s Unknown state, woken up by terminator, chunk was: %s' % (self.id, repr(chunk)))
- self.close_when_done()
-
- def handle_close(self):
- print('%s handle_close' % (self.id))
- if self.sm == NewJobData:
- print('%s data file: %s' % (self.id, repr(self.ibuffer)[:100]))
- # calling push() after the client has closed the socket will re-invoke handle_close, so
- # switch to terminal state to avoid inf recursion
- self.sm = EndOfFile
- self.dispatch()
- self.push(b'\x00')
- self.close_when_done()
- elif self.sm == EndOfFile:
- self.close()
- else:
- print('%s unexpected close of stream, sm=%d' % (self.id, self.sm))
- self.close()
-
- def dispatch(self):
- data = b''.join(self.ibuffer).decode(ENCODING)
- # log exceptions during dispatch so that we get the thread back to perform socket clean up
+
+ async def _data_file(self, size):
+ """(bytes, complete): the data file, or what arrived of it before the sender closed or reset the connection."""
+ chunks, got = [], 0
+ while got < size:
+ try:
+ chunk = await self._read(self.reader.read(min(65536, size - got)))
+ except ConnectionError:
+ break
+ if not chunk:
+ break
+ chunks.append(chunk)
+ got += len(chunk)
+ return b''.join(chunks), got >= size
+
+ def dispatch(self, data):
+ # log exceptions during dispatch so that we still get to close the connection
try:
- print('%s dispatching' % (self.id))
- self.controller(self.queue, self.sock.getpeername(), self.sock.getsockname(), self.controldata, data)
+ print('%s dispatching' % self.id)
+ self.controller(self.queue, self.writer.get_extra_info('peername'), self.writer.get_extra_info('sockname'),
+ self.control, data.decode(ENCODING))
except Exception as e:
print('LPD dispatch of print job threw exception: %s' % sys.exc_info()[0])
print(e)
sys.stdout.flush()
- print('%s dispatch complete' % (self.id))
-
-class LpdServer(asyncore.dispatcher):
- def __init__ (self, lpd_controller, ip='127.0.0.1', port=515):
- asyncore.dispatcher.__init__ (self)
- self.create_socket (socket.AF_INET, socket.SOCK_STREAM)
- self.set_reuse_addr()
- self.bind ((ip, port))
- self.listen (100)
+ print('%s dispatch complete' % self.id)
+
+
+class LpdServer(object):
+ """Listens for LPD connections and hands each received job to lpd_controller(queue, peer, local, control, data),
+ called on the event loop, so it shares the loop's single thread with everything else. Use as
+ `await server.start()`; `server.port` is the port actually bound (pass port=0 to be given one)."""
+
+ def __init__(self, lpd_controller, ip='127.0.0.1', port=515):
self.lpd_controller = lpd_controller
- print('[lpd] listening on port %s' % port)
+ self.ip = ip
+ self.port = port
+ self.server = None
+
+ async def start(self):
+ self.server = await asyncio.start_server(self._accept, self.ip or None, self.port, backlog=100)
+ self.port = self.server.sockets[0].getsockname()[1]
+ print('[lpd] listening on port %s' % self.port)
+ return self
+
+ async def _accept(self, reader, writer):
+ print('[lpd] Incoming connection from %s' % repr(writer.get_extra_info('peername')))
+ await LpdHandler(reader, writer, self.lpd_controller).run()
+
+ async def close(self):
+ if self.server:
+ self.server.close()
+ await self.server.wait_closed()
- def handle_accept(self):
- try:
- pair = self.accept()
- if pair is not None:
- sock, addr = pair
- print('[lpd] Incoming connection from %s' % repr(addr))
- LpdHandler(sock, addr, self.lpd_controller)
- except socket.error:
- print('[lpd] warning: server accept() threw an exception')
def jobPrinter(queue, local, remote, control, data):
print(' %s' % queue)
@@ -142,8 +185,10 @@ def defaultPort():
# rather than run as root, use iptables nat to redirect to a common service port:
# iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
# iptables -t nat -I OUTPUT -p tcp -d 127.0.0.1 --dport 80 -j REDIRECT --to-ports 8080
- s = LpdServer(jobPrinter, ip='localhost', port=defaultPort())
+ async def main():
+ await LpdServer(jobPrinter, ip='localhost', port=defaultPort()).start()
+ await asyncio.Event().wait()
try:
- asyncore.loop(timeout=2)
+ asyncio.run(main())
except KeyboardInterrupt:
print('Crtl+C pressed. Shutting down.')
diff --git a/main.py b/main.py
index ee9210d..ae5d331 100755
--- a/main.py
+++ b/main.py
@@ -4,10 +4,10 @@
from mako.lookup import TemplateLookup
from mako import exceptions
-import asynchat, asyncore, socket, os, re
+import asyncio, os, re, signal
from datetime import datetime
from lpdserver import LpdServer
-from httpserver import ToyHttpServer, Redirect
+from httpserver import HttpServer, Redirect
import mailer
from mailer import JobMailer
from docparser import DocParser
@@ -628,6 +628,35 @@ def htmlcol(rgb):
'/email_body':email_body
}
+async def serve():
+ """Run the LPD receiver and the web server on one event loop until interrupted."""
+ lpd = await LpdServer(saveJob, ip='', port=int(config.get('Main', 'lpd_port'))).start()
+ http = await HttpServer(path_handlers, web_dir, port=int(config.get('Main', 'http_port'))).start()
+ stopping = asyncio.Event()
+ for sig in (signal.SIGINT, signal.SIGTERM):
+ try:
+ asyncio.get_running_loop().add_signal_handler(sig, stopping.set)
+ except NotImplementedError:
+ pass # windows: Ctrl+C is raised as KeyboardInterrupt instead
+ try:
+ while not stopping.is_set():
+ try:
+ await asyncio.wait_for(stopping.wait(), 10)
+ except asyncio.TimeoutError:
+ pass
+ print('[control] poll %s' % str(datetime.now()))
+ printing.printlog.flush()
+ sys.stdout.flush()
+ print("Shutting down.")
+ except BaseException as e:
+ print("Terminating: Unexpected error: %s" % repr(e))
+ sys.stdout.flush()
+ raise
+ finally:
+ printing.printlog.flush()
+ await lpd.close()
+ await http.close()
+
if __name__=="__main__":
# launch the server on the specified port
for x in [jobdir, pdfdir]:
@@ -635,20 +664,7 @@ def htmlcol(rgb):
recover()
- s = LpdServer(saveJob, ip='', port=int(config.get('Main', 'lpd_port')))
- ToyHttpServer(port=int(config.get('Main', 'http_port')), pathhandlers=path_handlers, webroot=web_dir)
try:
- while True:
- asyncore.loop(timeout=1, count=10)
- print('[control] poll %s' % str(datetime.now()))
- printing.printlog.flush()
- sys.stdout.flush()
-
+ asyncio.run(serve())
except KeyboardInterrupt:
print("Crtl+C pressed. Shutting down.")
- printing.printlog.flush()
- except:
- print("Terminating: Unexpected error: %s" % sys.exc_info()[0])
- sys.stdout.flush()
- raise
-
diff --git a/requirements.txt b/requirements.txt
index ce372f6..fcebe51 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -2,4 +2,5 @@ Mako>=1.2.2
MarkupSafe>=2.0
reportlab>=4.0,<6
pillow>=9.0
+aiohttp>=3.9,<4
pytz>=2023.3
diff --git a/test_integration.py b/test_integration.py
index c245b70..389cced 100644
--- a/test_integration.py
+++ b/test_integration.py
@@ -1,6 +1,6 @@
# End to end tests: a real RFC 1179 client -> LpdServer -> main.saveJob -> parse -> PDF, then read back
# over HTTP. Runs against a throwaway PRINTERFACE_HOME, never ~/printerface.
-import asyncore
+import asyncio
import http.client
import io
import re
@@ -24,7 +24,7 @@
import emailtemplates
from stationary import DocFormatter
from lpdserver import LpdServer
-from httpserver import ToyHttpServer
+from httpserver import HttpServer
from textutil import split_lines
def put(lines, row, col, text):
@@ -73,13 +73,24 @@ def mailer_results():
return main.mailqueue.results
class ServerThread(threading.Thread):
+ """An event loop in a thread, so that the servers run as they do in main.py (handlers and the LPD receiver
+ on one loop thread) while the tests, in this thread, are their clients."""
def __init__(self):
threading.Thread.__init__(self)
self.daemon = True
- self.running = True
+ self.loop = asyncio.new_event_loop()
+
def run(self):
- while self.running:
- asyncore.loop(timeout=0.05, count=1)
+ asyncio.set_event_loop(self.loop)
+ self.loop.run_forever()
+
+ def call(self, coro):
+ return asyncio.run_coroutine_threadsafe(coro, self.loop).result(30)
+
+ def stop(self):
+ self.loop.call_soon_threadsafe(self.loop.stop)
+ self.join()
+ self.loop.close()
class TestPrinterface(unittest.TestCase):
@classmethod
@@ -103,19 +114,18 @@ def setUpClass(cls):
# likewise the Printers page: lpstat is only ever the canned text, never the machine's own CUPS
cls.lpstat_patch = mock.patch.object(printstatus, 'run_lpstat', return_value=printstatus.SAMPLE)
cls.lpstat_patch.start()
- cls.lpd = LpdServer(main.saveJob, ip='127.0.0.1', port=0)
- cls.http = ToyHttpServer(ip='127.0.0.1', port=0, pathhandlers=main.path_handlers, webroot=main.web_dir)
- cls.lpd_port = cls.lpd.socket.getsockname()[1]
- cls.http_port = cls.http.socket.getsockname()[1]
cls.thread = ServerThread()
cls.thread.start()
+ cls.lpd = cls.thread.call(LpdServer(main.saveJob, ip='127.0.0.1', port=0).start())
+ cls.http = cls.thread.call(HttpServer(main.path_handlers, main.web_dir, ip='127.0.0.1', port=0).start())
+ cls.lpd_port = cls.lpd.port
+ cls.http_port = cls.http.port
@classmethod
def tearDownClass(cls):
- cls.thread.running = False
- cls.thread.join()
- cls.lpd.close()
- cls.http.close()
+ cls.thread.call(cls.lpd.close())
+ cls.thread.call(cls.http.close())
+ cls.thread.stop()
cls.print_patch.stop()
cls.lpstat_patch.stop()
printing.printlog = cls.old_printlog
diff --git a/test_servers.py b/test_servers.py
new file mode 100644
index 0000000..b3c602e
--- /dev/null
+++ b/test_servers.py
@@ -0,0 +1,250 @@
+# The LPD receiver and the web server on their own, without main.py: protocol behaviour that the end to end
+# tests in test_integration.py take for granted.
+import asyncio
+import http.client
+import os
+import socket
+import tempfile
+import threading
+import unittest
+
+from httpserver import HttpServer, Redirect
+from lpdserver import LpdServer
+
+
+class LoopThread(object):
+ def __init__(self):
+ self.loop = asyncio.new_event_loop()
+ self.thread = threading.Thread(target=lambda: (asyncio.set_event_loop(self.loop), self.loop.run_forever()), daemon=True)
+ self.thread.start()
+
+ def call(self, coro):
+ return asyncio.run_coroutine_threadsafe(coro, self.loop).result(10)
+
+ def stop(self):
+ self.loop.call_soon_threadsafe(self.loop.stop)
+ self.thread.join()
+ self.loop.close()
+
+
+class TestLpd(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.loop = LoopThread()
+ cls.received = []
+ cls.controller_fails = False
+
+ def controller(queue, peer, local, control, data):
+ if cls.controller_fails:
+ raise RuntimeError('boom')
+ cls.received.append((queue, control, data))
+ cls.server = cls.loop.call(LpdServer(controller, ip='127.0.0.1', port=0).start())
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.loop.call(cls.server.close())
+ cls.loop.stop()
+
+ def setUp(self):
+ del self.received[:]
+ type(self).controller_fails = False
+
+ def connect(self):
+ s = socket.create_connection(('127.0.0.1', self.server.port), timeout=5)
+ self.addCleanup(s.close)
+ return s
+
+ def ack(self, s):
+ self.assertEqual(b'\x00', s.recv(1), 'no ack')
+
+ def to_data_file(self, s, queue=b'q', control=b'Hhost\nPuser\n', size=None, size_of=None):
+ s.sendall(b'\x02' + queue + b'\n'); self.ack(s)
+ s.sendall(b'\x02%d cfA001host\n' % len(control)); self.ack(s)
+ s.sendall(control + b'\x00'); self.ack(s)
+
+ def wait_for(self, n):
+ for _ in range(100):
+ if len(self.received) >= n:
+ return
+ threading.Event().wait(0.02)
+ self.fail('job not received')
+
+ def test_well_formed_job_keeps_its_trailing_null(self):
+ s = self.connect()
+ self.to_data_file(s)
+ s.sendall(b'\x03%d dfA001host\n' % 6); self.ack(s)
+ s.sendall(b'hello\n\x00'); self.ack(s)
+ self.assertEqual(b'', s.recv(1)) # the server closes after the data file
+ self.wait_for(1)
+ self.assertEqual([('q', {'H': 'host', 'P': 'user'}, 'hello\n\x00')], self.received)
+
+ def test_sender_that_closes_to_mark_the_end(self):
+ s = self.connect()
+ self.to_data_file(s)
+ s.sendall(b'\x03%d dfA001host\n' % 0x7fffffff); self.ack(s)
+ s.sendall(b'caf\xe9 \x0c\n')
+ s.shutdown(socket.SHUT_WR)
+ self.assertEqual(b'\x00', s.recv(1))
+ self.wait_for(1)
+ self.assertEqual('caf\xe9 \x0c\n', self.received[0][2]) # one byte, one character
+
+ def test_sender_that_vanishes_after_the_data_still_gets_its_job_kept(self):
+ s = self.connect()
+ self.to_data_file(s)
+ s.sendall(b'\x03%d dfA001host\n' % 0x7fffffff); self.ack(s)
+ s.sendall(b'abc')
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, b'\x01\x00\x00\x00\x00\x00\x00\x00') # RST on close
+ s.close()
+ self.wait_for(1)
+ self.assertEqual('abc', self.received[0][2])
+
+ def test_a_job_cut_off_before_its_data_is_dropped(self):
+ s = self.connect()
+ self.to_data_file(s)
+ s.close()
+ threading.Event().wait(0.3)
+ self.assertEqual([], self.received)
+
+ def test_a_failing_controller_does_not_stop_the_server(self):
+ type(self).controller_fails = True
+ s = self.connect()
+ self.to_data_file(s)
+ s.sendall(b'\x03%d dfA001host\n' % 1); self.ack(s)
+ s.sendall(b'x\x00'); self.ack(s)
+ self.assertEqual(b'', s.recv(1))
+ type(self).controller_fails = False
+ s = self.connect()
+ self.to_data_file(s)
+ s.sendall(b'\x03%d dfA001host\n' % 1); self.ack(s)
+ s.sendall(b'y\x00'); self.ack(s)
+ self.wait_for(1)
+ self.assertEqual('y\x00', self.received[0][2])
+
+ def test_unknown_commands_are_ignored(self):
+ s = self.connect()
+ s.sendall(b'\x09nonsense\n') # not acknowledged, and not fatal
+ self.to_data_file(s)
+ s.sendall(b'\x07what\n') # an unknown subcommand between files
+ s.sendall(b'\x03%d dfA001host\n' % 1); self.ack(s)
+ s.sendall(b'z\x00'); self.ack(s)
+ self.wait_for(1)
+
+ def test_two_senders_at_once(self):
+ a, b = self.connect(), self.connect()
+ self.to_data_file(a, queue=b'A')
+ self.to_data_file(b, queue=b'B')
+ for s, text in ((b, b'bb\x00'), (a, b'aa\x00')):
+ s.sendall(b'\x03%d dfA001host\n' % 2); self.ack(s)
+ s.sendall(text); self.ack(s)
+ self.wait_for(2)
+ self.assertEqual({('A', 'aa\x00'), ('B', 'bb\x00')}, {(q, d) for q, c, d in self.received})
+
+
+class TestHttp(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.webroot = tempfile.mkdtemp(prefix='printerface-web-')
+ cls.addClassCleanup(lambda: __import__('shutil').rmtree(cls.webroot, ignore_errors=True))
+ os.makedirs(os.path.join(cls.webroot, 'css'))
+ os.makedirs(os.path.join(cls.webroot, 'withindex'))
+ with open(os.path.join(cls.webroot, 'css', 'x.css'), 'wb') as f:
+ f.write(b'body { color: red }\n')
+ with open(os.path.join(cls.webroot, 'withindex', 'index.html'), 'wb') as f:
+ f.write(b'index
')
+ with open(os.path.join(os.path.dirname(cls.webroot), 'outside.txt'), 'wb') as f:
+ f.write(b'secret')
+ cls.addClassCleanup(lambda: os.remove(os.path.join(os.path.dirname(cls.webroot), 'outside.txt')))
+ cls.seen = {}
+
+ def echo(query_string=None, resp=None, postreq=None):
+ cls.seen = dict(query=query_string, post=postreq)
+ if postreq is not None:
+ return Redirect('/echo?done=1')
+ resp.add_header('X-Extra', 'yes')
+ return ('caf\xe9 %s' % query_string, 'text/plain')
+
+ def broken(query_string=None, resp=None, postreq=None):
+ raise RuntimeError('boom')
+
+ def blob(query_string=None, resp=None):
+ import io
+ return (io.BytesIO(b'%PDF-1.4 data'), 'application/pdf')
+
+ cls.loop = LoopThread()
+ cls.server = cls.loop.call(HttpServer({'/echo': echo, '/broken': broken, '/blob': blob}, cls.webroot, ip='127.0.0.1', port=0).start())
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.loop.call(cls.server.close())
+ cls.loop.stop()
+
+ def request(self, method, path, body=None, headers=None):
+ conn = http.client.HTTPConnection('127.0.0.1', self.server.port, timeout=5)
+ conn.request(method, path, body=body, headers=headers or {})
+ r = conn.getresponse()
+ data = r.read()
+ conn.close()
+ return r, data
+
+ def test_handler_get_with_query_string_and_extra_header(self):
+ r, body = self.request('GET', '/echo?a=1&a=2&b=x%20y&empty=')
+ self.assertEqual(200, r.status)
+ self.assertEqual({'a': ['1', '2'], 'b': ['x y']}, self.seen['query']) # blank values are dropped, as before
+ self.assertEqual('yes', r.getheader('X-Extra'))
+ self.assertEqual('text/plain; charset=utf-8', r.getheader('Content-Type'))
+ self.assertEqual('caf\xe9', body.decode().split()[0])
+ self.assertEqual(str(len(body)), r.getheader('Content-Length'))
+
+ def test_head_has_the_headers_but_no_body(self):
+ r, body = self.request('HEAD', '/echo')
+ self.assertEqual((200, b''), (r.status, body))
+ self.assertTrue(int(r.getheader('Content-Length')) > 0)
+
+ def test_post_form_fields_and_redirect(self):
+ r, body = self.request('POST', '/echo?from=url', 'name=a+b&name=c&empty=',
+ {'Content-Type': 'application/x-www-form-urlencoded'})
+ self.assertEqual(303, r.status)
+ self.assertEqual('/echo?done=1', r.getheader('Location'))
+ self.assertEqual({'name': ['a b', 'c'], 'empty': ['']}, self.seen['post'])
+ self.assertEqual({'from': ['url']}, self.seen['query'])
+
+ def test_file_object_bodies(self):
+ r, body = self.request('GET', '/blob')
+ self.assertEqual((200, b'%PDF-1.4 data', 'application/pdf'), (r.status, body, r.getheader('Content-Type')))
+
+ def test_a_failing_handler_is_a_500_and_the_server_carries_on(self):
+ self.assertEqual(500, self.request('GET', '/broken')[0].status)
+ self.assertEqual(500, self.request('POST', '/broken', 'a=1')[0].status)
+ self.assertEqual(200, self.request('GET', '/echo')[0].status)
+
+ def test_unknown_paths_and_methods(self):
+ self.assertEqual(404, self.request('GET', '/nothing')[0].status)
+ self.assertEqual(404, self.request('POST', '/nothing', 'a=1')[0].status)
+ self.assertEqual(501, self.request('DELETE', '/echo')[0].status)
+
+ def test_static_files(self):
+ r, body = self.request('GET', '/css/x.css')
+ self.assertEqual((200, b'body { color: red }\n', 'text/css'), (r.status, body, r.getheader('Content-Type')))
+ self.assertIsNotNone(r.getheader('Last-Modified'))
+ self.assertEqual(b'index
', self.request('GET', '/withindex/')[1])
+ r, _ = self.request('GET', '/withindex')
+ self.assertEqual((301, '/withindex/'), (r.status, r.getheader('Location')))
+ self.assertEqual(404, self.request('GET', '/css/')[0].status) # no directory listings
+
+ def test_static_files_cannot_leave_the_web_root(self):
+ for path in ('/../outside.txt', '/css/../../outside.txt', '/%2e%2e/outside.txt', '/..%2foutside.txt'):
+ r, body = self.request('GET', path)
+ self.assertNotEqual(b'secret', body, path)
+
+ def test_keep_alive_serves_several_requests_on_one_connection(self):
+ conn = http.client.HTTPConnection('127.0.0.1', self.server.port, timeout=5)
+ for _ in range(3):
+ conn.request('GET', '/echo')
+ r = conn.getresponse()
+ r.read()
+ self.assertEqual(200, r.status)
+ conn.close()
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tools/replay_corpus.py b/tools/replay_corpus.py
index fa266cd..f9bb94a 100755
--- a/tools/replay_corpus.py
+++ b/tools/replay_corpus.py
@@ -8,7 +8,7 @@
side is a recording callback rather than main.saveJob.
"""
import argparse
-import asyncore
+import asyncio
import os
import sys
import threading
@@ -23,13 +23,12 @@
args = ap.parse_args()
received = []
-server = LpdServer(lambda queue, local, remote, control, data: received.append((queue, control, data)), ip='127.0.0.1', port=0)
-port = server.socket.getsockname()[1]
-running = True
-def loop():
- while running:
- asyncore.loop(timeout=0.02, count=1)
-threading.Thread(target=loop, daemon=True).start()
+loop = asyncio.new_event_loop()
+threading.Thread(target=lambda: (asyncio.set_event_loop(loop), loop.run_forever()), daemon=True).start()
+server = asyncio.run_coroutine_threadsafe(
+ LpdServer(lambda queue, local, remote, control, data: received.append((queue, control, data)), ip='127.0.0.1', port=0).start(),
+ loop).result(10)
+port = server.port
import socket
def send(queue, control, data, eof_by_close=False):
@@ -86,6 +85,5 @@ def ack():
if rdata != j['data'] or rcontrol != j['control'] or queue != j.get('queue', 'RAW'):
bad += 1; print('MISMATCH', name, len(rdata), len(j['data']), rcontrol == j['control'])
-running = False
print('replayed=%d (%.1f MiB): sized transfers=%d, eof-by-close transfers=%d, mismatches=%d' % (sent, sizes / 1048576.0, nul_terminated, sent - nul_terminated, bad))
sys.exit(1 if bad else 0)
From fbd18167770e1187d25868555e0e54bc32aed838 Mon Sep 17 00:00:00 2001
From: Chris Shucksmith
Date: Fri, 20 Nov 2026 11:09:14 +0000
Subject: [PATCH 2/8] Send queued mail from the event loop, with smtplib in a
worker thread
The mail queue is an asyncio.Queue worked by a task on the loop, and the blocking smtplib
call runs through asyncio.to_thread. The results list and its pickle are now only touched
on the loop, so there is no thread sharing them. Queueing no longer blocks the web server
if the queue is full: it raises, and the send form already reports "unable to queue
email". Shutdown waits up to 30 seconds for queued mail to go.
Co-Authored-By: Claude Sonnet 5.5
Claude-Session: https://claude.ai/code/session_01DKcyxWnp9B7ZMfow73wHmP
---
README.md | 2 +-
mailer.py | 215 +++++++++++++++++++++++++++++++++++++++++++-----------
main.py | 2 +
3 files changed, 174 insertions(+), 45 deletions(-)
diff --git a/README.md b/README.md
index e94b3ea..1a8b2dd 100644
--- a/README.md
+++ b/README.md
@@ -35,7 +35,7 @@ template are POSTs, and their handlers return `httpserver.Redirect(...)` (a 303)
carrying at most a harmless note in the query string ("queued=1"). A POST that is refused re-renders the form
instead, with what was typed. New actions should follow the same pattern.
-Requires **python 3.11** or later. The LPD receiver and the web server share one asyncio event loop (so the job list needs no locking); mail is sent from a thread of its own.
+Requires **python 3.11** or later. The LPD receiver and the web server share one asyncio event loop (so the job list needs no locking); mail is queued on the loop and sent with smtplib in a worker thread.
Requirements are specified in requirements.txt
Unit tests run during `docker build` or with:
diff --git a/mailer.py b/mailer.py
index bcdd8c4..537cfa1 100644
--- a/mailer.py
+++ b/mailer.py
@@ -1,6 +1,6 @@
#
-# Asynchronous mail sender to Gmail, using a seperate thread.
-# Keeps the last 10 results around if you want to check results
+# Mail sender to Gmail: a queue worked by the event loop, with the blocking smtplib calls in a worker thread.
+# Keeps the last result_count results around if you want to check results
# Import smtplib for the actual sending function
import smtplib
@@ -13,8 +13,8 @@
# http://stackoverflow.com/questions/3362600/how-to-send-email-attachments-with-python
import datetime
-import os, re, threading
-import queue
+import asyncio
+import os, re
import traceback
import pickle
@@ -42,10 +42,17 @@ def sent_from_job(results, job_name):
return out
class JobMailer(object):
+ """Sends queued emails one at a time, in the order they were queued, and keeps the outcome of the last
+ `result_count` of them (newest first) in mailer.pickle.
+
+ The sending itself, smtplib, blocks, so it runs in a worker thread (asyncio.to_thread) while the event loop
+ carries on serving; everything else, the queue and the results list, is only touched on the loop. `append`
+ is called from page handlers and `start` / `close` from main.serve."""
def __init__(self, queuesz=10):
- self.queue = queue.Queue(queuesz)
+ self.queue = asyncio.Queue(queuesz)
self.results = []
+ self.task = None
self.resultLimit = config.getint('Gmail', 'result_count')
try:
@@ -59,47 +66,58 @@ def __init__(self, queuesz=10):
while len(self.results) > self.resultLimit:
self.results.pop()
- self.thread = threading.Thread(target=self.run)
- self.thread.daemon = True
- self.thread.start()
+ def start(self):
+ """Begin sending. Needs the running event loop."""
+ self.task = asyncio.get_running_loop().create_task(self.run())
+
+ async def close(self, timeout=30):
+ """Stop after sending what is already queued, for up to `timeout` seconds."""
+ if self.task:
+ try:
+ await asyncio.wait_for(self.queue.join(), timeout)
+ except asyncio.TimeoutError:
+ print('mailq: %d emails still queued at shutdown' % self.queue.qsize())
+ self.task.cancel()
+ self.task = None
def append(self, job):
+ """Queue an email. Raises asyncio.QueueFull if too many are waiting."""
job['added'] = datetime.datetime.now()
job['completed']=None
job['status']=None
- self.queue.put( job )
+ self.queue.put_nowait( job )
- def run(self):
+ def send(self, work):
+ """Send one queued email (blocking: runs in a worker thread) and record the outcome on it."""
+ try:
+ filename = os.path.basename(work['attachment'])
+ with open(os.path.expanduser(work['attachment']), 'rb') as fileobj:
+ self.sendJobAttachment(work['body'], fileobj, filename, work['subject'], work['to'])
+ work['completed'] = datetime.datetime.now()
+ work['error'] = None
+ except Exception as e:
+ print('mailq: failed to send email: ' + repr(e))
+ work['completed'] = datetime.datetime.now()
+ work['error'] = repr(e)
+
+ async def run(self):
print("mailq: run is called")
while True:
+ work = await self.queue.get()
try:
- work = self.queue.get(block=True, timeout=60)
print('mailq: Got work ' + repr(work))
-
- try:
- filename = os.path.basename(work['attachment'])
- with open(os.path.expanduser(work['attachment']), 'rb') as fileobj:
-
- x = self.sendJobAttachment(work['body'], fileobj, filename, work['subject'], work['to'])
-
- work['completed'] = datetime.datetime.now()
- work['error'] = None
-
- except Exception as e:
- print('mailq: failed to send email: ' + repr(e))
-
- work['completed'] = datetime.datetime.now()
- work['error'] = repr(e)
-
+ await asyncio.to_thread(self.send, work)
print('mailq: finished ' + repr(work))
self.results.insert(0, work)
if len(self.results) > self.resultLimit:
self.results.pop()
-
self.pickleResults()
-
- except queue.Empty:
- print('mailq: idling for jobs')
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ traceback.print_exc()
+ finally:
+ self.queue.task_done()
def pickleResults(self):
try:
@@ -159,21 +177,130 @@ def test_sent_from_job(self):
self.assertEqual([('newest', 'B'), ('a', 'A')], [(r['subject'], key) for r, key in found])
self.assertEqual([], sent_from_job(results, 'job-20000101-000000'))
-if __name__=="__main__":
-
- import time
- mailq = JobMailer(100)
+class TestJobMailer(unittest.TestCase):
+ def setUp(self):
+ import tempfile
+ global pickle_file
+ self.dir = tempfile.TemporaryDirectory()
+ self.addCleanup(self.dir.cleanup)
+ old, pickle_file = pickle_file, os.path.join(self.dir.name, 'mailer.pickle')
+ self.addCleanup(lambda: globals().update(pickle_file=old))
+
+ def mailer(self, size=10, limit=3, sender=None):
+ m = JobMailer(size)
+ m.resultLimit = limit
+ self.sent = []
+ def fake(text, fileobj, filename, subject, email_to):
+ if sender:
+ sender(subject)
+ self.sent.append((subject, filename, fileobj.read(), list(email_to)))
+ m.sendJobAttachment = fake
+ return m
+
+ def attachment(self, name='a.pdf', data=b'%PDF'):
+ path = os.path.join(self.dir.name, name)
+ with open(path, 'wb') as f:
+ f.write(data)
+ return path
+
+ def job(self, subject, **kw):
+ return dict(to=['x@example.com'], body='b', subject=subject, attachment=kw.get('attachment') or self.attachment())
+
+ def test_sends_in_order_records_newest_first_and_persists(self):
+ async def go():
+ m = self.mailer()
+ m.start()
+ for n in 'abc':
+ m.append(self.job(n))
+ await m.close()
+ return m
+ m = asyncio.run(go())
+ self.assertEqual(['a', 'b', 'c'], [x[0] for x in self.sent])
+ self.assertEqual(('a.pdf', b'%PDF', ['x@example.com']), self.sent[0][1:])
+ self.assertEqual(['c', 'b', 'a'], [r['subject'] for r in m.results])
+ self.assertTrue(all(r['error'] is None and r['completed'] for r in m.results))
+ with open(pickle_file, 'rb') as f:
+ self.assertEqual(['c', 'b', 'a'], [r['subject'] for r in pickle.load(f)])
+
+ def test_a_failure_is_recorded_and_the_next_still_goes(self):
+ def sender(subject):
+ if subject == 'bad':
+ raise RuntimeError('smtp down')
+ async def go():
+ m = self.mailer(sender=sender)
+ m.start()
+ m.append(self.job('bad'))
+ m.append(self.job('good'))
+ m.append(dict(self.job('gone'), attachment=os.path.join(self.dir.name, 'missing.pdf')))
+ await m.close()
+ return m
+ m = asyncio.run(go())
+ by = {r['subject']: r['error'] for r in m.results}
+ self.assertIn('smtp down', by['bad'])
+ self.assertIsNone(by['good'])
+ self.assertIn('FileNotFoundError', by['gone'])
+
+ def test_keeps_only_the_newest_results(self):
+ async def go():
+ m = self.mailer(limit=2)
+ m.start()
+ for n in '1234':
+ m.append(self.job(n))
+ await m.close()
+ return m
+ self.assertEqual(['4', '3'], [r['subject'] for r in asyncio.run(go()).results])
+
+ def test_sending_does_not_block_the_event_loop(self):
+ import threading
+ gate = threading.Event()
+ async def go():
+ m = self.mailer(sender=lambda subject: gate.wait(5))
+ m.start()
+ m.append(self.job('slow'))
+ await asyncio.sleep(0.1) # the worker thread is now stuck inside "smtplib"
+ ticks = 0
+ for _ in range(5):
+ await asyncio.sleep(0.01)
+ ticks += 1
+ gate.set()
+ await m.close()
+ return ticks, m
+ ticks, m = asyncio.run(go())
+ self.assertEqual(5, ticks)
+ self.assertEqual(['slow'], [r['subject'] for r in m.results])
+
+ def test_too_many_queued_is_an_error_not_a_stall(self):
+ async def go():
+ m = self.mailer(size=2)
+ m.append(self.job('1'))
+ m.append(self.job('2'))
+ with self.assertRaises(asyncio.QueueFull):
+ m.append(self.job('3'))
+ asyncio.run(go())
+
+ def test_results_survive_a_restart_and_a_smaller_limit_trims(self):
+ async def go():
+ m = self.mailer(limit=5)
+ m.start()
+ for n in '123':
+ m.append(self.job(n))
+ await m.close()
+ asyncio.run(go())
+ async def again():
+ return JobMailer(10)
+ m = asyncio.run(again())
+ self.assertEqual(['3', '2', '1'], [r['subject'] for r in m.results])
- for i in range(60):
- time.sleep(1)
- if i == 5:
- mailq.append(dict(
- to=['chris@shucksmith.co.uk'], body='body text here', subject='Statement for XX',
- attachment="~/repos/printerface/web/pdf/job-20130404-145700%f-accounts.pdf"))
+if __name__=="__main__":
+ async def demo():
+ mailq = JobMailer(100)
+ mailq.start()
+ mailq.append(dict(
+ to=['chris@shucksmith.co.uk'], body='body text here', subject='Statement for XX',
+ attachment="~/repos/printerface/web/pdf/job-20130404-145700%f-accounts.pdf"))
+ await mailq.close()
print(mailq.results)
- print('done')
-
-
+ asyncio.run(demo())
diff --git a/main.py b/main.py
index ae5d331..7fcd7ce 100755
--- a/main.py
+++ b/main.py
@@ -630,6 +630,7 @@ def htmlcol(rgb):
async def serve():
"""Run the LPD receiver and the web server on one event loop until interrupted."""
+ mailqueue.start()
lpd = await LpdServer(saveJob, ip='', port=int(config.get('Main', 'lpd_port'))).start()
http = await HttpServer(path_handlers, web_dir, port=int(config.get('Main', 'http_port'))).start()
stopping = asyncio.Event()
@@ -656,6 +657,7 @@ async def serve():
printing.printlog.flush()
await lpd.close()
await http.close()
+ await mailqueue.close()
if __name__=="__main__":
# launch the server on the specified port
From b2a6ae7c59d655f7467f95dd55ccf88518f69565 Mon Sep 17 00:00:00 2001
From: Chris Shucksmith
Date: Fri, 20 Nov 2026 22:41:51 +0000
Subject: [PATCH 3/8] Upload invoices, credit notes and statements to the
website
webupload.py turns a parsed job into the website's JSON, one document per
invoice, credit note or statement, and cuts the account PDF into a PDF per
document (a document can span pages). uploader.py queues them on the event
loop, posts each as multipart with the API token in a worker thread, retries
network failures and 5xx, and records the outcome in upload.pickle. The job
page gets an "Upload to website" button when [Web] base_url and api_key are
set, an "Uploaded from this job" table, and the home page counts failures.
Co-Authored-By: Claude Sonnet 5.5
Claude-Session: https://claude.ai/code/session_01DKcyxWnp9B7ZMfow73wHmP
---
defaults.cfg | 6 ++
main.py | 37 ++++++++++-
requirements.txt | 1 +
test_integration.py | 44 +++++++++++-
test_uploader.py | 141 +++++++++++++++++++++++++++++++++++++++
test_webupload.py | 158 ++++++++++++++++++++++++++++++++++++++++++++
uploader.py | 148 +++++++++++++++++++++++++++++++++++++++++
web/home.html | 4 ++
web/pdf.html | 26 ++++++++
webupload.py | 158 ++++++++++++++++++++++++++++++++++++++++++++
10 files changed, 719 insertions(+), 4 deletions(-)
create mode 100644 test_uploader.py
create mode 100644 test_webupload.py
create mode 100644 uploader.py
create mode 100644 webupload.py
diff --git a/defaults.cfg b/defaults.cfg
index 0057a81..56ca5ac 100644
--- a/defaults.cfg
+++ b/defaults.cfg
@@ -25,6 +25,12 @@ http_port=8081
baseuri=localhost:8081
tz=Europe/London
+# Where invoices, credit notes and statements are uploaded as they are printed. Blank turns it off.
+# base_url is the site, e.g. https://abfw-stage.herokuapp.com/ ; api_key is that site's token for the Printerface user.
+[Web]
+base_url=
+api_key=
+
[Robot]
auto_types=Delvnote,Pick lst
auto_printer=HP_TONY
diff --git a/main.py b/main.py
index 7fcd7ce..7066a59 100755
--- a/main.py
+++ b/main.py
@@ -15,6 +15,8 @@
from printing import getPrinters, printFile
import printing
import printstatus
+import uploader
+import webupload
import sys, pickle
import html
@@ -40,6 +42,7 @@
web_dir = os.path.join(base_dir, 'web')
jobs = []
mailqueue = JobMailer(100)
+uploadqueue = uploader.WebUploader()
# seed some 'system' accounts
email_accounts = { 'accounts': 'Accounts', 'plain': 'printerface', 'transport': 'Transport'}
@@ -228,8 +231,9 @@ def identify(j):
def home(query_string='', resp=None):
email_fails = sum([1 for x in mailqueue.results if x['error']])
+ upload_fails = sum([1 for x in uploadqueue.log.records if x['error']]) if uploader.enabled() else None
account = sum([ 1 for k in email_accounts if len(email_addresses[k]) > 0 ]), len(email_accounts.keys())
- return template_lookup.get_template("/home.html").render(email_fails=email_fails, account=account), 'text/html'
+ return template_lookup.get_template("/home.html").render(email_fails=email_fails, upload_fails=upload_fails, account=account), 'text/html'
def getrows_byslice(seq, rowlen):
for start in range(0, len(seq), rowlen):
@@ -467,13 +471,33 @@ def pdf(query_string=dict(), postreq=None, resp=None):
else:
email_error = "Oh snap! Some fields missing or incomplete!"
typed = dict(subject=email_subject, body=email_body, ticked=addresses)
+ elif postreq is not None and params.get('action', [''])[0] == 'upload':
+ try:
+ if not uploader.enabled():
+ raise webupload.UploadError('Uploading to the website is not set up: see [Web] in email.cfg')
+ items = uploader.prepare(job, key, pdfdir)
+ if not items:
+ raise webupload.UploadError('There is nothing to upload for %s' % key)
+ for item in items:
+ uploadqueue.append(item)
+ return Redirect('/pdf?' + urllib.parse.urlencode({'name': job['name'], 'key': key, 'uploading': len(items)}))
+ except Exception as e:
+ if not isinstance(e, webupload.UploadError):
+ traceback.print_exc(file=sys.stdout)
+ email_error = 'Not uploaded. %s' % html.escape(str(e) or 'The upload queue is full.')
elif postreq is None:
# a redirect from a send or a print lands here; the note only says what happened
try:
queued = int(query_string.get('queued', ['0'])[0])
except ValueError:
queued = 0
- if queued:
+ try:
+ uploading = int(query_string.get('uploading', ['0'])[0])
+ except ValueError:
+ uploading = 0
+ if uploading:
+ email_outcome = 'Queued %d document%s for the website. %s listed under "Uploaded from this job" once done.' % (uploading, '' if uploading == 1 else 's', 'It is' if uploading == 1 else 'They are')
+ elif queued:
email_outcome = 'Queued the email to %d recipient%s. It is listed under "Sent from this job" once it has gone.' % (queued, '' if queued == 1 else 's')
elif query_string.get('printed'):
email_outcome = 'Sent the document to printer %s.' % html.escape(query_string['printed'][0])
@@ -495,6 +519,9 @@ def pdf(query_string=dict(), postreq=None, resp=None):
sent_from_this_job = mailer.sent_from_job(mailqueue.results, job['name'])
# and what was sent to a printer from it, with the CUPS request ids
printed_from_this_job = printing.printlog.for_job(job['name'])
+ # and what was uploaded to the website
+ uploaded_from_this_job = uploadqueue.log.for_job(job['name'])
+ can_upload = uploader.enabled() and job.get('templ') in ('invoice', 'crednote', 'statement')
# what the editor's preview filter should be set to so that it shows this document
if template_kind == emailtemplates.DEFAULT:
@@ -505,7 +532,7 @@ def pdf(query_string=dict(), postreq=None, resp=None):
template_docnum = pages[0].get('doc_num', '').strip()
return ( template_lookup.get_template("/pdf.html").render(printers=getPrinters(), job=job, key=key, email_templ=email_body_default, email_subject_default=email_subject_default, ticked=typed['ticked'] if typed else None,
- template_kind=template_kind, template_warning=template_warning, template_docnum=template_docnum, sent_from_this_job=sent_from_this_job, printed_from_this_job=printed_from_this_job,
+ template_kind=template_kind, template_warning=template_warning, template_docnum=template_docnum, sent_from_this_job=sent_from_this_job, printed_from_this_job=printed_from_this_job, uploaded_from_this_job=uploaded_from_this_job, can_upload=can_upload,
email_body_url='/email_body?' + urllib.parse.urlencode({'name': job['name'], 'key': key}),
email_dest=email_dest, email_outcome=email_outcome, email_error=email_error), 'text/html')
@@ -631,6 +658,7 @@ def htmlcol(rgb):
async def serve():
"""Run the LPD receiver and the web server on one event loop until interrupted."""
mailqueue.start()
+ uploadqueue.start()
lpd = await LpdServer(saveJob, ip='', port=int(config.get('Main', 'lpd_port'))).start()
http = await HttpServer(path_handlers, web_dir, port=int(config.get('Main', 'http_port'))).start()
stopping = asyncio.Event()
@@ -647,6 +675,7 @@ async def serve():
pass
print('[control] poll %s' % str(datetime.now()))
printing.printlog.flush()
+ uploadqueue.log.flush()
sys.stdout.flush()
print("Shutting down.")
except BaseException as e:
@@ -655,6 +684,8 @@ async def serve():
raise
finally:
printing.printlog.flush()
+ await uploadqueue.close()
+ uploadqueue.log.flush()
await lpd.close()
await http.close()
await mailqueue.close()
diff --git a/requirements.txt b/requirements.txt
index fcebe51..8c8ccd0 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -4,3 +4,4 @@ reportlab>=4.0,<6
pillow>=9.0
aiohttp>=3.9,<4
pytz>=2023.3
+pypdf>=4,<7
diff --git a/test_integration.py b/test_integration.py
index 389cced..f997ea0 100644
--- a/test_integration.py
+++ b/test_integration.py
@@ -21,6 +21,7 @@
import mailer
import printing
import printstatus
+import uploader
import emailtemplates
from stationary import DocFormatter
from lpdserver import LpdServer
@@ -32,7 +33,7 @@ def put(lines, row, col, text):
line = lines[row + i]
lines[row + i] = line[:col] + part + line[col + len(part):]
-def make_invoice(doc_num='12345', acc='ACC001', pages=2, doc_nums=None, totals=None):
+def make_invoice(doc_num='12345', acc='ACC001', pages=2, doc_nums=None, totals=None, net=None, vat=None):
"""A synthetic Invoice print: 48 blank lines, then 48 lines per page. Each page ends in a form feed,
and the totals carry an 8-bit pound sign as the Windows print driver sends it. By default every page is
part of invoice doc_num; doc_nums gives each page its own invoice (and totals its own amount)."""
@@ -51,6 +52,9 @@ def make_invoice(doc_num='12345', acc='ACC001', pages=2, doc_nums=None, totals=N
put(lines, base + 19, 19, 'BAUCHET Customer Label\nDRAPPIER Carte D\'Or')
put(lines, base + 19, 55, '12\n6')
put(lines, base + 42, 89, totals[p] if totals else '\xa3123.45')
+ if net:
+ put(lines, base + 37, 89, net)
+ put(lines, base + 39, 89, vat)
lines[base + 47] = lines[base + 47][:100] + '\x0c'
return '\r\n'.join(lines) + '\r\n'
@@ -103,6 +107,7 @@ def setUpClass(cls):
main.pdfdir = os.path.join(cls.home, 'data', 'pdf') + os.sep
main.formatter = DocFormatter(main.pdfdir)
mailer.pickle_file = os.path.join(cls.home, 'mailer.pickle')
+ cls.old_uploadlog, main.uploadqueue.log = main.uploadqueue.log, uploader.UploadLog(os.path.join(cls.home, 'upload.pickle'))
cls.old_printlog, printing.printlog = printing.printlog, printing.PrintLog(os.path.join(cls.home, 'printer.pickle'))
cls.old_user_dir, emailtemplates.USER_DIR = emailtemplates.USER_DIR, os.path.join(cls.home, 'templates')
for x in [main.jobdir, main.pdfdir]:
@@ -129,6 +134,7 @@ def tearDownClass(cls):
cls.print_patch.stop()
cls.lpstat_patch.stop()
printing.printlog = cls.old_printlog
+ main.uploadqueue.log = cls.old_uploadlog
emailtemplates.USER_DIR = cls.old_user_dir
shutil.rmtree(cls.home, ignore_errors=True)
@@ -728,6 +734,42 @@ def test_printing_is_a_post_that_redirects(self):
self.assertEqual(200, r.status)
printed.assert_called_once()
+ def test_uploading_to_the_website_is_a_post_that_queues_every_document_in_the_pdf(self):
+ sent = []
+ async def start():
+ main.uploadqueue.transport = lambda item, base, key: (sent.append((item, base, key)) or (201, '{}'))
+ main.uploadqueue.start()
+ j = self.send_invoice(pages=2, doc_nums=['501', '502'], totals=['72.00', '48.00'], net='60.00', vat='12.00')
+ # not configured: no button, and a POST is refused with a reason
+ self.assertNotIn(b'Upload to website', self.get('/pdf?name=%s&key=ACC001' % j['name'])[1])
+ r, body = self.post('/pdf', name=j['name'], key='ACC001', action='upload')
+ self.assertEqual(200, r.status)
+ self.assertIn(b'not set up', body)
+ with mock.patch.object(uploader, 'settings', lambda: ('https://stage.example/', 'tok')):
+ self.thread.call(start())
+ try:
+ self.assertIn(b'Upload to website', self.get('/pdf?name=%s&key=ACC001' % j['name'])[1])
+ r, data = self.post('/pdf', name=j['name'], key='ACC001', action='upload')
+ self.assertEqual(303, r.status)
+ self.assertEqual('/pdf?name=%s&key=ACC001&uploading=2' % j['name'], r.getheader('Location'))
+ deadline = time.time() + 10
+ while len(main.uploadqueue.log.for_job(j['name'])) < 2 and time.time() < deadline:
+ time.sleep(0.05)
+ self.assertEqual(['502', '501'], [rec['docnum'] for rec in main.uploadqueue.log.for_job(j['name'])])
+ self.assertEqual({('https://stage.example/', 'tok')}, {(b, k) for _, b, k in sent})
+ first = json.loads(sent[0][0]['payload'])
+ self.assertEqual(('501', '60.00', '72.00'), (first['docnum'], first['total_net'], first['total_gross']))
+ from pypdf import PdfReader
+ self.assertEqual([1, 1], [len(PdfReader(io.BytesIO(i['pdf'])).pages) for i, _, _ in sent]) # one page each
+ body = self.get('/pdf?name=%s&key=ACC001&uploading=2' % j['name'])[1]
+ self.assertIn(b'Uploaded from this job', body)
+ self.assertIn(b'Queued 2 documents for the website', body)
+ # other types of document have no button
+ d = self.send_invoice(jtype='Delvnote')
+ self.assertNotIn(b'Upload to website', self.get('/pdf?name=%s&key=ACC001' % d['name'])[1])
+ finally:
+ self.thread.call(main.uploadqueue.close())
+
def test_print_history_is_listed_on_the_job_page(self):
j = self.send_invoice()
self.assertNotIn(b'Printed from this job', self.get('/pdf?name=%s&key=ACC001' % j['name'])[1])
diff --git a/test_uploader.py b/test_uploader.py
new file mode 100644
index 0000000..a3c2e8a
--- /dev/null
+++ b/test_uploader.py
@@ -0,0 +1,141 @@
+# The website upload queue: the wire format against a throwaway local server, retry behaviour, and the record kept.
+import asyncio
+import email
+import http.server
+import json
+import tempfile
+import threading
+import unittest
+from unittest import mock
+
+import uploader
+from uploader import WebUploader, UploadLog
+
+
+def item(docnum='100', kind='invoice'):
+ return dict(job='job-20261102-090507', key='ACC1', kind=kind, account='ACC1', docnum=docnum, payload=json.dumps({'docnum': docnum}), pdf=b'%PDF-1.4 x')
+
+
+class FakeSite(http.server.BaseHTTPRequestHandler):
+ replies = [] # (status, body) taken in turn; the last one repeats
+ seen = []
+
+ def do_POST(self):
+ body = self.rfile.read(int(self.headers['Content-Length']))
+ FakeSite.seen.append((self.path, self.headers['Authorization'], self.headers['Content-Type'], body))
+ status, text = FakeSite.replies[min(len(FakeSite.seen), len(FakeSite.replies)) - 1]
+ self.send_response(status)
+ self.send_header('Content-Type', 'application/json')
+ self.end_headers()
+ self.wfile.write(text.encode())
+
+ def log_message(self, *a):
+ pass
+
+
+class TestWire(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.httpd = http.server.HTTPServer(('127.0.0.1', 0), FakeSite)
+ threading.Thread(target=cls.httpd.serve_forever, daemon=True).start()
+ cls.url = 'http://127.0.0.1:%d/' % cls.httpd.server_port
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.httpd.shutdown()
+ cls.httpd.server_close()
+
+ def setUp(self):
+ FakeSite.replies, FakeSite.seen = [(201, '{}')], []
+ self.log = UploadLog(None, limit=5)
+ patch = mock.patch.object(uploader, 'settings', lambda: (self.url, 'secret'))
+ patch.start()
+ self.addCleanup(patch.stop)
+ patch = mock.patch.object(uploader, 'RETRY_DELAYS', (0.01, 0.01))
+ patch.start()
+ self.addCleanup(patch.stop)
+
+ def run_queue(self, *items):
+ async def go():
+ up = WebUploader(log=self.log)
+ up.start()
+ for i in items:
+ up.append(i)
+ await up.close(10)
+ asyncio.run(go())
+
+ def test_request_is_a_multipart_post_with_the_token(self):
+ self.run_queue(item('100'), item('7', 'statement'))
+ (path, auth, ctype, body), (spath, _, _, _) = FakeSite.seen
+ self.assertEqual(('/api/ingest/invoice/', 'Token secret', '/api/ingest/statement/'), (path, auth, spath))
+ msg = email.message_from_bytes(b'Content-Type: ' + ctype.encode() + b'\r\n\r\n' + body)
+ parts = {p.get_param('name', header='content-disposition'): p for p in msg.get_payload()}
+ self.assertEqual({'docnum': '100'}, json.loads(parts['payload'].get_payload(decode=True)))
+ self.assertEqual(b'%PDF-1.4 x', parts['pdf'].get_payload(decode=True))
+
+ def test_created_and_replaced_are_recorded(self):
+ FakeSite.replies = [(201, '{}'), (200, '{}')]
+ self.run_queue(item('1'), item('1'))
+ self.assertEqual(['replaced', 'created'], [r['outcome'] for r in self.log.records]) # newest first
+ self.assertEqual([None, None], [r['error'] for r in self.log.records])
+
+ def test_a_refusal_is_final_and_says_why(self):
+ FakeSite.replies = [(400, '{"date": ["bad"]}')]
+ self.run_queue(item())
+ (rec,) = self.log.records
+ self.assertEqual(('failed', 400), (rec['outcome'], rec['status']))
+ self.assertIn('bad', rec['error'])
+ self.assertEqual(1, len(FakeSite.seen)) # not retried
+ self.assertNotIn('secret', repr(rec))
+
+ def test_a_server_error_is_retried_then_succeeds(self):
+ FakeSite.replies = [(503, ''), (500, ''), (201, '{}')]
+ self.run_queue(item())
+ self.assertEqual(3, len(FakeSite.seen))
+ self.assertEqual('created', self.log.records[0]['outcome'])
+
+ def test_gives_up_after_the_last_retry(self):
+ FakeSite.replies = [(502, '')]
+ self.run_queue(item())
+ self.assertEqual(3, len(FakeSite.seen))
+ self.assertEqual(('failed', 502), (self.log.records[0]['outcome'], self.log.records[0]['status']))
+ self.assertNotIn('', self.log.records[0]['error'])
+
+ def test_an_unreachable_site_is_retried_and_reported(self):
+ with mock.patch.object(uploader, 'settings', lambda: ('http://127.0.0.1:1/', 'secret')):
+ self.run_queue(item())
+ (rec,) = self.log.records
+ self.assertEqual('failed', rec['outcome'])
+ self.assertIn('could not reach', rec['error'])
+
+ def test_the_next_document_goes_after_a_failure(self):
+ FakeSite.replies = [(400, '{}'), (201, '{}')]
+ self.run_queue(item('1'), item('2'))
+ self.assertEqual(['created', 'failed'], [r['outcome'] for r in self.log.records])
+
+
+class TestSettings(unittest.TestCase):
+ def test_off_by_default(self):
+ self.assertFalse(uploader.enabled())
+
+ def test_needs_both_settings(self):
+ with mock.patch.object(uploader, 'settings', lambda: ('https://x/', '')):
+ self.assertFalse(uploader.enabled())
+ with mock.patch.object(uploader, 'settings', lambda: ('https://x/', 'k')):
+ self.assertTrue(uploader.enabled())
+
+
+class TestLog(unittest.TestCase):
+ def test_persisted_and_capped(self):
+ with tempfile.TemporaryDirectory() as d:
+ log = UploadLog(d + '/upload.pickle', limit=2)
+ for n in range(3):
+ log.add(dict(job='j%d' % n, error=None))
+ log.flush()
+ again = UploadLog(d + '/upload.pickle', limit=2)
+ self.assertEqual(['j2', 'j1'], [r['job'] for r in again.records])
+ self.assertEqual(['j2'], [r['job'] for r in again.for_job('j2')])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/test_webupload.py b/test_webupload.py
new file mode 100644
index 0000000..1ac12b5
--- /dev/null
+++ b/test_webupload.py
@@ -0,0 +1,158 @@
+# The document layer for the website upload: what a job becomes on the wire. The corpus test runs only when
+# WEBUPLOAD_CORPUS points at a directory laid out like ~/printerface (data/pickle/YYYYMM/job-*); it checks every
+# stored invoice, credit note and statement.
+import datetime
+import glob
+import io
+import os
+import unittest
+from decimal import Decimal
+
+import webupload
+from webupload import UploadError
+
+
+def page(doc_num='100', lines=(), totals=('120.00', '24.00', '144.00'), date='02/11/26', accno='ACC1', summ=('1', '120.00', '20.00', '24.00')):
+ col = lambda key: '\n'.join(l[key] for l in lines) + '\n' * 3
+ p = dict(accno=accno, doc_num=doc_num, date=date, custref='PO9', ourref='555', salesperson='SAM',
+ addr_invoice='A WINE BAR\n1 HIGH ST\nTOWN\n\n', tot_net=totals[0], tot_vat=totals[1], tot_due=totals[2],
+ summ_code='%s\n\n' % summ[0], summ_netamt='%s\n\n' % summ[1], summ_rate='%s\n\n' % summ[2], summ_vat='%s\n\n' % summ[3])
+ for key in webupload.LINE_FIELDS:
+ p[key] = col(key)
+ return p
+
+
+def line(code='', desc='', qty='', price='', unit='', net='', vat=''):
+ return dict(prod_code=code, prod_desc=desc, prod_qty=qty, prod_price=price, prod_unit=unit, prod_net=net, prod_vcode=vat)
+
+
+def job(templ, parsed, name='job-20261102-090507'):
+ return dict(name=name, templ=templ, ts=datetime.datetime(2026, 11, 2, 9, 5, 7), parsed=parsed)
+
+
+class TestHelpers(unittest.TestCase):
+ def test_amount(self):
+ self.assertEqual('1234.50', webupload.amount(' 1,234.50 '))
+ self.assertEqual('-12.00', webupload.amount('12.00CR'))
+ self.assertEqual('-12.00', webupload.amount('-12.00'))
+ self.assertIsNone(webupload.amount(' '))
+ self.assertRaises(UploadError, webupload.amount, '12.0.0')
+
+ def test_dates(self):
+ self.assertEqual('2026-11-02', webupload.iso_date('02/11/26'))
+ self.assertRaises(UploadError, webupload.iso_date, '2026-11-02')
+ self.assertEqual('2026-11-02T09:05:07Z', webupload.received(dict(ts=datetime.datetime(2026, 11, 2, 9, 5, 7))))
+ bst = datetime.timezone(datetime.timedelta(hours=1))
+ self.assertEqual('2026-07-02T08:05:07Z', webupload.received(dict(ts=datetime.datetime(2026, 7, 2, 9, 5, 7, tzinfo=bst))))
+
+
+class TestInvoices(unittest.TestCase):
+ LINES = [line('BOR00101', 'Bordeaux 2015', '12', '10.00', 'BOTT', '120.00', '1')]
+
+ def test_invoice(self):
+ (doc,) = webupload.documents(job('invoice', {'ACC1': [page(lines=self.LINES)]}))
+ p = doc.payload
+ self.assertEqual(('invoice', 'ACC1', '100', [0]), (doc.kind, doc.account, doc.docnum, doc.pages))
+ self.assertEqual(('2026-11-02', False, 'PO9', '555', '120.00', '24.00', '144.00'),
+ (p['date'], p['is_credit_note'], p['cust_ref'], p['our_ref'], p['total_net'], p['total_vat'], p['total_gross']))
+ self.assertEqual(dict(acc='ACC1', name='A WINE BAR, 1 HIGH ST, TOWN', salesperson='SAM'), p['account'])
+ self.assertEqual([dict(product_code='BOR00101', description='Bordeaux 2015', quantity='12', unit='BOTT', unit_price='10.00',
+ net='120.00', vat_code='1', vat_rate='20.00')], p['lines'])
+ self.assertEqual([dict(vat_code='1', net='120.00', rate='20.00', vat='24.00')], p['vat_summary'])
+ self.assertEqual(('job-20261102-090507', '2026-11-02T09:05:07Z'), (p['job_name'], p['printed_at']))
+
+ def test_text_rows_are_not_lines_and_credit_notes_keep_their_references(self):
+ lines = [line('B0321001', 'BAUCHET Rose', '3', '21.53', 'BOTT', '64.59', '5'), line(desc='RE: KIR105 REF: 1452')]
+ (doc,) = webupload.documents(job('crednote', {'ACC1': [page('21636', lines, ('64.59', '0.00', '64.59'))]}))
+ self.assertTrue(doc.payload['is_credit_note'])
+ self.assertEqual(1, len(doc.payload['lines']))
+ self.assertEqual('RE: KIR105 REF: 1452', doc.payload['credit_refs'])
+ (inv,) = webupload.documents(job('invoice', {'ACC1': [page(lines=lines)]}))
+ self.assertEqual('', inv.payload['credit_refs'])
+
+ def test_a_document_over_several_pages_takes_its_totals_from_the_last(self):
+ first = page('7', [line('BOR00101', 'a', '1', '5.00', 'BOTT', '5.00', '1')], ('', '', ''))
+ second = page('7', [line('BOR00102', 'b', '2', '5.00', 'BOTT', '10.00', '1')], ('15.00', '3.00', '18.00'))
+ other = page('8', self.LINES)
+ (a, b) = webupload.documents(job('invoice', {'ACC1': [first, second, other]}))
+ self.assertEqual(([0, 1], '18.00', ['BOR00101', 'BOR00102']), (a.pages, a.payload['total_gross'], [l['product_code'] for l in a.payload['lines']]))
+ self.assertEqual(([2], '7' != '8'), (b.pages, True))
+
+ def test_missing_totals_are_an_error(self):
+ self.assertRaises(UploadError, webupload.documents, job('invoice', {'ACC1': [page(totals=('', '', ''))]}))
+
+ def test_other_types_are_not_uploaded(self):
+ self.assertEqual([], webupload.documents(job('delnote', {'ACC1': [page()]})))
+
+
+class TestStatements(unittest.TestCase):
+ def stmt(self, **ages):
+ p = dict(accno='ACC1', date='30/10/26', addr_invoice='A WINE BAR\n', age_curr='10.00', age_1m='5.00CR', age_2m='0.00', age_3m='', age_due='5.00')
+ p.update(ages)
+ return p
+
+ def test_statement(self):
+ (doc,) = webupload.documents(job('statement', {'ACC1': [self.stmt(age_3m='1.00')]}))
+ p = doc.payload
+ self.assertEqual('261102-090507-ACC1', p['docnum'])
+ self.assertEqual(('10.00', '-5.00', '0.00', '1.00', '5.00'), (p['amt_current'], p['amt_1month'], p['amt_2month'], p['amt_3month'], p['amt_due']))
+
+ def test_details_are_on_the_last_page(self):
+ blank = self.stmt(age_curr='', age_1m='', age_2m='', age_3m='', age_due='')
+ (doc,) = webupload.documents(job('statement', {'ACC1': [blank, self.stmt(age_3m='0.00')]}))
+ self.assertEqual(([0, 1], '5.00'), (doc.pages, doc.payload['amt_due']))
+
+ def test_incomplete_statement_is_an_error(self):
+ self.assertRaises(UploadError, webupload.documents, job('statement', {'ACC1': [self.stmt(age_due='')]}))
+
+
+class TestSplitPdf(unittest.TestCase):
+ def test_split(self):
+ from pypdf import PdfReader
+ from reportlab.pdfgen import canvas
+ buf = io.BytesIO()
+ c = canvas.Canvas(buf)
+ for n in range(3):
+ c.drawString(100, 100, 'page %d' % n)
+ c.showPage()
+ c.save()
+ out = PdfReader(io.BytesIO(webupload.split_pdf(buf.getvalue(), [2, 0])))
+ self.assertEqual(['page 2', 'page 0'], [p.extract_text().strip() for p in out.pages])
+ self.assertRaises(UploadError, webupload.split_pdf, buf.getvalue(), [3])
+
+
+@unittest.skipUnless(os.environ.get('WEBUPLOAD_CORPUS'), 'set WEBUPLOAD_CORPUS to a directory like ~/printerface')
+class TestCorpus(unittest.TestCase):
+ def test_every_document_adds_up(self):
+ import main
+ from docparser import DocParser
+ from textutil import load_job_pickle
+ seen, rejected = 0, []
+ for f in sorted(glob.glob(os.path.join(os.environ['WEBUPLOAD_CORPUS'], 'data/pickle/*/job-*'))):
+ with open(f, 'rb') as fh:
+ j = load_job_pickle(fh)
+ doctype = (j.get('control') or {}).get('J', '').strip()
+ if main.identify(dict(doctype=doctype)) not in ('invoice', 'crednote', 'statement'):
+ continue
+ j['doctype'], j['plain'] = doctype, main.control_char_re.sub(' ', j['data'])
+ j['templ'] = main.identify(j)
+ j['parsed'] = DocParser().parse(j)[1] or {}
+ try:
+ docs = webupload.documents(j)
+ except UploadError as e:
+ rejected.append('%s: %s' % (j['name'], e)) # the empty test documents sent while developing
+ continue
+ for doc in docs:
+ seen += 1
+ p = doc.payload
+ if doc.kind == 'invoice':
+ net = sum(Decimal(l['net']) for l in p['lines'])
+ self.assertEqual(Decimal(p['total_net']), net, '%s %s' % (j['name'], doc.docnum))
+ self.assertEqual(Decimal(p['total_gross']), Decimal(p['total_net']) + Decimal(p['total_vat']), '%s %s' % (j['name'], doc.docnum))
+ self.assertEqual(Decimal(p['total_vat']), sum(Decimal(v['vat']) for v in p['vat_summary']), '%s %s' % (j['name'], doc.docnum))
+ self.assertTrue(seen)
+ self.assertTrue(all('ACC001' in r or '12345' in r for r in rejected), rejected)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/uploader.py b/uploader.py
new file mode 100644
index 0000000..d652bec
--- /dev/null
+++ b/uploader.py
@@ -0,0 +1,148 @@
+#
+# Pushes invoices, credit notes and statements to the website as they are printed. A queue worked by the event
+# loop, like the mailer, with the blocking HTTP call in a worker thread. Each document is a multipart POST: a
+# JSON `payload` part (see webupload.py) and its own `pdf`. The website replaces a document it already has, so
+# sending one twice is harmless, and a failed one can simply be sent again.
+#
+# The outcome of the last `result_count` uploads is kept (newest first) in upload.pickle, flushed from the main loop.
+
+import asyncio
+import datetime
+import json
+import os
+import traceback
+import urllib.error
+import urllib.request
+import uuid
+
+import printing
+import webupload
+from settings import config, HOME
+
+pickle_file = os.path.join(HOME, 'upload.pickle')
+
+# a network failure or a 5xx is tried again after each of these delays (seconds); anything else is final
+RETRY_DELAYS = (5, 30)
+TIMEOUT = 30
+
+
+class UploadLog(printing.PrintLog):
+ """What was uploaded, newest first, one record per document: the job and key it came from, what the website
+ did with it and any error. Kept in a side pickle, like the printed history, and capped the same way."""
+
+
+def settings():
+ """(base_url, api_key); both blank when the feature is off."""
+ return (config.get('Web', 'base_url', fallback='').strip(), config.get('Web', 'api_key', fallback='').strip())
+
+
+def enabled():
+ return all(settings())
+
+
+def prepare(job, key, pdfdir):
+ """The uploads for a job page's key (an account, or 'accounts' for all of them), ready to queue. The PDF is cut
+ into one per document. Raises webupload.UploadError for a job that can't be converted."""
+ items = []
+ for doc in webupload.documents(job):
+ if key != 'accounts' and doc.account != key:
+ continue
+ with open(os.path.join(pdfdir, job['groupfiles'][(doc.account,)]), 'rb') as f:
+ pdf = webupload.split_pdf(f.read(), doc.pages)
+ items.append(dict(job=job['name'], key=doc.account, kind=doc.kind, account=doc.account, docnum=doc.docnum,
+ payload=webupload.payload_json(doc), pdf=pdf))
+ return items
+
+
+def multipart(fields, files):
+ """(content type, body) for a multipart/form-data post. fields: {name: text}; files: {name: (filename, bytes)}."""
+ boundary = uuid.uuid4().hex
+ out = []
+ for name, value in fields.items():
+ out.append(('--%s\r\nContent-Disposition: form-data; name="%s"\r\n\r\n' % (boundary, name)).encode() + value.encode('utf-8') + b'\r\n')
+ for name, (filename, data) in files.items():
+ out.append(('--%s\r\nContent-Disposition: form-data; name="%s"; filename="%s"\r\nContent-Type: application/pdf\r\n\r\n'
+ % (boundary, name, filename)).encode() + data + b'\r\n')
+ out.append(('--%s--\r\n' % boundary).encode())
+ return 'multipart/form-data; boundary=' + boundary, b''.join(out)
+
+
+def post(item, base_url, api_key):
+ """Blocking: POST one document. Returns (status, reply text), also for an error status. Raises OSError (which
+ URLError is) when the website could not be reached."""
+ kind = 'statement' if item['kind'] == 'statement' else 'invoice'
+ ctype, body = multipart({'payload': item['payload']}, {'pdf': ('%s-%s.pdf' % (item['kind'], item['docnum']), item['pdf'])})
+ req = urllib.request.Request(base_url.rstrip('/') + '/api/ingest/%s/' % kind, data=body, method='POST',
+ headers={'Content-Type': ctype, 'Authorization': 'Token ' + api_key, 'Accept': 'application/json'})
+ try:
+ with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
+ return r.status, r.read().decode('utf-8', 'replace')
+ except urllib.error.HTTPError as e:
+ return e.code, e.read().decode('utf-8', 'replace')
+
+
+def describe(status, text):
+ """A short message for a refusal: the website's own field errors if it sent them."""
+ try:
+ text = json.dumps(json.loads(text))
+ except ValueError:
+ text = '' # an HTML error page is no use in a table cell
+ return ('HTTP %d %s' % (status, text)).strip()[:300]
+
+
+class WebUploader(object):
+ """Uploads queued documents one at a time, in order. Like JobMailer, `append` is called from page handlers and
+ `start` / `close` from main.serve, all on the event loop."""
+
+ def __init__(self, queuesz=200, log=None, transport=None):
+ self.queue = asyncio.Queue(queuesz)
+ self.log = log if log is not None else UploadLog(pickle_file)
+ self.transport = transport or post # replaced in tests
+ self.task = None
+
+ def start(self):
+ self.task = asyncio.get_running_loop().create_task(self.run())
+
+ async def close(self, timeout=30):
+ if self.task:
+ try:
+ await asyncio.wait_for(self.queue.join(), timeout)
+ except asyncio.TimeoutError:
+ print('upload: %d documents still queued at shutdown' % self.queue.qsize())
+ self.task.cancel()
+ self.task = None
+
+ def append(self, item):
+ """Queue one document. Raises asyncio.QueueFull if too many are waiting."""
+ self.queue.put_nowait(item)
+
+ def attempt(self, item):
+ """One try (blocking: runs in a worker thread): (outcome, status, message, retry)."""
+ base_url, api_key = settings()
+ try:
+ status, text = self.transport(item, base_url, api_key)
+ except OSError as e:
+ return 'failed', None, 'could not reach the website: %s' % (e.reason if hasattr(e, 'reason') else e), True
+ if status in (200, 201):
+ return ('created' if status == 201 else 'replaced'), status, None, False
+ return 'failed', status, describe(status, text), status >= 500
+
+ async def run(self):
+ while True:
+ item = await self.queue.get()
+ try:
+ for delay in (0,) + RETRY_DELAYS:
+ if delay:
+ await asyncio.sleep(delay)
+ outcome, status, message, retry = await asyncio.to_thread(self.attempt, item)
+ if not retry:
+ break
+ print('upload: %s %s -> %s %s' % (item['kind'], item['docnum'], outcome, message or ''))
+ self.log.add(dict(job=item['job'], key=item['key'], kind=item['kind'], account=item['account'], docnum=item['docnum'],
+ added=datetime.datetime.now(), outcome=outcome, status=status, error=message if outcome == 'failed' else None))
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ traceback.print_exc()
+ finally:
+ self.queue.task_done()
diff --git a/web/home.html b/web/home.html
index cd95c68..180f0ff 100644
--- a/web/home.html
+++ b/web/home.html
@@ -44,6 +44,10 @@ Email
${email_fails} recent failure(s) sending email
+ % if upload_fails is not None:
+ ${upload_fails} recent failure(s) uploading to the website
+
+ % endif
Email Addresses » Sent Emails »
diff --git a/web/pdf.html b/web/pdf.html
index 3c6daf2..51eb215 100644
--- a/web/pdf.html
+++ b/web/pdf.html
@@ -21,6 +21,14 @@ Document Pages
% endfor
+ % if can_upload:
+
+ % endif
+