store

package
v0.0.0-...-8f018cb Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2026 License: AGPL-3.0, Apache-2.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ReasonNotRestorable             = "not_restorable"
	ReasonNotDeleted                = "not_deleted"
	ReasonMaxDepthExceeded          = "max_depth_exceeded"
	ReasonSubtreeMaxDepthExceeded   = "subtree_max_depth_exceeded"
	ReasonParentNotLive             = "parent_not_live"
	ReasonDraftCycle                = "draft_cycle"
	ReasonDraftTooDeep              = "draft_too_deep"
	ReasonDraftQuotaExceeded        = "draft_quota_exceeded"
	ReasonSubtreeTotalBytesExceeded = "subtree_total_bytes_exceeded"
	// ReasonPageNotLive marks an autosave whose target is not addressable in the request's space:
	// the page was deleted, snapshotted, or moved out of it, the existing draft belongs to another
	// space, or the page id was never reserved at all (no page row and no draft). The caller maps
	// it to 404 rather than a generic 400 — from the requester's view the page does not exist in
	// that space.
	ReasonPageNotLive = "page_not_live"
)

Reason codes for invariants decided atomically under a row lock (see RestorePage, RestoreSpace, CreatePage). Callers map these to their own error keys.

View Source
const (
	// ReasonConcurrentEdit: the page's EditAt no longer matches the baseline the caller published
	// against — someone else edited the page.
	ReasonConcurrentEdit = "concurrent_edit"
	// ReasonConcurrentAutosave: the draft's version token no longer matches what the caller read —
	// usually a concurrent autosave, but also a bulk write (a page delete reparenting a pending
	// draft, or a move-to-space re-homing it) that bumps the token without changing content.
	ReasonConcurrentAutosave = "concurrent_autosave"
)

Conflict reasons let a caller tell one CAS failure from another without parsing Resource. An ErrConflict with no Reason is an unqualified conflict (e.g. a primary-key collision).

View Source
const MaxPageDescendantsLimit = 5000

MaxPageDescendantsLimit is the maximum number of descendants returned by a subtree fetch.

View Source
const MaxPageDescendantsTotalBytes = 256 * 1024 * 1024

MaxPageDescendantsTotalBytes caps the combined Body+SearchText size of a subtree fetch, independent of row count, so a subtree of large pages still stays within a bounded memory footprint. Sized generously above typical subtree sizes but well below a dangerous multi-gigabyte allocation.

View Source
const MaxPageHierarchyDepth = 50

MaxPageHierarchyDepth limits CTE recursion depth.

View Source
const MaxPageSiblingsLimit = MaxPageDescendantsLimit

MaxPageSiblingsLimit caps a single parent's direct live children so any reposition operation (which renumbers the whole group atomically) stays bounded. Matches MaxPageDescendantsLimit so a full-fan-out subtree still fits the descendant cap.

View Source
const MaxRowsPerQuery = 5000

MaxRowsPerQuery caps unpaginated reads to prevent unbounded result sets. Paginated listings reject a non-positive limit outright rather than falling back to this cap.

Variables

This section is empty.

Functions

func ConflictReason

func ConflictReason(err error) string

ConflictReason returns the Reason of the ErrConflict in err's chain, or "" if err is not an ErrConflict or carries no reason.

func InvalidInputReason

func InvalidInputReason(err error) string

InvalidInputReason returns the Reason of the ErrInvalidInput in err's chain, or "" if err is not an ErrInvalidInput or carries no reason.

func IsErrCircularReference

func IsErrCircularReference(err error) bool

IsErrCircularReference reports whether err is an ErrCircularReference.

func IsErrConflict

func IsErrConflict(err error) bool

IsErrConflict reports whether err is an ErrConflict.

func IsErrInvalidInput

func IsErrInvalidInput(err error) bool

IsErrInvalidInput reports whether err is an ErrInvalidInput.

func IsErrLimitExceeded

func IsErrLimitExceeded(err error) bool

IsErrLimitExceeded reports whether err is an ErrLimitExceeded.

func IsErrNotFound

func IsErrNotFound(err error) bool

IsErrNotFound reports whether err is an ErrNotFound.

Types

type ErrCircularReference

type ErrCircularReference struct {
	PageID       string
	DestParentID string
}

ErrCircularReference is returned when a move would make a page its own ancestor or descendant.

func (*ErrCircularReference) Error

func (e *ErrCircularReference) Error() string

type ErrConflict

type ErrConflict struct {
	Resource string
	Reason   string
}

ErrConflict is returned when a unique constraint is violated or a CAS check fails. Reason, when set, names which CAS failed so a caller can map it to a specific response.

func (*ErrConflict) Error

func (e *ErrConflict) Error() string

type ErrInvalidInput

type ErrInvalidInput struct {
	Entity string
	Field  string
	Value  any
	// Reason optionally carries either the originating AppError.Id (e.g. from a model IsValid
	// check) or one of the short Reason* codes below, enabling callers to surface a specific
	// error key instead of a generic one.
	Reason string
}

ErrInvalidInput is returned when the caller supplies an invalid value.

func (*ErrInvalidInput) Error

func (e *ErrInvalidInput) Error() string

type ErrLimitExceeded

type ErrLimitExceeded struct {
	Resource string
	Limit    int
	// Reason optionally carries one of the short Reason* codes below, so a limit re-checked
	// under lock can communicate the same condition as any earlier pre-check; the app layer
	// maps the code to its own error key. Empty means storeAppError falls back to
	// app.store.too_large.app_error.
	Reason string
}

ErrLimitExceeded is returned when a result set exceeds a hard size limit.

func (*ErrLimitExceeded) Error

func (e *ErrLimitExceeded) Error() string

type ErrNotFound

type ErrNotFound struct {
	EntityName string
	ID         string
}

ErrNotFound is returned when a requested entity does not exist.

func (*ErrNotFound) Error

func (e *ErrNotFound) Error() string

type Store

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

Store holds the database handle used by the Docs plugin.

func New

func New(db *sql.DB, driverName string, log *pluginapi.LogService) (*Store, error)

New creates a Store wrapping the given master DB handle. log may be nil in tests that do not exercise migration warnings.

func (*Store) AutosaveDraft

func (s *Store) AutosaveDraft(draft *model.Draft, parentID *string, fileIDs *mmmodel.StringArray, props *mmmodel.StringInterface) (*model.Draft, bool, error)

AutosaveDraft is UpsertDraft with the autosave-path guards enabled: it refuses to establish a new draft row when the page id has no live page backing it (only CreateSpaceDraft may reserve a page id, so an autosave for an unknown id cannot squat on it), and it rejects an autosave addressed to a different space than an existing draft's stored SpaceId (ReasonPageNotLive) — e.g. a client still saving under a stale space URL after a cross-space move re-homed the draft — preventing cross-space drift. Updating the caller's own existing draft, including a new-page draft whose page is not yet published, is unaffected.

func (*Store) Close

func (s *Store) Close() error

Close releases the database connection. *sql.DB.Close is idempotent.

func (*Store) CreatePage

func (s *Store) CreatePage(page *model.Page, maxDepth int) (_ *model.Page, err error)

CreatePage inserts a new page, assigning it the next sort order among its siblings. maxDepth caps the page's depth in the hierarchy (root pages are depth 1); the caller owns the limit's value, this only enforces it atomically against the locked parent.

func (*Store) CreatePageSubtree

func (s *Store) CreatePageSubtree(pages []*model.Page, maxDepth int) (_ []*model.Page, err error)

CreatePageSubtree inserts a root page plus its descendants atomically in a single transaction, so a failure partway through cannot leave an orphaned partial subtree behind. pages[0] is the root, with SpaceId/ParentId already set to the destination; every entry's Id must already be assigned by the caller, since pages[1:]'s ParentId references an earlier entry's Id in this same slice. pages[1:] must be in pre-order. maxDepth <= 0 disables the depth re-check.

func (*Store) CreateSpace

func (s *Store) CreateSpace(space *model.Space) (*model.Space, error)

CreateSpace inserts a space row, fills in defaults and validates before inserting.

func (*Store) DeleteDraft

func (s *Store) DeleteDraft(userID, pageID string) error

DeleteDraft removes the draft keyed by (userID, pageID), or returns ErrNotFound.

func (*Store) DeleteDraftReparenting

func (s *Store) DeleteDraftReparenting(userID, spaceID, pageID string) (pageWasLive bool, err error)

DeleteDraftReparenting deletes the draft keyed by (userID, spaceID, pageID). When the discarded draft is a new-page draft (no live page yet), its child drafts are first reparented to its own parent so they don't dangle; an edit draft's children still point at the live page and are left untouched. Returns ErrNotFound when no draft exists for (userID, spaceID, pageID). pageWasLive is true when the deleted draft was an edit draft (the page exists as a live page), false for new-page drafts; callers use this to decide whether a presence broadcast is needed.

func (*Store) DeleteDraftVersion

func (s *Store) DeleteDraftVersion(userID, pageID string, expectedUpdateAt int64) (bool, error)

DeleteDraftVersion deletes the draft keyed by (userID, pageID) only if its UpdateAt still equals expectedUpdateAt. It returns true when a row was deleted, and false — without error — when the version no longer matches (a newer autosave exists and must be left intact) or no draft exists. Use it to discard a draft the caller believes it has finished with, without clobbering a concurrent autosave that landed in the meantime.

func (*Store) DeletePage

func (s *Store) DeletePage(pageID, spaceID, userID string) (_ string, err error)

DeletePage soft-deletes a live page and promotes its live children to the page's own parent as a contiguous block in the page's slot so their relative order survives. It rejects snapshots (OriginalId != ""). The invariant that no live page sits under a deleted parent holds even under concurrent CreatePage calls. Returns the deleted page's backing ChannelId (from the locked row) so the caller can notify its channel.

func (*Store) DeleteSpace

func (s *Store) DeleteSpace(spaceID string) (err error)

DeleteSpace soft-deletes a space and cascades to its live pages in the same transaction. Pages are scoped by SpaceId so a reused ChannelId is not affected.

func (*Store) GetDraft

func (s *Store) GetDraft(userID, pageID string) (*model.Draft, error)

GetDraft returns the draft keyed by (userID, pageID), or ErrNotFound. It is gated the same way as GetDraftsForSpace: the draft is returned only when its space is live and its page is either not yet created (a new-page draft) or a live page in the same space.

func (*Store) GetDraftSpaceID

func (s *Store) GetDraftSpaceID(userID, pageID string) (string, error)

GetDraftSpaceID returns the SpaceId of the draft keyed by (userID, pageID) without fetching the row, gated by the same liveness filter as GetDraft — for callers that need only the space (or bare existence) and must not haul the draft body. Returns ErrNotFound when no live draft exists.

func (*Store) GetDraftsForSpace

func (s *Store) GetDraftsForSpace(userID, spaceID string, offset, limit int) ([]*model.DraftSummary, error)

GetDraftsForSpace returns the user's drafts in the given space, most-recently-updated first, with Body and Props omitted (metadata only — see draftMetaColumns). Results pass applyDraftLivenessFilter, so a soft-deleted space lists no drafts (they survive the soft-delete and reappear after RestoreSpace) and a draft whose page is soft-deleted is excluded from results. Results are paginated via offset/limit (see applyLimitOffset); callers must pass a positive limit.

func (*Store) GetPage

func (s *Store) GetPage(pageID string, includeDeleted bool) (*model.Page, error)

GetPage fetches a live (or optionally deleted) page by ID.

func (*Store) GetPageActiveEditors

func (s *Store) GetPageActiveEditors(pageID, spaceID string, minActiveAt int64) ([]string, error)

GetPageActiveEditors returns the user IDs who last saved a draft on the page in spaceID at or after minActiveAt — users recently editing it. Presence is derived from the shared DOCS_Draft table so it is consistent across all cluster nodes.

The result is scoped to spaceID: a draft is keyed by (UserId, PageId) without a space, and an unpublished new-page draft has no page row to bound it, so two users in different spaces holding a draft at the same reserved page id would otherwise appear in each other's presence set. Scoping on the draft's own SpaceId keeps a broadcast to one space from disclosing the other space's editor.

The filter is LastActiveAt, not UpdateAt (see model.Draft): the maintenance writes that bump UpdateAt without the user touching the draft — a page delete reparenting its pending child drafts, a move-to-space re-homing them — would otherwise report the draft's owner as editing a page they never opened.

func (*Store) GetPageChildren

func (s *Store) GetPageChildren(pageID, spaceID string, offset, limit int) ([]*model.PageSummary, error)

GetPageChildren fetches metadata summaries for direct live children of a page, ordered by the caller-maintained SortOrder (ascending), with CreateAt then Id as stable tie-breakers. spaceID scopes the query: children in any other space never match. The parent's own liveness is not re-checked here — deletes reparent or cascade to children in the same transaction, so no live row can point at a deleted parent. limit must be > 0.

func (*Store) GetPageForDuplicate

func (s *Store) GetPageForDuplicate(pageID, sourceSpaceID string, includeChildren bool) (_ *model.Page, _ []*model.Page, err error)

GetPageForDuplicate fetches the source page, scoped to sourceSpaceID, plus its live descendants when includeChildren is set, as a consistent snapshot — concurrent subtree moves cannot interleave with the descendant reads.

func (*Store) GetPageParentInSpace

func (s *Store) GetPageParentInSpace(pageID, spaceID string) (string, bool, error)

GetPageParentInSpace returns the ParentId of the live page pageID in spaceID, without fetching the row — the move paths only need the current parent for their parent-change probes, so they avoid hauling the page body. The bool reports whether the page exists in the space.

func (*Store) GetSpace

func (s *Store) GetSpace(spaceID string, includeDeleted bool) (*model.Space, error)

GetSpace returns the space with the given ID, returning ErrNotFound if not found. When includeDeleted is false, soft-deleted spaces are also treated as not found.

func (*Store) GetSpacePages

func (s *Store) GetSpacePages(spaceID string, offset, limit int) ([]*model.PageSummary, error)

GetSpacePages fetches metadata summaries for a paginated set of live pages in a space, ordered by CreateAt DESC with Id DESC as a stable tie-breaker. Filters on SpaceId (not ChannelId) so pages from a prior soft-deleted space that shared the channel are never returned. limit must be > 0.

func (*Store) GetSpacesForTeam

func (s *Store) GetSpacesForTeam(teamID, userID string, offset, limit int) ([]*model.Space, error)

GetSpacesForTeam returns live spaces for the given team visible to userID, ordered by SortOrder ascending with CreateAt then Id as stable tie-breakers. Visibility is membership of the space's backing channel, resolved by a read-only join against core's ChannelMembers table: space ("S") channels are excluded from the generic channel-listing plugin APIs, so the caller cannot supply its visible-channel set. There is deliberately no unfiltered variant, so a listing can never bypass the membership filter. limit must be > 0.

func (*Store) MovePage

func (s *Store) MovePage(pageID, spaceID string, newParentID *string, newIndex *int64, expectedUpdateAt int64, force bool, maxDepth int) (_ *model.Page, priorParentID string, moved bool, err error)

MovePage reparents a live page under newParentID (nil = leave the parent unchanged) within the same space and positions it in the destination sibling group: newIndex nil appends it to the end; a non-nil newIndex places it at that zero-based position (clamped to the group) by renumbering the group's SortOrders. Returns the updated page plus the parent it had under the row lock, so callers publishing an old-parent reference use the value the move actually displaced rather than a pre-lock read a concurrent (or forced) move may have outdated. Optimistic-locked on expectedUpdateAt unless force. A non-root destination parent must be a live page in the same space, and must not be the page itself or one of its descendants (cycle guard, re-checked under lock).

The CAS baseline guards the page's own identity, parent, and content: a sibling whose SortOrder merely shifts because some other page moved into or out of its group deliberately keeps its UpdateAt (see reindexSiblingGroup and DeletePage's child promotion), so such a shift does not invalidate that sibling's baseline.

func (*Store) MovePageToSpace

func (s *Store) MovePageToSpace(pageID, sourceSpaceID, targetSpaceID, moverUserID string, parentPageID *string, expectedUpdateAt int64, force bool, maxDepth int) (_ *model.Page, priorParentID string, err error)

MovePageToSpace moves a page and its entire live subtree to a different space in one transaction: every live node's SpaceId/ChannelId is rewritten and the moved root is reparented (parentPageID nil/"" = target root) and appended to the destination sibling group. Alongside the moved root it returns the parent the root had under the row lock, for callers publishing an old-parent reference (see MovePage). The target's ChannelId is derived from its locked row, never trusted from the caller, so it always matches the target space's single backing channel. Target space, parent, depth, and cycle-safety are all re-validated under lock, so the move is safe regardless of concurrent operations between the caller's pre-checks and this call. Cross-owner resources (page-comment Posts, FileInfo) are not re-homed here.

func (*Store) PageExistsInSpace

func (s *Store) PageExistsInSpace(pageID, spaceID string) (bool, error)

PageExistsInSpace reports whether pageID is a live page in spaceID, without fetching the row — callers that only need to 404 on a missing page avoid hauling the page body.

func (*Store) PublishNewPageDraft

func (s *Store) PublishNewPageDraft(page *model.Page, userID, spaceID string, maxDepth int, draftUpdateAt int64) (_ *model.Page, err error)

PublishNewPageDraft atomically inserts page and deletes the user's draft for it in a single transaction. A PK collision returns ErrConflict so the caller can adopt the concurrent winner without a half-state; the whole transaction is rolled back.

draftUpdateAt pins the draft delete to the version the caller read (see deletePublishedDraftTx for how a version mismatch rolls the whole publish back).

func (*Store) PublishPageEditDraft

func (s *Store) PublishPageEditDraft(pageID, spaceID string, patch *model.PagePatch, baseEditAt int64, force bool, userID string, draftUpdateAt int64) (_ *model.Page, err error)

PublishPageEditDraft atomically applies patch to the live page (pageID, spaceID) and deletes the user's draft for it in a single transaction, via the shared applyPagePatchTx (the same row-lock, EditAt CAS, and merge invariants UpdatePage applies). baseEditAt is the optimistic-lock baseline the caller last saw; a mismatch returns ErrConflict and rolls the whole transaction back. force skips the CAS, but the patch still merges into the current row, so fields it leaves untouched keep any concurrent edit. userID records the editor.

draftUpdateAt pins the draft delete to the version the caller read (see deletePublishedDraftTx for how a version mismatch rolls the whole publish back).

func (*Store) RestorePage

func (s *Store) RestorePage(pageID, spaceID, userID string, maxDepth int) (_ *model.Page, err error)

RestorePage un-deletes a soft-deleted page and returns the restored page. Promoted children are NOT pulled back. Restore never fails on account of a deleted or now-too-deep original parent (see the fallback inside). Only a soft-deleted original page (OriginalId == "", DeleteAt > 0) in a live space is restorable. The restored page comes from the transaction's own locked read, so a caller never needs a second read that could fail after the commit.

func (*Store) RestoreSpace

func (s *Store) RestoreSpace(spaceID string) (err error)

RestoreSpace un-deletes a soft-deleted space and the pages that DeleteSpace cascaded, matched by the shared DeleteAt stamp. Pages deleted individually before the space, and version snapshots, stay deleted. Returns ErrNotFound when the space ID does not exist, ErrInvalidInput when the space exists but is already live (not deleted), and ErrConflict when another live space now owns the same backing channel.

func (*Store) RunMigrations

func (s *Store) RunMigrations() error

RunMigrations applies all pending morph migrations. Concurrent runs across an HA cluster are serialized internally by a distributed DB-table lock; no external cluster mutex is required.

func (*Store) UpdatePage

func (s *Store) UpdatePage(pageID, spaceID string, patch *model.PagePatch, baseEditAt int64, force bool, lastModifiedBy string) (_ *model.Page, err error)

UpdatePage applies patch to a live page. baseEditAt is the EditAt the caller last saw. When force is false it compare-and-swaps on EditAt, returning ErrConflict if a concurrent writer has advanced it. When force is true the CAS is skipped, but the patch is still merged into the current row, so fields the patch leaves untouched keep any concurrent edit rather than being clobbered by a stale snapshot. lastModifiedBy records the editor.

func (*Store) UpdateSpace

func (s *Store) UpdateSpace(spaceID string, patch *model.SpacePatch, expectedUpdateAt int64, force bool) (_ *model.Space, err error)

UpdateSpace applies patch to a live space's mutable fields (Title, Description, Icon, Props). The patch is merged into the row read under lock, so fields the patch leaves nil keep any concurrent writer's value rather than being clobbered by the caller's stale snapshot. expectedUpdateAt is the optimistic-lock baseline (first-one-wins): a mismatch returns ErrConflict. Passing force skips the check (last-write-wins), but the merge into the locked row still applies.

func (*Store) UpsertDraft

func (s *Store) UpsertDraft(draft *model.Draft, parentID *string, fileIDs *mmmodel.StringArray, props *mmmodel.StringInterface) (*model.Draft, bool, error)

UpsertDraft creates or replaces the draft keyed by (UserId, PageId). It fills in defaults and rejects an invalid draft itself, so the caller need not prepare or validate it beforehand.

An autosave may carry only the fields the editor changed, so on the update path an empty Title or Body means "not sent", not "cleared", and the stored value is kept (a cleared document is EmptyTipTapJSON, not ""). ParentId, FileIds, and Props do not follow this empty-means-not-sent rule: they use explicit pointer intent (see the parentID/fileIDs/props paragraphs below), where a nil pointer — not an empty value — means "not sent". CreateAt keeps the existing row's original value. UpdateAt is bumped strictly monotonically (GREATEST(incoming, stored+1)), so it is a collision-free version token: publish CAS-deletes the draft on this value, and two saves within the same millisecond can no longer share it. All of this happens inside the single upsert statement, so two concurrent autosaves cannot lose a field by merging against a stale read. The stored row is returned.

The draft's space must be live, and the PageId must belong to the draft's space.

parentID encodes the write intent for the ParentId column: nil means "omitted — preserve the existing stored parent", a pointer to "" means "clear to root", and a pointer to a valid ID means "set to that ID". The draft struct's own ParentId field is not used on the write path.

fileIDs encodes the write intent for the FileIds column: nil means "omitted — preserve the existing stored value", a pointer to an empty slice means "clear to no attachments", and a pointer to a non-empty slice means "replace with these IDs". This mirrors parentID's preserve/clear/set semantics.

props encodes the write intent for the Props column: nil means "omitted — preserve the existing stored map", and a non-nil pointer replaces the whole map with the pointed-to value (an empty map clears all keys). This is a whole-value replace, not a key-wise merge, mirroring parentID/fileIDs.

The pointed-to fileIDs and props values are bounded by model.ValidateDraftWriteIntent here, since the struct's own fields — the only ones IsValid checks — are not what gets written.

func (*Store) WithSpaceMembershipLock

func (s *Store) WithSpaceMembershipLock(spaceID string, fn func() error) error

WithSpaceMembershipLock runs fn while holding spaceID's membership advisory lock, serializing membership mutations for one space across processes. Guards that span multiple non-database calls — read the member list, then mutate it — are atomic with respect to each other only under this lock. The lock is session-scoped on a dedicated pooled connection, with no open transaction: fn does no database work of its own, so wrapping it in a transaction would only expose the guard to idle-in-transaction timeouts. The connection is still intentionally held for fn's whole duration — cross-process serialization of a read-modify-write that spans non-database calls has no cheaper primitive — so fn must stay short. fn's error is returned unchanged. When the lock cannot be acquired within spaceMembershipLockAcquireTimeout, ErrConflict is returned so the caller can surface a retryable conflict.

Jump to

Keyboard shortcuts

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