Posts tagged 'rust'

Mailsift: Extracting structured data from email messages

As a casual user of Gmail, I find its ability to recognize when I’ve received tickets, invoices, and flight confirmations, and to display this information in a structured way, very useful. Flights appear directly in Google Calendar, parcel delivery statuses are tracked, and reservations are easy to find at a glance.

However, my main email address is not Gmail, and I don’t want to migrate to Gmail for a number of reasons (privacy, data sovereignty, vendor lock-in). At the same time, I missed having that automatic extraction: having flight and train bookings appear in my calendar without manual copy-pasting, keeping track of incoming parcels, and having invoices neatly organized.

JSON-LD and schema.org

There is an established standard format for structured data called JSON-LD, which is used by Google and other search engines to extract structured data from web pages. JSON-LD represents linked data using JSON, and it can be embedded directly in HTML documents.

Email messages can also contain structured data in the form of JSON-LD, which can link the information in the email to external data sources. There are standardized schemas for structured data in email messages, such as the schema.org vocabulary, which defines types and properties for describing entities including flight reservations, train trips, hotel bookings, parcel deliveries, and invoices.

For example, an email containing a flight reservation might embed the following JSON-LD snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
  "@context": "https://schema.org",
  "@type": "FlightReservation",
  "reservationNumber": "ABC123",
  "underName": {
    "@type": "Person",
    "name": "John Doe"
  },
  "reservationFor": {
    "@type": "Flight",
    "flightNumber": "AA123",
    "departureAirport": {
      "@type": "Airport",
      "name": "John F. Kennedy International Airport"
    },
    "arrivalAirport": {
      "@type": "Airport",
      "name": "Los Angeles International Airport"
    },
    "departureTime": "2026-11-01T10:00:00-05:00",
    "arrivalTime": "2026-11-01T13:00:00-08:00"
  }
}

When this is present, reading email data is clean and straightforward. The reality, however, is that only a fraction of vendors actually include schema.org markup in their emails. Most airlines, train operators, couriers, and web shops still send regular HTML or plain-text messages with arbitrary layouts that change over time.

Mailsift

To bridge this gap on my own infrastructure, I built mailsift. Written in Rust, it is a daemon and CLI tool that monitors incoming email, extracts structured information, and routes it to standard files and services.

Rather than locking data into an internal database, mailsift embraces the Unix philosophy: it delegates extraction to small, isolated programs and files the resulting structured artifacts into standard formats and protocols:

  • Calendar events & reservations: Turned into iCalendar (.ics) events and pushed directly to a CalDAV server (such as Xandikos) or stored in a local directory.
  • Bills & invoices: Extracted as structured JSON records, organized by year, and optionally synced to a personal finance manager like Firefly III.
  • Parcels: Extracted as delivery records keyed by tracking number, merged across status update emails, and optionally registered with tracking APIs like 17track or Karrio.
  • Tickets & boarding passes: Saved as PDFs, Apple Wallet passes (.pkpass), or images, accompanied by JSON metadata sidecars linking them to the booking.
  • Receipts & orders: Filed as JSON records, synced over WebDAV, or forwarded via email.

How extractors work

Mailsift decouples the pipeline that handles emails from the logic that parses individual vendors. It discovers extractors from a directory of manifests.

The contract between mailsift and an extractor is deliberately simple:

  • Input: The raw RFC822 message is fed to the extractor on stdin.
  • Execution: The extractor runs in a fresh, temporary working directory, with a strict timeout (typically 10 seconds).
  • Output: The extractor writes zero or more named artifact files into its working directory and exits 0.

Extractors can be written in any programming language. In practice, most are small Python scripts that parse HTML with regexes or BeautifulSoup, using a small helper library (mailsift_extractor) that handles Unicode normalization and HTML body stripping.

Filtering and DKIM verification

Spawning a subprocess for every single email in an active inbox would be wasteful. Each extractor therefore has a YAML manifest declaring prefiltering criteria:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
name: easyjet
order: 50
from_domains:
  - easyjet.com
  - "*.easyjet.com"
subject_regex: "(?i)easyJet booking reference"
requires:
  - html
require_dkim:
  - easyjet.com

Before running an extractor, mailsift evaluates the message headers and MIME structure - possibly converting it to an IMAP filter. If the sender domain or subject doesn’t match, or the required MIME parts are missing, the extractor is skipped immediately.

Crucially, the manifest can also require a valid DKIM signature via require_dkim. Mailsift inspects the Authentication-Results: header produced by the receiving mail server. This guarantees that an extractor only processes messages that genuinely originated from the vendor’s domain, preventing forged emails from injecting fake calendar events or bills.

Generic vs. vendor extractors

Extractors fall into two categories:

  1. Generic extractors: schema-ld inspects the HTML for any <script type="application/ld+json"> blocks conforming to schema.org reservations. Another extractor, ics-passthrough, extracts standard iCalendar attachments.
  2. Vendor-specific extractors: For vendors that don’t include structured markup, dedicated extractors parse the message text. For instance, the easyjet extractor looks for booking references and flight tables, producing a standard FlightReservation artifact:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
reservation = {
    "@context": "https://schema.org",
    "@type": "FlightReservation",
    "reservationNumber": f"easyjet-{reference}-{flight_no}",
    "reservationFor": {
        "@type": "Flight",
        "flightNumber": flight_no,
        "departureAirport": {"@type": "Airport", "name": origin},
        "arrivalAirport": {"@type": "Airport", "name": dest},
        "departureTime": dep.isoformat(),
        "arrivalTime": arr.isoformat(),
    },
}
Path(f"{slug}.reservation.json").write_text(json.dumps(reservation))

The collection of extractors is maintained in a separate repository, mailsift-extractors, and currently includes nearly 60 extractors covering airlines (British Airways, KLM, EasyJet, Transavia, Eurostar), transport (NS, SNCF Connect, FlixBus), package carriers (Royal Mail, DPD, DHL, UPS, Evri, PostNL), online orders, and utility bills.

Handling forwarded mail

In real life, travel bookings or receipts are often forwarded by family, friends, or colleagues. By default, forwarded mail would fail sender checks, and DKIM signatures on inline forwards are broken by mail clients.

Mailsift handles this via a trusted_forwarders configuration. When an email arrives from a trusted forwarder, mailsift unwraps the forwarded message:

  • Attachment forwards: If the original email was attached as message/rfc822, mailsift extracts the original message and re-evaluates the vendor’s DKIM signature on the inner message.
  • Inline forwards: Mailsift reconstructs a synthetic RFC822 message from the client’s forwarded quotation header block and quotes, deriving a deterministic Message-ID.

This means hotel confirmations or flight tickets forwarded by a partner still end up in the family calendar automatically.

Running mailsift

Mailsift fits into existing email setups in several ways:

Dovecot Sieve

For local delivery, Sieve provides an elegant integration using the sieve_extprograms plugin. Because Sieve runs during local delivery after Dovecot has validated DKIM and added Authentication-Results:, require_dkim checks work as expected:

1
2
require ["vnd.dovecot.pipe"];
pipe :copy "mailsift";

The :copy flag ensures the email continues to the user’s inbox while a copy is piped through mailsift.

IMAP watching

If you don’t run your own mail server, or want to process mail on an existing remote mailbox, imap-scan connects over IMAP:

$ mailsift imap-scan imaps://[email protected]/INBOX \
    --password-file ~/.config/mailsift/imap.pass \
    --watch

With --watch, mailsift uses IMAP IDLE (RFC 2177) to wait for new messages and process them as they arrive. It supports standard passwords, Kerberos (SASL GSSAPI), and OAuth2 (XOAUTH2) for providers like Gmail and Microsoft 365 via an interactive mailsift imap-auth flow.

Other modes

  • Postfix Milter: mailsift milter runs as an MTA filter, processing messages in real-time as they pass through Postfix.
  • Maildir scan: mailsift maildir-scan walks an on-disk Maildir folder, useful for backfilling historical mail.
  • Replay: mailsift replay message.eml runs extractors on a single saved message file, which is invaluable when writing or testing an extractor.

Web UI and REST API

In addition to routing data to CalDAV and disk, mailsift includes an optional read-only web dashboard (mailsift web):

$ mailsift web --listen 127.0.0.1:8088

The dashboard provides an overview of upcoming trips, arriving packages, unpaid bills, and recent orders. It rescans the artifact directories on request, so it stays in sync with incoming mail without needing a separate database. JSON endpoints (such as /api/parcels.json or /api/bills.json) are also available for custom status scripts or home automation dashboards.

Status and getting involved

Mailsift has been running reliably on my mail server for over a year, and having flights, hotel bookings, and train journeys seamlessly sync into my calendar without relying on proprietary cloud services has been very satisfying.

The project is free software under the GPL-3.0:

Adding support for new vendors only requires writing a small YAML manifest and a Python script with a couple of regexes. If you have vendors you’d like to extract data from, contributions of new extractors are very welcome!

comments.

Inquest, a test result repository in Rust

testrepository

For a long time I’ve used Robert Collins’ testrepository (testr) to run tests in many of the projects I work on. It’s a small, focused tool built around a simple idea: decouple the running of tests from the recording and querying of their results.

The way it works is straightforward. A test runner emits a subunit stream — a compact binary protocol for test results — and testrepository stores those streams in a per-project .testrepository/ directory. Once results are in the repository, you can ask questions like “which tests failed in the last run?”, “re-run only the failures”, “what are the slowest tests?”, or “what changed between this run and the previous one?”.

The killer feature, for me, has always been the failing-test loop. When a big test suite breaks, you don’t want to re-run the whole thing after every fix — you want to iterate on just the failures, and only re-run the full suite once they’re all green. testrepository made that workflow ergonomic long before most language-specific test runners had anything comparable, and many of them still don’t have a good answer for it.

testrepository has served me well for over a decade, but it has been largely unmaintained for a while, and I had some ideas of improvements that I wanted to try out. So I wrote a Rust port, which has since grown a number of features of its own.

Inquest

Inquest is a Rust port of testrepository that has since grown a number of features of its own. The binary is called inq.

Goals

The goals are deliberately modest:

  • a single static binary, no Python runtime required
  • no need to write a dedicated config file for most projects
  • compatible enough with testrepository’s workflow that I can switch projects over without retraining my fingers
  • a richer on-disk format that captures more about each run (git commit, command line, duration, exit code, concurrency)
  • good support for the languages I actually use day-to-day: Rust, Python, Go, and Node.js
  • mostly Do What I Mean (DWIM), e.g. getting me to know as quickly as possible what tests are failing and why, and being clever about doing this

Inquest reads and writes subunit v2 streams, so anything that can produce subunit (directly or via one of the many converters) can feed into it.

Quick start

Inquest can usually figure out how to run your tests on its own. In a Rust, Python, Go or Node.js project:

 $ cd my-project
 $ inq

Or if the auto-detection doesn’t work, you can ask it to generate a config file and then run the tests:

 $ inq auto
 $ inq run

inq auto writes an inquest.toml describing how to invoke the test runner; inq run runs the tests, captures the subunit stream, and stores the results in a .inquest/ directory.

For a Rust project the generated config looks like:

 test_command = "cargo subunit $IDOPTION"
 test_id_option = "--test $IDFILE"
 test_list_option = "--list"

After the first run, the usual queries work:

 $ inq stats             # repository-wide statistics
 $ inq last              # results of the most recent run
 $ inq failing           # only the failing tests
 $ inq slowest           # the slowest tests in the last run
 $ inq run --failing     # re-run only what failed last time

The last one is the workflow I use most often: run the full suite once, fix the obvious failures, then iterate on inq run --failing until the list is empty.

A few things that aren’t in testrepository

Some of the features that have grown in inquest beyond the original testrepository functionality:

  • Timeouts. --test-timeout, --max-duration, and --no-output-timeout will kill a test process that is hanging or has stopped producing output. --test-timeout auto derives a per-test timeout from the historical duration of that test, which is handy for catching tests that hang.

    Once the test runner is killed, the test is marked as failed and the next test is started, so a broken test doesn’t hold up the whole suite.

  • Ordering --order can be used to run tests in a specific order, e.g. to run the slowest tests first, to run the tests that failed most recently first, or to run the widest variety of tests first to maximize the chance of finding a failure early on.

  • Live progress. inq running tails the in-progress subunit stream on disk and reports observed/expected test counts, percent complete, elapsed wall-clock time, and an ETA derived from each test’s historical duration. Useful when a CI run is taking longer than you’d like.

  • Flakiness ranking. inq flaky ranks tests by pass↔fail transitions in consecutive runs in which the test was recorded, so chronically broken tests rank low and genuinely flapping tests rank high.

  • Comparing runs. inq diff <A> <B> shows what changed between two test runs — newly failing, newly passing, and tests that flipped state — which makes it easy to see whether your last change actually fixed (or broke) anything.

  • Bisecting git history. inq bisect <TEST> drives git bisect to find the commit that broke a given test. It defaults the known-good and known-bad commits from the recorded run history (the most recent run where the test passed, and the most recent where it failed), so in the common case there is no need to remember either — just point it at the test name and let it work.

  • Richer run metadata. inq info shows the git commit, command line, duration, exit code, and concurrency for a run, with a flag for whether the working tree was dirty when the run started. Combined with inq diff this makes it much easier to triangulate when a regression was introduced.

  • Rerun a previous run verbatim. inq rerun <ID> re-runs exactly the tests of a previous run, in the same order, forwarding the same -- arguments that the original run used. inq rerun -1 repeats the latest.

  • Web based view. inq web serves a web-based view of the repository, with a dashboard of recent runs and detailed views of individual runs and tests.

Web UI

Most of the time I drive inquest from the command line, but for browsing historical results of a large suite — spotting flapping tests, drilling into a single test’s run history, or just getting a visual sense of which parts of the suite are hurting — a web view is more pleasant. inq web starts a local server with exactly that:

 $ inq web

The repository overview shows totals and a per-test history grid where each cell is one run, coloured by outcome. Bands of red make it easy to pick out tests that have been broken for a long time, and isolated red cells in an otherwise green column point at flaky tests.

Inquest web UI repository overview, with a grid of per-run results

Drilling into an individual test gives you its full run history, a duration sparkline, and per-run pass/fail status:

Inquest web UI per-test view with run history and duration sparkline

Migrating from testrepository

If you already have a .testrepository/ directory full of historical runs, inq upgrade will migrate it into the new .inquest/ format, with a progress bar for the impatient.

The legacy .testr.conf (INI) format is still understood, so existing projects don’t have to be converted to inquest.toml immediately — though the TOML format is preferred for new projects.

Trying it

The source is on GitHub at jelmer/inquest. To install from source:

 $ cargo install inquest

In a project with a Rust, Python, Go or Node.js test suite:

 $ inq

Bug reports and patches are welcome.

comments.

Porting Python projects to Rust

I’ve recently been working on porting some of my Python code to rust, both for performance reasons, and because of the strong typing in the language. As a fan of Haskell, I also just really enjoy using the language.

Porting any large project to a new language can be a challenge. There is a temptation to do a rewrite from the ground-up in idiomatic rust and using all new fancy features of the language.

Porting in one go

However, this is a bit of a trap:

  • It blocks other work. It can take a long time to finish the rewrite, during which time there is no good place to make other bug fixes/feature changes. If you make the change in the python branch, then you may also have to patch the in-progress rust fork.
  • No immediate return on investment. While the rewrite is happening, all of the investment in it is sunk costs.
  • Throughout the process, you can only run the tests for subsystems that have already been ported. It’s common to find subtle bugs later in code ported early.
  • Understanding existing code, porting it and making it idiomatic rust all at the same time takes more time and post-facto debugging.

Iterative porting

Instead, we’ve found that it works much better to take an iterative approach. One of the hidden gems of rust is the excellent PyO3 crate, which allows creating python bindings for rust code in a way that is several times less verbose and less painful than C or SWIG. Because of rust’s strong ownership model, it’s also really hard to muck up e.g. reference counts when creating Python bindings for rust code.

We port individual functions or classes to rust one at a time, starting with functionality that doesn’t have dependencies on other python code and gradually working our way up the call stack.

Each subsystem of the code is converted to two matching rust crates: one with a port of the code to pure rust, and one with python bindings for the rust code. Generally multiple python modules end up being a single pair of rust crates.

The signature for the pure Rust code follow rust conventions, but the business logic is mostly ported as-is (just in rust syntax) and the signatures of the python bindings match that of the original python code.

This then allows running the original python tests to verify that the code still behaves the same way. Changes can also immediately land on the main branch.

A subsequent step is usually to refactor the rust code to be more idiomatic - all the while keeping the tests passing. There is also the potential to e.g. switch to using external rust crates (with perhaps subtly different behaviour), or drop functionality altogether.

At some point, we will also port the tests from python to rust, and potentially drop the python bindings - once all the caller’s have been converted to rust.

Example

For example, imagine I have a Python module janitor/mail_filter.py with this function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def parse_plain_text_body(text):
   lines = text.splitlines()

   for i, line in enumerate(lines):
       if line == 'Reply to this email directly or view it on GitHub:':
           return lines[i + 1].split('#')[0]
       if (line == 'For more details, see:'
               and lines[i + 1].startswith('https://code.launchpad.net/')):
           return lines[i + 1]
       try:
           (field, value) = line.split(':', 1)
       except ValueError:
           continue
       if field.lower() == 'merge request url':
           return value.strip()
   return None

Porting this to rust naively (in a crate I’ve called “mailfilter”) it might look something like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
pub fn parse_plain_text_body(text: &str) -> Option<String> {
     let lines: Vec<&str> = text.lines().collect();

     for (i, line) in lines.iter().enumerate() {
         if line == &"Reply to this email directly or view it on GitHub:" {
             return Some(lines[i + 1].split('#').next().unwrap().to_string());
         }
         if line == &"For more details, see:"
             && lines[i + 1].starts_with("https://code.launchpad.net/")
         {
             return Some(lines[i + 1].to_string());
         }
         if let Some((field, value)) = line.split_once(':') {
             if field.to_lowercase() == "merge request url" {
                 return Some(value.trim().to_string());
             }
         }
     }
     None
 }

Bindings are created in a crate called mailfilter-py, which looks like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
use pyo3::prelude::*;

 #[pyfunction]
 fn parse_plain_text_body(text: &str) -> Option<String> {
     janitor_mail_filter::parse_plain_text_body(text)
 }

 #[pymodule]
 pub fn _mail_filter(py: Python, m: &PyModule) -> PyResult<()> {
     m.add_function(wrap_pyfunction!(parse_plain_text_body, m)?)?;

     Ok(())
 }

The metadata for the crates is what you’d expect. mailfilter-py uses PyO3 and depends on mailfilter.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
[package]
 name = "mailfilter-py"
 version = "0.0.0"
 authors = ["Jelmer Vernooij <[email protected]>"]
 edition = "2018"

 [lib]
 crate-type = ["cdylib"]

 [dependencies]
 janitor-mail-filter = { path = "../mailfilter" }
 pyo3 = { version = ">=0.14", features = ["extension-module"]}

I use python-setuptools-rust to get the python ecosystem to build the python bindings. Here is what setup.py looks like:

1
2
3
4
5
6
7
8
9
#!/usr/bin/python3
from setuptools import setup
from setuptools_rust import RustExtension, Binding

setup(
        rust_extensions=[RustExtension(
        "janitor._mailfilter", "crates/mailfilter-py/Cargo.toml",
        binding=Binding.PyO3)],
)

And of course, setuptools-rust needs to be listed as a setup requirement in pyproject.toml or setup.cfg.

After that, we can replace the original python code with a simple import and verify that the tests still run:

1
from ._mailfilter import parse_plain_text_body

Of course, not all bindings are as simple as this. Iterators in particular are more complicated, as is code that has a loose idea of ownership in python. But I’ve found that the time investment is usually well worth the ability to land changes on the development head early and often.

I’d be curious to hear if people have had success with other approaches to porting Python code to Rust. If you do, please leave a comment.

comments.