Files
allmende/internal/inbox/inbox.go
T
nilsandClaude Sonnet 5.5 a81595e9ee Announce incoming messages on the node's terminal
The node now checks for new messages every 10 s in the background (before,
only when the web UI asked), and Inbox.Collect reports newly filed visible
messages through OnArrivals. The CLI logs one line per conversation with the
listing title and a link to it, never the buyer's text. Hidden messages are not
announced, a backlog is capped at 5 lines, and a lock stops a background check
and a UI request from filing the same message twice.

The e2e checks that node A announces the message before its API is called.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 21:29:49 +01:00

332 lines
9.2 KiB
Go

// Package inbox is the owner's side of messaging: it collects the encrypted
// envelopes the network holds for the owner's listings, decrypts them with the
// device key, keeps the conversations, and sends replies and address grants.
//
// Everything here stays on the owner's node. Relays only ever see ciphertext.
package inbox
import (
"context"
"errors"
"fmt"
"sort"
"sync"
"time"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/message"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
const (
// DefaultMaxNewThreads is how many conversations a listing can start per
// day before further first messages wait.
DefaultMaxNewThreads = 20
// DefaultGrantDays is how long an address grant is shown to the buyer.
DefaultGrantDays = 7
)
var (
// ErrNoThread means no such conversation exists.
ErrNoThread = errors.New("inbox: no such conversation")
// ErrNotOwner means the listing belongs to another author.
ErrNotOwner = errors.New("inbox: not this node's listing")
// ErrInvalid wraps a reply that cannot be sent as given (the caller's
// mistake, as opposed to a failure of the node).
ErrInvalid = errors.New("inbox: invalid reply")
)
// Publisher sends an envelope into the network (p2p.Node implements it).
type Publisher interface {
PublishMessage(ctx context.Context, region string, e *message.Envelope) error
}
// Inbox belongs to one device.
type Inbox struct {
Store *store.Store
Device *identity.Device
Publisher Publisher
// Difficulty is the proof-of-work of the replies this node sends.
Difficulty int
// MaxNewThreads is the per-listing, per-24-hours limit on new
// conversations; 0 means DefaultMaxNewThreads.
MaxNewThreads int
Clock func() time.Time
// OnArrivals, if set, is called after a Collect that filed visible new
// messages, once per call, with one entry per message. It runs on the
// collecting goroutine, so it should return quickly. It never receives
// message text. Set it before the Inbox is used.
OnArrivals func([]Arrival)
mu sync.Mutex // one Collect at a time, so a message is filed and announced once
}
// Arrival describes a message that was just filed for one of the owner's
// listings. Hidden messages (those that broke the first-message rules) are not
// reported.
type Arrival struct {
Listing message.Ref
Thread string
// New is true if the message started a conversation.
New bool
}
func (i *Inbox) now() time.Time {
if i.Clock != nil {
return i.Clock()
}
return time.Now()
}
func (i *Inbox) maxNewThreads() int {
if i.MaxNewThreads > 0 {
return i.MaxNewThreads
}
return DefaultMaxNewThreads
}
type candidate struct {
hash string
env *message.Envelope
plain *message.Plain
work int
}
type threadKey struct {
ref message.Ref
thread string
}
// Collect reads the envelopes the node holds for the owner's listings,
// decrypts the ones it has not seen and files them into conversations. It
// returns how many messages were added.
//
// Two owner-side rules are applied here, because relays cannot see content:
// - until the owner has replied, a buyer's message must be short and free of
// links; a violating message is kept but hidden;
// - at most MaxNewThreads new conversations per listing start every 24
// hours. Surplus first messages stay queued, unread, until there is room
// (strongest proof-of-work first, then oldest) or they expire.
func (i *Inbox) Collect(ctx context.Context) (int, error) {
i.mu.Lock()
defer i.mu.Unlock()
var arrivals []Arrival
defer func() {
if i.OnArrivals != nil && len(arrivals) > 0 {
i.OnArrivals(arrivals)
}
}()
envs, err := i.Store.OwnerMessages(ctx, i.Device.Cert.Author)
if err != nil {
return 0, err
}
hashes := make([]string, len(envs))
for k, e := range envs {
if hashes[k], err = e.Hash(); err != nil {
return 0, err
}
}
seen, err := i.Store.SeenEnvelopes(ctx, hashes)
if err != nil {
return 0, err
}
var known []candidate
fresh := map[threadKey][]candidate{}
for k, e := range envs {
h := hashes[k]
if seen[h] {
continue
}
p, err := e.OpenAsOwner(i.Device)
if err != nil {
// Not for this device, damaged, or malformed: never look again.
if err := i.Store.MarkSeen(ctx, h, e.ExpiresAt); err != nil {
return 0, err
}
continue
}
work, _ := e.Work()
c := candidate{hash: h, env: e, plain: p, work: work}
key := threadKey{e.Listing, p.Thread}
exists, err := i.Store.HasThread(ctx, e.Listing, p.Thread)
if err != nil {
return 0, err
}
if exists {
known = append(known, c)
} else {
fresh[key] = append(fresh[key], c)
}
}
added := 0
admit := func(cs []candidate, starts bool) error {
sort.Slice(cs, func(a, b int) bool {
if cs[a].plain.SentAt != cs[b].plain.SentAt {
return cs[a].plain.SentAt < cs[b].plain.SentAt
}
return cs[a].plain.N < cs[b].plain.N
})
for k, c := range cs {
hidden, err := i.file(ctx, c)
if err != nil {
return err
}
added++
if !hidden {
arrivals = append(arrivals, Arrival{Listing: c.env.Listing, Thread: c.plain.Thread, New: starts && k == 0})
}
}
return nil
}
if err := admit(known, false); err != nil {
return added, err
}
// New conversations, strongest first, within each listing's daily budget.
byListing := map[message.Ref][]threadKey{}
for key := range fresh {
byListing[key.ref] = append(byListing[key.ref], key)
}
since := i.now().Add(-24 * time.Hour).Unix()
for ref, keys := range byListing {
used, err := i.Store.NewThreadsSince(ctx, ref, since)
if err != nil {
return added, err
}
room := i.maxNewThreads() - used
strength := func(k threadKey) (work int, oldest int64) {
oldest = 1<<62 - 1
for _, c := range fresh[k] {
if c.work > work {
work = c.work
}
if c.env.CreatedAt < oldest {
oldest = c.env.CreatedAt
}
}
return
}
sort.Slice(keys, func(a, b int) bool {
wa, oa := strength(keys[a])
wb, ob := strength(keys[b])
if wa != wb {
return wa > wb
}
if oa != ob {
return oa < ob
}
return keys[a].thread < keys[b].thread
})
for k := 0; k < len(keys) && k < room; k++ {
if err := admit(fresh[keys[k]], true); err != nil {
return added, err
}
}
}
return added, nil
}
// file stores one incoming message and reports whether it was hidden.
func (i *Inbox) file(ctx context.Context, c candidate) (hidden bool, err error) {
replied, err := i.Store.Replied(ctx, c.env.Listing, c.plain.Thread)
if err != nil {
return false, err
}
hidden = !replied && c.plain.CheckBuyerFirst() != nil
err = i.Store.AddInbox(ctx, store.InboxMessage{
Hash: c.hash, Listing: c.env.Listing, Thread: c.plain.Thread, Dir: store.InboxIn,
Plain: c.plain, Hidden: hidden, ReceivedAt: i.now().Unix(),
}, c.env.ExpiresAt)
return hidden, err
}
// Reply is what the owner sends back.
type Reply struct {
Type string // message.TypeText or message.TypeGrant
Text string // text
// Grant fields. Address, Phone and Email default to the values saved for
// the listing when left empty.
Address, Phone, Email, Note string
ValidDays int // 0 means DefaultGrantDays
}
// Send signs a reply, publishes it to the buyer's mailbox and records it in
// the conversation.
func (i *Inbox) Send(ctx context.Context, ref message.Ref, thread string, r Reply) (*message.Envelope, error) {
if ref.Author != i.Device.Cert.Author {
return nil, ErrNotOwner
}
ok, err := i.Store.HasThread(ctx, ref, thread)
if err != nil {
return nil, err
}
if !ok {
return nil, ErrNoThread
}
region, err := i.Store.Region(ctx, ref.Author, ref.ID)
if err != nil {
return nil, fmt.Errorf("inbox: the listing is gone, so the reply cannot be routed: %w", err)
}
n, err := i.Store.NextOut(ctx, ref, thread)
if err != nil {
return nil, err
}
now := i.now()
p := &message.Plain{Type: r.Type, Thread: thread, N: n, SentAt: now.Unix()}
switch r.Type {
case message.TypeText:
p.Text = r.Text
case message.TypeGrant:
p.Address, p.Phone, p.Email, p.Note = r.Address, r.Phone, r.Email, r.Note
if p.Address == "" {
saved, err := i.Store.GetAddress(ctx, ref)
if errors.Is(err, store.ErrNotFound) {
return nil, fmt.Errorf("%w: no address given and none saved for this listing", ErrInvalid)
}
if err != nil {
return nil, err
}
p.Address = saved.Address
if p.Phone == "" {
p.Phone = saved.Phone
}
if p.Email == "" {
p.Email = saved.Email
}
}
days := r.ValidDays
if days == 0 {
days = DefaultGrantDays
}
if days < 0 || time.Duration(days)*24*time.Hour > message.MaxGrantValidity {
return nil, fmt.Errorf("%w: valid_days must be between 1 and 30", ErrInvalid)
}
p.ValidUntil = now.Add(time.Duration(days) * 24 * time.Hour).Unix()
default:
return nil, fmt.Errorf("%w: unknown reply type %q", ErrInvalid, r.Type)
}
env, err := message.SealToBuyer(i.Device, ref, p, now, i.Difficulty)
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrInvalid, err)
}
if err := i.Publisher.PublishMessage(ctx, region, env); err != nil {
return nil, err
}
h, err := env.Hash()
if err != nil {
return nil, err
}
err = i.Store.AddInbox(ctx, store.InboxMessage{
Hash: h, Listing: ref, Thread: thread, Dir: store.InboxOut, Plain: p, ReceivedAt: now.Unix(),
}, env.ExpiresAt)
return env, err
}