Skip to content
Open
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
68 changes: 60 additions & 8 deletions broker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -262,11 +262,6 @@ Owner scoping still applies. Reading actions and their history uses existing
read permissions. Import is available only through trusted master access and
accepts this action with the same configuration validation.

`POST /batch_actions/{id}/run` (or `/broker/batch_actions/{id}/run`) queues one
manual run and returns `202`. It preserves the saved schedule and enabled state,
so a disabled action can be run once without enabling it. Okapi callers need
`broker.batch_actions.item.run.post`. Scheduled and manual batch runs can overlap,
including while earlier batch events or background actions remain unfinished.
Archive operations use database locking and atomic checks for each resource.

The legacy `archive` binary, `POST /archive_ill_transactions`, `call_archive.sh`,
Expand Down Expand Up @@ -359,7 +354,7 @@ Configuration is provided via environment variables:
| | `illConfig.noteFieldSeparator` . | |
| `CLIENT_DELAY` | Delay duration for outgoing ISO18626 messages | `0ms` |
| `SHUTDOWN_DELAY` | Delay duration for graceful shutdown (in-flight | `15s` |
| | connections) | |
| | HTTP connections and batch workers) | |
| `MAX_MESSAGE_SIZE` | Max accepted ISO18626 message size | `100KB` |
| `HOLDINGS_ADAPTER` | Comma-separated, ordered list of holdings lookup | `mock` |
| | methods: `mock` , `sru` and/or `consortium` (e.g. | |
Expand Down Expand Up @@ -403,13 +398,14 @@ Configuration is provided via environment variables:
| | Request on supplier side Deprecated: use supplier | |
| | `illConfig.supplierPatronPattern` . | |
| `LANGUAGE` | Language parameter used for ts_vector search in DB | `english` |
| `SCHEDULER_RETRY_DELAY` | Delay for failed tasks, pull-slip email runs | `5m` |
| | waiting for prior work, and fallback polling | |
| `SCHEDULER_RETRY_DELAY` | Scheduler polling and one-off task recovery delay | `5m` |
| `BATCH_WORKER_LEASE` | Worker ownership duration, from 1s to 30m | `5m` |
| `SMTP_HOST` | SMTP server host for sending emails, if not | (empty value) |
| | configured all email tasks will fail | |
| `SMTP_PORT` | SMTP server port | `2525` |
| `SMTP_USERNAME` | Username for SMTP authentication | (empty value) |
| `SMTP_PASSWORD` | Password for SMTP authentication | (empty value) |
| `SMTP_TIMEOUT` | SMTP delivery timeout as a Go duration | `30s` |
| `BATCH_PULLSLIP_MAX_COUNT` | Max count of Patron request to include in pullslip | `100` |
| | batch | |
| `BATCH_ACTION_RUN_RETENTION` | Number of batch action events to retain. Set to 0 | `5` |
Expand Down Expand Up @@ -522,6 +518,62 @@ For Loan and CopyOrLoan requests, generating a pull-slip PDF queues the `pullsli

The `email-pullslips` batch queues the same action after SMTP successfully accepts an email containing a PDF. Emails without PDFs and failed generation or sending do not advance requests. Actions run asynchronously and recheck the current state. If queuing fails after output, the operation reports an error; retrying may reproduce the PDF or email, while repeated `pullslip-printed` actions in `SEARCHING` are harmless. Existing saved batch queries are not rewritten; use `WILL_SUPPLY` for pull-slip queries and include `SEARCHING` in aging queries as needed.

### Batch runs and recovery

Batch actions reserve the action for their owner across all saved schedules
and broker replicas. An unrestricted run reserves the action for all owners.
Archive actions are exempt because each resource is archived atomically in
PostgreSQL and the operation has no external side effects. Scheduled
occurrences that conflict are skipped and logged with the blocking run ID
and start time.

Child tasks and notices inherit the run from their parent event. Queued tasks
can take their own leases. Inline tasks and workflows that resume a waiter on
another replica share the originating worker's lease. The run stays active
through completion callbacks and until all linked work is finished.

After a worker stops renewing its lease, a broker records unfinished tasks as
`ERROR` without publishing completion signals. Batch-action history shows the
batch and background tasks. Local message tasks and their inline actions appear
in the affected request’s event history. Live sibling tasks keep running. Startup and a
15-second poll recover expired workers and pick up queued work even if a
notification was missed. The initial worker lease is five minutes by default,
renewed every third of the configured interval, with retries until the current
deadline and a 30-minute cap. Delegated ISO tasks follow the owner's renewed
lease through PostgreSQL. Each broker runs up to eight batch workers.
Shutdown gives active workers up to `SHUTDOWN_DELAY` to complete.

To rerun a saved action, find its ID in `GET /batch_actions` and inspect its
history at `GET /batch_actions/{id}/events`. When unfinished tasks have completed or expired, send a POST to the action's
`runLink` (`/batch_actions/{id}/run`).
A `202` queues a fresh run with the saved configuration and preserves the
schedule and enabled state. A `409` identifies the active run and when it was queued.
Okapi callers can use the `/broker` prefix and need
`broker.batch_actions.item.run.post` plus the action's usual authorization.
Scheduled actions also continue at their next occurrence.

ISO 18626 requesting and supplying agency messages have 55 seconds from HTTP
handler entry to produce a confirmation. Once a new or retried ILL request has
been saved, the broker gives its workflow notice up to five seconds to publish
even if the requester disconnects. Confirmation tasks have a two-minute expiry.
Recovery and rollback clear pending signals on interrupted tasks and record
them as `ERROR` so they do not block transaction archiving.

SMTP delivery stops after `SMTP_TIMEOUT` (30 seconds by default) or at the
worker's lease deadline, whichever comes first. A successful final DATA
response counts as delivery.
A dropped connection during the DATA response, or an interruption after SMTP
accepted the email and before the request actions completed, can produce
duplicate slips on a later run. Review the run history and check whether staff
received the email before rerunning. Pull-slip actions recheck request state.

Before applying migration 083, drain and stop all older broker replicas.
The migration marks unfinished batch and local message tasks, including
their inline actions, as interrupted. It gives unfinished ISO 18626
confirmations their cleanup grace period.
Start the upgraded replicas before using the run endpoint.


## Action results and automatic execution

Action outcomes (`success`, `failure`, and `review`) only select their configured
Expand Down
27 changes: 24 additions & 3 deletions broker/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ type Context struct {
PsApiHandler psapi.PullSlipApiHandler
SchedApiHandler schedapi.SchedulerApiHandler
ImportApiHandler importapi.ApiHandler
stopScheduler context.CancelFunc
}

func configLog() slog.Handler {
Expand Down Expand Up @@ -225,7 +226,9 @@ func Init(ctx context.Context) (Context, error) {
}

schedApiHandler := schedapi.NewSchedulerApiHandler(API_PAGE_SIZE, schedRepo, eventRepo, tenantResolver, prRepo)
if err = StartScheduler(ctx, schedRepo, eventBus); err != nil {
schedulerCtx, stopScheduler := context.WithCancel(ctx)
if err = StartScheduler(schedulerCtx, schedRepo, eventBus); err != nil {
stopScheduler()
return Context{}, err
}

Expand All @@ -244,6 +247,7 @@ func Init(ctx context.Context) (Context, error) {
PsApiHandler: psApiHandler,
SchedApiHandler: schedApiHandler,
ImportApiHandler: importApiHandler,
stopScheduler: stopScheduler,
}, nil
}

Expand All @@ -266,6 +270,9 @@ func StartServer(ctx Context) error {
// StartServerWithListener serves HTTP on an already bound listener and closes it
// when the server stops or initialization fails. It takes ownership of listener.
func StartServerWithListener(ctx Context, listener net.Listener) error {
if ctx.stopScheduler != nil {
defer ctx.stopScheduler()
}
defer func() { _ = listener.Close() }()
ServeMux = http.NewServeMux()
oapiValidator, err := newOpenAPIRequestValidator()
Expand Down Expand Up @@ -332,12 +339,26 @@ func StartServerWithListener(ctx Context, listener net.Listener) error {
case sig := <-shutdown:
appCtx.Logger().Info("HTTP server shutdown initiated", "signal", sig)
// give outstanding requests a timeout to complete
ctx, cancel := context.WithTimeout(appCtx, SHUTDOWN_DELAY)
if ctx.stopScheduler != nil {
ctx.stopScheduler()
}
shutdownCtx, cancel := context.WithTimeout(appCtx, SHUTDOWN_DELAY)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
drained := make(chan error, 1)
go func() {
if bus, ok := ctx.EventBus.(*events.PostgresEventBus); ok {
drained <- bus.DrainBatchWorkers(shutdownCtx)
return
}
drained <- nil
}()
if err := server.Shutdown(shutdownCtx); err != nil {
server.Close()
return fmt.Errorf("HTTP server could not shutdown gracefully: %w", err)
}
if err := <-drained; err != nil {
appCtx.Logger().Warn("batch worker drain ended before all workers finished", "error", err)
}
appCtx.Logger().Info("HTTP server shutdown complete")
return nil
}
Expand Down
1 change: 1 addition & 0 deletions broker/chart/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ okapi-hooks:

containerPort: 8080
# envvars passed to the container
# Set env.SMTP_TIMEOUT to override the broker's 30s SMTP delivery timeout.
env: {}

# envvars passed to the container as secretKeyRef, format
Expand Down
27 changes: 20 additions & 7 deletions broker/client/client.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package client

import (
"context"
"errors"
"fmt"
"net/http"
Expand Down Expand Up @@ -456,27 +457,39 @@ func (c *Iso18626Client) checkConfirmationError(ctx common.ExtendedContext, resp
return status
}

func (c *Iso18626Client) HandleIllMessage(ctx common.ExtendedContext, peer *ill_db.Peer, msg *iso18626.ISO18626Message) (*iso18626.ISO18626Message, error) {
func (c *Iso18626Client) HandleIllMessage(ctx common.ExtendedContext, peer *ill_db.Peer, msg *iso18626.ISO18626Message, parentID *string) (*iso18626.ISO18626Message, error) {
if peer == nil {
return nil, fmt.Errorf("peer is nil")
}
if strings.EqualFold(peer.Vendor, string(dirapi.CrossLink)) {
return c.prMessageHandler.HandleMessage(ctx, msg, peer)
return c.prMessageHandler.HandleMessage(ctx, msg, peer, parentID)
}
return c.SendHttpPost(peer, msg)
return c.sendHttpPost(ctx, peer, msg)
}

func (c *Iso18626Client) SendHttpPost(peer *ill_db.Peer, msg *iso18626.ISO18626Message) (*iso18626.ISO18626Message, error) {
return c.sendHttpPost(context.Background(), peer, msg)
}

func (c *Iso18626Client) sendHttpPost(ctx context.Context, peer *ill_db.Peer, msg *iso18626.ISO18626Message) (*iso18626.ISO18626Message, error) {
httpClient := httpclient.NewClient().
WithMaxSize(int64(c.maxMsgSize)).
WithHeaders("User-Agent", vcs.GetSignature())
for k, v := range peer.HttpHeaders {
httpClient.WithHeaders(k, v)
}
time.Sleep(c.sendDelay)
if c.sendDelay > 0 {
timer := time.NewTimer(c.sendDelay)
defer timer.Stop()
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-timer.C:
}
}
iso18626Shim := getPeerShim(peer)
var resmsg iso18626.ISO18626Message
err := httpClient.RequestResponse(c.client, http.MethodPost,
err := httpClient.RequestResponseContext(ctx, c.client, http.MethodPost,
[]string{httpclient.ContentTypeApplicationXml, httpclient.ContentTypeTextXml},
peer.Url, msg, &resmsg, func(v any) ([]byte, error) {
if isoM, ok := v.(*iso18626.ISO18626Message); ok {
Expand Down Expand Up @@ -712,7 +725,7 @@ func (c *Iso18626Client) sendAndUpdateStatus(ctx common.ExtendedContext, trCtx t
resData.CustomData = map[string]any{common.DO_NOT_SEND: true}
resData.OutgoingMessage = nil
} else {
response, err := c.HandleIllMessage(ctx, trCtx.requester, message)
response, err := c.HandleIllMessage(ctx, trCtx.requester, message, &trCtx.event.ID)
if response != nil {
resData.IncomingMessage = response
}
Expand Down Expand Up @@ -835,7 +848,7 @@ func (c *Iso18626Client) sendAndUpdateSupplier(ctx common.ExtendedContext, trCtx
resData := events.EventResult{}
resData.OutgoingMessage = message
if !isDoNotSend(trCtx.event) {
response, err := c.HandleIllMessage(ctx, trCtx.selectedSupplierPeer, message)
response, err := c.HandleIllMessage(ctx, trCtx.selectedSupplierPeer, message, &trCtx.event.ID)
if response != nil {
resData.IncomingMessage = response
}
Expand Down
12 changes: 6 additions & 6 deletions broker/client/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1077,18 +1077,18 @@ func TestHandleIllMessage(t *testing.T) {
},
}

_, err := client.HandleIllMessage(appCtx, nil, sam)
_, err := client.HandleIllMessage(appCtx, nil, sam, nil)
assert.EqualError(t, err, "peer is nil")

// To internal peer
_, err = client.HandleIllMessage(appCtx, &ill_db.Peer{Vendor: string(dirapi.CrossLink)}, sam)
_, err = client.HandleIllMessage(appCtx, &ill_db.Peer{Vendor: string(dirapi.CrossLink)}, sam, nil)
assert.EqualError(t, err, "searching pr with id=req-1")

// Internal, case insensitive
_, err = client.HandleIllMessage(appCtx, &ill_db.Peer{Vendor: "crosslinK"}, sam)
_, err = client.HandleIllMessage(appCtx, &ill_db.Peer{Vendor: "crosslinK"}, sam, nil)
assert.EqualError(t, err, "searching pr with id=req-1")

_, err = client.HandleIllMessage(appCtx, &ill_db.Peer{}, sam)
_, err = client.HandleIllMessage(appCtx, &ill_db.Peer{}, sam, nil)
assert.EqualError(t, err, "Post \"\": unsupported protocol scheme \"\"")
}

Expand Down Expand Up @@ -1134,7 +1134,7 @@ func TestCancellationReasonDelivery(t *testing.T) {
client := CreateIso18626Client(nil, nil, prservice.PatronRequestMessageHandler{}, 1024*1024, 0)
msg := iso18626.NewISO18626Message()
msg.SupplyingAgencyMessage = &iso18626.SupplyingAgencyMessage{MessageInfo: iso18626.MessageInfo{ReasonForMessage: iso18626.TypeReasonForMessageCancelResponse, Note: note}, StatusInfo: iso18626.StatusInfo{Status: iso18626.TypeStatusCancelled}}
_, err := client.HandleIllMessage(ctx, &ill_db.Peer{Url: server.URL, Vendor: string(dirapi.Alma)}, msg)
_, err := client.HandleIllMessage(ctx, &ill_db.Peer{Url: server.URL, Vendor: string(dirapi.Alma)}, msg, nil)
assert.NoError(t, err)
assert.Equal(t, note, msg.SupplyingAgencyMessage.MessageInfo.Note)
})
Expand All @@ -1145,7 +1145,7 @@ func TestCancellationReasonDelivery(t *testing.T) {
client := CreateIso18626Client(nil, nil, handler, 1024*1024, 0)
msg := iso18626.NewISO18626Message()
msg.SupplyingAgencyMessage = &iso18626.SupplyingAgencyMessage{Header: iso18626.Header{RequestingAgencyRequestId: "pr"}, MessageInfo: iso18626.MessageInfo{ReasonForMessage: iso18626.TypeReasonForMessageCancelResponse, Note: note}, StatusInfo: iso18626.StatusInfo{Status: iso18626.TypeStatusCancelled}}
response, err := client.HandleIllMessage(ctx, &ill_db.Peer{Vendor: string(dirapi.CrossLink)}, msg)
response, err := client.HandleIllMessage(ctx, &ill_db.Peer{Vendor: string(dirapi.CrossLink)}, msg, nil)
assert.NoError(t, err)
if assert.NotNil(t, response) {
assert.Equal(t, iso18626.TypeMessageStatusOK, response.SupplyingAgencyMessageConfirmation.ConfirmationHeader.MessageStatus)
Expand Down
1 change: 1 addition & 0 deletions broker/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -57,5 +57,6 @@ services:
DB_PORT: 5432
DB_PROVISION: "true"
DB_MIGRATE: "true"
SMTP_TIMEOUT: ${SMTP_TIMEOUT:-30s}
ports:
- "8081:8081"
38 changes: 27 additions & 11 deletions broker/email/email.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package email

import (
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
Expand Down Expand Up @@ -37,17 +38,6 @@ var (
SMTP_PASSWORD = utils.GetEnv("SMTP_PASSWORD", "")
)

// Mailer is an interface over smtp.SendMail, allowing mocking in tests.
type Mailer interface {
SendMail(addr string, a smtp.Auth, from string, to []string, msg []byte) error
}

type DefaultMailer struct{}

func (m *DefaultMailer) SendMail(addr string, a smtp.Auth, from string, to []string, msg []byte) error {
return smtp.SendMail(addr, a, from, to, msg)
}

// EmailData carries the email payload inside an EventData.CustomData map.
type EmailData struct {
To []string `json:"to"`
Expand Down Expand Up @@ -100,6 +90,32 @@ func (s *EmailServiceImpl) SendEmail(from string, to []string, raw []byte) error
return s.mailer.SendMail(s.smtpAddr, s.smtpAuth, from, to, raw)
}

// SendEmailContext uses the connection deadline when supported by the mailer.
func (s *EmailServiceImpl) SendEmailContext(ctx context.Context, from string, to []string, raw []byte) error {
if !s.readyToSend {
return errors.New("email sender not configured")
}
if mailer, ok := s.mailer.(interface {
SendMailContext(context.Context, string, smtp.Auth, string, []string, []byte) error
}); ok {
return mailer.SendMailContext(ctx, s.smtpAddr, s.smtpAuth, from, to, raw)
}
return s.SendEmail(from, to, raw)
}

// SendWithContext submits email with the caller's deadline when the sender supports it.
func SendWithContext(ctx context.Context, sender EmailService, from string, to []string, raw []byte) error {
if err := ctx.Err(); err != nil {
return err
}
if contextual, ok := sender.(interface {
SendEmailContext(context.Context, string, []string, []byte) error
}); ok {
return contextual.SendEmailContext(ctx, from, to, raw)
}
return sender.SendEmail(from, to, raw)
}

func (s *EmailServiceImpl) IsReadyToSend() bool {
return s.readyToSend
}
Expand Down
Loading
Loading