Files

187 lines
8.8 KiB
Go

package outbound
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var (
// ErrOrganizationNotFound reports that the organization does not exist or
// that the account has no active membership in it. The two cases are the
// same on purpose, so a caller cannot tell an organization that exists
// from one that it may not enter.
ErrOrganizationNotFound = errors.New("organization not found")
// ErrOrganizationManagerRequired reports an account whose active
// membership does not have a role that manages the organization.
ErrOrganizationManagerRequired = errors.New("membership role cannot manage the organization")
// ErrOrganizationVersionConflict reports that the expected version of an
// organization is stale: another change advanced it. Nothing was changed;
// read the organization again.
ErrOrganizationVersionConflict = errors.New("organization changed concurrently")
// ErrMembershipExists reports a second membership for an account and
// organization that already have one, in any state.
ErrMembershipExists = errors.New("membership already exists")
// ErrMembershipNotFound reports that the account has no membership in the
// organization, in any state.
ErrMembershipNotFound = errors.New("membership not found")
// ErrOrganizationCreationResultNotFound reports a missing immutable result
// snapshot for a live organization creation idempotency record.
ErrOrganizationCreationResultNotFound = errors.New("organization creation result not found")
)
// MaxOrganizationPageSize matches the largest page of the contract.
const MaxOrganizationPageSize = 100
// OrganizationRepositories exposes the organization and membership
// repositories. UnitOfWork binds them to one transaction, which a write
// needs: an organization and its owner membership commit together.
//
// Tenant data of other aggregates, such as needs and invitations, refers to
// organizations(id) with a restricting foreign key and always filters by the
// organization taken from a membership, never from a body.
type OrganizationRepositories interface {
Organizations() OrganizationRepository
Memberships() MembershipRepository
}
// OrganizationRepository stores organizations. Every read and write names an
// account, and only an active membership gives access, so a caller cannot
// reach an organization through it without the membership that the
// operations of the contract require.
type OrganizationRepository interface {
// CreateWithOwner stores a new organization and the active owner
// membership of its creator. The two inserts run in the surrounding
// transaction, so a failure between them leaves neither. The organization
// joins the holding of the owner account: the holding is created in the
// same transaction when that account has none, and an existing one is
// reused, so concurrent creations of one account end in one holding. The
// database also refuses to commit an organization that has no active owner
// (constraint organizations_owner_required, SQLSTATE 23514, raised by the
// commit of the transaction), whatever code inserted it. owner must be an
// active owner membership of organization; an unknown account fails with
// ErrUserNotFound, and the caller's transaction is aborted.
CreateWithOwner(ctx context.Context, organization domain.Organization, owner domain.Membership) error
// SaveCreationResult stores the immutable domain snapshot returned by the
// original create command. The scope is the HMAC key of a live generic
// idempotency record. The snapshot is bounded and expires with that record;
// it does not follow later profile edits or membership changes.
SaveCreationResult(ctx context.Context, scope [IdempotencyDigestSize]byte, result OrganizationCreationResult) error
// GetCreationResult returns the original snapshot for a live idempotency
// scope. It never reads the current organization or membership rows.
GetCreationResult(ctx context.Context, scope [IdempotencyDigestSize]byte) (OrganizationCreationResult, error)
// GetForMember returns the organization with its representatives and the
// active membership of the account in it, read from one snapshot in one
// statement, so the profile and the list never come from two states. It
// returns ErrOrganizationNotFound when the organization does not exist,
// when the account has no membership in it, and when the membership is
// suspended, removed, or left.
GetForMember(ctx context.Context, organizationID, userID uuid.UUID) (domain.Organization, domain.Membership, error)
// LockActiveMembership locks the organization row first, then the active
// membership row, through the surrounding transaction. Writers that act on
// owner access use it to serialize against membership revocation and keep
// the same organization-then-membership lock order as profile updates. It
// returns ErrOrganizationNotFound for an unknown organization or an
// account without an active membership.
LockActiveMembership(ctx context.Context, organizationID, userID uuid.UUID) (domain.Membership, error)
// ListForUser returns one page of the organizations where the account has
// an active membership, newest membership first.
ListForUser(ctx context.Context, query OrganizationListQuery) (OrganizationPage, error)
// UpdateProfile stores the profile of organization as returned by
// domain.Organization.ApplyProfile on behalf of the account actorID. It
// applies only when the stored version still equals organization.Version()
// and the actor has an active membership with a role that manages the
// organization. The same statement advances the version by one, and the
// representative list is replaced in the same transaction, so the returned
// organization carries the new version. It never changes the verification
// level.
//
// Lock order: the statement locks the organization row, then the actor's
// membership row FOR SHARE, so a revocation committed while it waits stops
// the write. Every writer of both tables, such as the member management,
// must lock organizations first and memberships second, or two
// transactions can deadlock.
//
// It returns ErrOrganizationNotFound for an unknown organization or an
// actor without an active membership, ErrOrganizationManagerRequired for
// an active member whose role cannot manage, and
// ErrOrganizationVersionConflict for a stale version, checked in that
// order. A failure leaves the organization unchanged.
UpdateProfile(ctx context.Context, actorID uuid.UUID, organization domain.Organization) (domain.Organization, error)
}
// OrganizationCreationResult is the original business result of creating an
// organization. Keeping the domain values lets storage replay the response
// without depending on generated HTTP types or a later profile state.
type OrganizationCreationResult struct {
Organization domain.Organization
Owner domain.Membership
}
// MembershipRepository stores memberships. A membership is unique per account
// and organization.
type MembershipRepository interface {
// Insert stores a membership. A second membership of the same account in
// the same organization, in any state, returns an error wrapping
// ErrMembershipExists; an unknown organization returns
// ErrOrganizationNotFound and an unknown account ErrUserNotFound. The
// database error aborts the surrounding transaction.
Insert(ctx context.Context, membership domain.Membership) error
// Get returns the membership of the account in the organization in any
// state, or ErrMembershipNotFound. The caller checks GrantsAccess before
// it trusts the membership.
Get(ctx context.Context, organizationID, userID uuid.UUID) (domain.Membership, error)
}
// OrganizationListQuery selects one page of an account's organizations.
type OrganizationListQuery struct {
UserID uuid.UUID
// After continues after the position of the last item of the previous
// page; nil reads the first page.
After *OrganizationListPosition
// Limit is the page size, from 1 to MaxOrganizationPageSize.
Limit int32
}
// OrganizationListPosition is the ordering key of an item in ListForUser.
type OrganizationListPosition struct {
JoinedAt time.Time
OrganizationID uuid.UUID
}
// MemberOrganization is an organization with the membership of the account
// that listed it.
type MemberOrganization struct {
Organization domain.OrganizationSummary
Membership domain.Membership
}
// OrganizationPositionOf returns the ordering key of item for the next page.
func OrganizationPositionOf(item MemberOrganization) OrganizationListPosition {
return OrganizationListPosition{JoinedAt: item.Membership.CreatedAt(), OrganizationID: item.Organization.ID()}
}
// OrganizationPage is one page of ListForUser.
type OrganizationPage struct {
Items []MemberOrganization
// HasMore reports that another page follows; read it with After set to
// the position of the last item.
HasMore bool
}