"""Single-host tutorial core. No network calls or public approval endpoint."""
import
import
import
import
import
def
connect
path
10
return
def
init
path
with
as
'''
CREATE TABLE IF NOT EXISTS events(
delivery_id TEXT PRIMARY KEY, event_id TEXT UNIQUE NOT NULL);
CREATE TABLE IF NOT EXISTS jobs(
id TEXT PRIMARY KEY, tenant TEXT NOT NULL, inbox TEXT NOT NULL,
message TEXT NOT NULL, thread TEXT NOT NULL, state TEXT NOT NULL,
snapshot TEXT, digest TEXT, approved_by TEXT, expires REAL,
send_key TEXT NOT NULL, receipt TEXT,
UNIQUE(tenant,inbox,message));
'''
def
ingest
path, delivery_id, event, inbox_owners
if
'event_type'
'message.received'
return
'ignored'
'message'
'event_id'
'inbox_id'
'message_id'
'thread_id'
if
not
all
isinstance
str
and
for
in
raise
'invalid identifiers'
'inbox_id'
with
as
'INSERT OR IGNORE INTO events VALUES (?,?)'
2
if
not
return
'duplicate'
hex
'''INSERT OR IGNORE INTO jobs
(id,tenant,inbox,message,thread,state,send_key)
VALUES (?,?,?,?,?,'queued',?)'''
2
'reply-'
return
'stored'
def
stage
path, job_id, tenant, recipients, text, allowed
# Addresses here are explicit addr-spec strings selected by trusted app code.
if
not
or
not
all
isinstance
str
and
in
for
in
or
not
isinstance
str
or
not
raise
'recipient or body rejected'
with
as
'BEGIN IMMEDIATE'
'SELECT * FROM jobs WHERE id=? AND tenant=?'
if
not
or
'state'
not
in
'queued'
'pending'
raise
'job not editable'
'tenant'
'inbox'
'inbox'
'message'
'message'
'thread'
'thread'
'to'
'cc'
'bcc'
'reply_all'
False
'text'
False
True
','
':'
'''UPDATE jobs SET state='pending',snapshot=?,digest=?,
approved_by=NULL,expires=NULL WHERE id=?'''
return
def
approve
path, job_id, tenant, displayed_digest, actor
# actor must come from your authenticated internal operator session.
if
not
raise
'operator required'
with
as
'''UPDATE jobs SET state='approved',approved_by=?,expires=?
WHERE id=? AND tenant=? AND state='pending' AND digest=?'''
3600
if
1
raise
'stale approval'
def
dispatch
path, job_id, tenant, allowed, send_request
with
as
'BEGIN IMMEDIATE'
'SELECT * FROM jobs WHERE id=? AND tenant=?'
if
not
or
'state'
'approved'
or
'expires'
raise
'not approved or expired'
'snapshot'
if
'digest'
raise
'snapshot changed'
if
not
all
in
for
in
'to'
raise
'allowlist changed'
"UPDATE jobs SET state='sending' WHERE id=?"
# Claim commits before the external side effect. Other workers cannot claim it.
try
'send_key'
if
not
'message_id'
or
not
'thread_id'
raise
'ambiguous response'
with
as
"UPDATE jobs SET state='sent',receipt=? WHERE id=?"