Documentation
¶
Overview ¶
Package anysyncsdk is the top-level entrypoint: Open/Close, Config, and the public type aliases that middleware uses across packages.
The SDK is consumed in-process by a middleware layer (see docs/common-context.md). There are exactly three public import paths:
- github.com/anyproto/any-sync-sdk — Open, Close, Config
- github.com/anyproto/any-sync-sdk/auth — AuthProvider + mnemonic helper
- github.com/anyproto/any-sync-sdk/space — the whole caller surface: Space, SpaceService, VersionId, Query, Subscription, ModifyBatch, ACL, Members, TypesAPI, PropertiesAPI, SyncStatus
Everything else lives under internal/ and is not importable from outside the module. See docs/ for the grooming notes behind this layout.
Index ¶
- type AccountAPI
- type SDK
- func (s *SDK) Account() AccountAPI
- func (s *SDK) BootstrapDone() <-chan struct{}
- func (s *SDK) CRDTVersion() space.CRDTVersionState
- func (s *SDK) Close() error
- func (s *SDK) FileCacheSize(ctx context.Context) (int64, error)
- func (s *SDK) FreeUpFileCache(ctx context.Context, bytes int64) (freed int64, err error)
- func (s *SDK) Identities() space.IdentitiesAPI
- func (s *SDK) LocalDiscoveryEnabled() bool
- func (s *SDK) P2PStatus() p2p.Status
- func (s *SDK) PeerId() string
- func (s *SDK) PoolInternal() pool.Pool
- func (s *SDK) PubSub() space.PubSubAPI
- func (s *SDK) Push() space.PushAPI
- func (s *SDK) SetLocalDiscoveryEnabled(enabled bool)
- func (s *SDK) Spaces() space.Service
- func (s *SDK) Store() anystore.DB
- func (s *SDK) SweepFileCache(ctx context.Context) error
- func (s *SDK) TechSpaceId() string
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AccountAPI ¶
type AccountAPI interface {
// Id returns the account's identity string (StrKey-encoded).
Id() string
// Metadata returns the locally-stored profile (the source-of-truth
// copy that's also pushed to identityRepo on UpdateMetadata).
// Reading from the tech-space is deterministic — no coordinator
// round-trip, no 60-second watcher tick — so callers that just want
// to read back what they wrote (e.g. a settings UI rendering after a
// page reload) don't depend on identityRepo being reachable.
//
// `present` is false when no profile has been written yet on this
// device (fresh wallet). The same `present` and zero-value distinction
// the SDK exposes via tsp.GetProfile.
Metadata(ctx context.Context) (meta space.AccountMetadata, present bool, err error)
// UpdateMetadata updates the account's public metadata
// (identityRepo-backed). Applies across all spaces.
UpdateMetadata(ctx context.Context, meta space.AccountMetadata) error
}
AccountAPI exposes account-level operations outside any space.
type SDK ¶
type SDK struct {
// contains filtered or unexported fields
}
SDK is the top-level handle held by middleware for the lifetime of use. Constructed by Open; torn down by Close.
func Open ¶
Open brings up the SDK: initializes auth, opens storage, boots any-sync, derives the tech space, and returns a ready handle. Open is serial local I/O with no synchronous network dependency.
Contract: when Open returns, local reads are safe — Spaces().List, queries against loaded spaces, Create/Get/Modify all work. The account-facing boot work (eager space loading, offline catch-up replay, profile republish, read-state reconcile) runs on ONE SDK-owned background goroutine, strictly serial, started here and cancelled+joined by Close; BootstrapDone exposes its completion. Until a space's turn comes, queries against it serve the pre-offline state (the per-object lazy ColdRestore still covers direct Gets).
Storage layout:
<DataDir>/anysync/<spaceId>.db — any-sync per-space state (any-store v1) <DataDir>/sdk.db — SDK CRDT collections (any-store v2, shared)
any-sync uses v1 internally for its tree storage; the SDK uses v2 for everything it owns (CRDT controller collections, _meta watermark, type registry, _detached parked changes, per-space objects values). The two coexist via the /v2 module path.
func (*SDK) BootstrapDone ¶
func (s *SDK) BootstrapDone() <-chan struct{}
BootstrapDone returns a channel closed once the background boot pass has finished (or immediately for a headless Open). "Done" means no longer running — it also closes when Close cancels an in-flight pass. Local reads (Spaces().List, queries against loaded spaces) never need to wait on it; select on it when you need full offline catch-up — every space loaded and replayed up to what the sync nodes hold. Until a space's turn comes, queries against it serve the pre-offline state (the per-object lazy ColdRestore still covers direct Gets).
func (*SDK) CRDTVersion ¶
func (s *SDK) CRDTVersion() space.CRDTVersionState
CRDTVersion reports the account's CRDT version state: the version this SDK supports, the highest one recorded on the tech space, and whether the account is read-only because the recorded one is newer (space.CRDTVersion). A newer mark arriving through sync flips Newer at runtime; every synced write then fails with space.ErrCRDTVersionNewer until the SDK is upgraded.
func (*SDK) Close ¶
Close tears down the SDK: joins the bootstrap pass, snapshots per-space catch-up watermarks, stops the files queue, closes loaded spaces, the tech space, the SDK DB, and finally the any-sync app.
func (*SDK) FileCacheSize ¶
FileCacheSize returns the local bytes currently held by file content across all spaces (complete + partial copies; inline files hold no cache bytes).
func (*SDK) FreeUpFileCache ¶
FreeUpFileCache reclaims local file bytes until at least `bytes` are freed, least-recently-used first, dropping only content that is safe to drop (backed up on the network — a later Open refetches — or no longer referenced by any file). Returns the bytes actually freed, which is less than requested when nothing else is safely evictable.
func (*SDK) Identities ¶
func (s *SDK) Identities() space.IdentitiesAPI
Identities returns the account-global directory of identities this account has encountered (profiles + the spaces where each was seen).
func (*SDK) LocalDiscoveryEnabled ¶
LocalDiscoveryEnabled is the local-discovery switch state, false as well while p2p is disabled in config. Cheap: hosts polling it need not build the P2PStatus snapshot.
func (*SDK) P2PStatus ¶
P2PStatus reports the local-network layer: listener state, discovery possibility, and every known LAN peer with its shared spaces and live-connection flag. Per-space p2p state lives in SpaceSyncStatus (P2P / LocalPeers); this is the account-wide debug view.
func (*SDK) PeerId ¶
PeerId returns this device's libp2p peer id — stable per device installation, distinct from the account identity (Account().Id()). It is the row id of this device's entry in the devices registry (Spaces().SetDevice / ListDevices) and the value election consumers compare against space.ActiveDevice's winner.
func (*SDK) PoolInternal ¶
PoolInternal exposes the any-sync peer pool (dial by peerId with this account's identity in the handshake). Same-module internal surface — mirrors the PayloadsInternal pattern — used by the e2e suite to speak node-side protocols (e.g. fileprotov2 against a fileV2 broker).
func (*SDK) PubSub ¶
PubSub returns the account-wide ephemeral pub/sub surface: the same API as Space.PubSub(), bound to the tech space. The tech space's ACL is owner-only, so its peers are exactly this account's own devices — publishes here fan out account-wide with no separate transport. In headless mode the tech space is local-only, so delivery degrades to in-process loopback (no error).
func (*SDK) Push ¶
Push returns the push-notification API — device-token registration, space registration, topic subscriptions and encrypted publishes against the configured push node (config.Push). Always non-nil; when no push node is configured every method returns space.ErrPushNotConfigured.
func (*SDK) SetLocalDiscoveryEnabled ¶
SetLocalDiscoveryEnabled switches mDNS announce and browse on or off without a restart: off ends the running session at once, on starts one immediately (subject to the possibility probe), a restatement is a no-op. Config p2p.localDiscovery sets the state at Open.
Discovery traffic only: the QUIC listener, the global (iroh) layer and LAN peers already known are unaffected, so a live connection is kept and sync status keeps reporting it. Stopping every local-network exchange is p2p.enabled's job.
For hosts that own a local-network permission flow: the macOS Local Network prompt fires on the first multicast send, so such a host starts off and turns discovery on once the user has answered. A user-facing "LAN discovery" setting uses the same switch.
func (*SDK) Store ¶
Store returns the SDK's any-store DB (sdk.db) for consumer-owned, non-CRDT collections. The handle is the SDK's: it is open for the SDK's lifetime and closed by Close — consumers never close it.
Contract for consumers:
- Create and address collections ONLY under a consumer tag that is not a content id — a name whose segment before the first "_" is neither a space id nor a cid. The boot-time orphan sweep classifies such names ownerNone and never touches them (see docs/space.md § Space Lifecycle); every other prefix belongs to the CRDT layer, is swept by owner, and is rewritten by re-index. The "l_" tag is reserved for the any server's local store.
- Never write an SDK collection ("_meta", "<spaceId>_*", "<objectId>_*", "files_*", "_history_*", "_read_*"): a direct write bypasses the DAG and is reverted by the next re-index.
- Never open a write tx that spans a consumer collection and an SDK one. Reads across both in one tx are fine (that is the point of sharing the file: one snapshot for $lookup).
- Consumer collections are not rebuildable: a wiped sdk.db loses them, and the SDK's re-index paths leave them alone.
func (*SDK) SweepFileCache ¶
SweepFileCache runs one file-cache safety pass: prunes references of deleted files, deletes content no file references anymore (past a grace period), and drops long-untouched partial downloads of backed-up files. Never touches content that is not safely refetchable. This is the manual trigger; the same pass runs periodically only when cfg.Files.GCInterval is set.
func (*SDK) TechSpaceId ¶
TechSpaceId returns the account's tech space id. Spaces().Get with it yields the restricted tech-space handle — the home of account-level bundles (see space.Service.Get, space.ErrUnsupported).
Directories
¶
| Path | Synopsis |
|---|---|
|
Package auth is a pluggable provider of the two private keys any-sync needs: the account key (identity, signing, encryption) and the device key (per-installation peer identity).
|
Package auth is a pluggable provider of the two private keys any-sync needs: the account key (identity, signing, encryption) and the device key (per-installation peer identity). |
|
Package config holds the pure-data configuration types middleware passes to sdk.Open.
|
Package config holds the pure-data configuration types middleware passes to sdk.Open. |
|
examples
|
|
|
basic
command
Example: walks through the full SDK surface — Open, create a space, define a user type with properties, create an object of that type, write property values at multiple scopes (base, account, device), write user data to a type-owned dataset, query, subscribe.
|
Example: walks through the full SDK surface — Open, create a space, define a user type with properties, create an object of that type, write property values at multiple scopes (base, account, device), write user data to a type-owned dataset, query, subscribe. |
|
Package handler exposes the CRDT handler interface so callers can declare additional types whose instances carry custom datasets.
|
Package handler exposes the CRDT handler interface so callers can declare additional types whose instances carry custom datasets. |
|
internal
|
|
|
accountvalues
Package accountvalues defines the tech-space carrier for account-scoped values and the pure diff that mirrors carrier state into target-space records.
|
Package accountvalues defines the tech-space carrier for account-scoped values and the pure diff that mirrors carrier state into target-space records. |
|
anyencx
Package anyencx holds small anyenc helpers shared across the SDK.
|
Package anyencx holds small anyenc helpers shared across the SDK. |
|
anysyncx
Package anysyncx is the sole importer of github.com/anyproto/any-sync.
|
Package anysyncx is the sole importer of github.com/anyproto/any-sync. |
|
crdt
Package crdt implements the version-gated record store CRDT defined in docs/crdt.md and docs/crdt-spec.md.
|
Package crdt implements the version-gated record store CRDT defined in docs/crdt.md and docs/crdt-spec.md. |
|
fanout
Package fanout provides the shared add / cancel / dispatch primitive behind the SDK's synchronous callback firehoses (sync status, change feed, row events, read-state pings, member events, file status).
|
Package fanout provides the shared add / cancel / dispatch primitive behind the SDK's synchronous callback firehoses (sync status, change feed, row events, read-state pings, member events, file status). |
|
files/broker
Package broker is the fileprotov2 client of the files subsystem (SYN-27): batch RPCs against the space's responsible fileV2 nodes (routing by nodeconf.FileV2Peers with NotResponsible failover), the presigned HTTP upload, and durable-custody receipt verification against the fleet.
|
Package broker is the fileprotov2 client of the files subsystem (SYN-27): batch RPCs against the space's responsible fileV2 nodes (routing by nodeconf.FileV2Peers with NotResponsible failover), the presigned HTTP upload, and durable-custody receipt verification against the fleet. |
|
files/carfile
Package carfile reads and writes the files byte-layer pack format: one standard CARv2 (pragma + v2 header + CARv1 data payload + embedded multihash-sorted index) per file, keyed by its UnixFS root cid.
|
Package carfile reads and writes the files byte-layer pack format: one standard CARv2 (pragma + v2 header + CARv1 data payload + embedded multihash-sorted index) per file, keyed by its UnixFS root cid. |
|
files/crypt
Package crypt implements the files byte-layer cipher: whole-file AES-256-CFB with a zero IV and a random per-file key — the exact format anytype-heart writes (cfb.New(key, [aes.BlockSize]byte{})), so ciphertext and the derived UnixFS cids stay byte-compatible.
|
Package crypt implements the files byte-layer cipher: whole-file AES-256-CFB with a zero IV and a random per-file key — the exact format anytype-heart writes (cfb.New(key, [aes.BlockSize]byte{})), so ciphertext and the derived UnixFS cids stay byte-compatible. |
|
files/fetch
Package fetch is the client download path of the files subsystem (SYN-28): resolve a rootCid through the block-source ladder — local store → peer (SYN-24 seam) → public CARv2 GET with HTTP Range — and expose verified plaintext as a seekable reader.
|
Package fetch is the client download path of the files subsystem (SYN-28): resolve a rootCid through the block-source ladder — local store → peer (SYN-24 seam) → public CARv2 GET with HTTP Range — and expose verified plaintext as a seekable reader. |
|
files/filep2p
Package filep2p is the SDK's peer-to-peer file transfer: a read-only server that streams a device's stored CAR objects to LAN peers, and a PeerSource that fetches file objects from LAN peers before the public HTTP path.
|
Package filep2p is the SDK's peer-to-peer file transfer: a read-only server that streams a device's stored CAR objects to LAN peers, and a PeerSource that fetches file objects from LAN peers before the public HTTP path. |
|
files/gc
Package gc is the local-cache reclamation of the files subsystem (SYN-26).
|
Package gc is the local-cache reclamation of the files subsystem (SYN-26). |
|
files/status
Package status is the files background-work engine (SYN-29): one persistent queue with two job kinds — drive-toward-durable (every registered row whose backup hasn't succeeded yet) and pin (full background fetches).
|
Package status is the files background-work engine (SYN-29): one persistent queue with two job kinds — drive-toward-durable (every registered row whose backup hasn't succeeded yet) and pin (full background fetches). |
|
files/store
Package store is the local content-addressed payload store of the files subsystem (SYN-25): one CARv2 per file keyed by its root cid (byte-identical to the uploaded S3 object), plus an any-store metadata collection holding the small hot state — download bitmap, state, per-file refs, the per-space content-dedup index and LRU access times.
|
Package store is the local content-addressed payload store of the files subsystem (SYN-25): one CARv2 per file keyed by its root cid (byte-identical to the uploaded S3 object), plus an any-store metadata collection holding the small hot state — download bitmap, state, per-file refs, the per-space content-dedup index and LRU access times. |
|
files/upload
Package upload is the client upload path of the files subsystem (SYN-27): spool → tier decision (inline / BIND dedup / full) → encrypt → UnixFS DAG → local CARv2 → register the payloads row → enqueue the durable phase.
|
Package upload is the client upload path of the files subsystem (SYN-27): spool → tier decision (inline / BIND dedup / full) → encrypt → UnixFS DAG → local CARv2 → register the payloads row → enqueue the durable phase. |
|
history
Package history implements version history over any-sync object trees: structural diffs between reconstructed states (this file), on-demand causal replay, and the persistent history index.
|
Package history implements version history over any-sync object trees: structural diffs between reconstructed states (this file), on-demand causal replay, and the persistent history index. |
|
inbox
Package inbox is the coordinator-inbox notifier: the optional Layer-2 discovery for 1-1 spaces (docs/one-to-one-spaces.md).
|
Package inbox is the coordinator-inbox notifier: the optional Layer-2 discovery for 1-1 spaces (docs/one-to-one-spaces.md). |
|
object
Package object binds one any-sync object tree to one crdt.Controller and exposes the lifecycle surface used by space/: Create / Derive / Modify / Delete / Subscribe, plus ocache wiring so trees are loaded on demand and TTL-closed when idle.
|
Package object binds one any-sync object tree to one crdt.Controller and exposes the lifecycle surface used by space/: Create / Derive / Modify / Delete / Subscribe, plus ocache wiring so trees are loaded on demand and TTL-closed when idle. |
|
p2p/account
Package account is the account-level device-discovery record: every device of an account registers itself in one pkarr record addressed by a key derived from the identity key, and every device — a fresh restore included — resolves its siblings from it.
|
Package account is the account-level device-discovery record: every device of an account registers itself in one pkarr record addressed by a key derived from the identity key, and every device — a fresh restore included — resolves its siblings from it. |
|
payloads
Package payloads is the built-in file `payloads` dataset — the node-readable per-file index of the files subsystem (docs/files.md).
|
Package payloads is the built-in file `payloads` dataset — the node-readable per-file index of the files subsystem (docs/files.md). |
|
properties
Package properties owns the per-space `properties` system dataset: the CRDT handlers that keep it consistent with the object-owned base-scope data, the variant merge (device > account > base) used by projection, and the reserved variant field names (_device, _account, _base).
|
Package properties owns the per-space `properties` system dataset: the CRDT handlers that keep it consistent with the object-owned base-scope data, the variant merge (device > account > base) used by projection, and the reserved variant field names (_device, _account, _base). |
|
pushclient
Package pushclient is the client of the anytype-push-server (SYN-47): per-space key derivation, the signed/encrypted request builders, the thin DRPC transport, and the account-level service behind SDK.Push() / space.PushAPI.
|
Package pushclient is the client of the anytype-push-server (SYN-47): per-space key derivation, the signed/encrypted request builders, the thin DRPC transport, and the account-level service behind SDK.Push() / space.PushAPI. |
|
readstate
Package readstate owns the per-space read/unread engine: the unread entries, the per-object seen-heads frontier, per-tag counters, and the transitions log backing the read-state feed.
|
Package readstate owns the per-space read/unread engine: the unread entries, the per-object seen-heads frontier, per-tag counters, and the transitions log backing the read-state feed. |
|
readsync
Package readsync moves read state between an account's devices: it publishes each object's seen-heads frontier to the TECH space's key-value store and merges other devices' published frontiers into the local per-space readstate engines.
|
Package readsync moves read state between an account's devices: it publishes each object's seen-heads frontier to the TECH space's key-value store and merges other devices' published frontiers into the local per-space readstate engines. |
|
schema
Package schema implements the minimal JSON-Schema subset used by the types/properties layer.
|
Package schema implements the minimal JSON-Schema subset used by the types/properties layer. |
|
spaceimpl
Package spaceimpl is the concrete implementation of space.Service and space.Space.
|
Package spaceimpl is the concrete implementation of space.Service and space.Space. |
|
spaceobjects
Selective sync by tree type (SYN-18).
|
Selective sync by tree type (SYN-18). |
|
spacesync
Package spacesync runs the SDK's space-level catch-up against any-sync's head store at startup.
|
Package spacesync runs the SDK's space-level catch-up against any-sync's head store at startup. |
|
store
Package store owns the query and subscription primitives over any-store.
|
Package store owns the query and subscription primitives over any-store. |
|
subscribe
Package subscribe owns the per-space live-query engine and the projected Event types the apply path hands to it.
|
Package subscribe owns the per-space live-query engine and the projected Event types the apply path hands to it. |
|
syncstatus
Package syncstatus tracks per-space, per-object sync state from any-sync's StatusUpdater hooks and exposes it via the SyncStatusAPI surfaced on space.Space.
|
Package syncstatus tracks per-space, per-object sync state from any-sync's StatusUpdater hooks and exposes it via the SyncStatusAPI surfaced on space.Space. |
|
techspace
Package techspace is the hidden account-level space: a derived space with owner-only ACL, used as the account's index of spaces, chat-read tracker, and (later) account preferences.
|
Package techspace is the hidden account-level space: a derived space with owner-only ACL, used as the account's index of spaces, chat-read tracker, and (later) account preferences. |
|
types
Package types owns the types-and-properties machinery: the per-space Registry, the built-in `any` and `type` type objects, property definition schemas, schema compilation from property records, and the typePropertyHandler (implements crdt.Handler).
|
Package types owns the types-and-properties machinery: the per-space Registry, the built-in `any` and `type` type objects, property definition schemas, schema compilation from property records, and the typePropertyHandler (implements crdt.Handler). |
|
types/any
Package anytype is the built-in `any` type — the universal shape every object in a space implements: name, description, icon (synced, CRDT-mutable), plus id, author, spaceId, createdAt, modifiedAt, modifiedBy (derived, read-only, stamped from any-sync context).
|
Package anytype is the built-in `any` type — the universal shape every object in a space implements: name, description, icon (synced, CRDT-mutable), plus id, author, spaceId, createdAt, modifiedAt, modifiedBy (derived, read-only, stamped from any-sync context). |
|
types/collection
Package collectiontype is the built-in `collection` meta-type — the shape of collection objects.
|
Package collectiontype is the built-in `collection` meta-type — the shape of collection objects. |
|
types/spaceindex
Package spaceindex is the built-in `spaceIndex` type — one derived object per space carrying the space's display metadata (name, description, icon, spaceType) as CRDT-mutable base-scope properties.
|
Package spaceindex is the built-in `spaceIndex` type — one derived object per space carrying the space's display metadata (name, description, icon, spaceType) as CRDT-mutable base-scope properties. |
|
types/type
Package typetype is the built-in `type` meta-type — the shape of type objects themselves.
|
Package typetype is the built-in `type` meta-type — the shape of type objects themselves. |
|
Package p2p is the public surface of the SDK's local-network layer: the types exchanged with discovery drivers and the injection points platform embedders (gomobile bridges) use to plug native behavior in.
|
Package p2p is the public surface of the SDK's local-network layer: the types exchanged with discovery drivers and the injection points platform embedders (gomobile bridges) use to plug native behavior in. |
|
Package space is the public caller surface of the SDK.
|
Package space is the public caller surface of the SDK. |