Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -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

Expand Down
17 changes: 12 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,26 +22,33 @@ 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
* `printing.py` printing with CUPS via `lp`. Each document sent is recorded (job, key, printer, CUPS request id or the error) in `~/printerface/printer.pickle`, newest first and trimmed to `result_count` like the sent emails, and listed on the job page. The file is written from the main loop only when something changed
* `printing.py` printing with CUPS via `lp`. Each document sent is recorded (job, key, printer, CUPS request id or the error) in `~/printerface/printer.pickle`, newest first and trimmed to `[Printing] result_count` (the sent emails and uploads have their own `result_count` under `[Gmail]` and `[Web]`), and listed on the job page. The file is written from the main loop only when something changed
* `derived.py` a cache, `~/printerface/derived.pickle`, of what is slow to work out from a stored job: its parsed pages and the names of its PDFs. At startup a job whose file is unchanged and whose parser is unchanged takes these from the cache (a thousand jobs in under a second, against about eight), and a job that has left the loaded history drops out of the file the next time it is written (at most every three minutes, and at shutdown). The PDFs are not redrawn when the stationery changes: Settings > Stationery counts the documents drawn under older stationery and redraws them on request
* `printstatus.py` read-only CUPS status for the Printers page (one `lpstat -t` in the C locale, cached for 10s), and the check of whether auto-printing can work. lpstat can show a stuck or stopped queue but not that a page was printed

Job pickles that appear in `~/printerface/data/pickle` without arriving over LPD (copied in from another instance, say)
are picked up every few seconds, once they have been still for a couple of seconds, and are treated exactly like a job
that has just arrived: they go into the history in file name order and are auto-printed and auto-uploaded if their
type says so. So copy in only what should be acted on: a file older than everything in a full history is ignored, but
one inside it is not.

A GET never changes anything: sending an email, printing, editing the address book and saving or reverting a
template are POSTs, and their handlers return `httpserver.Redirect(...)` (a 303) to a page that is safe to refresh,
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 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:

$ 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
Expand Down
12 changes: 12 additions & 0 deletions defaults.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ purch_instruction_fr=Veuillez confirmer reception de cette commande et sa\ndate
purch_instruction_en=Please contact immediately if any problems or\nqueries.
logo=logo.jpg
logo2=
# How many printed documents to remember (newest first) on the Printed Documents page
result_count=200

[Main]
summary_trim=AAAA,BBBBBB
Expand All @@ -25,6 +27,16 @@ 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=
# Kinds of document uploaded as soon as they arrive, comma separated: invoice, crednote, statement
auto_types=
# How many uploads to remember (newest first) on the Uploads page
result_count=120

[Robot]
auto_types=Delvnote,Pick lst
auto_printer=HP_TONY
Expand Down
121 changes: 121 additions & 0 deletions derived.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
"""
A cache of what is slow to work out from a stored job: the parsed pages, and the names of the PDFs made from them.
Reading the job pickles is quick (0.1 s for a thousand); parsing them and drawing the PDFs is what makes a start
slow, so the next start can take those from here.

The cache is only ever an optimisation. The job pickles stay the record, and anything wrong with an entry (a
different job file, newer parser code, a missing PDF) means that job is worked out again. One file, written
atomically; one entry per job file name, so it follows the history: a job that leaves the loaded history is
dropped from the file the next time it is written.

An entry is only trusted if
* the job file is the one it was made from (size and modification time),
* it was parsed by the same parser (`parse_stamp`: docparser.py and textutil.py),
and the PDFs it names are still on disk. How the PDFs were drawn (`render_stamp`: stationary.py, the [Printing]
company details and the logos) is recorded with it, but a change does not redraw them by itself: the Stationery
settings page counts the jobs drawn under older stationery and has the button that redraws them.
"""

import hashlib
import os
import pickle
import time
import traceback

from settings import BASE_DIR, HOME, config

PATH = os.path.join(HOME, 'derived.pickle')

# bumped if the layout of an entry changes
FORMAT = 1

# the file is rewritten at most this often (seconds) while something is changing
FLUSH_EVERY = 180


def _digest(parts):
h = hashlib.sha256()
for p in parts:
h.update(p if isinstance(p, bytes) else repr(p).encode('utf-8'))
h.update(b'\0')
return h.hexdigest()[:16]


def _source(name):
with open(os.path.join(BASE_DIR, name), 'rb') as f:
return f.read()


def parse_stamp():
return _digest([FORMAT, _source('docparser.py'), _source('textutil.py')])


def render_stamp():
parts = [FORMAT, _source('stationary.py'), sorted(config.items('Printing'))]
for key in ('logo', 'logo2'):
path = os.path.expanduser(config.get('Printing', key, fallback=''))
try:
st = os.stat(path) if path else None
except OSError:
st = None
parts.append((path, st and (st.st_size, st.st_mtime_ns)))
return _digest(parts)


class DerivedCache(object):
def __init__(self, path=PATH):
self.path = path
self.entries = {}
self.dirty = False
self.last_flush = 0
self.parse_stamp = parse_stamp()
self.render_stamp = render_stamp()
try:
with open(path, 'rb') as f:
data = pickle.load(f)
if data.get('format') == FORMAT:
self.entries = data['entries']
except FileNotFoundError:
pass
except Exception:
print('[derived] ignoring an unreadable cache %s' % path)
traceback.print_exc()

def lookup(self, name, stat):
"""The entry for this job file if it is still good, else None."""
e = self.entries.get(name)
if e and e['stat'] == stat and e['parse_stamp'] == self.parse_stamp:
return e
return None

def snapshot(self, jobs):
"""The entries for the jobs as they are now: what a flush writes."""
out = {}
for j in jobs:
if j.get('stat') and 'groupfiles' in j:
out[j['name']] = dict(stat=j['stat'], parse_stamp=self.parse_stamp, render_stamp=j.get('render_stamp'),
parsed=j['parsed'], groupkey=j['groupkey'], groupfiles=j['groupfiles'])
return out

def flush(self, jobs, force=False):
"""Write the cache if it changed, and not more than every FLUSH_EVERY seconds unless forced. Never raises: a
full disk mustn't stop the server."""
if not self.dirty or (not force and time.time() - self.last_flush < FLUSH_EVERY):
return False
try:
entries = self.snapshot(jobs)
tmp = self.path + '.tmp'
with open(tmp, 'wb') as f:
pickle.dump(dict(format=FORMAT, entries=entries), f, protocol=pickle.HIGHEST_PROTOCOL)
os.replace(tmp, self.path)
self.entries = entries
self.dirty = False
self.last_flush = time.time()
return True
except Exception:
traceback.print_exc()
return False

def stale(self, jobs):
"""The jobs whose PDFs were drawn under different stationery from today's."""
return [j for j in jobs if j.get('render_stamp') != self.render_stamp]
Loading
Loading