Call a hook between dialling the printer and writing to it

The job store must commit a delivery's sending mark after the printer's
connection opens and before the first byte goes out, so that a job
interrupted mid-send is never sent again after a restart, while a dial
failure writes nothing. Send now takes a beforeWrite function for that
step. An error from it closes the connection with nothing written.

The write deadline is computed after beforeWrite returns, so a slow
synced commit does not use up printer.write_timeout. The queue passes
nil for now, so nothing changes in what is sent.

Part of stage 1c of docs/plans/job-store.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-12-01 12:29:52 -06:00
1 parent 66531e7314
commit 50db21190b
4 files changed
+96 -9

No files matched your search

+13 -2
View File
@@ -56,14 +56,25 @@ func (c *Client) Addr() string {
return c.addr return c.addr
} }
// Send writes data to the printer in one connection. // Send writes data to the printer in one connection. Once the connection
func (c *Client) Send(ctx context.Context, data []byte) error { // is open, and before the first byte is written, it calls beforeWrite, if
// not nil; an error from it closes the connection with nothing written and
// is returned. The write deadline starts after beforeWrite returns, so a
// slow beforeWrite does not shorten the write. ctx bounds the wait for the
// connection and the dial, and its deadline bounds the write; cancelling
// it once the connection is open does not stop the write.
func (c *Client) Send(ctx context.Context, data []byte, beforeWrite func() error) error {
conn, release, err := c.connect(ctx) conn, release, err := c.connect(ctx)
if err != nil { if err != nil {
return err return err
} }
defer release() defer release()
if beforeWrite != nil {
if err := beforeWrite(); err != nil {
return err
}
}
writeDeadline, _ := c.deadline(ctx, c.writeTimeout) writeDeadline, _ := c.deadline(ctx, c.writeTimeout)
if err := conn.SetWriteDeadline(writeDeadline); err != nil { if err := conn.SetWriteDeadline(writeDeadline); err != nil {
return fmt.Errorf("setting printer write deadline: %w", err) return fmt.Errorf("setting printer write deadline: %w", err)
+77 -3
View File
@@ -43,7 +43,7 @@ func TestSend(t *testing.T) {
received <- data received <- data
}) })
client := printer.NewClient(addr, time.Second, time.Second) client := printer.NewClient(addr, time.Second, time.Second)
if err := client.Send(context.Background(), []byte("receipt")); err != nil { if err := client.Send(context.Background(), []byte("receipt"), nil); err != nil {
t.Fatal(err) t.Fatal(err)
} }
select { select {
@@ -56,6 +56,80 @@ func TestSend(t *testing.T) {
} }
} }
// beforeWrite runs once the connection is open and before the first byte;
// when it fails, the printer receives nothing and Send returns its error.
func TestSendCallsBeforeWrite(t *testing.T) {
accepted := make(chan struct{}, 2)
firstByte := make(chan struct{}, 2)
received := make(chan []byte, 2)
addr := fakePrinter(t, func(conn net.Conn) {
accepted <- struct{}{}
first := make([]byte, 1)
if _, err := io.ReadFull(conn, first); err != nil {
received <- nil
return
}
firstByte <- struct{}{}
rest, _ := io.ReadAll(conn)
received <- append(first, rest...)
})
client := printer.NewClient(addr, time.Second, time.Second)
var calls int
err := client.Send(context.Background(), []byte("receipt"), func() error {
calls++
select {
case <-accepted:
case <-time.After(2 * time.Second):
t.Error("the printer never accepted the connection")
}
select {
case <-firstByte:
t.Error("the printer got a byte before beforeWrite returned")
case <-time.After(50 * time.Millisecond):
}
return nil
})
if err != nil || calls != 1 {
t.Fatalf("Send = %v after %d calls, want nil after 1", err, calls)
}
if got := <-received; !bytes.Equal(got, []byte("receipt")) {
t.Errorf("printer got %q", got)
}
refused := errors.New("not recorded")
if err := client.Send(context.Background(), []byte("receipt"), func() error { return refused }); !errors.Is(err, refused) {
t.Errorf("Send = %v, want the error beforeWrite returned", err)
}
select {
case got := <-received:
if len(got) != 0 {
t.Errorf("printer got %q after beforeWrite failed, want nothing", got)
}
case <-time.After(2 * time.Second):
t.Fatal("the connection was not closed after beforeWrite failed")
}
}
// A dial that fails never calls beforeWrite.
func TestSendDialFailureSkipsBeforeWrite(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := ln.Addr().String()
_ = ln.Close()
client := printer.NewClient(addr, 500*time.Millisecond, time.Second)
called := false
if err := client.Send(context.Background(), []byte("x"), func() error { called = true; return nil }); err == nil {
t.Fatal("expected a connection error")
}
if called {
t.Error("beforeWrite ran although the dial failed")
}
}
func TestSendUnreachable(t *testing.T) { func TestSendUnreachable(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0") ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil { if err != nil {
@@ -65,7 +139,7 @@ func TestSendUnreachable(t *testing.T) {
_ = ln.Close() // nothing listens here now _ = ln.Close() // nothing listens here now
client := printer.NewClient(addr, 500*time.Millisecond, time.Second) client := printer.NewClient(addr, 500*time.Millisecond, time.Second)
if err := client.Send(context.Background(), []byte("x")); err == nil { if err := client.Send(context.Background(), []byte("x"), nil); err == nil {
t.Fatal("expected a connection error") t.Fatal("expected a connection error")
} }
} }
@@ -94,7 +168,7 @@ func TestSendRespectsCancelledContextWhileBusy(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel() defer cancel()
if err := client.Send(ctx, []byte("x")); !errors.Is(err, context.DeadlineExceeded) { if err := client.Send(ctx, []byte("x"), nil); !errors.Is(err, context.DeadlineExceeded) {
t.Errorf("err = %v, want context.DeadlineExceeded", err) t.Errorf("err = %v, want context.DeadlineExceeded", err)
} }
} }
+5 -3
View File
@@ -86,9 +86,11 @@ type Renderer interface {
Render(ctx context.Context, job receipt.Job) ([]byte, error) Render(ctx context.Context, job receipt.Job) ([]byte, error)
} }
// Sender delivers bytes to the printer. // Sender delivers bytes to the printer. It calls beforeWrite, if not nil,
// once it can write and before the first byte, and writes nothing when
// beforeWrite fails.
type Sender interface { type Sender interface {
Send(ctx context.Context, data []byte) error Send(ctx context.Context, data []byte, beforeWrite func() error) error
} }
// Options configures a Queue. // Options configures a Queue.
@@ -259,7 +261,7 @@ func (q *Queue) print(runCtx, jobCtx context.Context, job receipt.Job, logger *s
} }
delay := q.options.RetryDelay delay := q.options.RetryDelay
for attempt := 1; ; attempt++ { for attempt := 1; ; attempt++ {
err := q.sender.Send(jobCtx, data) err := q.sender.Send(jobCtx, data, nil)
if err == nil { if err == nil {
return attempt, nil return attempt, nil
} }
+1 -1
View File
@@ -31,7 +31,7 @@ type fakeSender struct {
block chan struct{} // if set, Send waits for it to close block chan struct{} // if set, Send waits for it to close
} }
func (f *fakeSender) Send(_ context.Context, data []byte) error { func (f *fakeSender) Send(_ context.Context, data []byte, _ func() error) error {
if f.block != nil { if f.block != nil {
<-f.block <-f.block
} }