store

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: 24 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 store owns the PostgreSQL pool, the embedded goose migrations and every SQL query of the gateway. All queries are parameterized.

Input: a database URL (Open) or an existing pool (New, used by tests). Output: typed values and the sentinel errors ErrNotFound and ErrNotMigrated.

Index

Constants

View Source
const (
	SavedNew       = "ok"
	SavedDuplicate = "duplicate"
	SavedConflict  = "isa13_conflict"
)

Outcomes of SaveInbound.

View Source
const (
	ReservedNew      = "new"      // a new key (or a reopened one) with a new outbox row or an approval request
	ReservedSame     = "same"     // the key exists with the same request hash
	ReservedConflict = "conflict" // the key exists with another request hash
	ReservedDenied   = "denied"   // the policy forbids the call; nothing was reserved
)

Outcomes of Reserve.

View Source
const DefaultApprovalTTL = 30 * time.Minute

DefaultApprovalTTL is the life of an approval request at time scale 1.

View Source
const TokenPrefix = "edg_"

TokenPrefix starts every gateway token.

Variables

View Source
var (
	ErrNotPending     = errors.New("approval is not pending")
	ErrAlreadyDecided = errors.New("already decided by this operator")
	ErrOwnRequest     = errors.New("the requester cannot decide the request")
)

Errors of a decision on a request. A request of another tenant and an unknown one both give ErrNotFound.

View Source
var ErrNotFailed = errors.New("key is not failed")

ErrNotFailed means a key is not in the state failed, so it cannot be reopened.

View Source
var ErrNotFound = errors.New("not found")

ErrNotFound means no row matched. A row of another tenant must look the same as a missing one, so callers answer both with not_found.

View Source
var ErrNotMigrated = errors.New("database migrations are not applied")

ErrNotMigrated means the database schema is not at the latest migration.

Functions

func HashToken

func HashToken(token string) []byte

HashToken returns the SHA-256 of a token.

func NewToken

func NewToken() (token string, sum []byte, err error)

NewToken makes a token (edg_ + base64url of 32 random bytes) and its SHA-256. The token is shown once; only the hash is stored.

func NewTxnID

func NewTxnID() string

NewTxnID makes a random version 4 UUID for the answer of an open tool.

Types

type AdvanceHints

type AdvanceHints struct {
	AckTimeout time.Duration  // how long a sent document may wait for its 997
	Denied     map[int]bool   // steps the gateway could not start because the policy refused
	Existence  map[int]string // for a step that failed without an answer: found, not_found or unknown
}

AdvanceHints are facts the store cannot find out by itself.

type Approval

type Approval struct {
	ID          string
	Kind        string
	Tool        string
	Tier        int
	Approvers   int
	Status      string
	RequestedBy string
	DecidedBy   []string
	RequestedAt time.Time
	ExpiresAt   time.Time
	Rules       json.RawMessage
	View        json.RawMessage
}

Approval is a request as the operator sees it. View and Rules hold typed values and rule names; the payload of the effect (args) is never read out.

type AuditEvent

type AuditEvent struct {
	TenantID      string
	EventType     string
	TraceID       string
	PrincipalID   string
	Tool          string
	IdemKey       []byte
	PayloadSHA256 []byte
	Outcome       string
	Detail        []byte // JSON
	PolicyExplain []byte // JSON: the decision of the policy, its deny and fired rules

	ControlNumbers []byte // JSON: ISA13, GS06 and ST02 of an outgoing document
}

AuditEvent is one row of audit_log. Empty Tool and nil hashes, keys and details are stored as NULL.

type Claim

type Claim struct {
	Row OutboxRow
	// contains filtered or unexported fields
}

Claim holds one locked outbox row inside an open transaction. The relay ends it with exactly one of Ack, Retry, Fail or Release, so that the change of the row, of the key and the audit row commit together.

func (*Claim) Ack

func (c *Claim) Ack(ctx context.Context, externalRef string) error

Ack records a delivered effect: the row is acked with its external reference, the key is completed, and "effect_applied" goes to the audit log.

func (*Claim) DocIncident

func (c *Claim) DocIncident(ctx context.Context, docID string) (string, error)

DocIncident reports why the document of the claimed row is already an incident ("" when it is not). A 997 with AK5 = R can arrive while a repeat of the transmission waits.

func (*Claim) Fail

func (c *Claim) Fail(ctx context.Context, status, reason, lastError string) error

Fail ends the row for good with status "failed" (the adapter refused the effect) or "dead" (attempts are used up). The key becomes failed with the recorded answer {"status":"rejected","reason":reason}; the audit row is "effect_failed".

func (*Claim) FailSend

func (c *Claim) FailSend(ctx context.Context, docID, reason, lastError string) error

FailSend ends the claimed row of a document for good: the document becomes an incident with the reason, the row is dead and the key failed. No new transmission follows.

func (*Claim) RecordTransmission

func (c *Claim) RecordTransmission(ctx context.Context, docID string, ok bool, mdn []byte) error

RecordTransmission counts one transmission of the document. When its MDN counted (ok), the MDN is stored and the document becomes sent, or delivered if the 997 came first. An MDN for a document that is already an incident changes nothing but the audit log.

func (*Claim) Release

func (c *Claim) Release(ctx context.Context)

Release gives the row back untouched (rollback). Safe to call after a commit.

func (*Claim) Retry

func (c *Claim) Retry(ctx context.Context, lastError string, delay time.Duration) error

Retry keeps the row pending for another attempt after delay.

type ControlNumbers

type ControlNumbers struct {
	Gateway     string // the interchange id of the tenant (ISA07:ISA08)
	ISA, GS, ST int64
}

ControlNumbers is what a document to a partner needs besides its content.

type Decision

type Decision struct {
	ID        string
	Status    string
	Approvals int
	Approvers int
}

Decision is the result of a decision on a request: its status afterwards and how many different operators have approved so far.

type Document

type Document struct {
	ID          string
	ST01        string
	PartnerID   string
	BusinessRef string
	Status      string
	Body        []byte // JSON
	CreatedAt   time.Time
}

Document is a stored document as the read tools see it.

type FixturePartner

type FixturePartner struct {
	PartnerID     string
	Role          string
	Name          string
	AutoMaxAmount string
	DailyAutoMax  string
	// ForecastAmount is the expected order amount; empty means the same as AutoMaxAmount.
	ForecastAmount string
	Contacts       []string
	ShipToCodes    []string
	SupplierOrders []FixtureSupplierOrder
}

FixturePartner is a partner with its limits, contacts and ship-to codes.

type FixturePrice

type FixturePrice struct {
	SKU       string
	Unit      string
	UnitPrice string
}

FixturePrice is a row of the price list.

type FixtureSupplierLine

type FixtureSupplierLine struct {
	SKU       string `json:"sku"`
	Qty       string `json:"qty"`
	UnitPrice string `json:"unit_price"`
}

FixtureSupplierLine is a line of such an order; Qty and UnitPrice are decimal strings.

type FixtureSupplierOrder

type FixtureSupplierOrder struct {
	OrderNumber string
	Total       string
	Lines       []FixtureSupplierLine
}

FixtureSupplierOrder is an order to a supplier that an invoice is checked against.

type FixtureTemplate

type FixtureTemplate struct {
	TemplateID string
	Category   string
}

FixtureTemplate is a mail template the tenant may use with notify.send_email.

type Fixtures

type Fixtures struct {
	TenantID      string
	InterchangeID string
	Currency      string
	Partners      []FixturePartner
	Prices        []FixturePrice
	Templates     []FixtureTemplate
}

Fixtures is the starting data of a stand: one tenant, its partners with limits, contacts and ship-to codes, and the price list. Amounts are decimal strings.

type InboundAck

type InboundAck struct {
	GS06 string
	Sets []InboundAckSet
}

InboundAck is a 997 to match: the group it answers (AK102) and the verdict on each of its sets.

type InboundAckSet

type InboundAckSet struct {
	ST02 string
	Code string
}

InboundAckSet is the verdict on one set: ST02 (AK202) and AK501.

type InboundDocument

type InboundDocument struct {
	GS06        string
	ST01        string
	ST02        string
	BusinessRef string // "" is stored as NULL
	BKRef       string // raw BEG03 or BIG02, internal only; "" is stored as NULL
	Body        []byte // JSON; nil is stored as NULL
	Status      string // received or rejected
	Errors      []byte // JSON array; nil is stored as NULL
	Notes       []InboundNote
}

InboundDocument is one transaction set of an interchange to store.

type InboundInterchange

type InboundInterchange struct {
	TenantID  string
	PartnerID string
	ISA13     string
	MessageID string
	Raw       []byte
	SHA256    []byte // of Raw; also stored as the MIC
	MDN       []byte // JSON of the MDN sent for a new interchange
	Documents []InboundDocument
	Acks      []InboundAck // the verdicts of the 997 sets of the interchange, matched in the same transaction

	// GatewayID (ISA07:ISA08 of the tenant) and Replies: the 997 to send for the groups of 850
	// and 810 of a new interchange, queued in the same transaction. Nothing is queued for a repeat.
	GatewayID string
	Replies   []outbound.AckSpec
}

InboundInterchange is a parsed interchange from a partner, ready to store.

type InboundNote

type InboundNote struct {
	Ref         string
	SegmentPath string
	Reason      string // free_text or format
	Body        string
	TaintLabel  string
	Canary      string
}

InboundNote is a piece of partner text kept out of the body, stored with the document it came from.

type Manifest

type Manifest struct {
	Server    string
	Tool      string
	SHA256    []byte // 32 bytes
	Signature []byte
	Lint      []byte // JSON array of findings
	PinnedBy  string
	PinnedAt  string // RFC 3339, set when read
}

Manifest is the pin of one tool of an upstream server.

type NoteRef

type NoteRef struct {
	Ref         string
	SegmentPath string
	Reason      string
}

NoteRef is what the agent may know about a note: where it is and why it is a note. The text stays in the table.

type OrderSaga

type OrderSaga struct {
	SagaID           string
	State            string
	PartnerID        string
	Ref              string // the raw business reference (BEG03)
	Payload          []byte // JSON: the order as the gateway built it
	SourceDocumentID string
	OrderKeyState    string // the state of the key of erp.create_sales_order
	BusinessKey      []byte // JSON: [partner, reference], and in the mode no-bizkey a third part that tells orders apart
}

OrderSaga is the order saga a sales_order_txn_id leads to.

type OrderSource

type OrderSource struct {
	ID        string
	PartnerID string
	BKRef     string // raw BEG03 or BIG02 without spaces at the edges; "" when the document has none
	Status    string
	Body      []byte // JSON
}

OrderSource is the part of a stored 850 (an order) or 810 (an invoice) that an effect is made from.

type OutboxRow

type OutboxRow struct {
	ID         int64
	TenantID   string
	Key        []byte
	EffectType string
	Payload    []byte // JSON
	Attempts   int    // failed attempts so far
}

OutboxRow is a row the relay has locked.

type Partner

type Partner struct {
	TenantID  string
	PartnerID string // ISA05:ISA06, for example ZZ:ZZTESTBUYER
	Role      string
	Name      string
}

Partner is a trading partner of a tenant. Role is "customer" (sends 850) or "supplier" (sends 810). The amount limits are filled and used from wave 2-6.

type PartnerAccess

type PartnerAccess struct {
	Role      string
	Active    bool
	GatewayID string // ISA07:ISA08 of the tenant; empty when the tenant has none
}

PartnerAccess is what /edi/inbound needs to know about a partner token.

type PartnerPolicy

type PartnerPolicy struct {
	Role          string
	Active        bool
	AutoMaxCents  *int64
	DailyMaxCents *int64
	ForecastCents *int64
	ShipToCodes   []string
	Contacts      []string
}

PartnerPolicy is the partner record the policy checks a call against. A limit that is nil is not set. Amounts are whole cents.

type PlainTxn

type PlainTxn struct {
	TxnID  string
	Tool   string
	Args   []byte // JSON
	Result []byte // JSON: the answer the tool gave
}

PlainTxn is a row of plain_txns.

type Price

type Price struct {
	UnitPrice string
	Currency  string
	Unit      string
}

Price is a row of the price list; UnitPrice is a decimal string with two places.

type Principal

type Principal struct {
	ID        string
	TenantID  string
	Kind      string
	PartnerID string
}

Principal is the caller identity found by a token. Tenant and kind come only from this record, never from the request.

type QuarantineCall

type QuarantineCall struct {
	TenantID         string
	TraceID          string
	DocumentID       string
	Ref              string
	SchemaID         string
	Model            string
	PromptTokens     *int // nil when the model reported none
	CompletionTokens *int
	LatencyMS        int
	Outcome          string
}

QuarantineCall is the cost record of one call to the model (protocol item O1). The note text and the answer are not part of it.

type RawNote

type RawNote struct {
	Ref         string
	SegmentPath string
	Reason      string
	Text        string
}

RawNote is a note with its text, for the modes that show the text of the partner.

type ReserveInput

type ReserveInput struct {
	TenantID    string
	Tool        string
	PrincipalID string
	TraceID     string
	DocumentID  string // the source document; it becomes "processed"
	Key         []byte // 32 bytes, from txn.Key
	BusinessKey []byte // JSON array
	ReqHash     []byte
	EffectType  string
	Payload     []byte // JSON, the body of the effect

	// PartnerID and AmountCents are set for a tool whose amount counts against
	// daily_auto_max (T1): the sum accepted automatically today is read under lock
	// and handed to Decide, and AmountCents is added to it when the call goes through
	// without approval. Empty PartnerID: no counter.
	PartnerID   string
	AmountCents int64

	// Decide runs inside the transaction for a new or reopened key, after the daily
	// counter is locked. A nil Decide means no policy (tests of the key itself).
	Decide func(dailyAutoCents int64) (Verdict, error)

	// ReviewView is the typed view of the call, for the review request that a
	// conflicting duplicate opens (nil: no review).
	ReviewView []byte

	// Saga ties the key to a step of a saga, in the same transaction (nil: no saga).
	Saga *SagaLink

	// BeforeOutbox is for tests: it runs after the key is written and before the
	// outbox row; an error from it rolls the whole reservation back.
	BeforeOutbox func() error
}

ReserveInput is one call of an effect tool, ready to reserve.

type Reserved

type Reserved struct {
	Outcome    string
	TxnID      string
	Status     string
	Reason     string
	ApprovalID string
	Verdict    Verdict
}

Reserved is the answer of Reserve. For ReservedNew and ReservedSame, Status is the recorded status of the key: "accepted", "pending_approval" (with ApprovalID), or for a failed key "rejected" or "expired" with the recorded Reason. For ReservedDenied, Verdict holds the rules; for ReservedConflict only Outcome is set.

type Saga

type Saga struct {
	ID, TenantID, Kind, State string
	BusinessKey, Payload      []byte
	SourceDocumentID          string
	Steps                     []SagaStep
}

Saga is a saga with its steps.

type SagaLink struct {
	Kind             string
	StepNo           int
	Steps            []string
	Payload          []byte
	SourceDocumentID string
}

SagaLink ties the key of a call to a step of a saga. Steps is set by the call that starts the saga (the names of all its steps; Payload and SourceDocumentID describe the order); a call that continues a saga leaves it nil and the saga must exist.

type SagaStep

type SagaStep struct {
	No        int
	Name      string // the effect type: onec.create_order, edi.send_855, wms.reserve, wms.ship, edi.send_856
	Status    string
	Key       []byte // the key of the effect; nil until the step is called
	KeyState  string // the state of that key; "" when there is none
	KeyReason string // why the key failed: the recorded reason or status
	CompKey   []byte // the key of the compensation; nil until it is queued
	CompState string
	DocID     string // the document the step sent; "" when it did not send one
	DocState  string
	DocReason string
	Overdue   bool // the MDN was counted and no 997 came within the time limit
}

SagaStep is one step with the facts about it.

type SaveResult

type SaveResult struct {
	Outcome string
	MDN     []byte
}

SaveResult tells what SaveInbound did. MDN is the one stored with the first copy of a duplicate interchange.

type ShipmentProgress

type ShipmentProgress struct {
	Exists       bool
	State        string
	ReserveState string // the state of the key of wms.reserve; "" when the step was not called
}

ShipmentProgress tells how far the shipment saga of an order is: whether it exists and whether its first step (the reservation) is done.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store is the gateway's access to PostgreSQL.

func New

func New(pool *pgxpool.Pool) *Store

New wraps an existing pool.

func Open

func Open(ctx context.Context, url string) (*Store, error)

Open connects to the database at url.

func (*Store) AddPartner

func (s *Store) AddPartner(ctx context.Context, p Partner) error

AddPartner registers a partner, or updates the role and name of a known one.

func (*Store) AddTenant

func (s *Store) AddTenant(ctx context.Context, id, name, interchangeID string) error

AddTenant creates a tenant. interchangeID is the gateway's ISA07:ISA08 for this tenant ("" for none). For an existing tenant the name stays and the interchange id is set only when one is given.

func (*Store) AdvanceSaga

func (s *Store) AdvanceSaga(ctx context.Context, id string, h AdvanceHints) (bool, error)

AdvanceSaga looks at the facts of a saga and does the next thing, in one transaction. It reports whether anything changed. A saga another process is working on is left to it.

func (*Store) AnchorAuditNow

func (s *Store) AnchorAuditNow(ctx context.Context, a *audit.Anchorer) error

AnchorAuditNow makes the anchors that are due and brings the anchor files up to date.

func (*Store) AppendAudit

func (s *Store) AppendAudit(ctx context.Context, e AuditEvent) error

AppendAudit adds a row to audit_log in a transaction of its own. The table rejects UPDATE and DELETE.

func (*Store) CheckMigrated

func (s *Store) CheckMigrated(ctx context.Context) error

CheckMigrated reports ErrNotMigrated unless the database version equals the latest embedded migration. It also fails when the database does not answer.

func (*Store) ClaimOutbox

func (s *Store) ClaimOutbox(ctx context.Context, skip ...string) (*Claim, error)

ClaimOutbox locks the oldest pending row that is due (FOR UPDATE SKIP LOCKED, so workers and processes never take the same row). It returns nil when there is none. A process that dies while holding a claim loses the lock with its connection and the row is taken again.

The row of a saga step waits until every earlier step of its saga has completed (invariant I5): the 855 does not leave before the order exists in the ERP. Rows of the effect types in skip are left alone (a relay that cannot deliver them).

func (*Store) ClaimOutboxOnly

func (s *Store) ClaimOutboxOnly(ctx context.Context, only ...string) (*Claim, error)

ClaimOutboxOnly is ClaimOutbox for a relay that delivers rows of the given effect types only (the open modes, which have no other rows than the 997 of the intake).

func (*Store) Close

func (s *Store) Close()

Close releases the pool.

func (*Store) DecideApproval

func (s *Store) DecideApproval(ctx context.Context, tenantID, operatorID, traceID, id string, approve bool) (Decision, error)

DecideApproval records the decision of an operator on a request of the tenant.

Reject closes the request and fails the key ({"status":"rejected","reason": "approval_rejected"}). Approve adds the operator to decided_by; when as many different operators as the request needs have approved, the request is approved and, in the same transaction, the outbox row appears and the answer of the key becomes accepted (I3). The same operator twice, and the requester, are refused. A review request is only closed: the key is not touched.

func (*Store) DefaultCurrency

func (s *Store) DefaultCurrency(ctx context.Context, tenantID, partnerID string) (string, error)

DefaultCurrency is the currency of a document that names none: the currency of the partner, else the currency of the tenant. ErrNotFound when the partner is not registered.

func (*Store) DocumentNotes

func (s *Store) DocumentNotes(ctx context.Context, tenantID, documentID string) ([]RawNote, error)

DocumentNotes returns the notes of a document of the tenant with their text, in document order. The caller has already read the document, so an unknown id gives an empty list.

func (*Store) ExpireApprovals

func (s *Store) ExpireApprovals(ctx context.Context) (int, error)

ExpireApprovals closes the pending requests whose time is over: the request becomes expired and the key of an effect request fails with {"status":"expired"}. It returns how many requests it closed. Several processes may call it at once.

func (*Store) FindPrincipal

func (s *Store) FindPrincipal(ctx context.Context, tokenSHA256 []byte) (Principal, error)

FindPrincipal looks a principal up by token hash. Unknown and revoked tokens both give ErrNotFound.

func (*Store) HasEmailTemplate

func (s *Store) HasEmailTemplate(ctx context.Context, tenantID, templateID string) (bool, error)

HasEmailTemplate reports whether the tenant has this mail template.

func (*Store) IssueMissingPartnerTokens

func (s *Store) IssueMissingPartnerTokens(ctx context.Context, tenantID string, partnerIDs []string) (map[string]string, error)

IssueMissingPartnerTokens gives a token to each of the partners that has no active one and returns the tokens by partner id. The principal is named stand-<tenant>-<partner>. The token is shown here once; only its hash is stored.

func (*Store) IssuePrincipal

func (s *Store) IssuePrincipal(ctx context.Context, p Principal, tokenSHA256 []byte) error

IssuePrincipal stores a principal with the hash of its token.

func (*Store) ListApprovals

func (s *Store) ListApprovals(ctx context.Context, tenantID, status string) ([]Approval, error)

ListApprovals returns the requests of the tenant with this status, oldest first (at most 100).

func (*Store) ListInbox

func (s *Store) ListInbox(ctx context.Context, tenantID, status string, limit int) ([]Document, error)

ListInbox returns the visible documents of one tenant, newest first. status "" means both visible statuses.

func (*Store) ListManifests

func (s *Store) ListManifests(ctx context.Context, server string) ([]Manifest, error)

ListManifests returns the pins of a server (all servers when server is empty), ordered.

func (*Store) ListNotes

func (s *Store) ListNotes(ctx context.Context, tenantID, documentID string) ([]NoteRef, error)

ListNotes returns the notes of a document of the tenant in document order. The caller has already read the document, so an unknown id gives an empty list.

func (*Store) LoadFixtures

func (s *Store) LoadFixtures(ctx context.Context, f Fixtures) error

LoadFixtures writes the data in one transaction. Running it again changes nothing that is already there: tenants, partners and prices are updated in place, contacts and ship-to codes are added only when new.

func (*Store) LoadSaga

func (s *Store) LoadSaga(ctx context.Context, id string, ackTimeout time.Duration) (Saga, error)

LoadSaga reads a saga with its steps. An unknown id gives ErrNotFound.

func (*Store) Manifests

func (s *Store) Manifests(ctx context.Context, server string) (map[string]Manifest, error)

Manifests returns the pins of one server by tool name.

func (*Store) Migrate

func (s *Store) Migrate(ctx context.Context) error

Migrate applies all embedded migrations (forward only).

func (*Store) NextControlNumbers

func (s *Store) NextControlNumbers(ctx context.Context, tenantID, partnerID string) (ControlNumbers, error)

NextControlNumbers allocates the three control numbers of one outgoing interchange from the counters the sagas use. The partner must be registered; the tenant must have an interchange id.

func (*Store) OpenSagas

func (s *Store) OpenSagas(ctx context.Context) ([]string, error)

OpenSagas lists the sagas that need attention: those still running or compensating, and finished ones whose document turned into an incident afterwards (a contradicting 997).

func (*Store) OrderSagaByRef

func (s *Store) OrderSagaByRef(ctx context.Context, tenantID, partnerID, ref string) (OrderSaga, error)

OrderSagaByRef finds the newest order saga of a business reference of the tenant, for the tools that take their values from the model and name the order by its number. An empty partnerID matches any partner. Unknown gives ErrNotFound.

func (*Store) OrderSagaByTxn

func (s *Store) OrderSagaByTxn(ctx context.Context, tenantID, txnID, createTool string) (OrderSaga, error)

OrderSagaByTxn finds the order saga of the txn_id that erp.create_sales_order gave. A txn_id of another tenant, of another tool and an unknown one all give ErrNotFound.

func (*Store) OrderSource

func (s *Store) OrderSource(ctx context.Context, tenantID, documentID, st01 string) (OrderSource, error)

OrderSource reads a document of the set st01 ("850" or "810") of the tenant in the status received or processed. Any other document, another tenant's document and an unknown id give ErrNotFound.

func (*Store) PartnerAccess

func (s *Store) PartnerAccess(ctx context.Context, tenantID, partnerID string) (PartnerAccess, error)

PartnerAccess reads the partner and the tenant's interchange id. ErrNotFound when the partner is not registered for the tenant.

func (*Store) PartnerContacts

func (s *Store) PartnerContacts(ctx context.Context, tenantID, partnerID string) ([]string, error)

PartnerContacts lists the e-mail addresses of a partner from the starting data of the gateway, in alphabetical order (never nil).

func (*Store) PartnerOfContact

func (s *Store) PartnerOfContact(ctx context.Context, tenantID, email string) (string, error)

PartnerOfContact returns the partner that has this address among its contacts, or ErrNotFound. A letter written by the model names no partner, so the mode no-contracts finds it this way.

func (*Store) PartnerPolicy

func (s *Store) PartnerPolicy(ctx context.Context, tenantID, partnerID string) (PartnerPolicy, error)

PartnerPolicy reads the partner of the tenant with its ship-to codes and contacts. An unknown partner gives ErrNotFound.

func (*Store) PinManifest

func (s *Store) PinManifest(ctx context.Context, m Manifest) error

PinManifest writes or replaces the pin of a tool.

func (*Store) PlainByKey

func (s *Store) PlainByKey(ctx context.Context, tenantID string, key []byte) (PlainTxn, bool, error)

PlainByKey finds the stored answer of a request key (mode reqhash).

func (*Store) PlainLast

func (s *Store) PlainLast(ctx context.Context, tenantID, tool, partnerID, ref string) ([]byte, error)

PlainLast returns the arguments of the last call of a tool for a partner and a business reference, or ErrNotFound. Confirming and shipping an order find its lines this way.

func (*Store) PlainSave

func (s *Store) PlainSave(ctx context.Context, tenantID string, t PlainTxn, key []byte) (saved bool, stored PlainTxn, err error)

PlainSave writes the row of a call that did its effect. key is nil in the mode plain. When two calls with one key finish together, the first row stays and is returned with saved false.

func (*Store) PlainState

func (s *Store) PlainState(ctx context.Context, tenantID, txnID string) (PlainTxn, error)

PlainState reads the answer an open tool gave for a txn_id of the tenant. Another tenant's txn_id and an unknown one both give ErrNotFound.

func (*Store) PriceListID

func (s *Store) PriceListID(ctx context.Context, tenantID string) (*string, error)

PriceListID reads the label of the price list of the tenant; nil when none is set.

func (*Store) Prices

func (s *Store) Prices(ctx context.Context, tenantID string, skus []string) (map[string]Price, error)

Prices returns the price list rows of the tenant for the given SKUs, by SKU. A SKU that is not in the list is missing from the map.

func (*Store) ReadDocument

func (s *Store) ReadDocument(ctx context.Context, tenantID, id string) (Document, error)

ReadDocument returns one visible document of the tenant. A document of another tenant, a 997, a rejected set and an unknown id all give ErrNotFound.

func (*Store) ReadNote

func (s *Store) ReadNote(ctx context.Context, tenantID, documentID, ref string) (StoredNote, error)

ReadNote returns a note of a visible document (850 or 810, accepted) of the tenant. Another tenant, a 997, a rejected set, an unknown document and an unknown ref all give ErrNotFound.

func (*Store) RecordQuarantineCall

func (s *Store) RecordQuarantineCall(ctx context.Context, c QuarantineCall) error

RecordQuarantineCall stores the cost record of a call.

func (*Store) ReopenKey

func (s *Store) ReopenKey(ctx context.Context, tenantID, principalID, traceID string, key []byte) error

ReopenKey moves a failed key of the tenant to "reopened" and writes the audit row "txn_reopen" with the operator. A key of another tenant and an unknown key give ErrNotFound; a key in any other state than failed gives ErrNotFailed.

func (*Store) Reserve

func (s *Store) Reserve(ctx context.Context, in ReserveInput) (Reserved, error)

Reserve writes the key, its answer, the outbox row and the audit row "effect_reserved" in one transaction (invariants I1 and I3).

INSERT ... ON CONFLICT DO NOTHING decides a race: a second call waits for the first on the unique index and then reads the same row (SELECT ... FOR UPDATE). Same request hash: the same txn_id and the current state. Another hash: conflicting duplicate, an audit row with both hashes and no effect. A reopened key is reused with a new txn_id, a new hash and a new outbox row.

func (*Store) RevokePrincipal

func (s *Store) RevokePrincipal(ctx context.Context, id string) error

RevokePrincipal marks a principal revoked. ErrNotFound if there is none.

func (*Store) RunAuditAnchors

func (s *Store) RunAuditAnchors(ctx context.Context, a *audit.Anchorer, interval time.Duration, log *slog.Logger)

RunAuditAnchors signs and writes the anchors of the audit chain every interval until ctx ends (see audit.Anchorer).

func (*Store) SaveInbound

func (s *Store) SaveInbound(ctx context.Context, in InboundInterchange) (SaveResult, error)

SaveInbound stores an interchange and its documents in one transaction. The unique index on (tenant, direction, partner, ISA13) decides a race between two identical requests: the second one waits for the first and then reads its row. Same ISA13 and same SHA-256: duplicate, nothing is written, the stored MDN is returned. Same ISA13 and another body: the body goes to edi_rejected and nothing else is written.

func (*Store) SaveRejected

func (s *Store) SaveRejected(ctx context.Context, tenantID, partnerID, isa13 string, raw, sha []byte, detail string) error

SaveRejected stores an interchange that was refused as a whole (envelope error). isa13 is "" when it could not be read.

func (*Store) SaveUpstreamNote

func (s *Store) SaveUpstreamNote(ctx context.Context, tenantID, server, tool, traceID, body, label string) (int64, error)

SaveUpstreamNote keeps the text of a quarantined upstream result and returns its number; the agent gets the reference $up_<number>.

func (*Store) SetApprovalTTL

func (s *Store) SetApprovalTTL(d time.Duration)

SetApprovalTTL sets how long new approval requests stay open. It is called once at start, before the store is shared.

func (*Store) SetPriceListID

func (s *Store) SetPriceListID(ctx context.Context, tenantID, label string) error

SetPriceListID sets (or with "" clears) the label of the price list of a tenant. It is part of the starting data and is not reachable from any tool. ErrNotFound for an unknown tenant.

func (*Store) ShipmentSagaOf

func (s *Store) ShipmentSagaOf(ctx context.Context, tenantID string, businessKey []byte) (ShipmentProgress, error)

ShipmentSagaOf reads the shipment saga of a business key.

func (*Store) SupplierOrder

func (s *Store) SupplierOrder(ctx context.Context, tenantID, partnerID, orderNumber string) (SupplierOrder, error)

SupplierOrder reads the order of the tenant to the supplier. An unknown one gives ErrNotFound.

func (*Store) TxnState

func (s *Store) TxnState(ctx context.Context, tenantID, txnID string) (TxnState, error)

TxnState reads the key with this txn_id. A key of another tenant and an unknown txn_id both give ErrNotFound.

func (*Store) VerifyAudit

func (s *Store) VerifyAudit(ctx context.Context, o audit.Options) (audit.Result, error)

VerifyAudit checks the audit chain and the anchors of a tenant (see audit.Verify).

type StoredNote

type StoredNote struct {
	Body       string
	TaintLabel string
	Canary     string
}

StoredNote is a note with its text, for the quarantined reader only.

type SupplierOrder

type SupplierOrder struct {
	TotalCents int64
	Currency   string
	Lines      []byte
}

SupplierOrder is an order to a supplier. Lines is JSON: [{"sku","qty","unit_price"}].

type TxnState

type TxnState struct {
	State        string // reserved, completed, failed or reopened
	ResultStatus string // the recorded status: accepted, pending_approval, rejected or expired
	ExternalRef  string
	SagaState    string // the state of the saga the key is a step of; "" when it is not
}

TxnState is what txn.status needs: the state of the key and the external reference of the latest delivered effect ("" when there is none).

type Verdict

type Verdict struct {
	Deny     []string
	Approval string
	Tier     int
	Rules    []string
	View     []byte
	Explain  []byte
}

Verdict is the decision of the policy as Reserve needs it. Deny names the rules that forbid the call (nothing is reserved). Approval is "none" (the effect goes to the outbox), "one" or "two" (an approval request is opened instead). Rules are the names of the rules that caused the request, View what the operator sees, Explain the JSON for audit_log.policy_explain.

Directories

Path Synopsis
Package storetest gives tests a throwaway migrated database.
Package storetest gives tests a throwaway migrated database.

Jump to

Keyboard shortcuts

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