txn

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 19, 2026 License: Apache-2.0 Imports: 23 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package txn holds the pure parts of the guarantee "at most one effect per business key": the idempotency key (invariant I2), the hash of the request and the order payload (this file and order.go), and the relay that delivers the outbox (relay.go). The SQL lives in internal/store.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BusinessKeyJSON

func BusinessKeyJSON(partnerID, ref string) ([]byte, error)

BusinessKeyJSON is the form of the business key stored next to the idempotency key: ["<partner_id>","<ref>"].

func Key

func Key(tenant, tool, partnerID, ref string) [32]byte

Key is k = SHA-256(part(tenant) || part(tool) || part(partner_id) || part(ref)), where part(x) is the length of x in bytes (uint32, big endian) followed by the bytes. The lengths keep ("ab","c") and ("a","bc") apart. ref is BEG03 of an 850 without spaces at the edges; case and leading zeros stay.

func NormSupplierOrder

func NormSupplierOrder(raw []byte) ([]policy.NormLine, error)

NormSupplierOrder reads the lines of a stored order to a supplier ([{"sku","qty","unit_price"}], decimal strings) into the normal form.

func ReqHash

func ReqHash(payload any) ([]byte, error)

ReqHash is SHA-256 of the canonical JSON (RFC 8785) of the payload of the effect. It is taken over what the effect will carry, not over the raw arguments, so the same order that arrives again in a new exchange gives the same hash.

func RequestKey

func RequestKey(args []byte, parts ...string) ([32]byte, error)

RequestKey is the key of the weak configurations: SHA-256 of the length-prefixed parts (as in Key) where the last part is the arguments of the call in the canonical form of RFC 8785. The mode reqhash (C1) passes (tool, args), the mode no-bizkey (C3-A3) passes (tenant, tool, args). Arguments that are not valid JSON are an error.

func SKUs

func SKUs(lines []document.Line) []string

SKUs lists the product ids of the lines that can be looked up in the price list: a line without a SKU and a SKU that is a note reference are left out (BuildOrder refuses them as unknown_sku).

Types

type Chaos

type Chaos struct {
	ExitBeforeSend float64       // chance to exit after a row is chosen, before the ERP is asked
	ExitAfterApply float64       // chance to exit right after the ERP took the effect, before the row is updated
	CrashAfter     time.Duration // if set, the process exits at a random moment 1 to 1.5 times this long after Start
	Rand           func() float64
	Exit           func() // defaults to os.Exit(137)
}

Chaos injects faults into the relay, for tests of the guarantee only. The probabilities are off (zero) by default.

func NewChaos

func NewChaos(exitBeforeSend, exitAfterApply float64, crashAfter time.Duration, seed *uint64) *Chaos

NewChaos builds the fault injector. With a seed the draws repeat from run to run; without one they come from crypto/rand.

func (*Chaos) Start

func (c *Chaos) Start()

Start arms the timed crash, if CrashAfter is set.

type DenyError

type DenyError struct{ Explain []string }

DenyError means the document cannot become an order. Explain holds the names of the broken checks; the tool answers policy_denied with them.

func (*DenyError) Error

func (e *DenyError) Error() string

type InvoiceLine

type InvoiceLine struct {
	SKU       string `json:"sku"`
	Qty       string `json:"qty"`
	Unit      string `json:"unit"`
	UnitPrice string `json:"unit_price"`
}

InvoiceLine is one line of the supplier invoice as the effect carries it. Quantity has three decimal places, the price two; both are strings.

type InvoicePayload

type InvoicePayload struct {
	PartnerID     string        `json:"partner_id"`
	InvoiceNumber string        `json:"invoice_number"`
	OrderRef      string        `json:"order_ref"`
	Lines         []InvoiceLine `json:"lines"`
	Total         string        `json:"total"`
	Currency      string        `json:"currency"`
}

InvoicePayload is the payload of the effect "onec.post_vendor_invoice" and the thing the request hash is taken over. Everything comes from the typed 810: supplier, number (the raw BIG02), the order number (BIG04), lines, total (TDS01) and currency.

func BuildInvoice

func BuildInvoice(h document.Header810, lines []document.Line, partnerID, ref, defaultCurrency string) (InvoicePayload, []policy.NormLine, error)

BuildInvoice makes the payload from the typed 810. It also returns the lines in the normal form the policy compares with the order to the supplier. Anything that does not fit gives a *DenyError: no lines (no_lines), a line without a usable SKU, quantity or price (invalid_line), a missing or malformed total (invalid_total), a malformed currency (invalid_currency). CUR is optional: a document without it takes defaultCurrency (the currency of the partner, else of the tenant), as an order does through the price list.

type OrderLine

type OrderLine struct {
	SKU       string `json:"sku"`
	Qty       string `json:"qty"`
	Unit      string `json:"unit"`
	UnitPrice string `json:"unit_price"`
}

OrderLine is one line of the order as the effect carries it. Quantity has three decimal places, prices two; both are strings, never floating point numbers.

type OrderPayload

type OrderPayload struct {
	PartnerID           string      `json:"partner_id"`
	BusinessRef         string      `json:"business_ref"`
	ShipTo              string      `json:"ship_to"`
	Lines               []OrderLine `json:"lines"`
	Total               string      `json:"total"`
	Currency            string      `json:"currency"`
	DeliveryInstruction string      `json:"delivery_instruction"`
}

OrderPayload is the payload of the effect "onec.create_order" and the thing the request hash is taken over. Prices, unit and currency come from the price list, never from the 850 (flow P4).

func BuildOrder

func BuildOrder(h document.Header850, lines []document.Line, partnerID, ref, delivery string, prices map[string]store.Price) (OrderPayload, error)

BuildOrder makes the payload of the effect from the typed document: prices of the price list for every line, the total and the currency. partnerID and ref are the business key (ref is the raw BEG03). Anything that does not fit gives a *DenyError: a SKU that is not in the price list or is a note reference (unknown_sku), a missing or non-positive quantity (invalid_quantity), no lines (no_lines), lines in more than one currency (mixed_currency). An empty delivery instruction is "none".

type Relay

type Relay struct {
	Store   *store.Store
	Adapter adapters.Adapter
	AS2     Transmitter // nil: rows of documents for partners stay queued
	Only    []string    // if set, the relay delivers rows of these effect types only (the open modes: the 997 of the intake)
	Workers int         // parallel workers; at least 1
	Scale   float64     // pauses are divided by it (EDIGATE_TIME_SCALE); 0 means 1
	Log     *slog.Logger
	Chaos   *Chaos // nil: no fault injection

	// MDNRepeatAfter is the pause before a transmission without an MDN is repeated.
	// Zero means 30 minutes divided by Scale, but not less than 10 seconds.
	MDNRepeatAfter time.Duration

	// AfterApply is for tests: it runs right after a successful Apply, before the
	// row is updated. An error from it leaves the row untouched, like a crash there.
	AfterApply func() error

	// BeforeSend is for tests: it runs before a document is sent to the partner, after its
	// numbers and bytes were fixed. An error from it leaves the row untouched.
	BeforeSend func() error
}

Relay delivers outbox rows to the ERP, the warehouse and the partner. Every worker takes one row per transaction (FOR UPDATE SKIP LOCKED), asks the adapter whether the effect is already there, applies it if not, and records the result in the same transaction. Whatever dies in between, the row is taken again, and the idempotent receiver (external_id = hex of the key) keeps the effect single. A document for a partner goes to AS2 instead: it is sent as it was stored, again and again with the same bytes until an MDN counts.

func (*Relay) Run

func (r *Relay) Run(ctx context.Context)

Run starts the workers and blocks until ctx ends.

func (*Relay) Step

func (r *Relay) Step(ctx context.Context) (bool, error)

Step handles one due outbox row. It reports false when there was none. An error means the row stays as it was (the transaction is rolled back).

type Transmitter

type Transmitter interface {
	Transmit(ctx context.Context, t adapters.Transmission) (adapters.Receipt, error)
}

Transmitter sends a document to a partner and returns the MDN it answered with.

Directories

Path Synopsis
Package saga drives the sagas (invariant I5): it looks at the open sagas again and again and does what each one needs next.
Package saga drives the sagas (invariant I5): it looks at the open sagas again and again and does what each one needs next.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL