store

package
v0.1.21 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: AGPL-3.0 Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const MaxDurationSetting = 7 * 24 * time.Hour

MaxDurationSetting bounds a duration an operator may record. For the feed URL bound it is the seven days S3 and compatible stores cap a presigned URL at; anything beyond is a typo, and a typo here stalls every update period the install sells.

View Source
const MaxFeedListLimit = 5000

MaxFeedListLimit caps how many published rows the store will return to the service for semver-max computation (see service.latestComputeWindow). 5000 covers any realistic single-product release backlog.

View Source
const MaxOTPAttempts = 5

MaxOTPAttempts is how many guesses one login code allows.

View Source
const RefreshReuseGrace = 30 * time.Second

RefreshReuseGrace is how long a just-rotated refresh token is still honoured. Several tabs whose sessions lapse together all renew with the same cookie, and a refresh whose response was lost is retried with it; without a grace period every one of those would look like token theft and sign the user out everywhere. Kept short so a captured token is useless almost at once. Revocation by logout or by reuse detection deletes the row instead, so it is never covered by this window.

View Source
const SeatInviteTTL = 7 * 24 * time.Hour

SeatInviteTTL is how long a freshly-minted invite token stays claimable. 7 days mirrors the GitHub / Slack convention and is long enough that "you got invited last weekend" still works.

View Source
const SettingFeedURLTTLBound = "feed_url_ttl_bound"

SettingFeedURLTTLBound is the longest lifetime this install is known to have signed public feed links with. Every start raises it to the replica's own STORAGE_FEED_URL_TTL and every drain check reads it, so a replica configured with a shorter one cannot decide that links another replica signed for longer have expired — nor can a restart after the value was lowered.

It is deliberately not a guess about the past: an install upgrading into this build records what it runs now, and what an earlier build signed links with is a question only the operator can answer (see the migration).

Lowering it is allowed and is an ordered operation: put the shorter STORAGE_FEED_URL_TTL on every replica first, let the rollout finish, wait out the links signed under the old bound, and only then lower this. While a replica with the longer TTL is still running, its next start raises it again — which is the point.

View Source
const SettingMaintenanceFeatures = "maintenance_features_enabled"

SettingMaintenanceFeatures is the operator's confirmation that every replica runs a version that understands the maintenance period. Elapsed time cannot prove that and replicas on the previous version leave no trace in the database, so everything that depends on it — gated feeds, bounded update periods, renewals on sale, manual cutoffs — stays refused until an admin turns this on. It is theirs to turn off again before rolling back to a version without it: a replica that predates the feature reads none of this, so nothing here can notice one.

View Source
const TeamLockKey = 8675310

TeamLockKey serializes every team role change.

View Source
const (
	UpgradeCheckoutTTL = time.Hour
)

UpgradeCheckoutTTL is how long a checkout upgrading a licence to a plan sold per seat or with a seat limit can be paid (its expires_at); an abandoned one holds invites up no longer. upgradeCheckoutOpenFor adds a margin for the moments between the upgrade row and the checkout being created.

Variables

View Source
var (
	// ErrIdempotencyInFlight: same (key, endpoint) is currently being
	// processed by a concurrent request — the original hasn't yet
	// stored its response. The client should retry with backoff.
	ErrIdempotencyInFlight = errors.New("idempotency key in-flight")

	// ErrIdempotencyBodyMismatch: same key was used previously with a
	// different body. Reusing keys across different requests is a
	// programming error; we refuse rather than guess intent.
	ErrIdempotencyBodyMismatch = errors.New("idempotency key reused with a different request body")
)

Idempotency sentinel errors. Surfaced by the middleware to map onto HTTP responses; the handler logic never sees them directly.

View Source
var (
	ErrReleaseNotFound       = errors.New("release not found")
	ErrReleaseAlreadyExists  = errors.New("release with same product/version already exists")
	ErrReleaseNotPublishable = errors.New("release is not in a publishable state")
	ErrReleaseNotYankable    = errors.New("release is not in a yankable state")
	// ErrReleaseNotDeletable: only DRAFT releases can be hard-deleted.
	// Published / yanked stay in the DB so audit trail is preserved.
	ErrReleaseNotDeletable = errors.New("only draft releases can be deleted")

	// Atomic-publish preconditions surfaced by PublishRelease when its
	// inline gate rejects the transition. The gate evaluates them in a
	// single SQL UPDATE, so these errors describe state observed AT the
	// moment of the update — concurrent AddArtifact / FinalizeArtifact
	// cannot create a stale "checked then violated" race.
	ErrReleaseNoArtifacts        = errors.New("release has no artifacts")
	ErrReleaseArtifactsNotReady  = errors.New("one or more artifacts have not finished uploading")
	ErrReleaseArtifactsNotSigned = errors.New("one or more artifacts are missing required signatures")
	// ErrReleaseSigningKeyRetired: the key the release was signed with
	// was rotated out or deactivated before the publish committed.
	ErrReleaseSigningKeyRetired = errors.New("the signing key was retired during publish")

	// Artifact-related.
	ErrArtifactNotFound = errors.New("release artifact not found")
	// ErrArtifactReplaced: a signature was for a file the artifact no
	// longer points at (finalized again while it was being signed).
	ErrArtifactReplaced      = errors.New("release artifact was replaced while it was being signed")
	ErrArtifactAlreadyExists = errors.New("release already has an artifact for this platform")
)

Release-related sentinel errors.

View Source
var (
	ErrSigningKeyNotFound      = errors.New("release signing key not found")
	ErrActiveSigningKeyMissing = errors.New("no active signing key for product")
	// ErrSigningKeyAlreadyActive is returned when we try to insert a second
	// active key for the same product. Callers should call RotateSigningKey
	// instead of two separate Create calls.
	ErrSigningKeyAlreadyActive = errors.New("product already has an active signing key; rotate instead of create")
	// ErrSigningKeyInactive is returned by DeactivateSigningKey for a key
	// already deactivated, by a rotation or another call.
	ErrSigningKeyInactive = errors.New("signing key is already inactive")
)

Sentinel errors for the release signing key store.

View Source
var All = Page{}

All is that unbounded page, named so the call sites that mean it say so.

View Source
var ErrAddonInactive = errors.New("addon is no longer offered")

ErrAddonInactive is returned by AddLicenseAddon for an addon no longer offered (active=false) that the licence does not already have.

View Source
var ErrAlreadyActivated = errors.New("identifier is already activated")

ActivateWithinLimit atomically creates an activation only if the limit hasn't been reached. Locks the license row (not activation rows) to serialize concurrent activations. ErrAlreadyActivated reports that this machine already holds an activation on this license, so nothing was taken from the limit.

View Source
var ErrChangeInProgress = errors.New("a change to this license is being made")

ErrChangeInProgress: another change to the licence's subscription is with Stripe right now.

View Source
var ErrDeviceHeld = errors.New("device held by another key on the licence")

ErrDeviceHeld is returned by ActivateForKey when the machine is the device of another key on the licence.

View Source
var ErrDeviceMoved = fmt.Errorf("%w: moved to the member's key", ErrAlreadyActivated)

ErrDeviceMoved is ErrAlreadyActivated for a device ActivateForKey has just moved from the licence's key to the member's.

View Source
var ErrFloatingLimitReached = errors.New("floating session limit reached")

ErrFloatingLimitReached is returned when all floating sessions are in use.

View Source
var ErrKeyRevoked = errors.New("license key no longer valid")

ErrKeyRevoked is returned by ActivateForKey and CheckOutFloatingForKey when the key no longer opens the licence the way it did when it was looked up: its member was removed or their accept rolled back, the licence's key was changed, or the product no longer has seats for a member's key to work.

View Source
var ErrLastOwner = errors.New("cannot remove the last owner")

ErrLastOwner is returned when a role change would leave zero owners. Every change that can take the owner role away goes through SetRoleAtomic; raw UPDATEs that only grant a role (setup, ADMIN_EMAILS promotion, EnsureOwner) cannot break the invariant.

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

ErrLicenseNotFound: no licence has the id given.

View Source
var ErrLicenseNotReinstatable = errors.New("license not found or cannot be reinstated from current status")

ErrLicenseNotReinstatable refuses a reinstate the licence's current status does not allow, or of a licence that does not exist.

View Source
var ErrLicenseNotSuspendable = errors.New("only an active, trialing or past-due license can be suspended")

ErrLicenseNotSuspendable refuses to suspend a licence that is not in use: suspending is for an active, trialing or past-due one. Above all not a revoked one — reinstating would then hand back what was revoked.

View Source
var ErrLicenseRestricted = errors.New("license state does not allow this subscription change")

ErrLicenseRestricted reports that a Stripe-driven write was refused because the licence's own state forbids it: revoked, suspended by an operator, canceled with nothing but an event payload (no current read of Stripe) saying otherwise, or a pause meeting a licence an operator suspended or that ended. Nothing was written — no status, no dates — and the caller must not announce the change.

View Source
var ErrNotOwner = errors.New("only an owner can manage team members")

ErrNotOwner is returned by SetRoleAtomic when the acting user is no longer an owner by the time the team lock is held.

View Source
var ErrNotificationClaimLost = errors.New("reminder claim taken over")

ErrNotificationClaimLost: the reminder claim the caller held was taken over by another pass while it worked. That pass owns the reminder now, so nothing was queued.

View Source
var ErrPlanChanged = errors.New("the plan changed type while this license was being created")

ErrPlanChanged: the plan a license was built from has since changed its license type. Everything about the row follows from that type — status, valid_until, the update period, whether a subscription row belongs to it — so the half-built license is refused rather than written. Reading the plan again and rebuilding is the fix, which is what a webhook retry does.

View Source
var ErrPlanHasLicenses = errors.New("plan has licenses")

ErrPlanHasLicenses: the plan's license type was to change, but a license appeared on it — the type decides what a license carries (a subscription row, an update period), so the licenses move first.

View Source
var ErrProductNoReleases = errors.New("the product's type has no releases")

ErrProductNoReleases: the product's type does not have releases (any more), checked under the shape lock.

View Source
var ErrQuantityNotPerSeat = errors.New("the license's plan is not sold per seat")

ErrQuantityNotPerSeat: the licence's plan is not sold per seat, so a quantity would change nothing it holds.

View Source
var ErrQuantityStripeManaged = errors.New("the quantity of a Stripe-billed license is its subscription's")

ErrQuantityStripeManaged: the licence is billed by a Stripe subscription, whose quantity is the one it holds.

View Source
var ErrRefreshTokenReused = errors.New("refresh token reuse detected")

ErrRefreshTokenReused is returned by RotateRefreshToken when a caller presents a token that has already been rotated (revoked_at is set). This is the security signal — the caller should revoke every refresh_token for the same user, since either the legit user or an attacker holding the captured old token will be cut off.

View Source
var ErrRefreshUserNotFound = errors.New("refresh token user not found")

ErrRefreshUserNotFound is returned when a refresh token's user no longer exists.

View Source
var ErrReinstateNeedsNewExpiry = errors.New("this license's expiry date has passed — set a new expiry date first: that reactivates an expired license, and a canceled one can then be reinstated")

ErrReinstateNeedsNewExpiry refuses to reinstate an expired or canceled licence whose expiry date has passed: it would show as active, yet stay unusable and be expired again by the next hourly sweep. Setting a new expiry date comes first (SetLicenseValidUntil): it reactivates an expired licence, and a canceled one, usable again but still canceled, can then be reinstated.

View Source
var ErrRenewalIneligible = errors.New("license has no finite update period to extend")

ErrRenewalIneligible: the license no longer has a finite update period on a perpetual plan, so a paid renewal cannot be applied. It is not recorded as fulfilled; the payment needs an operator.

View Source
var ErrSeatInviteInvalid = errors.New("seat invite invalid or expired")

ErrSeatInviteInvalid is the single failure sentinel for accept — covers unknown / expired / removed / already-accepted tokens so the public endpoint doesn't reveal which condition was hit.

View Source
var ErrSeatLimitReached = errors.New("seat limit reached")

ErrSeatLimitReached is returned by AddSeatWithinLimit when the plan's max_seats cap is already hit. Callers translate this to 409 SEAT_LIMIT so the SDK can show a meaningful upsell prompt.

View Source
var ErrSeatNotJoined = errors.New("seat is not a member who has joined")

ErrSeatNotJoined is returned by RotateMemberKey for a seat that is an invitation not yet accepted, or removed: it has no key.

View Source
var ErrSecretEncryptionUnavailable = errors.New(
	"cannot store a secret without an encryption key: set RELEASE_KEY_ENCRYPTION_KEY")

ErrSecretEncryptionUnavailable is returned when a secret setting is saved on an install with no master key. Storing it plaintext would leak a long-lived credential, so the write is refused instead.

View Source
var ErrSelfSignupClosed = errors.New("the plan no longer takes self sign-ups")

ErrSelfSignupClosed means the plan stopped taking self sign-ups (was deactivated, or gained a price) after the caller read it.

View Source
var ErrSelfSignupExists = errors.New("this address already has a self sign-up licence for this product")

ErrSelfSignupExists means the address already holds a self sign-up licence for the product.

View Source
var ErrSessionHeld = errors.New("floating session held by another key")

ErrSessionHeld is returned by CheckOutFloatingForKey when the machine's running session was checked out with another key on the licence.

View Source
var ErrSignupCapReached = errors.New("the plan's daily sign-up limit is reached")

ErrSignupCapReached means the plan took as many self sign-ups today (UTC) as its signup_daily_cap allows.

View Source
var ErrStaleSubscriptionRead = errors.New("a newer read of this subscription is already applied")

ErrStaleSubscriptionRead reports that a newer read of the licence's Stripe subscription has already been applied, so this older one was not. Like ErrSubscriptionUnlinked it is an expected answer.

View Source
var ErrSubscriptionUnlinked = errors.New("license no longer linked to this subscription")

ErrSubscriptionUnlinked reports that the licence no longer points at the subscription the caller resolved it from, so the write was not made. It is the expected answer, not a failure: an admin unlinked the licence while a Stripe event for the old subscription was in flight, and that event must not put subscription-managed state back on a licence that is now managed locally.

View Source
var ErrTermsHeld = errors.New("license terms are held by a downgrade")

ErrTermsHeld: the read was written but for the plan and seats, which a downgrade holds (see LowerLicenseTerms) and the read did not show. A caller that can be asked again later (a webhook) is, once the hold is over.

View Source
var ErrUpdatePeriodNotEnforceable = errors.New("update period is not enforceable for this product")

ErrUpdatePeriodNotEnforceable: the license was to be written with a finite update period the product cannot enforce yet — its update feeds are public, or they were gated so recently that what the public feed handed out still works. Writing the period anyway would sell a cutoff the customer can walk around; writing the license without it would grant more than was sold. The caller leaves the paid purchase pending instead, and the reason travels with the error so it can say which of the two it is.

View Source
var ErrUpgradeCheckoutOpen = errors.New("an upgrade checkout is open")

ErrUpgradeCheckoutOpen is returned by AddSeatWithinLimit while a checkout upgrading the licence to a plan sold per seat is open: its seats were counted from the people on the licence when it opened, so nobody joins until it is paid or closed.

View Source
var ErrUpgradeSeatLimit = errors.New("the plan being upgraded to has no seat left")

ErrUpgradeSeatLimit is returned by AddSeatWithinLimit while a checkout upgrading the licence to a plan with a seat limit is open and the team already fills that limit: the team was checked against it when the checkout opened, so it grows only as far as that limit meanwhile. Unlike ErrUpgradeCheckoutOpen, paying does not make room.

View Source
var ErrUsageQuantityTooLarge = errors.New("usage quantity too large")

ErrUsageQuantityTooLarge means the increment would overflow the counter.

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

ErrUserNotFound is returned by SetRoleAtomic when the target user does not exist.

View Source
var LicenseKeyDecryptFailures = promauto.NewCounter(prometheus.CounterOpts{
	Name: "keygate_license_key_decrypt_failures_total",
	Help: "Cumulative count of license_key_encrypted decrypt failures.",
})

LicenseKeyDecryptFailures counts how many DecryptLicenseKey calls have failed AEAD verification. A non-zero value usually means either:

  • ciphertext corruption (DB tampering, partial disk write), or
  • master key change without re-encrypting existing rows, or
  • a bug in the AAD binding logic.

Alert when this counter increments. Phase C deployment is unsafe while any failures are recorded.

View Source
var LicenseKeysUnencrypted = promauto.NewGauge(prometheus.GaugeOpts{
	Name: "keygate_license_keys_unencrypted",
	Help: "Number of license rows still requiring license_key_encrypted backfill.",
})

LicenseKeysUnencrypted is a gauge for the count of license rows where license_key_encrypted IS NULL but license_key is non-empty, plus the members' keys in the same state (seats.member_key). This is the number of rows that still need backfill before Phase B can flip the read path to encrypted-only.

Updated on each backfill batch + once at startup; used as the deciding metric for "is it safe to enable Phase B?".

Functions

func ApplyLicenseRenewalIn added in v0.1.6

func ApplyLicenseRenewalIn(ctx context.Context, tx bun.IDB, r *model.LicenseRenewal) error

ApplyLicenseRenewalIn records a paid renewal of r.Days and moves the license's updates_until, both on the given transaction, so a crash between the two can never leave a renewal that was paid for but not applied, or applied but not recorded. The new end is computed under a row lock from the end the license has at that moment, so two renewals applied at once stack instead of overwriting each other. Eligibility is checked under the same lock: a license that meanwhile got updates for life or left its perpetual plan has nothing to extend, and the renewal is refused with ErrRenewalIneligible rather than recorded as fulfilled for no benefit. The computed dates are written back into r.

func ClaimProcessedEventIn added in v0.1.6

func ClaimProcessedEventIn(ctx context.Context, db bun.IDB, provider, eventID string) (bool, error)

ClaimProcessedEventIn is ClaimProcessedEvent on a given connection or transaction.

func CountActiveSeatsIn added in v0.1.17

func CountActiveSeatsIn(ctx context.Context, db bun.IDB, licenseID string) (int, error)

CountActiveSeatsIn is CountActiveSeats on a caller's transaction.

func CountLiveReleasesIn added in v0.1.20

func CountLiveReleasesIn(ctx context.Context, db bun.IDB, productID string) (int, error)

CountLiveReleasesIn counts the product's draft and published releases: the ones a type without releases would leave unreachable.

func CountPlansIncompatibleWithTypeIn added in v0.1.20

func CountPlansIncompatibleWithTypeIn(ctx context.Context, db bun.IDB, productID, newType string) (int, error)

CountPlansIncompatibleWithTypeIn is CountPlansIncompatibleWithType inside a transaction.

func CreateLicenseUpgradeIn added in v0.1.16

func CreateLicenseUpgradeIn(ctx context.Context, db bun.IDB, u *model.LicenseUpgrade) error

CreateLicenseUpgradeIn records a pending upgrade for a checkout session just created.

func CreatePlanIn added in v0.1.6

func CreatePlanIn(ctx context.Context, db bun.IDB, p *model.Plan) error

CreatePlanIn writes the plan on a caller's transaction. The caller fills the ids (CreatePlan does it), so a plan created under the feed gating lock is inserted by the same transaction that checked the gate.

func CurrentPeriodKey

func CurrentPeriodKey(period string) string

func DeleteProcessedEventIn added in v0.1.6

func DeleteProcessedEventIn(ctx context.Context, db bun.IDB, provider, eventID string) error

DeleteProcessedEventIn is DeleteProcessedEvent on a given connection or transaction.

func DurationSettingIn added in v0.1.6

func DurationSettingIn(ctx context.Context, db bun.IDB, key string, fallback time.Duration) (time.Duration, error)

DurationSettingIn reads a duration setting on a caller's connection or transaction. Only a missing row reads as fallback — that is "not recorded yet". A row that is there but says nothing usable (empty, not a duration, zero, negative, longer than MaxDurationSetting) is an error, and so is any read failure: this is what a drain is measured against, and falling back to the caller's own, possibly shorter, value would end that wait early without anyone noticing.

func EndLicenseUpgradeIn added in v0.1.16

func EndLicenseUpgradeIn(ctx context.Context, db bun.IDB, u *model.LicenseUpgrade, state, reason string) error

EndLicenseUpgradeIn closes an upgrade that never applied (expired, refunded or void), or records why one that applied ended. It changes nothing on the licence.

func FeedDrainLeftIn added in v0.1.6

func FeedDrainLeftIn(ctx context.Context, db bun.IDB, prod *model.Product, ttl time.Duration) (drain, left time.Duration, err error)

FeedDrainLeftIn reports the full drain a newly gated product waits out and how much of it is left. What the public feed handed out keeps working after the gate goes up: a shared cache may serve the feed for its max-age, and every copy carries presigned artifact URLs valid for ttl — the lifetime this replica signs them with — so the wait is the longer of the two. A product that never published a release handed out nothing.

func FeedGatingLockIn added in v0.1.6

func FeedGatingLockIn(ctx context.Context, tx bun.IDB, productID string) error

FeedGatingLockIn takes the product's feed gating lock for this transaction — the lock the triggers take — so the gating state read after it cannot change before the transaction commits.

func FeedsCanEnforcePeriodsIn added in v0.1.6

func FeedsCanEnforcePeriodsIn(ctx context.Context, db bun.IDB, productID string, feedURLTTL time.Duration) (bool, string, error)

FeedsCanEnforcePeriodsIn reports whether a finite update period written for this product would be enforceable now, and why not when it would not. Two conditions: the update feeds must require the license key (or the product serves no feeds), and what the public feed handed out before the gate went up must have expired — a copy of it, or a presigned link inside one, serves releases past any cutoff written while it is still usable.

feedURLTTL is how long this replica signs those links for (STORAGE_FEED_URL_TTL); the wait is the longer of it and the bound the install has recorded. The 60-second cache window is only the floor — waiting that alone would call a link signed for a day expired after a minute.

Callers hold the product's feed gating lock (FeedGatingLockIn) so the answer still holds when they write.

func FindLicenseRenewalByPaymentIntentIn added in v0.1.6

func FindLicenseRenewalByPaymentIntentIn(ctx context.Context, db bun.IDB, paymentIntentID string) (*model.LicenseRenewal, error)

FindLicenseRenewalByPaymentIntentIn looks the renewal up on a given connection or transaction. It takes no row lock: every path that writes renewals locks the license row first and the renewal rows after it, and a lock taken here in the other order could deadlock against an admin edit. Callers that change the row re-read it under the license lock (RevertLicenseRenewalIn).

func FindPlanByIDIn added in v0.1.6

func FindPlanByIDIn(ctx context.Context, db bun.IDB, id string) (*model.Plan, error)

FindPlanByIDIn reads the plan on a caller's transaction, for writers that must see the plan a locked license points at right now.

func FindProductByIDIn added in v0.1.6

func FindProductByIDIn(ctx context.Context, db bun.IDB, id string) (*model.Product, error)

FindProductByIDIn reads the product on a caller's transaction, for writers that re-read its gating state under a lock.

func GenerateRawAPIKey

func GenerateRawAPIKey() string

GenerateRawAPIKey creates a raw API key string like "kg_live_xxxxxxxx..."

func GenerateSeatInviteToken added in v0.1.1

func GenerateSeatInviteToken() (plain, hash string)

GenerateSeatInviteToken mints a 32-byte random token. The plain value is returned to the caller (email + URL); only the SHA256 hash is persisted, mirroring the api_keys hashing pattern so a DB dump can't be replayed as invite acceptance.

func GuardTrialFallbackTargetIn added in v0.1.17

func GuardTrialFallbackTargetIn(ctx context.Context, tx bun.IDB, planID string) error

GuardTrialFallbackTargetIn refuses with *TrialFallbackInUseError when trial plans name planID as their fallback. The caller holds planID's row lock (LockPlanIn), which a trial plan naming it waits on (see LockTrialFallbackIn): either that write committed first and is seen here, or it waits and then sees this one.

func HasProcessedEventIn added in v0.1.6

func HasProcessedEventIn(ctx context.Context, db bun.IDB, provider, eventID string) (bool, error)

HasProcessedEventIn is HasProcessedEvent on a given connection or transaction.

func HashAPIKey

func HashAPIKey(raw string) string

func HashSeatInviteToken added in v0.1.1

func HashSeatInviteToken(plain string) string

HashSeatInviteToken is the canonical way to compute the lookup key from a plain token. Exposed (vs an internal helper) so the admin and portal handlers share the same hash function — drift here would make valid tokens look unknown.

func IsCheckoutSessionConflict added in v0.1.5

func IsCheckoutSessionConflict(err error) bool

IsCheckoutSessionConflict recognises the unique index on licenses.stripe_checkout_session_id: a second license for one paid checkout session.

func IsForeignKeyViolation added in v0.1.16

func IsForeignKeyViolation(err error) bool

IsForeignKeyViolation reports whether err is a Postgres foreign-key violation (SQLSTATE 23503): a row that names a parent which does not exist, or a delete of a parent that still has children.

func IsRenewalSessionConflict added in v0.1.6

func IsRenewalSessionConflict(err error) bool

IsRenewalSessionConflict reports the unique-index violation raised when a second worker records the same renewal checkout session.

func IsSelfSignupConflict added in v0.1.16

func IsSelfSignupConflict(err error) bool

IsSelfSignupConflict reports whether err is the unique index on self sign-up licences refusing a second one for the same address.

func IsSelfSignupPlanConflict added in v0.1.16

func IsSelfSignupPlanConflict(err error) bool

IsSelfSignupPlanConflict reports whether err is the plans_self_signup_free constraint refusing a self sign-up plan with a price or an update period.

func IsStillReferenced added in v0.1.20

func IsStillReferenced(err error) bool

IsStillReferenced reports whether err is a delete refused because rows still refer to the row: a foreign key (23503) or a restrict (23001) violation. A delete that counted those rows first and found none met one added after the count.

func IsTrialFallbackMissing added in v0.1.17

func IsTrialFallbackMissing(err error) bool

IsTrialFallbackMissing reports whether err is the foreign key on plans.trial_fallback_plan_id: the plan named as a trial's fallback does not exist (deleted after it was checked).

func IsTrialFallbackPlanConflict added in v0.1.17

func IsTrialFallbackPlanConflict(err error) bool

IsTrialFallbackPlanConflict reports whether err is a plans CHECK refusing trial_fallback_plan_id: on a plan that is not a trial plan, or naming the plan itself. The admin API refuses both first; this is the answer when concurrent edits slipped past it.

func IsUniqueViolation added in v0.1.16

func IsUniqueViolation(err error) bool

IsUniqueViolation is isUniqueViolation for handlers that turn a duplicate into a 409 instead of a 500.

func LicenseKeyDecryptFailureCount added in v0.1.1

func LicenseKeyDecryptFailureCount() int64

LicenseKeyDecryptFailureCount returns the running atomic count for tests.

func ListPendingUpgradesIn added in v0.1.16

func ListPendingUpgradesIn(ctx context.Context, db bun.IDB, licenseID string) ([]*model.LicenseUpgrade, error)

ListPendingUpgradesIn returns a licence's upgrades whose checkout may still be open, locked, oldest first.

func LockLicenseIn added in v0.1.6

func LockLicenseIn(ctx context.Context, tx bun.IDB, id string) (*model.License, error)

LockLicenseIn, LockPlanIn and LockProductIn take the row lock a write of that row would take, so a caller can hold it before reaching for the feed gating lock. Order matters: the triggers take the gating lock while the row they fire for is already locked, so every writer takes the row first and the gate second.

func LockLicenseUpgradeBySessionIn added in v0.1.16

func LockLicenseUpgradeBySessionIn(ctx context.Context, db bun.IDB, sessionID string) (*model.LicenseUpgrade, error)

LockLicenseUpgradeBySessionIn reads the upgrade a session belongs to and locks its row.

func LockLicenseUpgradeIn added in v0.1.16

func LockLicenseUpgradeIn(ctx context.Context, db bun.IDB, id string) (*model.LicenseUpgrade, error)

LockLicenseUpgradeIn reads an upgrade by id and locks its row.

func LockPlanIn added in v0.1.6

func LockPlanIn(ctx context.Context, tx bun.IDB, id string) error

func LockProductIn added in v0.1.6

func LockProductIn(ctx context.Context, tx bun.IDB, id string) (*model.Product, error)

func LockReferencedRowsIn added in v0.1.6

func LockReferencedRowsIn(ctx context.Context, db bun.IDB, planID, productID string) error

LockReferencedRowsIn takes the row locks an insert's foreign keys would take anyway — the plan and the product a license points at — before its caller reaches for the feed gating lock.

Order is the whole point. Writers that touch a product's gating state take the row first and the gate second (see LockLicenseIn): an insert that took the gate first and then met the plan's or the product's key lock inside its own INSERT would be waiting for a row while holding the gate a row-holder is waiting for, and Postgres would abort one of them — a paid fulfilment or an admin edit, depending on which lost.

func LockTrialFallbackIn added in v0.1.17

func LockTrialFallbackIn(ctx context.Context, tx bun.IDB, targetID, productID string) error

LockTrialFallbackIn takes a share lock on targetID, the plan a trial plan of productID is to name as its fallback, and checks it can be one as it reads under the lock: an edit or delete of the target holds its row lock across its own check (GuardTrialFallbackTargetIn), so the two never both pass.

func MaintenanceFeaturesEnabledForWriteIn added in v0.1.6

func MaintenanceFeaturesEnabledForWriteIn(ctx context.Context, tx bun.IDB) (bool, error)

MaintenanceFeaturesEnabledForWriteIn reads the switch on the caller's transaction and holds the row until it commits, so a write that depends on the answer and an operator switching it off cannot both go through. FOR SHARE, not FOR UPDATE: any number of writes may read it at once, while the settings update — an ordinary UPDATE of that row — waits for them.

On the caller's transaction for a second reason: a read through the pool while a transaction is open needs a second connection, and enough concurrent writers doing that exhaust the pool with each holding one and waiting for another.

func MarkLicenseUpgradeAppliedIn added in v0.1.16

func MarkLicenseUpgradeAppliedIn(ctx context.Context, db bun.IDB, u *model.LicenseUpgrade) error

MarkLicenseUpgradeAppliedIn records that an upgrade took effect: the payment that made it, and the licence as it found it.

func NewID

func NewID() string

NewID generates a new UUID. Exported for use by setup handler.

func NewLicenseUpgradeID added in v0.1.16

func NewLicenseUpgradeID() string

NewLicenseUpgradeID returns an id for an upgrade row. The checkout carries it in its metadata, so it exists before the row does.

func ParseDurationSetting added in v0.1.6

func ParseDurationSetting(key, v string) (time.Duration, error)

ParseDurationSetting is the one rule for what a duration setting may say, shared by the readers above and the admin API that writes it.

func PlanLicenseCountIn added in v0.1.6

func PlanLicenseCountIn(ctx context.Context, db bun.IDB, planID string) (int, error)

PlanLicenseCountIn counts on a caller's transaction, for a writer that holds the plan's row lock across the count and the write.

func ProductHasEverPublishedReleaseIn added in v0.1.6

func ProductHasEverPublishedReleaseIn(ctx context.Context, db bun.IDB, productID string) (bool, error)

ProductHasEverPublishedReleaseIn answers on a caller's transaction.

func ProductHasMaintenanceIn added in v0.1.6

func ProductHasMaintenanceIn(ctx context.Context, db bun.IDB, productID string) (bool, error)

ProductHasMaintenanceIn answers on a caller's transaction, for a writer that decides under the product's lock.

func ProductShapeLockIn added in v0.1.20

func ProductShapeLockIn(ctx context.Context, db bun.IDB, productID string, exclusive bool) error

ProductShapeLockIn takes the product's shape lock for the transaction: exclusive for a change of the product's type, shared for a write whose validity depends on that type (a plan's activation and seat fields, a release made or put back on sale).

A type change checks what the product holds and a writer checks the type, each before writing; without the lock both could pass on what the other had not yet committed, leaving, say, a desktop product with a plan selling seats. Taken as the transaction's first lock by every party, it orders them without entering the order of any row lock.

func ProductTypeIn added in v0.1.20

func ProductTypeIn(ctx context.Context, db bun.IDB, productID string) (string, error)

ProductTypeIn reads the product's type, under its shape lock.

func RecordRefundedRenewalIn added in v0.1.6

func RecordRefundedRenewalIn(ctx context.Context, tx bun.IDB, r *model.LicenseRenewal) error

RecordRefundedRenewalIn writes a renewal that was refunded before it could be applied. It changes nothing on the license and only keeps the ledger complete, so retries of the session see it as done. The row still captures the end the license had at that moment: the ledger replay starts from the first row's previous end, and a nil there would read as "updates for life" once later renewals are refunded.

func ResetSubscriptionCancelStateIn added in v0.1.16

func ResetSubscriptionCancelStateIn(ctx context.Context, db bun.IDB, licenseID string) error

ResetSubscriptionCancelStateIn forgets whether a licence's subscription ends at its period end. The subscription row outlives the Stripe subscription an upgrade linked: once that is gone, or replaced by a new one, the recorded state belongs to nothing, and with it recorded the cancel-state sync would never ask about the new one.

func RevertLicenseRenewalIn added in v0.1.6

func RevertLicenseRenewalIn(ctx context.Context, tx bun.IDB, r *model.LicenseRenewal) error

RevertLicenseRenewalIn takes a refunded renewal back out of the license's maintenance period. The new end is replayed from the ledger without this renewal, so refunds in any order land on the same dates a customer who never bought them would have. If the license's current end is not what the ledger predicts, an admin edited it since; then only this renewal's days are subtracted so the edit survives. A license with updates for life, or a renewal from a previous period, is left alone. Marks the renewal refunded; a second call is a no-op.

Lock order is license row first, renewal rows after — the same order the admin edits use — so the two can never deadlock. The renewal is re-read under that lock, since it was looked up before.

func RunInTx added in v0.1.6

func RunInTx(ctx context.Context, db *bun.DB, fn func(ctx context.Context, tx bun.Tx) error) error

RunInTx runs fn in a transaction on db and commits when it returns nil; any error rolls the transaction back.

func SecondsUntil added in v0.1.1

func SecondsUntil(t time.Time) int

SecondsUntil returns seconds from now to t, capped non-negative. Used by the middleware to surface Retry-After hints.

func SetLicenseUpdatesUntilIn added in v0.1.6

func SetLicenseUpdatesUntilIn(ctx context.Context, tx bun.IDB, licenseID string, expected, next *time.Time, supersede bool) (bool, error)

SetLicenseUpdatesUntilIn is SetLicenseUpdatesUntil on a caller's transaction, for writers that must hold a lock across the check and the write.

func ShortID added in v0.1.2

func ShortID() string

ShortID generates a URL-safe 8-character unique ID for checkout links. Exported for use by the setup handler.

func SyncLicenseSubscriptionIn added in v0.1.7

func SyncLicenseSubscriptionIn(ctx context.Context, db bun.IDB, licenseID string, plan *model.Plan, status string, validUntil *time.Time) error

SyncLicenseSubscriptionIn keeps a licence's subscription row in step with a plan change, on the caller's transaction.

Issuance creates that row for trial and subscription plans and stamps the licence's status on it. Nothing put it right afterwards: the licence write touches only the licences table, and the hourly SyncSubscriptionStatuses repairs expired, canceled and revoked alone. A licence that left a trial plan therefore read as "active" in one table and "trialing" in the other for good — and every subscription query saw the trial.

The row is created when the new plan is one that would have had it, and kept (not deleted) when the plan no longer is: it may carry the provider's identifiers, which are not ours to throw away.

validUntil is the licence's own deadline, and the trial window is derived from it rather than computed again from the plan's days. The licence is what the expiry job reads, so a second reckoning here could only disagree with it: moving between two trial plans (or picking the plan the licence is already on) leaves licenses.valid_until alone, and a freshly computed trial_end would have the subscription view showing a trial that runs later than the date the licence actually expires on.

func UpdateLicenseAndSupersedeRenewalsIn added in v0.1.6

func UpdateLicenseAndSupersedeRenewalsIn(ctx context.Context, db bun.IDB, l *model.License, cols ...string) error

UpdateLicenseAndSupersedeRenewalsIn does the same on a caller's transaction.

func UpdateLicenseIn added in v0.1.6

func UpdateLicenseIn(ctx context.Context, db bun.IDB, l *model.License, cols ...string) error

UpdateLicenseIn writes the named columns on a caller's transaction, for writers that hold a lock across a check and this write.

func UpdatePlanIn added in v0.1.6

func UpdatePlanIn(ctx context.Context, db bun.IDB, p *model.Plan, cols ...string) error

UpdatePlanIn writes the plan on a caller's transaction. With no columns named it writes the whole row; with columns, only those — so an edit of one field cannot put another request's change back.

func UpdateProductGatingNowIn added in v0.1.6

func UpdateProductGatingNowIn(ctx context.Context, db bun.IDB, p *model.Product, cols ...string) error

UpdateProductGatingNowIn writes the named columns and stamps feed_gated_at with the database clock, reading the stored instant back into p. The wait a gated feed imposes runs from the moment the public feed actually stopped — this write — not from a time read on some replica before the transaction began.

func UpdateProductIn added in v0.1.6

func UpdateProductIn(ctx context.Context, db bun.IDB, p *model.Product, cols ...string) error

UpdateProductIn writes the product on a caller's transaction. With no columns named it writes the whole row; with columns, only those — a caller that has to refuse the rest of a request can still commit the part it must not lose.

func UpgradeLockKey added in v0.1.17

func UpgradeLockKey(licenseID string) int64

UpgradeLockKey names the advisory lock StartUpgrade holds per licence while it opens a checkout, so two clicks cannot both open one. An invite waits for it (see AddSeatWithinLimit): the checkout's seats are counted under it, and its upgrade is seen once it is open.

func ValidIdempotencyKey added in v0.1.1

func ValidIdempotencyKey(s string) bool

ValidIdempotencyKey reports whether a header value is acceptable as an idempotency key. Reject empty, oversized, and control-char inputs so attackers can't poison the table by sending pathological strings.

Types

type AggregatedSnapshot

type AggregatedSnapshot struct {
	Period           string `json:"period"`
	TotalLicenses    int    `json:"total_licenses"`
	ActiveLicenses   int    `json:"active_licenses"`
	NewLicenses      int    `json:"new_licenses"`
	Churned          int    `json:"churned"`
	TotalActivations int    `json:"total_activations"`
	TotalSeats       int    `json:"total_seats"`
	TotalUsage       int64  `json:"total_usage"`
}

type AnalyticsFilter

type AnalyticsFilter struct {
	ProductID   string
	PlanID      string
	LicenseType string
	Status      string
	From        time.Time
	To          time.Time
}

AnalyticsFilter holds optional filters shared across analytics queries.

type AnalyticsSummary

type AnalyticsSummary struct {
	TotalLicenses            int     `json:"total_licenses"`
	ActiveLicenses           int     `json:"active_licenses"`
	TrialingLicenses         int     `json:"trialing_licenses"`
	ExpiredLicenses          int     `json:"expired_licenses"`
	CanceledLicenses         int     `json:"canceled_licenses"`
	SuspendedLicenses        int     `json:"suspended_licenses"`
	RevokedLicenses          int     `json:"revoked_licenses"`
	PastDueLicenses          int     `json:"past_due_licenses"`
	TotalActivations         int     `json:"total_activations"`
	TotalSeats               int     `json:"total_seats"`
	AvgActivationsPerLicense float64 `json:"avg_activations_per_license"`
}

type AppliedMigration

type AppliedMigration struct {
	Filename  string    `bun:"filename" json:"filename"`
	AppliedAt time.Time `bun:"applied_at" json:"applied_at"`
}

type BreakdownItem

type BreakdownItem struct {
	Key   string `json:"key"`
	Label string `json:"label"`
	Count int    `json:"count"`
}

type ChangeLock added in v0.1.17

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

ChangeLock is a licence's change lock, on a connection of its own.

func (*ChangeLock) Unlock added in v0.1.17

func (l *ChangeLock) Unlock()

Unlock gives the change lock back.

type FeatureUsageItem

type FeatureUsageItem struct {
	Feature     string `json:"feature"`
	TotalUsage  int64  `json:"total_usage"`
	UniqueUsers int    `json:"unique_users"`
}

type GrowthMetrics

type GrowthMetrics struct {
	NetGrowthRate        float64 `json:"net_growth_rate"`
	TrialConversion      float64 `json:"trial_conversion"`
	AvgLicenseAgeDays    float64 `json:"avg_license_age_days"`
	MedianLicenseAgeDays float64 `json:"median_license_age_days"`
	TotalTrials          int     `json:"total_trials"`
	ConvertedTrials      int     `json:"converted_trials"`
	NewLast30d           int     `json:"new_last_30d"`
	ChurnedLast30d       int     `json:"churned_last_30d"`
}

type InUse added in v0.1.17

type InUse struct {
	People, Activations, Sessions int
}

InUse is what a licence uses of its limits: its people (the owner included), activations, and floating sessions running now.

func CountInUseIn added in v0.1.17

func CountInUseIn(ctx context.Context, db bun.IDB, licenseID string) (InUse, error)

CountInUseIn is CountInUse on a caller's transaction.

type LapsedTermHold added in v0.1.17

type LapsedTermHold struct {
	LicenseID string    `bun:"id"`
	Until     time.Time `bun:"terms_held_until"`
}

LapsedTermHold is a hold FindLapsedTermHolds found: the licence, and the hold's end, which names it (a downgrade since holds until later).

type LatestPublished added in v0.1.20

type LatestPublished struct {
	ProductID string `json:"product_id"`
	Channel   string `json:"channel"`
	Version   string `json:"version"`
}

LatestPublished is the highest published version of one product on one channel.

type LicenseAgeDistribution

type LicenseAgeDistribution struct {
	Bucket string `json:"bucket"`
	Count  int    `json:"count"`
}

type LicenseListFilter added in v0.1.1

type LicenseListFilter struct {
	ProductID           string
	Status              string
	Search              string
	ExternalCustomerID  string
	ExternalWorkspaceID string
	// Sort is the column the caller asked to order by. The zero
	// value orders by newest first, which is what every caller that
	// does not care about order wants.
	Sort   Sort
	Offset int
	// Limit must be positive. Unlike Page, a zero here is not "every
	// row": bun drops the LIMIT clause entirely, and the whole table
	// then comes back and has its activations counted in one IN list.
	// The handler clamps what it reads from the query string before
	// it gets here, so no request can ask for that.
	Limit int
}

LicenseListFilter narrows ListLicenses queries. New filters slot in here rather than as positional params so callers (handler + future internal uses) don't have to grow a long argument list.

type LicenseTerms added in v0.1.17

type LicenseTerms struct {
	PlanID   string `bun:"plan_id"`
	Quantity int    `bun:"quantity"`
}

LicenseTerms are what a licence is paid for: its plan and how many seats.

type Page added in v0.1.7

type Page struct {
	Limit  int
	Offset int
}

Page is the slice of a list a caller wants. It is the store's half of the contract the admin API answers with: a bounded window plus the number of rows the filter matched, so a client can tell how far the list goes without asking for all of it.

A Limit of zero or less means "every row". Only callers inside this process build one of those — the analytics sweep that walks every product, the public plan list of a single product. A request never can: the handler clamps what it reads from the query string before it gets here, so an unbounded page cannot be asked for over HTTP.

type PendingCheckoutSession added in v0.1.5

type PendingCheckoutSession struct {
	SessionID string    `bun:"event_id"`
	CreatedAt time.Time `bun:"created_at"`
}

PendingCheckoutSession is one row of the delayed-payment backlog.

type QuantityInUseError added in v0.1.17

type QuantityInUseError struct {
	Code, Kind   string
	InUse, Limit int
}

QuantityInUseError: the quantity is below what the licence uses, as the portal refuses a downgrade (Code SEATS_IN_USE or DEVICES_IN_USE, Kind activations or sessions for the latter). Nobody and nothing is removed by a change of seats, so the room is freed first.

func (*QuantityInUseError) Error added in v0.1.17

func (e *QuantityInUseError) Error() string

type QuantityRangeError added in v0.1.17

type QuantityRangeError struct{ Min, Max int }

QuantityRangeError: the quantity is outside what the licence's plan sells, Min to Max seats, as a checkout or the portal would refuse it.

func (*QuantityRangeError) Error added in v0.1.17

func (e *QuantityRangeError) Error() string

type QueuedEmail

type QueuedEmail struct {
	ID          string     `bun:"id,pk"`
	ToAddr      string     `bun:"to_addr"`
	Subject     string     `bun:"subject"`
	Body        string     `bun:"body"`
	Attempts    int        `bun:"attempts"`
	MaxAttempts int        `bun:"max_attempts"`
	Status      string     `bun:"status"`
	NextRetry   *time.Time `bun:"next_retry"`
	Error       string     `bun:"error"`
	// ClaimToken names the processor that holds this mail. Every
	// finishing write carries it, so one that stalled past its lease
	// cannot report on the mail somebody else has taken over.
	ClaimToken string `bun:"claim_token"`
}

type RecentActivity

type RecentActivity struct {
	ID        string    `json:"id"`
	Entity    string    `json:"entity"`
	EntityID  string    `json:"entity_id"`
	Action    string    `json:"action"`
	ActorType string    `json:"actor_type"`
	CreatedAt time.Time `json:"created_at"`
}

type RefreshRenewal added in v0.1.12

type RefreshRenewal struct {
	Token     *RefreshToken
	User      *model.User
	ExpiresAt time.Time
	// Grace is set when the presented token had been rotated within
	// RefreshReuseGrace: another tab, or a retry whose first response
	// was lost.
	Grace bool
}

RefreshRenewal is a successful RenewRefreshToken: the presented token, its user, and when the new token expires.

type RefreshToken

type RefreshToken struct {
	ID        string     `bun:"id,pk"`
	UserID    string     `bun:"user_id,notnull"`
	TokenHash string     `bun:"token_hash,notnull"`
	ExpiresAt time.Time  `bun:"expires_at,notnull"`
	CreatedAt time.Time  `bun:"created_at,default:now()"`
	RevokedAt *time.Time `bun:"revoked_at"`
}

type ReleaseFilter added in v0.1.1

type ReleaseFilter struct {
	ProductID string
	Channel   string
	Status    string
	Limit     int
	Offset    int
}

ReleaseFilter narrows ListReleases queries.

type RetentionData

type RetentionData struct {
	Period       string  `json:"period"`
	StartCount   int     `json:"start_count"`
	EndCount     int     `json:"end_count"`
	RetentionPct float64 `json:"retention_pct"`
	ChurnPct     float64 `json:"churn_pct"`
}

type SeatAddOutcome added in v0.1.1

type SeatAddOutcome string

SeatAddOutcome distinguishes the ways AddSeatWithinLimit can succeed. The service layer mails the invite for Created, Restored and Resent, and fires seat.added for Created and Restored only: a resent invite adds no seat. Existed is an idempotent no-op.

const (
	SeatCreated  SeatAddOutcome = "created"  // brand-new seat row inserted
	SeatRestored SeatAddOutcome = "restored" // soft-deleted row reactivated
	SeatExisted  SeatAddOutcome = "existed"  // already an active seat for this email
	SeatResent   SeatAddOutcome = "resent"   // pending invite renewed and sent again
)

type SeatLeftover added in v0.1.17

type SeatLeftover struct {
	ID        string `bun:"id"`
	LicenseID string `bun:"license_id"`
	ProductID string `bun:"product_id"`
	Email     string `bun:"email"`
}

SeatLeftover is a removed seat that still holds what a removal clears.

type Setting

type Setting struct {
	bun.BaseModel `bun:"table:settings"`
	Key           string `bun:",pk" json:"key"`
	Value         string `json:"value"`
}

type Sort added in v0.1.8

type Sort struct {
	Expr string
	Desc bool
}

Sort is a validated ordering for a list query.

Expr is a SQL expression, so it must never be built from anything a caller sent. The handler picks it out of a fixed map keyed by the name the client asked for; an unrecognised name is refused there and never reaches this struct. Keeping the resolved expression here rather than the client's word for it is what makes the concatenation in applySort safe.

type Stats

type Stats struct {
	TotalLicenses    int              `json:"total_licenses"`
	ActiveLicenses   int              `json:"active_licenses"`
	TotalActivations int              `json:"total_activations"`
	TotalProducts    int              `json:"total_products"`
	TotalSeats       int              `json:"total_seats"`
	TotalUsageEvents int              `json:"total_usage_events"`
	TotalWebhooks    int              `json:"total_webhooks"`
	ByStatus         map[string]int   `json:"by_status"`
	RecentLicenses   []*model.License `json:"recent_licenses"`
}

type Store

type Store struct {
	DB *bun.DB
	// LicenseKeyAEAD is optional: when set, license keys are AES-GCM
	// encrypted at rest in license_key_encrypted alongside the plaintext
	// column. Reads prefer the encrypted column with fallback to plaintext.
	// nil means encryption is disabled (legacy mode).
	LicenseKeyAEAD *crypto.AESGCM
	// contains filtered or unexported fields
}

func New

func New(dsn string) (*Store, error)

func (*Store) AcceptSeatInvite added in v0.1.1

func (s *Store) AcceptSeatInvite(ctx context.Context, plainToken string) (*model.User, *model.Seat, error)

AcceptSeatInvite consumes a plain invite token. Atomically:

  • looks up the seat by SHA256(plain)
  • rejects when removed, expired, or already accepted
  • looks up or creates a user keyed off the SEAT's email (NOT anything client-supplied — the token is the email-ownership proof)
  • binds seat.user_id, seat.accepted_at, clears invite_token_hash

Returns the resolved user + seat. ErrSeatInviteInvalid is the caller-facing failure for any of: bad token, removed, expired, already accepted; collapsing these into one sentinel avoids telling an attacker whether a token "was real".

func (*Store) ActivateForKey added in v0.1.17

func (s *Store) ActivateForKey(ctx context.Context, act *model.Activation, maxActivations int, key string) error

ActivateForKey is ActivateWithinLimit for a client presenting key, the member's key when act.SeatID is set, else the licence's own (see FindLicenseByKey). A key that stopped opening the licence since it was looked up (its member removed or their accept rolled back, the licence's key changed, the product's seats gone) is refused with ErrKeyRevoked: each of those takes the licence row lock this decides under, or is re-checked under it, so no device is left on a key that no longer works. A machine already activated stays whoever's activated it: another key holder's key is refused with ErrDeviceHeld, as for a floating session, while the licence's own key, which manages every device, finds it activated. The one move is a device activated with the licence's key before members had keys of their own (PredatesMemberKeys), when members used that key: it moves, once, to the member whose key activates it, so a member who used the shared key carries their machine onto their own and a change of the licence's key later leaves it alone.

func (*Store) ActivateWithinLimit

func (s *Store) ActivateWithinLimit(ctx context.Context, act *model.Activation, maxActivations int) error

ActivateWithinLimit takes one activation slot for a machine, or says why it could not.

Every decision happens under the license row lock. The service also looks for an existing activation before calling, which handles the ordinary repeat, but that read is not in this transaction: two requests from the SAME machine could both miss it and arrive here together. Whichever way the limit fell, the second one was wrong. At the cap it counted the slot the first had just taken and answered "activation limit reached", telling a machine the license it already holds is full. Below the cap both passed the count and the second insert hit the unique index on (license_id, identifier), which surfaced as a 500. A client retrying a timed-out activation, or an app opened twice, met one or the other.

It checks no key. Every path a client reaches goes through ActivateForKey, which re-checks the key it was given under the same lock; this one is for callers that hold none, such as tests.

func (*Store) AddLicenseAddon

func (s *Store) AddLicenseAddon(ctx context.Context, la *model.LicenseAddon) (created bool, err error)

AddLicenseAddon attaches an addon to a licence, or enables it again when it is already attached. la is filled from the stored row, so an existing attachment comes back with its own id; created reports whether the row is new.

An addon taken off sale (active=false) is attached to no licence more, and enabled again on none that had it switched off, as a retired price takes no new subscriptions: ErrAddonInactive. The licences that have it keep it, so asking again for one of those answers with its attachment. The addon row is held for the write, so it is not taken off sale between the check and the attachment; gone, it is sql.ErrNoRows.

func (*Store) AddSeatWithinLimit added in v0.1.1

func (s *Store) AddSeatWithinLimit(ctx context.Context, seat *model.Seat, maxSeats int) (SeatAddOutcome, []*model.Activation, error)

AddSeatWithinLimit is the atomic version of "count + insert" for seats. It also returns the devices a restored seat still had from its last time on the team (a seat removed by an older version kept them), which it removes, so the caller reports them as deactivated. Without this, two concurrent /seats/add requests can both pass the count check and both insert — overshooting max_seats.

The fix mirrors ActivateWithinLimit: take a row-level lock on the license inside a tx, then count, then insert. We also handle the re-invite case here: if a row with this email already exists but is soft-deleted (removed_at IS NOT NULL), restore it instead of trying to insert a brand-new row that would collide on the partial-unique index.

maxSeats is the plan's max_seats: how many people the license holds, the owner included. The owner has no seat row (self-invites are refused), so the rows may number one less. maxSeats <= 0 means "no limit" (uniform with the rest of the code that reads `lic.Plan.MaxSeats > 0` as the cap-active sentinel).

func (*Store) ApplyLicenseRenewal added in v0.1.6

func (s *Store) ApplyLicenseRenewal(ctx context.Context, r *model.LicenseRenewal) error

ApplyLicenseRenewal records a paid renewal of r.Days and moves the license's updates_until in one transaction; see ApplyLicenseRenewalIn.

func (*Store) Audit

func (s *Store) Audit(ctx context.Context, log *model.AuditLog)

func (*Store) BackfillKeyHashes

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

BackfillKeyHashes updates all licenses that don't have a key_hash yet.

func (*Store) BackfillLicenseKeyEncrypted added in v0.1.1

func (s *Store) BackfillLicenseKeyEncrypted(ctx context.Context, logger *slog.Logger) (int, error)

BackfillLicenseKeyEncrypted streams licenses where the encrypted column is NULL and populates it by encrypting the existing plaintext.

Concurrency-safe: each UPDATE includes `AND license_key = ?` so a concurrent admin operation that rotates the key invalidates this backfill's update for that row (RowsAffected = 0). The next backfill run will re-process the row with the new plaintext.

Idempotent: safe to call repeatedly. Each row is processed in a small SELECT/UPDATE batch (default 100) so the function can run in production without holding long locks. Progress + remaining are logged.

No-op when LicenseKeyAEAD is nil (encryption is not configured).

Per-row encrypt failures are logged + counted but DON'T abort the run — one bad row shouldn't stop the rest of the backfill. The function returns the count of successfully-encrypted rows, then the next invocation can retry the failures.

func (*Store) CancelScheduledLicenses added in v0.1.17

func (s *Store) CancelScheduledLicenses(ctx context.Context, licenseIDs []string) (map[string]bool, error)

CancelScheduledLicenses reports which of the licences have a subscription set to end at its period end rather than renew, as last recorded from Stripe (SetSubscriptionCancelScheduled).

func (*Store) CheckInFloating

func (s *Store) CheckInFloating(ctx context.Context, licenseID, identifier, seatID string) error

CheckInFloating ends the machine's session. seatID is the member whose key asks, who ends only their own; "" is the licence's key, which ends any.

func (*Store) CheckOutFloating

func (s *Store) CheckOutFloating(ctx context.Context, sess *model.FloatingSession) error

func (*Store) CheckOutFloatingForKey added in v0.1.17

func (s *Store) CheckOutFloatingForKey(ctx context.Context, sess *model.FloatingSession, maxSessions int, key string) (isNew bool, err error)

CheckOutFloatingForKey is CheckOutFloatingWithLimit for a client presenting key, the member's when sess.SeatID is set, else the licence's own; the same rules as ActivateForKey. A key cleared since it was looked up is refused with ErrKeyRevoked. A machine's running session stays its holder's: renewed by them or by the licence's key, and refused to any other key with ErrSessionHeld. Sessions are short leases, so none ever moves: once one lapses, the machine goes to whoever checks it out next.

func (*Store) CheckOutFloatingWithLimit

func (s *Store) CheckOutFloatingWithLimit(ctx context.Context, sess *model.FloatingSession, maxSessions int) (isNew bool, err error)

CheckOutFloatingWithLimit atomically creates a floating session only if the active session count is below maxSessions. Uses SELECT FOR UPDATE to prevent race conditions. Returns the created/refreshed session and whether it was a new checkout.

It checks no key. Every path a client reaches goes through CheckOutFloatingForKey, which re-checks the key it was given under the same lock; this one is for callers that hold none, such as tests.

func (*Store) ClaimNextEmail added in v0.1.6

func (s *Store) ClaimNextEmail(ctx context.Context) (*QueuedEmail, error)

ClaimNextEmail takes one queued mail for this processor alone, or nil when the queue has nothing due. Every replica runs a processor, so reading pending rows and then sending them would deliver the same mail several times: the row is claimed in the same statement that reads it, and SKIP LOCKED hands the next caller a different one. The claim is a lease written into next_retry rather than a status change, so a processor that dies mid-send releases the mail instead of stranding it.

One mail at a time on purpose: a batch would share one lease while the processor sends them one by one, and the last mail's lease could expire — and another replica send it — before its turn came.

func (*Store) ClaimNotification added in v0.1.6

func (s *Store) ClaimNotification(ctx context.Context, licenseID, tag string) (token string, err error)

ClaimNotification takes the lease on the (license, tag) pair before anything is sent. It returns a token identifying this claim; empty when the lease was not won. The unique index is the lock: with every replica running the reminder loop, a check-then-record would let two of them mail the same customer. A row already marked sent is never won again; an unsent row is won again once its lease has expired, and the take-over issues a fresh token so the previous holder can no longer complete or release it.

func (*Store) ClaimOTPAttempt added in v0.1.16

func (s *Store) ClaimOTPAttempt(ctx context.Context, id string) (attempts int, ok bool, err error)

ClaimOTPAttempt takes one of the code's attempts and returns how many it has used now. ok is false when none was left, or the code was used or expired meanwhile: the guess must then not be compared at all.

The attempt is taken before the compare, in one statement. Read first and counted after, a burst of parallel guesses all saw a count under the limit and were all compared.

func (*Store) ClaimPendingDeliveries added in v0.1.20

func (s *Store) ClaimPendingDeliveries(ctx context.Context, limit int, lease time.Duration) ([]*model.WebhookDelivery, error)

ClaimPendingDeliveries takes up to limit due deliveries for this sender alone. Every replica runs the retry loop, so reading pending rows and then sending them would POST the same delivery id from several replicas: the rows are claimed in the statement that reads them, and SKIP LOCKED hands a concurrent caller different ones. As with ClaimNextEmail, the claim is a lease in next_retry plus a token, not a status change, so a sender that dies mid-send releases the row when the lease runs out.

The batch shares one lease while its rows wait their turn for a sending slot, so each is renewed (RenewWebhookClaim) right before it is sent: a row whose lease ran out while it waited has been taken over by then, and is not sent twice.

func (*Store) ClaimProcessedEvent added in v0.1.5

func (s *Store) ClaimProcessedEvent(ctx context.Context, provider, eventID string) (claimed bool, err error)

ClaimProcessedEvent atomically records an event. claimed is false when the event was already recorded; err reports a database failure, which callers must not confuse with "already processed".

func (*Store) CleanExpiredFloating

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

CleanExpiredFloating removes floating sessions past their lease, and any a licence that stopped still holds (see stoppedStatuses): the writes that stop a licence end its sessions, and this catches one that did not.

func (*Store) CleanExpiredOTPs added in v0.1.1

func (s *Store) CleanExpiredOTPs(ctx context.Context)

func (*Store) CleanExpiredRefreshTokens

func (s *Store) CleanExpiredRefreshTokens(ctx context.Context)

func (*Store) ClearReleaseSignatures added in v0.1.4

func (s *Store) ClearReleaseSignatures(ctx context.Context, releaseID string) error

UpdateArtifactSignature stores the Ed25519 signature for an artifact. Bound to a specific signing key by ID so post-rotation clients can pick the correct public key.

INTENTIONALLY lock-free. A concurrent UpdateArtifactFile (which DOES take FOR UPDATE on the parent release) can clear the sig right after this write, which would leave a published-without-sig artifact — EXCEPT that PublishRelease's atomic UPDATE re-validates `ed25519_sig != ” AND signing_key_id IS NOT NULL` at commit time when the caller passes `requireSignatures=true`. So the worst outcome of a race here is the publish UPDATE rejecting with ErrReleaseArtifactsNotSigned; the caller (Publish) re-runs the sign loop and retries. ClearReleaseSignatures drops every signature on a draft release. Used when a release is deliberately published unsigned, so nothing from an earlier signing attempt ships.

Locks the release row first: under READ COMMITTED a plain UPDATE with a status subquery can see "draft" while a concurrent publish is committing, and then erase signatures from a release that is live.

func (*Store) ClearSeatLeftovers added in v0.1.17

func (s *Store) ClearSeatLeftovers(ctx context.Context, seatID string) ([]*model.Activation, bool, error)

ClearSeatLeftovers finishes a removal an older version left undone: the seat's key is cleared and its devices and floating sessions removed, under the licence row lock as RemoveSeat does. Only while the seat is still not on the team (removed, or pending): one accepted meanwhile is left alone. It returns the devices removed, and whether anything was done.

func (*Store) ClearStripeSubscription added in v0.1.7

func (s *Store) ClearStripeSubscription(ctx context.Context, licenseID, expectedSubID string) (bool, error)

ClearStripeSubscription unlinks a licence from the Stripe subscription the caller confirmed is over, and reports whether it was still linked to that one.

The expected id is part of the write: what the admin was shown, and what Stripe answered about, is the subscription being cut loose. If the licence has moved to another one in between, this changes nothing and says so, rather than detaching a subscription nobody asked about.

NULL, not the empty string: the column carries a plain UNIQUE constraint, so a second licence cleared to an empty string would collide with the first one — while NULLs do not collide at all, which is why every licence without a subscription holds NULL.

func (*Store) Close

func (s *Store) Close() error

func (*Store) CompleteProcessedEvent added in v0.1.5

func (s *Store) CompleteProcessedEvent(ctx context.Context, claimProvider, eventID string) error

CompleteProcessedEvent removes the in-flight marker of a claim; the reservation row (written under the name older binaries use) stays as the done marker, so one row per event remains.

func (*Store) ConsumeOTPCode added in v0.1.16

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

ConsumeOTPCode marks an unused code used and reports whether this call was the one that did it. Two requests presenting the same code at once both pass the hash check; only one of them gets true here.

func (*Store) CountActivations

func (s *Store) CountActivations(ctx context.Context, licenseID string) (int, error)

func (*Store) CountActiveFloating

func (s *Store) CountActiveFloating(ctx context.Context, licenseID string) (int, error)

func (*Store) CountActiveSeats

func (s *Store) CountActiveSeats(ctx context.Context, licenseID string) (int, error)

CountActiveSeats returns how many members a license has, the owner not included (see memberSeatsSQL).

func (*Store) CountDevicesBySeat added in v0.1.17

func (s *Store) CountDevicesBySeat(ctx context.Context, licenseID string) (map[string]int, error)

CountDevicesBySeat is how many devices each member's own key has activated on a licence, by seat ID.

func (*Store) CountInUse added in v0.1.17

func (s *Store) CountInUse(ctx context.Context, licenseID string) (InUse, error)

CountInUse counts what a licence uses of its limits.

func (*Store) CountLicensesOverSeatLimit added in v0.1.17

func (s *Store) CountLicensesOverSeatLimit(ctx context.Context, planID string, maxSeats int) (int, error)

CountLicensesOverSeatLimit returns how many licenses on the plan have more people joined, the owner included, than maxSeats would allow: those on which lowering the plan's max_seats to it would pause the members who joined last (see seatPausedSQL). Pending invitations are not counted; they only wait for a free seat. 0 when maxSeats <= 0 (no limit).

func (*Store) CountOwners

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

CountOwners returns the number of users with the 'owner' role.

func (*Store) CountPlansIncompatibleWithType added in v0.1.1

func (s *Store) CountPlansIncompatibleWithType(ctx context.Context, productID, newType string) (int, error)

CountPlansIncompatibleWithType counts plans under the given product whose capability fields would become invalid under newType. Used to block product-type changes that would silently leave behind plan rows with max_activations or floating license_model on a SaaS product, or max_seats on a desktop product.

Rules mirror model.ProductSupports:

  • if newType doesn't support activations → max_activations>0 OR license_model='floating' is a conflict
  • if newType doesn't support seats → max_seats>0 is a conflict

func (*Store) CountRecentOTPCodes added in v0.1.1

func (s *Store) CountRecentOTPCodes(ctx context.Context, email string) (int, error)

func (*Store) CountReleases added in v0.1.1

func (s *Store) CountReleases(ctx context.Context, f ReleaseFilter) (int, error)

CountReleases returns total rows matching the filter (ignores limit/offset).

func (*Store) CountSelfSignupsToday added in v0.1.16

func (s *Store) CountSelfSignupsToday(ctx context.Context, planID string) (int, error)

CountSelfSignupsToday returns how many self sign-up licences were claimed on the plan today (UTC), wherever they have moved since. Read outside the claim lock it is only a hint: CreateSelfSignupLicense counts again under the lock.

func (*Store) CreateAPIKey

func (s *Store) CreateAPIKey(ctx context.Context, ak *model.APIKey, rawKey string) error

func (*Store) CreateActivation

func (s *Store) CreateActivation(ctx context.Context, a *model.Activation) error

func (*Store) CreateAddon

func (s *Store) CreateAddon(ctx context.Context, a *model.Addon) error

func (*Store) CreateAnalyticsSnapshot

func (s *Store) CreateAnalyticsSnapshot(ctx context.Context, snap *model.AnalyticsSnapshot) error

func (*Store) CreateArtifact added in v0.1.1

func (s *Store) CreateArtifact(ctx context.Context, a *model.ReleaseArtifact) error

CreateArtifact attaches a new artifact to a release.

Wrapped in a tx with `SELECT ... FOR UPDATE` on the parent release so PublishRelease's atomic gate cannot flip the release to 'published' between the status check and the artifact INSERT. Either path is consistent:

  • We acquire FOR UPDATE first → publisher's UPDATE waits on us → after our commit publisher sees the new (pending) artifact and fails its NOT EXISTS gate.
  • Publisher's UPDATE acquires the row-X lock first → we wait → after publisher commits, status='published' so we return ErrReleaseNotPublishable.

Returns ErrArtifactAlreadyExists if the (release_id, platform) tuple already exists.

func (*Store) CreateEntitlement

func (s *Store) CreateEntitlement(ctx context.Context, e *model.Entitlement) error

func (*Store) CreateLicense

func (s *Store) CreateLicense(ctx context.Context, l *model.License) error

func (*Store) CreateLicenseWithSubscription

func (s *Store) CreateLicenseWithSubscription(ctx context.Context, l *model.License, plan *model.Plan) error

CreateLicenseWithSubscription creates a license and, for subscription/trial plans, a subscription record in a single transaction to prevent orphan records.

func (*Store) CreateOTPCode added in v0.1.1

func (s *Store) CreateOTPCode(ctx context.Context, otp *model.OTPCode) error

func (*Store) CreatePlaceholderUser

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

CreatePlaceholderUser creates a plain user with minimal info for team invites; the invite then grants the role through SetRoleAtomic. The user will get proper name when they first log in.

func (*Store) CreatePlan

func (s *Store) CreatePlan(ctx context.Context, p *model.Plan) error

func (*Store) CreateProduct

func (s *Store) CreateProduct(ctx context.Context, p *model.Product) error

func (*Store) CreateRefreshToken

func (s *Store) CreateRefreshToken(ctx context.Context, userID, tokenHash string, expiresAt time.Time) error

func (*Store) CreateRelease added in v0.1.1

func (s *Store) CreateRelease(ctx context.Context, r *model.Release) error

CreateRelease inserts a new release in the draft state. No artifacts — callers add platform-specific artifacts via AddArtifact. CreateRelease inserts a release, while the product's type has releases (ErrProductNoReleases otherwise, see ProductShapeLockIn).

func (*Store) CreateSeat

func (s *Store) CreateSeat(ctx context.Context, seat *model.Seat) error

func (*Store) CreateSelfSignupLicense added in v0.1.16

func (s *Store) CreateSelfSignupLicense(ctx context.Context, l *model.License, plan *model.Plan) error

CreateSelfSignupLicense writes a licence a customer claimed through self sign-up. Under a per-product lock it re-reads the plan and holds it, so a plan switched off, deactivated or given a price since the caller read it takes no more claims, and an edit waits for a claim already past the check. It then refuses a second self sign-up licence for the same address on the product (ErrSelfSignupExists) and a claim over the plan's daily cap (ErrSignupCapReached). The partial unique index on (product_id, lower(email)) backs the first check up.

func (*Store) CreateSigningKey added in v0.1.1

func (s *Store) CreateSigningKey(ctx context.Context, k *model.ReleaseSigningKey) error

CreateSigningKey inserts a new signing key. Caller is responsible for ensuring at most one active key per product exists at the time of call; the partial unique index will reject violations with a unique-constraint error which we surface as ErrSigningKeyAlreadyActive.

It takes RotateSigningKey's lock: a rotation overlapping it then sees the key made here and retires it, rather than meeting it in the unique index.

func (*Store) CreateSubscription

func (s *Store) CreateSubscription(ctx context.Context, sub *model.Subscription) error

func (*Store) CreateWebhook

func (s *Store) CreateWebhook(ctx context.Context, w *model.Webhook) error

func (*Store) CreateWebhookDelivery

func (s *Store) CreateWebhookDelivery(ctx context.Context, d *model.WebhookDelivery) error

CreateWebhookDelivery writes a delivery its creator is about to send, so the creator holds it from the start: the row gets a claim token, and d.NextRetry is its lease, as if ClaimPendingDeliveries had handed it out.

func (*Store) DeactivateSigningKey added in v0.1.1

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

DeactivateSigningKey marks a key inactive without creating a replacement. Used when an admin wants to disable signing entirely (e.g. before deleting a product). Future releases for this product will be unsigned until a new key is created via CreateSigningKey or RotateSigningKey.

func (*Store) DecryptLicenseKey added in v0.1.1

func (s *Store) DecryptLicenseKey(l *model.License) string

DecryptLicenseKey returns the plaintext license key for a row.

Read order:

  1. If LicenseKeyEncrypted is populated AND the AEAD is configured, decrypt and return that. Failure logs at WARN + bumps the LicenseKeyDecryptFailures metric so ops can detect ciphertext corruption (and, post-Phase C, the empty-result that follows). We still fall back to plaintext during Phase A/B so a corrupted row doesn't black-hole the license; Phase C drops the plaintext column, after which a decrypt failure surfaces as an empty key — which the metric makes visible.
  2. Else return LicenseKey (plaintext column) — used during transition for un-migrated rows and when encryption is unconfigured.

Callers that need to display the key (admin API, customer portal, post-purchase email) MUST go through this path rather than reading model.License.LicenseKey directly. Phase C will null those direct reads.

func (*Store) DecryptMemberKey added in v0.1.17

func (s *Store) DecryptMemberKey(seat *model.Seat) string

DecryptMemberKey is the member's key as stored, "" when they have none yet. Unlike MemberKey it never makes one: it is for showing a key's hint in a list, where looking must not change anything.

func (*Store) DeleteAPIKey

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

func (*Store) DeleteActivation

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

DeleteActivation removes one activation: sql.ErrNoRows when it is already gone, so of two releasing the same device only one goes on to audit it and fire license.deactivated.

func (*Store) DeleteActivationByID

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

DeleteActivationByID removes one activation; sql.ErrNoRows when it is already gone (see DeleteActivation).

func (*Store) DeleteAddon

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

func (*Store) DeleteArtifact added in v0.1.1

func (s *Store) DeleteArtifact(ctx context.Context, id string) (fileKey string, err error)

DeleteArtifact removes an artifact from a draft release. Returns the file_key for storage cleanup. Cannot delete artifacts of a published or yanked release.

func (*Store) DeleteEntitlement

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

func (*Store) DeleteExpiredActivations

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

DeleteExpiredActivations removes activations for expired/revoked licenses.

func (*Store) DeleteFulfilledPendingSessions added in v0.1.5

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

DeleteFulfilledPendingSessions removes pending-session markers for sessions that already produced a license.

func (*Store) DeletePlan

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

func (*Store) DeletePlanUnlessFallback added in v0.1.17

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

DeletePlanUnlessFallback deletes a plan, unless licences are on it (ErrPlanHasLicenses) or trial plans name it as their fallback (*TrialFallbackInUseError): the checks and the delete under the plan's row lock, which a licence insert's foreign key waits on.

func (*Store) DeleteProcessedEvent added in v0.1.5

func (s *Store) DeleteProcessedEvent(ctx context.Context, provider, eventID string) error

DeleteProcessedEvent forgets a recorded event.

func (*Store) DeleteProduct

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

DeleteProduct removes the product and the rows the 20260515 bundle refactor left behind for it.

releases_legacy is that migration's rollback evidence: the old releases table, renamed and kept whole so the down migration can rename it back. Nothing reads it, no endpoint can clear it, and its product_id still restricts — so on an install that upgraded through that migration, a product whose current releases have all been deleted would still refuse to go, with nothing the admin could do about it. The rows for this one product are dropped with it; the rest of the table, and the rollback it exists for, are untouched.

func (*Store) DeleteRefreshToken

func (s *Store) DeleteRefreshToken(ctx context.Context, tokenHash string)

DeleteRefreshToken removes a token outright. Used on logout, where we want the token gone immediately rather than just revoked (logout is explicit user intent — no need for reuse-detection state to outlive it).

func (*Store) DeleteRelease added in v0.1.1

func (s *Store) DeleteRelease(ctx context.Context, id string) (fileKeys []string, err error)

DeleteRelease removes a draft release and CASCADE-removes its artifacts. Returns the file_keys of all artifacts so the caller can clean up storage. Only DRAFT releases are deletable; published / yanked must stay.

func (*Store) DeleteSetting added in v0.1.3

func (s *Store) DeleteSetting(ctx context.Context, key string) error

DeleteSetting removes a row outright. Used to clear stored secrets: blanking the value would leave a row that reads as "configured but empty", which is a different state from "never set".

func (*Store) DeleteUserRefreshTokens

func (s *Store) DeleteUserRefreshTokens(ctx context.Context, userID string)

DeleteUserRefreshTokens wipes every refresh token for a user. Called on reuse detection (security) and on user-requested "log out everywhere".

func (*Store) DeleteWebhook

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

func (*Store) EnqueueEmail

func (s *Store) EnqueueEmail(ctx context.Context, to, subject, body string) error

func (*Store) EnqueueEmailAndCloseNotification added in v0.1.6

func (s *Store) EnqueueEmailAndCloseNotification(ctx context.Context, to, subject, body, token string) error

EnqueueEmailAndCloseNotification queues one mail and closes the reminder claim that produced it, in a single transaction. Doing them separately would let a crash in between leave a queued mail with an open claim, and the next pass would queue a second copy. A claim taken over meanwhile rolls the insert back.

func (*Store) EnsureOwner added in v0.1.14

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

EnsureOwner promotes an admin to owner when admins exist but no owner does, and returns the promoted email ("" when nothing changed). It picks the admin listed first in ADMIN_EMAILS, else the earliest admin. Installs from before setup existed, and admins who first signed in through ADMIN_EMAILS after startup, were left with no owner, so no one could manage roles.

func (*Store) ExpireLicenseAfterGrace added in v0.1.20

func (s *Store) ExpireLicenseAfterGrace(ctx context.Context, id string) (ok bool, err error)

ExpireLicenseAfterGrace marks an active or past-due licence expired while its grace has run out by its plan as it is now (7 days without one, as License.GraceDays). The grace sweep reads a plan's grace days with the licence; an admin who raises them, or moves the licence to another plan, during the sweep would otherwise see licences still in their new grace expired, and their devices cleared.

func (*Store) ExpireLicenseIf added in v0.1.12

func (s *Store) ExpireLicenseIf(ctx context.Context, id string, statuses []string, before *time.Time) (ok bool, err error)

ExpireLicenseIf marks a licence expired only while it still qualifies: its status is one of statuses and, when before is set, its valid_until is still earlier than before. The expiry sweeps read their candidates first and write later. In between an admin may have extended or reinstated the licence, and an unconditional write would undo that. ok is false when the licence no longer qualified and nothing changed.

func (*Store) ExpireStalePastDueLicenseIf added in v0.1.12

func (s *Store) ExpireStalePastDueLicenseIf(ctx context.Context, id string, threshold time.Time) (bool, error)

ExpireStalePastDueLicenseIf is ExpireLicenseIf for the dunning sweep: the licence must still be past_due, and past due since before the threshold — a licence that was paid and fell past due again after the sweep read it starts a fresh dunning clock.

func (*Store) ExpiryRemindersSent added in v0.1.12

func (s *Store) ExpiryRemindersSent(ctx context.Context, licenseID string, validUntil time.Time) ([]int, error)

ExpiryRemindersSent lists the reminder windows (in days) already sent for this license and expiry date. A reminder recorded in the old, dateless form counts when it was sent inside its window before this date, so licenses mid-way through their reminders at the upgrade are not reminded twice.

func (*Store) ExportLicenses

func (s *Store) ExportLicenses(ctx context.Context, productID, status string) ([]*model.License, error)

ExportLicenses returns all licenses matching filters (no pagination).

func (*Store) FillMemberEmails added in v0.1.17

func (s *Store) FillMemberEmails(ctx context.Context, rows []*model.Activation) error

FillMemberEmails sets MemberEmail on the devices members' keys activated, so a list of devices says whose each is.

func (*Store) FillPlanIDs added in v0.1.6

func (s *Store) FillPlanIDs(p *model.Plan)

FillPlanIDs gives a new plan the ids CreatePlan would, for callers that insert it on their own transaction with CreatePlanIn.

func (*Store) FindAPIKeyByID added in v0.1.1

func (s *Store) FindAPIKeyByID(ctx context.Context, id string) (*model.APIKey, error)

FindAPIKeyByID is the byID lookup used by the admin/rotate path. It does not eager-load the product since the rotate response only needs the row's name + scopes for audit context.

func (*Store) FindActivation

func (s *Store) FindActivation(ctx context.Context, licenseID, identifier string) (*model.Activation, error)

func (*Store) FindActivationByID added in v0.1.13

func (s *Store) FindActivationByID(ctx context.Context, id string) (*model.Activation, error)

FindActivationByID loads one activation.

func (*Store) FindActiveSigningKey added in v0.1.1

func (s *Store) FindActiveSigningKey(ctx context.Context, productID string) (*model.ReleaseSigningKey, error)

FindActiveSigningKey returns the (single) active key for a product. Returns ErrActiveSigningKeyMissing if none exists.

func (*Store) FindAddonByID

func (s *Store) FindAddonByID(ctx context.Context, id string) (*model.Addon, error)

func (*Store) FindAllLicensesByStripeCustomer

func (s *Store) FindAllLicensesByStripeCustomer(ctx context.Context, customerID string) ([]*model.License, error)

FindAllLicensesByStripeCustomer returns all licenses for a Stripe customer.

func (*Store) FindAppliedUpgrade added in v0.1.16

func (s *Store) FindAppliedUpgrade(ctx context.Context, licenseID string) (*model.LicenseUpgrade, error)

FindAppliedUpgrade returns the upgrade in effect on a licence, or sql.ErrNoRows.

func (*Store) FindArtifact added in v0.1.1

func (s *Store) FindArtifact(ctx context.Context, id string) (*model.ReleaseArtifact, error)

FindArtifact returns an artifact by ID.

func (*Store) FindArtifactByPlatform added in v0.1.1

func (s *Store) FindArtifactByPlatform(ctx context.Context, releaseID, platform string) (*model.ReleaseArtifact, error)

FindArtifactByPlatform returns the artifact for (release, platform).

func (*Store) FindEntitlementByID

func (s *Store) FindEntitlementByID(ctx context.Context, id string) (*model.Entitlement, error)

func (*Store) FindExpiredTrials

func (s *Store) FindExpiredTrials(ctx context.Context) ([]*model.License, error)

FindExpiredTrials returns trialing licenses that have passed valid_until.

A trial a Stripe subscription bills is Stripe's to end: at its end Stripe charges and turns it active, or past due, and says so by webhook, which may come some time after valid_until. Expiring it first would tell a customer who is paying that their trial ended, and clear their devices. It is left to Stripe for the plan's grace days, and only past them, with nothing heard, expired as a trial (webhooks lost for good). At least a day, whatever the grace days: Stripe's charge and webhook take that much. (Whether the key works meanwhile is the grace days' own rule, see assertUsable; with none it stops at valid_until.)

func (*Store) FindExpiringLicenses

func (s *Store) FindExpiringLicenses(ctx context.Context, from, to time.Time) ([]*model.License, error)

FindExpiringLicenses returns active licenses that expire between `from` and `to`.

func (*Store) FindFloatingSession

func (s *Store) FindFloatingSession(ctx context.Context, licenseID, identifier string) (*model.FloatingSession, error)

func (*Store) FindLapsedTermHolds added in v0.1.17

func (s *Store) FindLapsedTermHolds(ctx context.Context, limit int) ([]LapsedTermHold, error)

FindLapsedTermHolds lists licences whose downgrade hold ran out with no read since to settle it: the change's outcome was never known, and no event may come to say. One whose last check could not finish waits until its next check is due, behind the others. limit caps the batch.

func (*Store) FindLatestValidOTPCode added in v0.1.1

func (s *Store) FindLatestValidOTPCode(ctx context.Context, email string) (*model.OTPCode, error)

func (*Store) FindLicenseByID

func (s *Store) FindLicenseByID(ctx context.Context, id string) (*model.License, error)

func (*Store) FindLicenseByIDWithCounts added in v0.1.8

func (s *Store) FindLicenseByIDWithCounts(ctx context.Context, id string) (*model.License, error)

FindLicenseByIDWithCounts is FindLicenseByID with the computed fields a list response carries filled in, so a caller reading one license sees the same numbers as the row it clicked on.

func (*Store) FindLicenseByKey

func (s *Store) FindLicenseByKey(ctx context.Context, key string) (*model.License, error)

FindLicenseByKey finds the licence a key opens: the licence's own key, or a team member's (see Store.MemberKey), which opens the licence the member belongs to and sets KeySeat to their seat. A removed member's key is cleared, so it opens nothing; nor does a member's key while the product has no seats (its type changed), when the team cannot be managed and so a member could not be removed.

func (*Store) FindLicenseByStripeCheckoutSession added in v0.1.5

func (s *Store) FindLicenseByStripeCheckoutSession(ctx context.Context, sessionID string) (*model.License, error)

func (*Store) FindLicenseByStripePaymentIntent added in v0.1.5

func (s *Store) FindLicenseByStripePaymentIntent(ctx context.Context, paymentIntentID string) (*model.License, error)

func (*Store) FindLicenseByStripeSubscription

func (s *Store) FindLicenseByStripeSubscription(ctx context.Context, subID string) (*model.License, error)

func (*Store) FindLicenseRenewalByPaymentIntent added in v0.1.6

func (s *Store) FindLicenseRenewalByPaymentIntent(ctx context.Context, paymentIntentID string) (*model.LicenseRenewal, error)

func (*Store) FindLicenseRenewalBySession added in v0.1.6

func (s *Store) FindLicenseRenewalBySession(ctx context.Context, sessionID string) (*model.LicenseRenewal, error)

func (*Store) FindLicenseUpgradeByID added in v0.1.16

func (s *Store) FindLicenseUpgradeByID(ctx context.Context, id string) (*model.LicenseUpgrade, error)

FindLicenseUpgradeByID returns an upgrade by id, or sql.ErrNoRows.

func (*Store) FindLicenseUpgradeByPaymentIntent added in v0.1.16

func (s *Store) FindLicenseUpgradeByPaymentIntent(ctx context.Context, paymentIntentID string) (*model.LicenseUpgrade, error)

FindLicenseUpgradeByPaymentIntent returns the upgrade a one-time payment paid for, or sql.ErrNoRows.

func (*Store) FindLicenseUpgradeBySession added in v0.1.16

func (s *Store) FindLicenseUpgradeBySession(ctx context.Context, sessionID string) (*model.LicenseUpgrade, error)

FindLicenseUpgradeBySession returns the upgrade a checkout session belongs to, or sql.ErrNoRows.

func (*Store) FindLicenseUpgradeBySubscription added in v0.1.16

func (s *Store) FindLicenseUpgradeBySubscription(ctx context.Context, subscriptionID string) (*model.LicenseUpgrade, error)

FindLicenseUpgradeBySubscription returns the newest upgrade that started a subscription, or sql.ErrNoRows.

func (*Store) FindLicensesForExpiryReminder added in v0.1.12

func (s *Store) FindLicensesForExpiryReminder(ctx context.Context, from, to time.Time) ([]*model.License, error)

FindLicensesForExpiryReminder returns active and trialing licenses that run out between from and to and will not renew on their own: no Stripe subscription, or one Stripe confirmed ends at the period end. One that renews gets the renewal reminder instead (FindLicensesForRenewalReminder); one whose state is not known yet gets neither until it is — a late reminder beats a wrong one.

func (*Store) FindLicensesForGraceExpiry

func (s *Store) FindLicensesForGraceExpiry(ctx context.Context) ([]*model.License, error)

FindLicensesForGraceExpiry returns active/past_due licenses that have passed valid_until.

func (*Store) FindLicensesForRenewalReminder added in v0.1.12

func (s *Store) FindLicensesForRenewalReminder(ctx context.Context, from, to time.Time) ([]*model.License, error)

FindLicensesForRenewalReminder returns active licenses whose Stripe subscription renews between from and to: billed by Stripe, and Stripe confirmed it is not set to end at the period end.

func (*Store) FindLicensesWithUpdatesEnding added in v0.1.6

func (s *Store) FindLicensesWithUpdatesEnding(ctx context.Context, from, to time.Time) ([]*model.License, error)

FindLicensesWithUpdatesEnding lists active perpetual licenses whose maintenance period ends inside [from, to], with product and plan loaded for the reminder email.

func (*Store) FindPlanByCheckoutID added in v0.1.1

func (s *Store) FindPlanByCheckoutID(ctx context.Context, checkoutID string) (*model.Plan, error)

func (*Store) FindPlanByID

func (s *Store) FindPlanByID(ctx context.Context, id string) (*model.Plan, error)

func (*Store) FindPlanByStripePrice

func (s *Store) FindPlanByStripePrice(ctx context.Context, priceID string) (*model.Plan, error)

func (*Store) FindPlanByStripeRenewalPrice added in v0.1.6

func (s *Store) FindPlanByStripeRenewalPrice(ctx context.Context, priceID string) (*model.Plan, error)

FindPlanByStripeRenewalPrice returns a plan selling renewals at the given price; several plans may share one, the first is returned.

func (*Store) FindProductByAPIKey

func (s *Store) FindProductByAPIKey(ctx context.Context, keyHash string) (*model.Product, *model.APIKey, error)

func (*Store) FindProductByID

func (s *Store) FindProductByID(ctx context.Context, id string) (*model.Product, error)

func (*Store) FindProductBySlug

func (s *Store) FindProductBySlug(ctx context.Context, slug string) (*model.Product, error)

func (*Store) FindRefreshToken

func (s *Store) FindRefreshToken(ctx context.Context, tokenHash string) (*RefreshToken, error)

FindRefreshToken returns an *active* refresh token (not expired, not revoked). Used for read-only checks that don't rotate. The rotation path uses RotateRefreshToken instead, which distinguishes "missing" from "reused".

func (*Store) FindReleaseByID added in v0.1.1

func (s *Store) FindReleaseByID(ctx context.Context, id string) (*model.Release, error)

FindReleaseByID loads a release with its product + artifacts.

func (*Store) FindReleaseByVersion added in v0.1.1

func (s *Store) FindReleaseByVersion(ctx context.Context, productID, version string) (*model.Release, error)

FindReleaseByVersion finds an exact (product, version) tuple. The unique constraint excludes platform — same artifact bytes for the same version would conflict across platforms otherwise.

func (*Store) FindSeatByEmail

func (s *Store) FindSeatByEmail(ctx context.Context, licenseID, email string) (*model.Seat, error)

FindSeatByEmail is the live seat the address holds on the licence, matched case-insensitively, as the portal's licence list matches it: seats made before addresses were lower-cased may keep mixed case. An accepted seat wins over one still pending, as PortalViewerSeat picks.

func (*Store) FindSeatByID

func (s *Store) FindSeatByID(ctx context.Context, id string) (*model.Seat, error)

func (*Store) FindSeatLeftovers added in v0.1.17

func (s *Store) FindSeatLeftovers(ctx context.Context, limit int) ([]SeatLeftover, error)

FindSeatLeftovers returns up to limit seats not on the team, removed or invited and not yet accepted, that still hold a key, devices or floating sessions. This version never leaves any on such a seat (RemoveSeat clears them, and only an accepted member gets a key), so only what an older version left during a rolling upgrade is found: a member it removed (it set removed_at alone), or removed and invited back.

func (*Store) FindSelfSignupLicense added in v0.1.16

func (s *Store) FindSelfSignupLicense(ctx context.Context, productID, email string) (*model.License, error)

FindSelfSignupLicense returns the self sign-up licence email holds for the product, on whatever plan it is now, or sql.ErrNoRows. The plan comes with it: whether the licence is still usable depends on the plan's grace period.

func (*Store) FindSigningKeyByID added in v0.1.1

func (s *Store) FindSigningKeyByID(ctx context.Context, id string) (*model.ReleaseSigningKey, error)

FindSigningKeyByID looks up a key (active or rotated). Used for verifying signatures produced by rotated keys (a deployed client may still have the old public key embedded for some time after rotation).

func (*Store) FindStalePastDueLicenses

func (s *Store) FindStalePastDueLicenses(ctx context.Context, before time.Time) ([]*model.License, error)

FindStalePastDueLicenses returns past_due licenses whose dunning clock (past_due_at) crossed the threshold. Falls back to updated_at when past_due_at is unset, so legacy rows that pre-date the column don't get stranded.

func (*Store) FindStripeCancelStatesToSync added in v0.1.12

func (s *Store) FindStripeCancelStatesToSync(ctx context.Context, after *StripeCancelStateTarget, limit int) ([]StripeCancelStateTarget, error)

FindStripeCancelStatesToSync lists live Stripe-billed licences whose subscription cancel state has never been recorded, soonest to expire first, so the reminders that are due next are unblocked first. A non-nil after continues the walk past that target, so subscriptions Stripe keeps failing to answer for (a 404 stays unknown) cannot hold the head of the list and starve the rest.

func (*Store) FindSubscriptionByExternal

func (s *Store) FindSubscriptionByExternal(ctx context.Context, provider, externalID string) (*model.Subscription, error)

func (*Store) FindSubscriptionByID

func (s *Store) FindSubscriptionByID(ctx context.Context, id string) (*model.Subscription, error)

func (*Store) FindSubscriptionByLicense

func (s *Store) FindSubscriptionByLicense(ctx context.Context, licenseID string) (*model.Subscription, error)

func (*Store) FindUserByEmail

func (s *Store) FindUserByEmail(ctx context.Context, email string) (*model.User, error)

func (*Store) FindUserByID

func (s *Store) FindUserByID(ctx context.Context, id string) (*model.User, error)

func (*Store) FindUserIsAdmin

func (s *Store) FindUserIsAdmin(ctx context.Context, userID string) bool

FindUserIsAdmin checks if a user has admin privileges by querying the database. This is called on every authenticated request to ensure role changes take effect immediately.

func (*Store) FindWebhookByID

func (s *Store) FindWebhookByID(ctx context.Context, id string) (*model.Webhook, error)

func (*Store) FindWebhookDeliveryByID added in v0.1.1

func (s *Store) FindWebhookDeliveryByID(ctx context.Context, id string) (*model.WebhookDelivery, error)

FindWebhookDeliveryByID returns a single delivery row. Used by the delivery detail view + the resend endpoint so admins can inspect payload / response and trigger a manual re-fire.

func (*Store) FindWebhooksForEvent

func (s *Store) FindWebhooksForEvent(ctx context.Context, productID, event string) ([]*model.Webhook, error)

func (*Store) FinishWebhookDelivery added in v0.1.20

func (s *Store) FinishWebhookDelivery(ctx context.Context, d *model.WebhookDelivery) (bool, error)

FinishWebhookDelivery records the outcome of an attempt on a delivery the caller holds, and lets go of it. It is keyed by the token like RenewWebhookClaim: a sender that stalled past its lease must not write its result over the new holder's, or put a delivered row back to pending. Reports whether the row was still the caller's.

func (*Store) GetActivationProductID added in v0.1.1

func (s *Store) GetActivationProductID(ctx context.Context, activationID string) (string, error)

GetActivationProductID resolves the product behind an activation in a single query. Used by the activation delete handler to enforce API-key product scoping without loading the full activation row.

func (*Store) GetActivationTrend

func (s *Store) GetActivationTrend(ctx context.Context, productID string, from, to time.Time) ([]TrendPoint, error)

GetActivationTrend counts activations per UTC day. The from/to bounds are UTC days too; bucketing by the session's time zone instead would shift every bar on a database not set to UTC.

func (*Store) GetAnalyticsSummary

func (s *Store) GetAnalyticsSummary(ctx context.Context, f AnalyticsFilter) (*AnalyticsSummary, error)

func (*Store) GetGrowthMetrics

func (s *Store) GetGrowthMetrics(ctx context.Context, productID string) (*GrowthMetrics, error)

func (*Store) GetLicenseAgeDistribution

func (s *Store) GetLicenseAgeDistribution(ctx context.Context, productID string) ([]LicenseAgeDistribution, error)

func (*Store) GetLicenseBreakdown

func (s *Store) GetLicenseBreakdown(ctx context.Context, f AnalyticsFilter, dimension string) ([]BreakdownItem, error)

func (*Store) GetLicenseProductID added in v0.1.1

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

GetLicenseProductID is a one-column lookup used by handlers that only need to know which product a license belongs to (for API key scope enforcement). Cheaper than FindLicenseByID which eager-loads product, plan, entitlements, and activations.

func (*Store) GetPublicSettings

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

GetPublicSettings returns settings safe for unauthenticated access (site branding).

func (*Store) GetRecentActivity

func (s *Store) GetRecentActivity(ctx context.Context, productID string, limit int) ([]RecentActivity, error)

func (*Store) GetReleaseProductID added in v0.1.1

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

GetReleaseProductID resolves which product a release belongs to in one column lookup. Used by handlers that only need the FK for API-key product scoping; FindReleaseByID would eager-load product + artifacts unnecessarily.

func (*Store) GetRetentionData

func (s *Store) GetRetentionData(ctx context.Context, productID string, months int) ([]RetentionData, error)

func (*Store) GetSecretSetting added in v0.1.10

func (s *Store) GetSecretSetting(ctx context.Context, key string) (string, error)

GetSecretSetting returns the decrypted plaintext of a secret setting, or "" if it is not set. A value stored before encryption was enabled (no prefix) is returned as-is, so turning encryption on does not strand existing config.

func (*Store) GetSetting

func (s *Store) GetSetting(ctx context.Context, key string) (string, error)

func (*Store) GetSettings

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

func (*Store) GetStats

func (s *Store) GetStats(ctx context.Context) (*Stats, error)

func (*Store) GetTopFeatureUsage

func (s *Store) GetTopFeatureUsage(ctx context.Context, productID string, from, to time.Time, limit int) ([]FeatureUsageItem, error)

func (*Store) GetTopUsers

func (s *Store) GetTopUsers(ctx context.Context, productID string, limit int) ([]TopUser, error)

GetTopUsers returns the top customers by license count and usage. Excludes admin/owner users — they are platform operators, not customers.

func (*Store) GetUsageCounter

func (s *Store) GetUsageCounter(ctx context.Context, licenseID, feature, period, periodKey string) (*model.UsageCounter, error)

func (*Store) GetUsageSummary

func (s *Store) GetUsageSummary(ctx context.Context, licenseID string) ([]*model.UsageCounter, error)

func (*Store) GetUserDetail

func (s *Store) GetUserDetail(ctx context.Context, userID string) (*UserDetail, error)

func (*Store) HasAccountOrLicense added in v0.1.3

func (s *Store) HasAccountOrLicense(ctx context.Context, email string) (bool, error)

HasAccountOrLicense reports whether email already belongs to this installation: an existing user, a license owner, or a live seat.

The comparison is case-insensitive on purpose. Login lowercases what the visitor types, but the addresses this checks against are typed by someone else — an admin filling in the license form, or Stripe echoing back whatever the customer entered at checkout — so "Alice@example.com" on the license and "alice@example.com" at the login box are routinely the same person. Comparing them literally would lock that customer out of an installation that runs signup_mode=licensed_only.

func (*Store) HasNotification

func (s *Store) HasNotification(ctx context.Context, licenseID, tag string) bool

HasNotification checks if a notification with the given tag was already sent for a license.

func (*Store) HasProcessedEvent added in v0.1.5

func (s *Store) HasProcessedEvent(ctx context.Context, provider, eventID string) (bool, error)

HasProcessedEvent reports whether a marker exists, keeping database failures apart from a missing row: a takeover decision must not be made on a lookup that did not run.

func (*Store) HeartbeatFloating

func (s *Store) HeartbeatFloating(ctx context.Context, licenseID, identifier, seatID string, newExpiry time.Time) (bool, error)

HeartbeatFloating extends a session that is still running, and reports whether there was one to extend.

The `expires_at > now()` guard is what keeps the concurrency cap honest. Without it a client whose lease had already lapsed could raise itself from the dead with a heartbeat: the slot it used to hold has by then been handed to somebody else by CheckOut, and renewing the old row puts the license over its limit with neither call ever seeing the other. A machine that drops off the network for longer than the timeout has lost its seat, and has to compete for one again through CheckOut like any other.

seatID is as for CheckInFloating: a member renews only their own session, the licence's key ("") any.

func (*Store) IdempotencyAbandon added in v0.1.1

func (s *Store) IdempotencyAbandon(ctx context.Context, key, endpoint string)

IdempotencyAbandon deletes a slot the originator failed to complete (panic, context cancel, server crash mid-handler). Called from a defer so the next retry can claim the slot fresh instead of being stuck in IN_FLIGHT until expiry.

func (*Store) IdempotencyClaim added in v0.1.1

func (s *Store) IdempotencyClaim(ctx context.Context, key, endpoint, bodyHash string) (*model.IdempotencyKey, error)

IdempotencyClaim attempts to register (key, endpoint, bodyHash) as the in-flight owner of this idempotency slot. The semantics:

  • Returns (existing-row, nil) if a row already exists. The caller inspects `ResponseComplete`:

  • true → replay the cached response, do not run the handler.

  • false → another request is mid-flight, return 409 to the client and let them retry.

  • Returns (nil, nil) if the slot was successfully claimed. The caller runs the handler, captures the response, then calls IdempotencyComplete.

  • Returns (nil, ErrIdempotencyBodyMismatch) if (key, endpoint) already exists with a DIFFERENT bodyHash — the client reused the key for a semantically different request, which is a bug.

A row past its expires_at is claimed afresh, so the 24h TTL holds even when the periodic prune has not run yet.

Concurrency safety: we use INSERT ... ON CONFLICT + a followup SELECT, both atomic at the SQL layer. A race between two concurrent claims of the same key is resolved by exactly ONE row's INSERT succeeding; the other sees the row via SELECT and returns in-flight.

func (*Store) IdempotencyComplete added in v0.1.1

func (s *Store) IdempotencyComplete(ctx context.Context, key, endpoint string, status int, body string) error

IdempotencyComplete writes the final response into the slot. Only the originator (the request that won IdempotencyClaim) should call this.

func (*Store) IdempotencyPruneExpired added in v0.1.1

func (s *Store) IdempotencyPruneExpired(ctx context.Context) (int64, error)

IdempotencyPruneExpired drops rows past their TTL. Safe to call on a timer; rowsAffected is informational only.

func (*Store) IncrementUsageCounter

func (s *Store) IncrementUsageCounter(ctx context.Context, licenseID, feature, period, periodKey string, quantity int64) (*model.UsageCounter, error)

func (*Store) IncrementUsageCounterWithLimit

func (s *Store) IncrementUsageCounterWithLimit(ctx context.Context, licenseID, feature, period, periodKey string, quantity, limit int64) (*model.UsageCounter, bool, error)

IncrementUsageCounterWithLimit atomically increments the counter only if the new value would not exceed the limit. Returns the updated counter and whether the increment was accepted. Uses SELECT FOR UPDATE to prevent race conditions where concurrent requests could both pass the limit check and exceed the quota.

func (*Store) InsertMeteredEvent added in v0.1.1

func (s *Store) InsertMeteredEvent(ctx context.Context, licenseID, feature, periodKey, eventName, customerID string, quantity int64) error

InsertMeteredEvent appends an event-log row to be pushed to Stripe by MeteredBillingSync. quantity is the DELTA from this single usage call (not the cumulative total).

The identifier is the row's ID — opaque to callers, used as the Stripe meter event's identifier so retries dedupe within Stripe's rolling 24h window.

eventName and customerID are the Stripe meter and customer the usage is recorded against. The row is sent there, whatever the entitlement or the license say by the time it syncs.

func (*Store) IsEventProcessed added in v0.1.5

func (s *Store) IsEventProcessed(ctx context.Context, provider, eventID string) bool

TryRecordProcessedEvent atomically records a processed event. Returns true if this is the first time the event was recorded (should be processed). Returns false if the event was already recorded (should be skipped). IsEventProcessed reports whether a marker exists; a database error reads as "no". Use HasProcessedEvent where the difference matters.

func (*Store) IsOutdatedDunningEmail added in v0.1.21

func (s *Store) IsOutdatedDunningEmail(ctx context.Context, emailID string) (bool, error)

IsOutdatedDunningEmail reports whether a queued mail is a dunning notice that no longer applies: the license has left that past-due episode, or the ladder has moved on to a higher step of it. A notice can sit in the queue for days while the mail server is down or its credentials are wrong. A customer who has paid in the meantime must not be told their access is ending, and one still past due should get the notice they are on now, not every notice they missed.

func (*Store) LatestPublishedVersions added in v0.1.20

func (s *Store) LatestPublishedVersions(ctx context.Context, productID string) ([]LatestPublished, error)

LatestPublishedVersions returns, for each product (or the one named) and channel, its highest published version by semver. The release list is paged and filtered; this is what it is compared with, so a draft below what is already out says so whatever page it is on.

func (*Store) LicenseTermsHeld added in v0.1.17

func (s *Store) LicenseTermsHeld(ctx context.Context, licenseID string) (bool, error)

LicenseTermsHeld reports whether a downgrade holds the licence's terms now (see LowerLicenseTerms).

func (*Store) ListAPIKeys

func (s *Store) ListAPIKeys(ctx context.Context, productID, search string, p Page) ([]*model.APIKey, int, error)

func (*Store) ListActivations

func (s *Store) ListActivations(ctx context.Context, licenseID string) ([]*model.Activation, error)

func (*Store) ListAddons

func (s *Store) ListAddons(ctx context.Context, productID, search string, p Page) ([]*model.Addon, int, error)

func (*Store) ListAdmins

func (s *Store) ListAdmins(ctx context.Context, p Page) ([]*model.User, int, error)

ListAdmins returns all users with admin or owner role.

func (*Store) ListAnalyticsSnapshots

func (s *Store) ListAnalyticsSnapshots(ctx context.Context, productID string, from, to time.Time) ([]*model.AnalyticsSnapshot, error)

func (*Store) ListAnalyticsSnapshotsAggregated

func (s *Store) ListAnalyticsSnapshotsAggregated(ctx context.Context, productID string, from, to time.Time, granularity string) ([]*AggregatedSnapshot, error)

func (*Store) ListAppliedMigrations

func (s *Store) ListAppliedMigrations(ctx context.Context) ([]*AppliedMigration, error)

func (*Store) ListArtifactsMissingTauriSignature added in v0.1.13

func (s *Store) ListArtifactsMissingTauriSignature(ctx context.Context, limit, offset int) ([]*model.ReleaseArtifact, error)

ListArtifactsMissingTauriSignature returns signed artifacts that have no Tauri signature yet, with their release loaded, oldest first. These were signed before Tauri signatures were stored.

func (*Store) ListAuditLogs

func (s *Store) ListAuditLogs(ctx context.Context, entity, entityID, productID string, offset, limit int) ([]*model.AuditLog, int, error)

func (*Store) ListFloatingSessions

func (s *Store) ListFloatingSessions(ctx context.Context, licenseID string, p Page) ([]*model.FloatingSession, int, error)

func (*Store) ListLicenseAddons

func (s *Store) ListLicenseAddons(ctx context.Context, licenseID string, p Page) ([]*model.LicenseAddon, int, error)

func (*Store) ListLicenseRenewals added in v0.1.6

func (s *Store) ListLicenseRenewals(ctx context.Context, licenseID string) ([]*model.LicenseRenewal, error)

ListLicenseRenewals returns a license's renewal ledger, oldest first, refunded rows included.

func (*Store) ListLicenses

func (s *Store) ListLicenses(ctx context.Context, f LicenseListFilter) ([]*model.License, int, error)

func (*Store) ListLicensesByEmail

func (s *Store) ListLicensesByEmail(ctx context.Context, email string) ([]*model.License, error)

func (*Store) ListLicensesByStripeCustomer added in v0.1.5

func (s *Store) ListLicensesByStripeCustomer(ctx context.Context, customerID string) ([]*model.License, error)

ListLicensesByStripeCustomer returns every license bought under a Stripe customer, newest first.

func (*Store) ListMeteredBilling

func (s *Store) ListMeteredBilling(ctx context.Context, licenseID string) ([]*model.MeteredBilling, error)

func (*Store) ListPendingCheckoutSessions added in v0.1.5

func (s *Store) ListPendingCheckoutSessions(ctx context.Context, maxAge time.Duration, after *PendingCheckoutSession, limit int) ([]PendingCheckoutSession, error)

ListPendingCheckoutSessions pages through Stripe checkout sessions that completed unpaid (recorded under stripe_pending_session) and were not fulfilled since, oldest first, no older than maxAge. Pass the last row of the previous page as `after` to continue; a nil `after` starts from the beginning. Keyset paging means a round visits every row once, so a stuck batch never hides newer rows.

func (*Store) ListPlans

func (s *Store) ListPlans(ctx context.Context, productID, search string, p Page) ([]*model.Plan, int, error)

ListPlans returns one page of a product's plans (or of every product's, unfiltered) and how many the filter matched. Entitlements are a has-many relation, which bun loads in a query of its own, so the limit applies to plans and not to their rows.

func (*Store) ListProducts

func (s *Store) ListProducts(ctx context.Context, search string, types []string, p Page) ([]*model.Product, int, error)

ListProducts returns one page of the catalogue and how many products the filter matched.

types narrows to the product kinds the caller can actually use — the releases pages ask for the ones that ship binaries. Filtering here rather than over the page the dashboard happens to hold is the difference between "these are the products you can pick" and "these are the ones that were on screen".

The order carries id as a tiebreaker: two products created in the same instant would otherwise be free to swap places between two queries, and under paging that means a row shown twice while another is never shown at all.

func (*Store) ListPublishedReleasesForFeed added in v0.1.1

func (s *Store) ListPublishedReleasesForFeed(ctx context.Context, productID, channel, platform string, limit int, publishedBefore *time.Time) ([]*model.Release, error)

ListPublishedReleasesForFeed returns published, non-yanked releases for (product, channel), most recent first, up to limit. Each release has its artifacts preloaded.

When platform is non-empty, only releases that have an uploaded artifact for that platform are returned. This filter is pushed into SQL (EXISTS subquery) so that `limit` counts platform-compatible releases — not raw rows. Without this, a Tauri client requesting "latest for windows-x64" could see 204 even when older versions shipped a windows-x64 build, because the latest release happened to only ship macOS. Platform filtering at the handler level after a LIMIT can't fix that; only pushing the predicate down can.

`uploaded` is encoded as `file_key <> ” AND sha256 <> ”` to mirror the model's IsUploaded() check.

publishedBefore, when set, keeps only releases published at or before that instant. It belongs in the query, not in a filter on the result: for a license whose update period ended long ago, the newest limit rows may all be too new, and the entitled releases would never be seen.

func (*Store) ListReleases added in v0.1.1

func (s *Store) ListReleases(ctx context.Context, f ReleaseFilter) ([]*model.Release, error)

ListReleases returns releases matching the filter (with their artifacts). Defaults: limit=50 (clamped to [1,200]), offset clamped to >=0.

bun requires `Model(&dst)` (pointer to slice) for the Relation eager-load to wire the join correctly — using `Model((*Release)(nil))` + Scan(ctx, &dst) silently drops the Relation join, returning an empty slice.

func (*Store) ListSeats

func (s *Store) ListSeats(ctx context.Context, licenseID string, p Page) ([]*model.Seat, int, error)

func (*Store) ListSigningKeys added in v0.1.1

func (s *Store) ListSigningKeys(ctx context.Context, productID string) ([]*model.ReleaseSigningKey, error)

ListSigningKeys returns the recent history (active + rotated) for a product, most recent first. Capped at 200 rows — older entries are available via direct DB query if archaeology is needed.

func (*Store) ListSubscriptions

func (s *Store) ListSubscriptions(ctx context.Context, productID, status string, offset, limit int) ([]*model.Subscription, int, error)

func (*Store) ListUnsyncedMetered

func (s *Store) ListUnsyncedMetered(ctx context.Context, limit, maxAttempts int) ([]*model.MeteredBilling, error)

ListUnsyncedMetered returns pending rows that still have attempts left. Rows at the ceiling are excluded here, not just skipped by the caller: they are never going to sync, and with created_at ordering enough of them at the head of the queue would fill every batch and starve rows that could.

func (*Store) ListUnsyncedMeteredAfter added in v0.1.20

func (s *Store) ListUnsyncedMeteredAfter(ctx context.Context, last *model.MeteredBilling, limit, maxAttempts int) ([]*model.MeteredBilling, error)

ListUnsyncedMeteredAfter is ListUnsyncedMetered from after the row last (nil: from the start), in (created_at, id) order: a pass sending the whole queue in batches goes on past rows it tried, whether they were sent or failed, rather than meeting a failed one again at the head of the queue and spending its retries at once.

func (*Store) ListUpgradeTargetPlans added in v0.1.16

func (s *Store) ListUpgradeTargetPlans(ctx context.Context, productIDs []string) ([]*model.Plan, error)

ListUpgradeTargetPlans returns the active, priced plans of the given products, for working out which licences can be upgraded.

func (*Store) ListUsageEvents

func (s *Store) ListUsageEvents(ctx context.Context, licenseID, feature string, offset, limit int) ([]*model.UsageEvent, int, error)

func (*Store) ListUsers

func (s *Store) ListUsers(ctx context.Context, search string, offset, limit int) ([]*model.User, int, error)

ListUsers returns only customers (role='user'). Admins are managed separately.

func (*Store) ListWebhookDeliveries

func (s *Store) ListWebhookDeliveries(ctx context.Context, f WebhookDeliveryFilter) ([]*model.WebhookDelivery, int, error)

func (*Store) ListWebhooks

func (s *Store) ListWebhooks(ctx context.Context, productID, search string, p Page) ([]*model.Webhook, int, error)

func (*Store) LockLicenseChange added in v0.1.17

func (s *Store) LockLicenseChange(ctx context.Context, licenseID string, wait time.Duration) (*ChangeLock, error)

LockLicenseChange takes the licence's change lock: one change to its subscription at a time. It waits up to wait for a change already under way, then gives up with ErrChangeInProgress; nothing else waits for it. Unlock gives it back; should the process stop first, the database gives it back with the connection.

func (*Store) LowerLicenseTerms added in v0.1.17

func (s *Store) LowerLicenseTerms(ctx context.Context, licenseID string, to LicenseTerms, hold time.Duration, check func(InUse) error) (prev LicenseTerms, err error)

LowerLicenseTerms moves a licence to lower terms ahead of the change to its subscription that makes them, so nothing is taken meanwhile on limits about to go: under the licence row lock (the one every slot is taken under), what is in use is counted, check may refuse (its error is returned as is, and nothing changes), and the terms are written. The read stamp moves to now, so a read of the subscription from before cannot put the old terms back; and the terms are held for hold, so no read until then that still shows the old ones can either, whatever becomes of the request that lowered them (a lost answer, a restart). A read that shows the new terms ends the hold, as do ReleaseLicenseTerms and RestoreLicenseTerms. It returns the terms the licence had, for RestoreLicenseTerms should Stripe not make the change.

func (*Store) MaintenanceFeaturesEnabled added in v0.1.6

func (s *Store) MaintenanceFeaturesEnabled(ctx context.Context) (bool, error)

MaintenanceFeaturesEnabled reports whether the switch is on. A missing row reads as off; a read failure is an error, never an open gate.

func (*Store) MarkEmailDeferred added in v0.1.10

func (s *Store) MarkEmailDeferred(ctx context.Context, id, token, errMsg string)

MarkEmailFailed records a failed attempt on the mail this processor holds, keyed by the same token as MarkEmailSent: a stalled processor must not push the row another one is sending back to pending, or reopen a reminder that has meanwhile gone out. MarkEmailDeferred reschedules a mail that failed for a reason only an operator can fix — a bad SMTP/Cloudflare credential, a wrong account id, an auth rejection — rather than anything wrong with the message itself. Unlike MarkEmailFailed it does NOT count against max_attempts and does NOT drop the body: the mail carries a licence key and must survive until the config is corrected, however long that takes. Otherwise a token rotation that lasted past the five backoff attempts (~15 minutes) would wipe licence mail for good. The row goes back to pending on a fixed delay; a later pass sends it once resolve() returns a working provider.

func (*Store) MarkEmailFailed

func (s *Store) MarkEmailFailed(ctx context.Context, id, token, errMsg string)

func (*Store) MarkEmailFailedPermanent added in v0.1.10

func (s *Store) MarkEmailFailedPermanent(ctx context.Context, id, token, errMsg string)

MarkEmailFailedPermanent gives up on a mail immediately, without scheduling a retry. It is for failures that retrying cannot fix — a rejected request, bad credentials, a permanent bounce — where trying again just re-delivers to a bad address and burns sending reputation. The body is dropped for the same reason MarkEmailSent drops it: a row nobody will send again must not keep the credential it carried.

func (*Store) MarkEmailSent

func (s *Store) MarkEmailSent(ctx context.Context, id, token string)

MarkEmailSent closes the mail this processor holds. The token is what it holds it by: a processor that stalled past its lease finds the row taken over and changes nothing.

func (*Store) MarkLicenseRead added in v0.1.17

func (s *Store) MarkLicenseRead(ctx context.Context, licenseID string) error

MarkLicenseRead moves the licence's read stamp to now: every read of its subscription that began before is out of date. A downgrade Stripe may have made marks it so before its hold can end, so that no read from before the change can put the old terms back.

func (*Store) MarkMeteredAttempted added in v0.1.1

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

MarkMeteredAttempted bumps attempts without changing synced state. Called on every push regardless of outcome so retry budgets are visible. Successful pushes also call MarkMeteredSynced which already clears last_error.

func (*Store) MarkMeteredSynced

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

func (*Store) MarkPausedSeats added in v0.1.17

func (s *Store) MarkPausedSeats(ctx context.Context, licenseID string, seats []*model.Seat) error

MarkPausedSeats sets Seat.Paused on seats of one licence.

func (*Store) MemberKey added in v0.1.17

func (s *Store) MemberKey(ctx context.Context, seat *model.Seat) (string, error)

MemberKey returns the member's own key, making it the first time it is asked for: a member who has accepted and not been removed always has one, anyone else gets "". Making it here rather than when the invite is accepted gives the members who joined before keys of their own existed one as well, the first time they open the portal.

func (*Store) MoveEndedTrialToFallback added in v0.1.17

func (s *Store) MoveEndedTrialToFallback(ctx context.Context, id string, before time.Time) (TrialMove, error)

MoveEndedTrialToFallback moves a licence whose trial ended before before onto the plan its trial plan names in trial_fallback_plan_id, in the shape that plan issues licences in: active, with no expiry and no update period — the same re-shape an admin's change-plan gives a licence leaving a trial. The key, activations, seats and add-ons stay as they are, so the customer keeps working on the new plan.

It locks the licence and re-checks it first: the sweep read it earlier, and an admin may have extended, moved or reinstated it since (neither Moved nor Expire is set then; nothing changed). The fallback is locked against a concurrent edit and judged again here, as it stands now, so a plan repriced after it was named can never be handed out for nothing.

A licence Stripe bills is left to Stripe, which owns its plan (see the admin change-plan): it expires as before.

func (*Store) NewLicenseKey added in v0.1.17

func (s *Store) NewLicenseKey(ctx context.Context, productID string) (string, error)

NewLicenseKey generates a key for a license of the product, with the prefix that product has now.

func (*Store) NormalizeSeatRoles added in v0.1.17

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

NormalizeSeatRoles turns any seat with the admin role into a member: the role is gone (20261028_member_keys), but an older version still running during a rolling upgrade may have written one since. It returns how many it changed.

func (*Store) PausedSeats added in v0.1.17

func (s *Store) PausedSeats(ctx context.Context, licenseID string) (map[string]bool, error)

PausedSeats returns the joined seats of a licence whose members are paused, by seat ID: the rule of seatPausedSQL, ranked in one pass rather than counted again for each seat, as a list of a large licence would. A member's place in the join order is n, and the owner holds the first seat, so those from the limit on wait.

func (*Store) PlanLicenseCount

func (s *Store) PlanLicenseCount(ctx context.Context, planID string) (int, error)

func (*Store) PlanTermsAt added in v0.1.6

func (s *Store) PlanTermsAt(ctx context.Context, planID string, t time.Time) (days int, licenseType string, known bool, err error)

PlanTermsAt returns what the plan was selling at t — the update period and the kind of licence — and whether the history reaches back that far.

func (*Store) PostponeTermsCheck added in v0.1.17

func (s *Store) PostponeTermsCheck(ctx context.Context, h LapsedTermHold, after time.Duration) error

PostponeTermsCheck puts off the next check of a lapsed hold by after, keeping its record: the check could not finish, and is tried again then. A hold placed since is another downgrade's, and is left alone.

func (*Store) ProductBlockers added in v0.1.7

func (s *Store) ProductBlockers(ctx context.Context, productID string) (plans, licenses, releases int, err error)

ProductBlockers counts what a product delete would have to destroy and the database refuses to: plans, licences and releases all hold it by a foreign key that restricts. All three are counted in one call so the caller can name the one that matters most rather than whichever query happened to run first.

What is NOT counted is what the database removes with the product (api keys, webhooks, addons, signing keys, analytics): those cascade by design.

func (*Store) ProductHasEverPublishedRelease added in v0.1.6

func (s *Store) ProductHasEverPublishedRelease(ctx context.Context, productID string) (bool, error)

ProductHasEverPublishedRelease reports whether any release of the product has ever appeared in a feed — published, or yanked after being published. A product without one has never handed out a presigned artifact URL, so gating its feeds takes effect at once; with one, links from before the gate may still be usable.

func (*Store) ProductHasMaintenance added in v0.1.6

func (s *Store) ProductHasMaintenance(ctx context.Context, productID string) (bool, error)

ProductHasMaintenance reports whether the product has anything the feed gate protects: a plan selling a bounded update period or renewals, or a license with a finite cutoff (which outlives the plan setting that created it).

func (*Store) ProductLicenseCount

func (s *Store) ProductLicenseCount(ctx context.Context, productID string) (int, error)

func (*Store) ProductOfAudited added in v0.1.19

func (s *Store) ProductOfAudited(ctx context.Context, entity, entityID string) string

ProductOfAudited is the product an audited entity belongs to, or "" when it has none, is gone, or cannot be read: an audit line is written regardless. A handler deleting an entity asks before the delete.

func (*Store) PromoteAdminEmail added in v0.1.14

func (s *Store) PromoteAdminEmail(ctx context.Context, userID string) (string, error)

PromoteAdminEmail raises a plain user listed in ADMIN_EMAILS to admin, or to owner when the install has no owner yet, and returns the role the user ends up with.

func (*Store) PublishRelease added in v0.1.1

func (s *Store) PublishRelease(ctx context.Context, id string, requireSignatures bool, signingKeyID string) error

PublishRelease atomically transitions draft → published. The UPDATE inlines every invariant a published release must satisfy:

  • status is still 'draft'
  • the release has at least one artifact
  • every artifact has non-empty file_key AND non-empty sha256
  • when requireSignatures is true, every artifact has non-empty ed25519_sig AND signing_key_id (defends the race where a concurrent UpdateArtifactFile cleared a signature between the service-layer sign loop and this commit)

Concurrent AddArtifact / FinalizeArtifact / DeleteArtifact requests committed before this UPDATE evaluates are visible to the subqueries; uncommitted ones are blocked from racing past the gate because every mutating artifact path takes a row-level lock on the parent release (see CreateArtifact, DeleteArtifact, UpdateArtifactFile).

On 0 rows affected, diagnoseUnpublishable inspects current state and returns the most specific sentinel. signingKeyID, when non-empty, is the key the caller signed with: every artifact must carry a signature from exactly that key. Two publishes overlapping a key rotation can otherwise interleave their per-artifact signature writes and ship a release whose platforms verify against different public keys.

The key must still be active when the release goes live, and is held so until the publish commits: a rotation or deactivation waits for it, or, coming first, refuses the publish (ErrReleaseSigningKeyRetired). Otherwise a release could go out signed by a key already withdrawn, which clients holding the published public key reject.

func (*Store) RaiseDurationSetting added in v0.1.6

func (s *Store) RaiseDurationSetting(ctx context.Context, key string, d time.Duration) (time.Duration, error)

RaiseDurationSetting records d unless a longer value is already recorded, and returns whichever is longer. Two replicas starting at once must not lose the longer one, so the read and the write happen in one transaction with the row locked between them: the second writer waits, then compares against what the first committed. It only ever raises — an operator lowering the value by hand is left alone until the next start of a replica configured higher.

A recorded value that is not a usable duration is an error, not something to replace: it may stand for a lifetime longer than this replica's, so the caller stops instead of starting with a shorter one.

func (*Store) RecordMeteredSyncFailure added in v0.1.1

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

RecordMeteredSyncFailure stamps the row with the failure reason and bumps the attempts counter. We DON'T flip synced=true — the next sync pass tries again. last_error is human-readable and surfaces in the admin UI so operators can investigate without log-diving.

func (*Store) RecordRefundedRenewal added in v0.1.6

func (s *Store) RecordRefundedRenewal(ctx context.Context, r *model.LicenseRenewal) error

RecordRefundedRenewal writes a renewal that was refunded before it could be applied; see RecordRefundedRenewalIn.

func (*Store) RecordSubscriptionCancelStateIfUnknown added in v0.1.12

func (s *Store) RecordSubscriptionCancelStateIfUnknown(ctx context.Context, licenseID string, scheduled bool, asOf time.Time) error

RecordSubscriptionCancelStateIfUnknown records the state only while none is recorded yet: the background sync and fulfilment only fill the gap, and leave anything a webhook recorded alone.

func (*Store) RecordUsageEvent

func (s *Store) RecordUsageEvent(ctx context.Context, e *model.UsageEvent) error

func (*Store) ReinstateLicense

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

ReinstateLicense gives a suspended, expired or canceled licence back and returns the status it now has. The licence and its subscription row change in one transaction.

func (*Store) ReleaseLicenseTerms added in v0.1.17

func (s *Store) ReleaseLicenseTerms(ctx context.Context, licenseID string) error

ReleaseLicenseTerms ends a downgrade's hold, once Stripe is known to have made it: the next read sets the terms as Stripe has them.

func (*Store) ReleaseNotification added in v0.1.6

func (s *Store) ReleaseNotification(ctx context.Context, token string) error

ReleaseNotification gives the claim the token names back, for a delivery that failed after the claim; the next run tries again. A token whose claim was taken over meanwhile changes nothing.

func (*Store) ReleaseStaleProcessedEvent added in v0.1.5

func (s *Store) ReleaseStaleProcessedEvent(ctx context.Context, provider, eventID string, maxAge time.Duration) (bool, error)

ReleaseStaleProcessedEvent drops a recorded event older than maxAge. Used for fulfilment claims whose owner died mid-way.

func (*Store) RemoveLicenseAddon

func (s *Store) RemoveLicenseAddon(ctx context.Context, licenseID, addonID string) error

func (*Store) RemoveSeat

func (s *Store) RemoveSeat(ctx context.Context, id string) ([]*model.Activation, bool, error)

RemoveSeat takes the member off the licence. Their key is cleared and the devices and floating sessions it took are removed with it, in one transaction under the licence row lock those take, so none slips in afterwards (see ActivateForKey). It returns the devices removed, and whether the member was removed just now rather than already gone.

func (*Store) RenewRefreshToken added in v0.1.12

func (s *Store) RenewRefreshToken(ctx context.Context, tokenHash, newHash string, expiresAt time.Time) (*RefreshRenewal, error)

RenewRefreshToken exchanges a refresh token for a new one (newHash, expiring at expiresAt) and reads its user, all in one transaction: it either succeeds whole or leaves the presented token as it was. That is what keeps a failure retryable — a token consumed by a renewal whose answer never reached the browser would be presented again later and read as theft. Outcomes:

  • (renewal, nil): issue the session and the new token. On a grace renewal the presented token stays as it was and the new token keeps its expiry instead of expiresAt, so a stolen token replayed inside the window is worth no more than it already was.
  • (renewal with Token, ErrRefreshTokenReused): a rotated token presented after the window. The caller MUST wipe every refresh token of Token.UserID.
  • (nil, sql.ErrNoRows): unknown or expired token; a plain 401.
  • (nil, ErrRefreshUserNotFound): the user is gone; a plain 401.
  • (nil, other error): nothing changed; answer 5xx so the client retries.

The row is taken FOR UPDATE first, so concurrent renewals with one token (several tabs) serialise: one rotates, the rest are grace.

func (*Store) RenewWebhookClaim added in v0.1.20

func (s *Store) RenewWebhookClaim(ctx context.Context, id, token string, lease time.Duration) (bool, error)

RenewWebhookClaim extends the lease on a delivery the caller holds by token, and reports whether it still holds it. False means the lease ran out and another sender has taken the row over (or it is no longer pending): the caller must not send it.

func (*Store) RenewalReminderSentLegacy added in v0.1.12

func (s *Store) RenewalReminderSentLegacy(ctx context.Context, licenseID string, validUntil time.Time) bool

RenewalReminderSentLegacy reports a renewal reminder recorded in the old, dateless form ("renewal_24h") for this renewal date, so the upgrade does not repeat one already sent.

func (*Store) ReplaceArtifactFile added in v0.1.20

func (s *Store) ReplaceArtifactFile(ctx context.Context, id, fileKey string, size int64, sha256, contentType string) (replaced string, err error)

ReplaceArtifactFile is UpdateArtifactFile, and returns the file key the artifact pointed at until this write, read under the release lock, so the caller removes the object this write replaced. One read before the lock may be another finalize's, recorded since: two finalizes at once each removed the key they had read, and the first one's copy was left with nothing pointing at it.

func (*Store) ResetUsageCounter

func (s *Store) ResetUsageCounter(ctx context.Context, licenseID, feature, period, periodKey string) error

func (*Store) RestoreLicenseTerms added in v0.1.17

func (s *Store) RestoreLicenseTerms(ctx context.Context, licenseID string, lowered, prev LicenseTerms) error

RestoreLicenseTerms puts back the terms LowerLicenseTerms replaced, for a change Stripe did not make, unless something has moved them since.

func (*Store) RevertLicenseRenewal added in v0.1.6

func (s *Store) RevertLicenseRenewal(ctx context.Context, r *model.LicenseRenewal) error

RevertLicenseRenewal takes a refunded renewal back out of the license's maintenance period; see RevertLicenseRenewalIn.

func (*Store) RevokeLicense

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

func (*Store) RollbackSeatAccept added in v0.1.1

func (s *Store) RollbackSeatAccept(ctx context.Context, seatID string) ([]*model.Activation, error)

RollbackSeatAccept undoes the AcceptSeatInvite UPDATE when a post-accept policy check fails — e.g. the license is suspended. We clear user_id + accepted_at so the seat row is recoverable (the owner can re-invite the same email and the unique partial index won't bite), but we deliberately leave invite_token_hash + invite_expires_at NULL: the plaintext token has already been processed once, so we don't keep it valid. The customer-facing flow is: re-invite from the portal, which mints a fresh token.

A key made in the moment the seat stood accepted is cleared, and anything it took with it removed, the way RemoveSeat does and under the same licence row lock. It returns the devices removed.

func (*Store) RotateAPIKey added in v0.1.1

func (s *Store) RotateAPIKey(ctx context.Context, id, rawKey, prefix string) error

RotateAPIKey swaps the secret for an existing row. The ID, name, scopes, and product binding are preserved so callers can update their config without re-registering the key. last_used/last_used_ip are reset since the previous physical secret is no longer valid. RotateAPIKey gives a key a new secret; sql.ErrNoRows when the key was deleted meanwhile, so no secret is handed out that opens nothing.

func (*Store) RotateLicenseKey added in v0.1.17

func (s *Store) RotateLicenseKey(ctx context.Context, licenseID string) (string, []*model.Activation, error)

RotateLicenseKey gives the licence a new key. The old one stops working at once, and the devices it activated and the floating sessions it took are removed, since they can no longer check in; the members' own, on their own keys, stay. It returns the new key and the devices removed. Only an admin reissues a key: a licence's key is fixed once issued, as far as its customer is concerned.

func (*Store) RotateMemberKey added in v0.1.17

func (s *Store) RotateMemberKey(ctx context.Context, seatID string) (string, []*model.Activation, error)

RotateMemberKey gives a member a new key of their own, as RotateLicenseKey does the licence's: the old one stops working at once, and the devices it activated and the floating sessions it took are removed; everyone else's keys and devices stay. It runs under the licence row lock that activations decide under, so an activation with the old key cannot land after it. It returns the new key and the devices removed, ErrSeatNotJoined when the seat has no key to replace, and sql.ErrNoRows when there is no such seat.

func (*Store) RotateSigningKey added in v0.1.1

func (s *Store) RotateSigningKey(ctx context.Context, newKey *model.ReleaseSigningKey, note string) error

RotateSigningKey atomically deactivates the current active key (if any) and inserts a new active key. Both happen inside a single transaction + per-product advisory lock so concurrent rotate calls cannot interleave (which under READ COMMITTED would otherwise produce flap-flop where one caller's "active" key gets immediately deactivated by the other).

The newKey must have ProductID set; ID is auto-generated if empty; Active is forced to true.

func (*Store) RunInTx added in v0.1.6

func (s *Store) RunInTx(ctx context.Context, fn func(ctx context.Context, tx bun.Tx) error) error

RunInTx runs fn in one transaction of this store.

func (*Store) RunMigrations

func (s *Store) RunMigrations(dir string) error

RunMigrations executes all .up.sql files from the migrations directory in order. Guarantees:

  • Advisory lock prevents concurrent execution across multiple instances
  • Each migration + its tracking record run in the SAME transaction (atomic)
  • Checksum validation detects tampered migration files
  • Timeout protection prevents indefinite blocking
  • Failed migrations are fully rolled back — no partial state

func (*Store) SeatPaused added in v0.1.17

func (s *Store) SeatPaused(ctx context.Context, seatID string) (bool, error)

SeatPaused reports whether the member of a joined seat is paused (see seatPausedSQL).

func (*Store) SetArtifactTauriSignature added in v0.1.13

func (s *Store) SetArtifactTauriSignature(ctx context.Context, id, signingKeyID, tauriSig string) error

SetArtifactTauriSignature fills in the Tauri signature of an artifact that has none, without touching its Ed25519 signature. Allowed on published releases: it adds a second encoding of the signature the release already ships, made with the same key.

func (*Store) SetFeedURLTTL added in v0.1.6

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

SetFeedURLTTL records how long this install signs the presigned links inside a public feed for (STORAGE_FEED_URL_TTL). The store needs it for the same reason the admin API does: a licence with a finite update period may only be written once the links the public feed handed out have expired, and that is how long they live.

func (*Store) SetLicenseQuantity added in v0.1.17

func (s *Store) SetLicenseQuantity(ctx context.Context, id string, quantity int) (prev int, err error)

SetLicenseQuantity sets how many seats a licence nothing bills holds (an offline sale, say) and returns what it had. The licence row is locked for the decision, so a Stripe subscription linked meanwhile is seen, and refused: its quantity comes from Stripe alone.

func (*Store) SetLicenseUpdatesUntil added in v0.1.6

func (s *Store) SetLicenseUpdatesUntil(ctx context.Context, licenseID string, expected, next *time.Time, supersede bool) (bool, error)

SetLicenseUpdatesUntil is the admin's edit of a license's period end, done under the row lock the renewal path uses. It applies only if the license still has the end the admin saw (expected); a paid renewal committed meanwhile makes it return false so the edit is redone on the current value instead of silently overwriting the extension. supersede closes the renewal ledger (lifetime grant).

func (*Store) SetLicenseValidUntil added in v0.1.12

func (s *Store) SetLicenseValidUntil(ctx context.Context, id string, validUntil *time.Time) (prev, status string, err error)

SetLicenseValidUntil moves a licence's expiry and returns its status before and after. An expired licence given a future (or no) expiry is usable again, so it takes back the status of its plan. Every other status is left alone: suspended, revoked and canceled are somebody's decision about the licence, and a date edit must not undo them.

The row is locked while the decision is made, so a concurrent reinstate, suspend or expiry sweep cannot interleave with it.

func (*Store) SetRoleAtomic added in v0.1.14

func (s *Store) SetRoleAtomic(ctx context.Context, actorID, targetID, role string) (string, bool, error)

SetRoleAtomic changes a team member's role under one transaction lock shared by every team change, and reports the role the target held before, read under that lock, and whether the role changed. It recounts owners inside the lock: a change that takes the owner role from the last owner fails with ErrLastOwner. When actorID is set, the actor must still be an owner under the lock, or it fails with ErrNotOwner; the handler's own check ran before the lock, and a concurrent change may have demoted the actor since. An empty actorID skips that check, for changes the system makes on its own.

Why the lock? Counting owners and then updating in separate statements let two concurrent demotions of two different owners both see count=2 and leave zero owners; inviting an owner as admin skipped the check entirely. Row locks alone only serialize changes to the same target, so one advisory lock covers them all. Comparing the current role inside it also keeps concurrent identical changes from each reporting a change.

func (*Store) SetSetting

func (s *Store) SetSetting(ctx context.Context, key, value string) error

func (*Store) SetSettings

func (s *Store) SetSettings(ctx context.Context, settings map[string]string) error

SetSettings writes all keys in one transaction: callers that store related state (an endpoint id with its secret, a rotation with the previous secret) never leave half of it behind.

func (*Store) SetSubscriptionCancelScheduled added in v0.1.12

func (s *Store) SetSubscriptionCancelScheduled(ctx context.Context, licenseID string, scheduled bool, asOf time.Time) error

SetSubscriptionCancelScheduled records what Stripe says about a licence's subscription — set to end at the period end, or renewing — as read from Stripe after asOf (a StripeReadStamp taken before the read). The reminders read it to tell "renews" from "runs out".

The newest read wins, not the last write: two webhooks for one subscription can overlap, and the one that asked Stripe first may write last. Its answer is then older than the one already recorded and is dropped. The last change in Stripe is always followed by a webhook whose read starts after it, so that read — the newest — sees the final state.

func (*Store) SettleLapsedHold added in v0.1.17

func (s *Store) SettleLapsedHold(ctx context.Context, h LapsedTermHold) error

SettleLapsedHold ends a lapsed hold once a check settled it. A hold placed since is another downgrade's, and stays.

func (*Store) SetupNeeded added in v0.1.14

func (s *Store) SetupNeeded(ctx context.Context, db bun.IDB) (bool, error)

SetupNeeded reports whether this database still waits for its first owner. Setup creates that owner without authentication, so anything showing the install is in use closes it: setup_complete, or an owner, an admin or a product in the database. Counting owners alone left setup open on installs whose admins never became owner (#42). Pass the setup transaction as db to check under its lock.

func (*Store) StripeReadStamp added in v0.1.12

func (s *Store) StripeReadStamp(ctx context.Context) (time.Time, error)

StripeReadStamp reads the database clock for a caller about to ask Stripe for a subscription. Whatever Stripe answers is at least as new as this moment, so the stamp orders the answers: see SetSubscriptionCancelScheduled and UpdateLicenseFromSubscriptionRead. The database clock, not this process's, so instances whose clocks drift still agree on the order.

func (*Store) SuspendLicense

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

func (*Store) SyncAdminEmails

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

SyncAdminEmails promotes users whose emails are in the ADMIN_EMAILS list to admin role, and ensures at least one owner exists. Called on startup for backward compatibility.

func (*Store) SyncSubscriptionStatuses

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

SyncSubscriptionStatuses syncs subscription.status with its license.status for consistency.

func (*Store) TakeAllSnapshots

func (s *Store) TakeAllSnapshots(ctx context.Context, date time.Time) error

func (*Store) TakeMissingSnapshots added in v0.1.20

func (s *Store) TakeMissingSnapshots(ctx context.Context, date time.Time) error

TakeMissingSnapshots takes the snapshot of date for every product that has none for it yet, and leaves the ones taken alone. Run at start and every hour, it gives each day its snapshot however often the server restarts: a wait of 24 hours from start, restarted by every restart, never came round on a server restarted more than once a day.

func (*Store) TakeSnapshot

func (s *Store) TakeSnapshot(ctx context.Context, productID string, date time.Time) error

func (*Store) TouchAPIKey added in v0.1.1

func (s *Store) TouchAPIKey(id, ip string)

TouchAPIKey records the most recent successful auth for a key. Fire-and-forget: failure must not block the request. Called from the auth middleware AFTER the request context has the client IP, because the lookup path (FindProductByAPIKey) doesn't see it.

func (*Store) TouchActivation

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

func (*Store) TryMeteredSyncLock added in v0.1.20

func (s *Store) TryMeteredSyncLock(ctx context.Context) (release func(), ok bool, err error)

TryMeteredSyncLock takes the metered sync lock if no other pass holds it, on any replica. Every replica runs the sync loop, and the rows a pass reads are not claimed: two passes at once pushed each row twice and counted two attempts for it, so a short Stripe outage spent a row's retries at twice the rate. ok is false when another pass is running; release must be called once the pass is done otherwise.

The lock is held by a connection of its own, for the pass, and goes with it if the process dies.

func (*Store) TryRecordNotification added in v0.1.19

func (s *Store) TryRecordNotification(ctx context.Context, licenseID, tag string) (bool, error)

TryRecordNotification records tag for a licence and reports whether this call recorded it: of several concurrent callers exactly one goes on to send.

func (*Store) TryRecordPastDueNotification added in v0.1.12

func (s *Store) TryRecordPastDueNotification(ctx context.Context, licenseID, subscriptionID string, pastDueAt time.Time, tag string) (bool, error)

TryRecordPastDueNotification records tag for a licence only while it is still past_due on subscriptionID, in the episode that began at pastDueAt (to the second), and reports whether this call recorded it: of several concurrent callers exactly one goes on to send, and none does once the licence has recovered, been unlinked or begun another episode. A database error is returned, for the caller to retry: a guess either way would send a duplicate or miss the notice.

func (*Store) TryRecordProcessedEvent

func (s *Store) TryRecordProcessedEvent(ctx context.Context, provider, eventID string) bool

func (*Store) UnyankRelease added in v0.1.1

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

UnyankRelease undoes a yank: yanked → published. UnyankRelease puts a yanked release back on sale, while the product's type has releases (ErrProductNoReleases otherwise): the type may change once every release is yanked, and one restored on a type without releases would be unreachable.

func (*Store) UpdateAddon

func (s *Store) UpdateAddon(ctx context.Context, a *model.Addon) error

func (*Store) UpdateArtifactFile added in v0.1.1

func (s *Store) UpdateArtifactFile(ctx context.Context, id, fileKey string, size int64, sha256, contentType string) error

UpdateArtifactFile sets the artifact upload metadata after a successful PUT to storage. Allowed only when the parent release is DRAFT — once published, the (sha256, sig) become contracts with already-distributed clients.

Wrapped in a tx with `SELECT … FOR UPDATE` on the parent release so a concurrent PublishRelease can't observe the artifact's new file_key while we're mid-rewrite, AND so we don't clear the ed25519_sig between a sign-loop's UpdateArtifactSignature and the corresponding publish commit. Without this, finalizing an upload during the small sign-then-publish window would race the publisher into shipping an empty-sig artifact.

func (*Store) UpdateArtifactSignature added in v0.1.1

func (s *Store) UpdateArtifactSignature(ctx context.Context, id, sig, signingKeyID, tauriSig string) error

UpdateArtifactSignature writes a signature onto an artifact whose release is still a draft. A shipped release's signatures are immutable: a publish that lost the race to another publish (or ran after a rotation) must not rewrite what clients already verify.

Same shape as DeleteArtifact: FOR UPDATE on the parent release so this waits behind an in-flight PublishRelease and then sees its committed status, instead of racing it on an MVCC snapshot.

func (*Store) UpdateArtifactSignatureOf added in v0.1.20

func (s *Store) UpdateArtifactSignatureOf(ctx context.Context, id, fileKey, sha256, sig, signingKeyID, tauriSig string) error

UpdateArtifactSignatureOf is UpdateArtifactSignature for the file the signer read: written only while the artifact still points at fileKey with that sha256, ErrArtifactReplaced otherwise. A finalize landing while a publish signed the artifact would otherwise be given the signature of the file it replaced, and clients would reject the release. An empty fileKey writes whatever the artifact points at.

func (*Store) UpdateEntitlement

func (s *Store) UpdateEntitlement(ctx context.Context, e *model.Entitlement) error

func (*Store) UpdateLicense

func (s *Store) UpdateLicense(ctx context.Context, l *model.License, cols ...string) error

func (*Store) UpdateLicenseAndSubscription

func (s *Store) UpdateLicenseAndSubscription(ctx context.Context, lic *model.License, cols ...string) error

UpdateLicenseAndSubscription writes the licence and mirrors its status onto the subscription row, both in one transaction.

func (*Store) UpdateLicenseAndSupersedeRenewals added in v0.1.6

func (s *Store) UpdateLicenseAndSupersedeRenewals(ctx context.Context, l *model.License, cols ...string) error

UpdateLicenseAndSupersedeRenewals writes the given license columns and closes the renewal ledger in one transaction. Used when the maintenance period is reset outside the ledger — the license leaves or re-enters a perpetual plan, or is granted updates for life — so refunds of earlier renewals cannot reach the new period.

func (*Store) UpdateLicenseEmailByStripeCustomer

func (s *Store) UpdateLicenseEmailByStripeCustomer(ctx context.Context, customerID, email string) error

UpdateLicenseEmailByStripeCustomer updates email on all licenses for a Stripe customer.

func (*Store) UpdateLicenseFromSubscription added in v0.1.7

func (s *Store) UpdateLicenseFromSubscription(ctx context.Context, lic *model.License, cols ...string) error

UpdateLicenseFromSubscription is the same write for a caller that found this licence *by* its subscription id — every Stripe subscription webhook does.

It applies only while the licence still carries that id. Between the read and this write an admin may have unlinked it — a deliberate act taken only after Stripe confirmed the subscription was over — and an unconditional write by primary key would undo it, restoring a status and a period nothing in Stripe backs any more. Then it answers ErrSubscriptionUnlinked and writes nothing.

func (*Store) UpdateLicenseFromSubscriptionEnded added in v0.1.12

func (s *Store) UpdateLicenseFromSubscriptionEnded(ctx context.Context, lic *model.License, asOf time.Time, cols ...string) error

UpdateLicenseFromSubscriptionEnded is the write for a subscription that is over (customer.subscription.deleted). It always applies — nothing in Stripe can bring the subscription back, so a newer read can only agree — and it moves the licence's read stamp up to asOf, so a read taken before the deletion (one that may still have seen "active") is refused afterwards. The stamp never moves back.

func (*Store) UpdateLicenseFromSubscriptionRead added in v0.1.12

func (s *Store) UpdateLicenseFromSubscriptionRead(ctx context.Context, lic *model.License, asOf time.Time, cols ...string) error

UpdateLicenseFromSubscriptionRead is UpdateLicenseFromSubscription for a write made from Stripe's answer to a read taken after asOf (a StripeReadStamp). Two webhooks for one subscription can overlap and the one that asked Stripe first may write last; the newest read wins, in the same UPDATE that makes the write, and an older one gets ErrStaleSubscriptionRead. The last change in Stripe is followed by a webhook whose read starts after it, so the licence ends on the final state.

func (*Store) UpdateLicenseFromSubscriptionReadTerms added in v0.1.17

func (s *Store) UpdateLicenseFromSubscriptionReadTerms(ctx context.Context, lic *model.License, asOf time.Time, cols ...string) (before LicenseTerms, written bool, err error)

UpdateLicenseFromSubscriptionReadTerms is UpdateLicenseFromSubscriptionRead for a write that may move the licence's plan or quantity. It returns them as they stood under the row lock just before the write, so the caller announces a change only when this write is the one that made it: two deliveries of the same change both find the old values in their own copy of the licence, and only the first finds them here.

A licence an operator suspended refuses the write (ErrLicenseRestricted) but still takes the plan and seats Stripe bills, so it does not come back from the suspension with seats nobody pays for. written says the terms were written, either way: not while a downgrade holds them (see LowerLicenseTerms) and this read still shows the old ones.

func (*Store) UpdateLicenseUser added in v0.1.1

func (s *Store) UpdateLicenseUser(ctx context.Context, licenseID, userID string) error

func (*Store) UpdatePlan

func (s *Store) UpdatePlan(ctx context.Context, p *model.Plan, cols ...string) error

func (*Store) UpdateProduct

func (s *Store) UpdateProduct(ctx context.Context, p *model.Product) error

func (*Store) UpdateReleaseNotes added in v0.1.1

func (s *Store) UpdateReleaseNotes(ctx context.Context, id, name, notes string) error

UpdateReleaseNotes updates user-facing display fields. Allowed in any state — typos in published notes happen.

func (*Store) UpdateSubscription

func (s *Store) UpdateSubscription(ctx context.Context, sub *model.Subscription, cols ...string) error

func (*Store) UpdateUserProfile

func (s *Store) UpdateUserProfile(ctx context.Context, userID, name string) error

UpdateUserProfile updates a user's display name. Only the name can be changed by the user — email and role are controlled by the system.

func (*Store) UpdateWebhook

func (s *Store) UpdateWebhook(ctx context.Context, w *model.Webhook, columns ...string) error

UpdateWebhook writes only the named columns of w, and reads the row back into w as it now stands. Writing the whole row put back what the caller had read for the rest, so two edits on two replicas (a new URL on one, active=false on the other) kept only one: a receiver switched off came back on. sql.ErrNoRows when the webhook is gone.

func (*Store) UpsertOAuth

func (s *Store) UpsertOAuth(ctx context.Context, a *model.OAuthAccount) error

func (*Store) UpsertUser

func (s *Store) UpsertUser(ctx context.Context, u *model.User) error

func (*Store) WithAdvisoryLock added in v0.1.5

func (s *Store) WithAdvisoryLock(ctx context.Context, key int64, fn func(ctx context.Context) error) error

WithAdvisoryLock runs fn while holding a session-level advisory lock on a pinned connection, serialising the section across every replica that shares the database. The lock is released when fn returns, or by Postgres if the process dies.

func (*Store) WithXactLock added in v0.1.6

func (s *Store) WithXactLock(ctx context.Context, key int64, fn func(ctx context.Context, tx bun.Tx) error) error

WithXactLock runs fn inside one transaction that holds a transaction-scoped advisory lock on key. Unlike WithAdvisoryLock it pins no extra connection: the lock lives on the transaction's own connection and every statement in fn runs on it, so a burst of callers cannot hold the pool hostage while waiting for a second connection to do the work. The lock goes with the commit or rollback.

func (*Store) YankRelease added in v0.1.1

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

YankRelease transitions a published release → yanked with a reason. All artifacts are implicitly hidden from feeds (they're queried via the release status, not their own state).

type StripeCancelStateTarget added in v0.1.12

type StripeCancelStateTarget struct {
	LicenseID      string `bun:"license_id"`
	SubscriptionID string `bun:"subscription_id"`
	// SortKey is its place in the walk (valid_until, 'infinity' when
	// unset, as text), so a walk resumes after it even if the licence's
	// own date has moved since.
	SortKey string `bun:"sort_key"`
}

StripeCancelStateTarget is a Stripe subscription whose cancel state has not been recorded yet (see FindStripeCancelStatesToSync).

type TopUser

type TopUser struct {
	Email           string `json:"email"`
	UserID          string `json:"user_id"`
	LicenseCount    int    `json:"license_count"`
	ActiveCount     int    `json:"active_count"`
	TotalUsage      int64  `json:"total_usage"`
	ActivationCount int    `json:"activation_count"`
}

type TrendPoint

type TrendPoint struct {
	Date  string `json:"date"`
	Count int    `json:"count"`
}

type TrialFallbackInUseError added in v0.1.17

type TrialFallbackInUseError struct{ Plans []string }

TrialFallbackInUseError: trial plans name the plan as their fallback, so it cannot stop being one they can move to, nor go.

func (*TrialFallbackInUseError) Error added in v0.1.17

func (e *TrialFallbackInUseError) Error() string

type TrialFallbackRefusedError added in v0.1.17

type TrialFallbackRefusedError struct{ Msg string }

TrialFallbackRefusedError: the plan named as a trial's fallback cannot be one, as it reads under its lock; the message says why, worded as the admin API's own check words it.

func (*TrialFallbackRefusedError) Error added in v0.1.17

func (e *TrialFallbackRefusedError) Error() string

type TrialMove added in v0.1.17

type TrialMove struct {
	// Moved: the licence is now on To, and From is the trial plan it
	// left.
	Moved bool
	// Expire: the licence still qualifies for the trial sweep, but its
	// plan names no fallback, or one that no longer qualifies (Refusal
	// says why, for the log), or Stripe bills it. It was expired here,
	// in the same transaction and under the same locks that decided it,
	// as it was before fallbacks existed; the caller announces it.
	Expire  bool
	Refusal string
	// FallbackPlanID is the plan the trial plan names, if any.
	FallbackPlanID string
	License        *model.License
	From, To       *model.Plan
}

TrialMove says what MoveEndedTrialToFallback did.

type UpgradeRevert added in v0.1.16

type UpgradeRevert struct {
	// Reverted reports that the licence is back as the upgrade found it.
	Reverted bool
	// Unlinked: the licence is no longer billed by what the upgrade
	// linked (an operator unlinked it, or it was deleted). The upgrade
	// is closed and the licence left alone, since writing it would undo
	// what the operator did.
	Unlinked bool
	// FreePlanGone: the plan the licence came from was deleted, so there
	// is nothing to put it back on. The upgrade is closed and the caller
	// handles the licence as it would have before upgrades existed.
	FreePlanGone bool
	License      *model.License
	// Plan is the plan the licence is back on; PrevPlanID the one it
	// left, which is not the upgrade's target if the customer changed
	// plan since.
	Plan       *model.Plan
	PrevPlanID string
	// PrevQuantity is the seats the licence had on the upgrade's plan.
	PrevQuantity int
}

UpgradeRevert says what RevertLicenseUpgradeIn did.

func RevertLicenseUpgradeIn added in v0.1.16

func RevertLicenseUpgradeIn(ctx context.Context, tx bun.IDB, u *model.LicenseUpgrade, reason string) (UpgradeRevert, error)

RevertLicenseUpgradeIn puts the licence an applied upgrade changed back the way the upgrade found it: its plan, status, dates, payment provider and Stripe customer, with the Stripe links removed. The key and the activations were never touched. The caller has locked the upgrade row; this locks the licence.

A revoked licence, or one an operator suspended, keeps that status: only its plan and billing go back. Whatever the outcome, the upgrade is closed (see UpgradeRevert), so a retry finds nothing left to do.

type UserDetail

type UserDetail struct {
	User     *model.User      `json:"user"`
	Licenses []*model.License `json:"licenses"`
	// Memberships are the seats the customer holds on other people's
	// licences, each with its licence: where they are a member, not the
	// owner.
	Memberships   []*model.Seat         `json:"memberships"`
	Subscriptions []*model.Subscription `json:"subscriptions"`
	TotalUsage    int64                 `json:"total_usage"`
	ActiveSeats   int                   `json:"active_seats"`
	Activations   int                   `json:"activations"`
	AuditLogs     []*model.AuditLog     `json:"recent_audit_logs"`
}

type WebhookDeliveryFilter added in v0.1.1

type WebhookDeliveryFilter struct {
	WebhookID string
	Status    string // pending | delivered | failed
	Event     string // exact event name, e.g. license.created
	Offset    int
	Limit     int
}

WebhookDeliveryFilter narrows ListWebhookDeliveries. Status / Event are optional — empty values mean "no filter on this dimension". Used by the admin UI to drill into "show me only failed deliveries" without pulling the whole history.

Jump to

Keyboard shortcuts

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