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
- Variables
- func HashToken(token string) []byte
- func NewToken() (token string, sum []byte, err error)
- func NewTxnID() string
- type AdvanceHints
- type Approval
- type AuditEvent
- type Claim
- func (c *Claim) Ack(ctx context.Context, externalRef string) error
- func (c *Claim) DocIncident(ctx context.Context, docID string) (string, error)
- func (c *Claim) Fail(ctx context.Context, status, reason, lastError string) error
- func (c *Claim) FailSend(ctx context.Context, docID, reason, lastError string) error
- func (c *Claim) RecordTransmission(ctx context.Context, docID string, ok bool, mdn []byte) error
- func (c *Claim) Release(ctx context.Context)
- func (c *Claim) Retry(ctx context.Context, lastError string, delay time.Duration) error
- type ControlNumbers
- type Decision
- type Document
- type FixturePartner
- type FixturePrice
- type FixtureSupplierLine
- type FixtureSupplierOrder
- type FixtureTemplate
- type Fixtures
- type InboundAck
- type InboundAckSet
- type InboundDocument
- type InboundInterchange
- type InboundNote
- type Manifest
- type NoteRef
- type OrderSaga
- type OrderSource
- type OutboxRow
- type Partner
- type PartnerAccess
- type PartnerPolicy
- type PlainTxn
- type Price
- type Principal
- type QuarantineCall
- type RawNote
- type ReserveInput
- type Reserved
- type Saga
- type SagaLink
- type SagaStep
- type SaveResult
- type ShipmentProgress
- type Store
- func (s *Store) AddPartner(ctx context.Context, p Partner) error
- func (s *Store) AddTenant(ctx context.Context, id, name, interchangeID string) error
- func (s *Store) AdvanceSaga(ctx context.Context, id string, h AdvanceHints) (bool, error)
- func (s *Store) AnchorAuditNow(ctx context.Context, a *audit.Anchorer) error
- func (s *Store) AppendAudit(ctx context.Context, e AuditEvent) error
- func (s *Store) CheckMigrated(ctx context.Context) error
- func (s *Store) ClaimOutbox(ctx context.Context, skip ...string) (*Claim, error)
- func (s *Store) ClaimOutboxOnly(ctx context.Context, only ...string) (*Claim, error)
- func (s *Store) Close()
- func (s *Store) DecideApproval(ctx context.Context, tenantID, operatorID, traceID, id string, approve bool) (Decision, error)
- func (s *Store) DefaultCurrency(ctx context.Context, tenantID, partnerID string) (string, error)
- func (s *Store) DocumentNotes(ctx context.Context, tenantID, documentID string) ([]RawNote, error)
- func (s *Store) ExpireApprovals(ctx context.Context) (int, error)
- func (s *Store) FindPrincipal(ctx context.Context, tokenSHA256 []byte) (Principal, error)
- func (s *Store) HasEmailTemplate(ctx context.Context, tenantID, templateID string) (bool, error)
- func (s *Store) IssueMissingPartnerTokens(ctx context.Context, tenantID string, partnerIDs []string) (map[string]string, error)
- func (s *Store) IssuePrincipal(ctx context.Context, p Principal, tokenSHA256 []byte) error
- func (s *Store) ListApprovals(ctx context.Context, tenantID, status string) ([]Approval, error)
- func (s *Store) ListInbox(ctx context.Context, tenantID, status string, limit int) ([]Document, error)
- func (s *Store) ListManifests(ctx context.Context, server string) ([]Manifest, error)
- func (s *Store) ListNotes(ctx context.Context, tenantID, documentID string) ([]NoteRef, error)
- func (s *Store) LoadFixtures(ctx context.Context, f Fixtures) error
- func (s *Store) LoadSaga(ctx context.Context, id string, ackTimeout time.Duration) (Saga, error)
- func (s *Store) Manifests(ctx context.Context, server string) (map[string]Manifest, error)
- func (s *Store) Migrate(ctx context.Context) error
- func (s *Store) NextControlNumbers(ctx context.Context, tenantID, partnerID string) (ControlNumbers, error)
- func (s *Store) OpenSagas(ctx context.Context) ([]string, error)
- func (s *Store) OrderSagaByRef(ctx context.Context, tenantID, partnerID, ref string) (OrderSaga, error)
- func (s *Store) OrderSagaByTxn(ctx context.Context, tenantID, txnID, createTool string) (OrderSaga, error)
- func (s *Store) OrderSource(ctx context.Context, tenantID, documentID, st01 string) (OrderSource, error)
- func (s *Store) PartnerAccess(ctx context.Context, tenantID, partnerID string) (PartnerAccess, error)
- func (s *Store) PartnerContacts(ctx context.Context, tenantID, partnerID string) ([]string, error)
- func (s *Store) PartnerOfContact(ctx context.Context, tenantID, email string) (string, error)
- func (s *Store) PartnerPolicy(ctx context.Context, tenantID, partnerID string) (PartnerPolicy, error)
- func (s *Store) PinManifest(ctx context.Context, m Manifest) error
- func (s *Store) PlainByKey(ctx context.Context, tenantID string, key []byte) (PlainTxn, bool, error)
- func (s *Store) PlainLast(ctx context.Context, tenantID, tool, partnerID, ref string) ([]byte, error)
- func (s *Store) PlainSave(ctx context.Context, tenantID string, t PlainTxn, key []byte) (saved bool, stored PlainTxn, err error)
- func (s *Store) PlainState(ctx context.Context, tenantID, txnID string) (PlainTxn, error)
- func (s *Store) PriceListID(ctx context.Context, tenantID string) (*string, error)
- func (s *Store) Prices(ctx context.Context, tenantID string, skus []string) (map[string]Price, error)
- func (s *Store) ReadDocument(ctx context.Context, tenantID, id string) (Document, error)
- func (s *Store) ReadNote(ctx context.Context, tenantID, documentID, ref string) (StoredNote, error)
- func (s *Store) RecordQuarantineCall(ctx context.Context, c QuarantineCall) error
- func (s *Store) ReopenKey(ctx context.Context, tenantID, principalID, traceID string, key []byte) error
- func (s *Store) Reserve(ctx context.Context, in ReserveInput) (Reserved, error)
- func (s *Store) RevokePrincipal(ctx context.Context, id string) error
- func (s *Store) RunAuditAnchors(ctx context.Context, a *audit.Anchorer, interval time.Duration, ...)
- func (s *Store) SaveInbound(ctx context.Context, in InboundInterchange) (SaveResult, error)
- func (s *Store) SaveRejected(ctx context.Context, tenantID, partnerID, isa13 string, raw, sha []byte, ...) error
- func (s *Store) SaveUpstreamNote(ctx context.Context, tenantID, server, tool, traceID, body, label string) (int64, error)
- func (s *Store) SetApprovalTTL(d time.Duration)
- func (s *Store) SetPriceListID(ctx context.Context, tenantID, label string) error
- func (s *Store) ShipmentSagaOf(ctx context.Context, tenantID string, businessKey []byte) (ShipmentProgress, error)
- func (s *Store) SupplierOrder(ctx context.Context, tenantID, partnerID, orderNumber string) (SupplierOrder, error)
- func (s *Store) TxnState(ctx context.Context, tenantID, txnID string) (TxnState, error)
- func (s *Store) VerifyAudit(ctx context.Context, o audit.Options) (audit.Result, error)
- type StoredNote
- type SupplierOrder
- type TxnState
- type Verdict
Constants ¶
const ( SavedNew = "ok" SavedDuplicate = "duplicate" SavedConflict = "isa13_conflict" )
Outcomes of SaveInbound.
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.
const DefaultApprovalTTL = 30 * time.Minute
DefaultApprovalTTL is the life of an approval request at time scale 1.
const TokenPrefix = "edg_"
TokenPrefix starts every gateway token.
Variables ¶
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.
var ErrNotFailed = errors.New("key is not failed")
ErrNotFailed means a key is not in the state failed, so it cannot be reopened.
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.
var ErrNotMigrated = errors.New("database migrations are not applied")
ErrNotMigrated means the database schema is not at the latest migration.
Functions ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 Principal ¶
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 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 ¶
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 ¶
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 (*Store) AddPartner ¶
AddPartner registers a partner, or updates the role and name of a known one.
func (*Store) AddTenant ¶
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 ¶
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 ¶
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 ¶
CheckMigrated reports ErrNotMigrated unless the database version equals the latest embedded migration. It also fails when the database does not answer.
func (*Store) ClaimOutbox ¶
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 ¶
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) 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 ¶
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 ¶
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 ¶
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 ¶
FindPrincipal looks a principal up by token hash. Unknown and revoked tokens both give ErrNotFound.
func (*Store) HasEmailTemplate ¶
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 ¶
IssuePrincipal stores a principal with the hash of its token.
func (*Store) ListApprovals ¶
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 ¶
ListManifests returns the pins of a server (all servers when server is empty), ordered.
func (*Store) ListNotes ¶
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 ¶
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) 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 ¶
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 ¶
PartnerContacts lists the e-mail addresses of a partner from the starting data of the gateway, in alphabetical order (never nil).
func (*Store) PartnerOfContact ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
SetApprovalTTL sets how long new approval requests stay open. It is called once at start, before the store is shared.
func (*Store) SetPriceListID ¶
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.
type StoredNote ¶
StoredNote is a note with its text, for the quarantined reader only.
type SupplierOrder ¶
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.