package ditto
import "github.com/getditto/ditto-go-sdk/v5/ditto"
Package ditto contains the public API for the Ditto Go SDK.
The Ditto Go SDK is a cross-platform SDK that allows apps to sync with and even without Internet connectivity. Simply install the SDK into your application, then use the APIs to read and write data into its storage system, and it will then automatically sync any changes to other devices. Unlike other synchronization techniques, the Ditto Go SDK is designed for “peer-to-peer” synchronization where it can directly communicate with other devices, no server required! The SDK automatically manages the complexity of using multiple network transports, like Bluetooth and Wi-Fi, to find and connect to other devices and then synchronize any changes.
If you are looking for an overview of how to use the Ditto Go SDK, see our guide documentation:
Index
- Constants
- Variables
- func DefaultDatabaseID() string
- func DefaultRootDirectory() string
- func ExportLog(path string) (uint64, error)
- func IsEmojiLogLevelHeadingsEnabled() bool
- func IsLoggerEnabled() bool
- func LogDebug(message string)
- func LogDebugF(format string, args ...any)
- func LogError(message string)
- func LogErrorF(format string, args ...any)
- func LogInfo(message string)
- func LogInfoF(format string, args ...any)
- func LogVerbose(message string)
- func LogVerboseF(format string, args ...any)
- func LogWarning(message string)
- func LogWarningF(format string, args ...any)
- func SetCustomLogCallback(callback func(level LogLevel, message string))
- func SetEmojiLogLevelHeadingsEnabled(enabled bool)
- func SetLogFile(logFilePath string) error
- func SetLoggerEnabled(enabled bool)
- func SetMinimumLogLevel(level LogLevel)
- func TransactionWithResult(store *Store, opts *TransactionOptions, fn func(*Transaction) (T, error)) (T, error)
- func Version() string
- type Address
- type AddressType
-
-
-
-
- type AuthenticationExpirationHandler
- type AuthenticationProvider
- type AuthenticationStatus
- type AuthenticationStatusObservationHandler
- type AuthenticationStatusObserver
-
type Authenticator
- func (a *Authenticator) GetExpirationHandler() AuthenticationExpirationHandler
- func (a *Authenticator) Login(token string, provider AuthenticationProvider) (clientInfoJSON string, err error)
- func (a *Authenticator) LoginWithCredentials(username, password string, provider AuthenticationProvider) (err error)
- func (a *Authenticator) Logout(cleanup func(*Ditto))
- func (a *Authenticator) ObserveStatus(observer AuthenticationStatusObservationHandler) *AuthenticationStatusObserver
- func (a *Authenticator) SetExpirationHandler(handler AuthenticationExpirationHandler)
- func (a *Authenticator) Status() *AuthenticationStatus
- type Connection
- type ConnectionRequest
- type ConnectionRequestAuthorization
- type ConnectionRequestHandler
- type ConnectionType
- type Diff
- type Differ
-
-
-
-
type Ditto
- func Open(config *DittoConfig) (*Ditto, error)
- func (d *Ditto) AbsolutePersistenceDirectory() string
- func (d *Ditto) Auth() *Authenticator
- func (d *Ditto) Close()
- func (d *Ditto) Config() *DittoConfig
- func (d *Ditto) DatabaseID() string
- func (d *Ditto) DeviceName() string
- func (d *Ditto) IsActivated() bool
- func (d *Ditto) IsClosed() bool
- func (d *Ditto) IsEncrypted() bool
- func (d *Ditto) Presence() *Presence
- func (d *Ditto) SetDeviceName(name string)
- func (d *Ditto) SetOfflineOnlyLicenseToken(token string) error
- func (d *Ditto) SmallPeerInfo() *SmallPeerInfo
- func (d *Ditto) Store() *Store
- func (d *Ditto) Sync() *Sync
- type DittoConfig
- type DittoConfigConnect
- type DittoConfigConnectServer
- type DittoConfigConnectSmallPeersOnly
- type DittoConfigConnectType
- type DittoConfigConnectUnion
- type Document
- type LogLevel
- type Move
- type Peer
- type PeerOS
-
type Presence
- func (p *Presence) GetPeerMetadata() (map[string]any, error)
- func (p *Presence) GetPeerMetadataJSONData() ([]byte, error)
- func (p *Presence) Graph() *PresenceGraph
- func (p *Presence) Observe(callback PresenceObservationHandler) *PresenceObserver
- func (p *Presence) SetConnectionRequestHandler(handler ConnectionRequestHandler)
- func (p *Presence) SetPeerMetadata(metadata map[string]any) error
- func (p *Presence) SetPeerMetadataJSONData(jsonData []byte) error
- type PresenceGraph
- type PresenceObservationHandler
- type PresenceObserver
- type QueryArguments
- type QueryExecutor
-
type QueryResult
- func (r *QueryResult) Close()
- func (r *QueryResult) CommitID() (uint64, bool)
- func (r *QueryResult) Item(i int) *QueryResultItem
- func (r *QueryResult) ItemCount() int
- func (r *QueryResult) Items() iter.Seq2[int, *QueryResultItem]
- func (r *QueryResult) MutatedDocumentIDs() []any
- func (r *QueryResult) Values() []Document
-
type QueryResultItem
- func (i *QueryResultItem) CBORData() []byte
- func (i *QueryResultItem) Close()
- func (i *QueryResultItem) Dematerialize()
- func (i *QueryResultItem) IsMaterialized() bool
- func (i *QueryResultItem) JSONData() []byte
- func (i *QueryResultItem) JSONString() string
- func (i *QueryResultItem) Materialize()
- func (i *QueryResultItem) UnmarshalTo(v any) error
- func (i *QueryResultItem) Value() Document
- type SignalNext
-
type SmallPeerInfo
- func (s *SmallPeerInfo) IsEnabled() bool
- func (s *SmallPeerInfo) Metadata() map[string]any
- func (s *SmallPeerInfo) MetadataJSONString() string
- func (s *SmallPeerInfo) SetEnabled(enabled bool) error
- func (s *SmallPeerInfo) SetMetadata(metadata map[string]any) error
- func (s *SmallPeerInfo) SetMetadataJSONString(jsonStr string) error
-
type Store
- func (s *Store) Execute(query string, args ...QueryArguments) (*QueryResult, error)
- func (s *Store) Observers() []*StoreObserver
- func (s *Store) RegisterObserver(query string, args QueryArguments, handler StoreObservationHandler) (*StoreObserver, error)
- func (s *Store) RegisterObserverWithSignalNext(query string, args QueryArguments, ...) (*StoreObserver, error)
- func (s *Store) Transaction(opts *TransactionOptions, ...) (TransactionCompletionAction, error)
- type StoreObservationHandler
- type StoreObservationHandlerWithSignalNext
- type StoreObserver
- type Sync
- type SyncSubscription
- type Transaction
- type TransactionCompletionAction
- type TransactionInfo
- type TransactionOptions
-
-
-
Examples
Constants
const ( AttachmentFetchEventTypeProgress = FetchEventTypeProgress AttachmentFetchEventTypeCompleted = FetchEventTypeCompleted AttachmentFetchEventTypeFailed = FetchEventTypeFailed AttachmentFetchEventTypeCanceled = FetchEventTypeCanceled )
Backward compatibility constants. New code should use the FetchEventType* constants.
const ( // LogLevelError logs only errors LogLevelError = LogLevel(ffi.LogLevelError) // LogLevelWarning logs warnings and above LogLevelWarning = LogLevel(ffi.LogLevelWarning) // LogLevelInfo logs info and above LogLevelInfo = LogLevel(ffi.LogLevelInfo) // LogLevelDebug logs debug and above LogLevelDebug = LogLevel(ffi.LogLevelDebug) // LogLevelVerbose logs everything LogLevelVerbose = LogLevel(ffi.LogLevelVerbose) )
const ( ConnectionRequestAuthorizationAllow = ConnectionRequestAuthorization(ffi.ConnectionRequestAuthorizationAllow) ConnectionRequestAuthorizationDeny = ConnectionRequestAuthorization(ffi.ConnectionRequestAuthorizationDeny) )
const ( // TransactionCompletionActionCommit commits the transaction, applying all changes. TransactionCompletionActionCommit = TransactionCompletionAction(ffi.TransactionCompletionActionCommit) // TransactionCompletionActionRollback rolls back the transaction, discarding all changes. TransactionCompletionActionRollback = TransactionCompletionAction(ffi.TransactionCompletionActionRollback) )
Variables
var ErrAuthenticatorNotAvailable = errors.New("authenticator is not available for this connection type")
ErrAuthenticatorNotAvailable is returned when authentication methods are called but the Authenticator is not available (e.g., when using SmallPeersOnly connection).
var ( ErrDittoClosed = &DittoError{Code: ffi.ErrorCodeInternal, Message: "Ditto instance is closed"} // TODO: should this even be a DittoError? )
var ErrExpirationHandlerNotSet = errors.New("expiration handler must be set before starting sync with server connection")
ErrExpirationHandlerNotSet is returned when StartSync is called on a server connection without setting an expiration handler.
var ErrTransactionClosed = errors.New("transaction is already closed")
ErrTransactionClosed is returned when attempting to use a closed transaction.
Functions
func DefaultDatabaseID
func DefaultDatabaseID() string
DefaultDatabaseID returns the default identifier for a Ditto instance.
This identifier is used when no explicit Database ID is provided. It is typically a constant UUID string that ensures a predictable default value. In most cases, you should provide your own unique identifier to avoid conflicts when syncing with other peers.
func DefaultRootDirectory
func DefaultRootDirectory() string
DefaultRootDirectory returns the default root directory used for Ditto data persistence.
On different platforms:
- macOS: Returns "~/Library/Application Support/Ditto" (avoids permission issues in CI)
- Linux/Windows: Returns the current working directory
- iOS/Android: Would return the app's data directory (not currently supported in Go)
The macOS behavior matches the Swift SDK and ensures consistent permissions in CI environments where the current directory may have restricted access.
This value is used when a relative persistence directory path (or empty string) is provided in the configuration.
See also:
- DittoConfig.PersistenceDirectory
- Ditto.AbsolutePersistenceDirectory
func ExportLog
func ExportLog(path string) (uint64, error)
ExportLog exports collected logs to a compressed file.
Ditto collects a limited amount of diagnostic logs in the background, which can be exported to a compressed file for analysis. This includes logs from all Ditto instances created in the same process.
The exported file is a gzip-compressed JSON Lines file (`.jsonl.gz`), with one JSON object per line representing a log entry. The logs are ordered from oldest to newest.
Parameters:
- path: The filesystem path where the log file should be written. The file must not already exist, and the containing directory must exist. It is recommended to use the `.jsonl.gz` extension, though not required.
Returns:
- The number of bytes written to disk
- An error if the export fails (e.g., file already exists, permission denied)
Note: This function works independently of the current log level setting and exports all logs at Debug level and above. Logs are limited to 15 MB and a maximum age of 3 days.
func IsEmojiLogLevelHeadingsEnabled
func IsEmojiLogLevelHeadingsEnabled() bool
IsEmojiLogLevelHeadingsEnabled returns whether emoji are used as the log level indicator in logs.
func IsLoggerEnabled
func IsLoggerEnabled() bool
IsLoggerEnabled returns whether logging is enabled.
Logs exported through ExportLog are not affected by this setting and will also include logs emitted while enabled is false
func LogDebug
func LogDebug(message string)
LogDebug logs a debug message
func LogDebugF
func LogDebugF(format string, args ...any)
LogDebugF logs a formatted debug message
func LogError
func LogError(message string)
LogError logs an error message
func LogErrorF
func LogErrorF(format string, args ...any)
LogErrorF logs a formatted error message
func LogInfo
func LogInfo(message string)
LogInfo logs an info message
func LogInfoF
func LogInfoF(format string, args ...any)
LogInfoF logs a formatted info message
func LogVerbose
func LogVerbose(message string)
LogVerbose logs a verbose message
func LogVerboseF
func LogVerboseF(format string, args ...any)
LogVerboseF logs a formatted verbose message
func LogWarning
func LogWarning(message string)
LogWarning logs a warning message
func LogWarningF
func LogWarningF(format string, args ...any)
LogWarningF logs a formatted warning message
func SetCustomLogCallback
func SetCustomLogCallback(callback func(level LogLevel, message string))
SetCustomLogCallback sets a custom callback for log messages. The callback receives the log level and message from the Ditto core.
When a custom callback is set, it will receive all log messages that pass through the Ditto logging system, regardless of the current log level setting. The callback is called on the thread that generates the log message.
Parameters:
- callback: A function that receives log messages. If nil, removes the current callback.
func SetEmojiLogLevelHeadingsEnabled
func SetEmojiLogLevelHeadingsEnabled(enabled bool)
SetEmojiLogLevelHeadingsEnabled enables or disables whether emoji are used as the log level indicator in logs.
func SetLogFile
func SetLogFile(logFilePath string) error
SetLogFile registers a file path where logs will be written to, whenever Ditto wants to issue a log (in addition to emitting the log to the console).
If the given path is the empty string, then the current logging file, if any, is unregistered. Otherwise, the file path must be within an already existing directory
func SetLoggerEnabled
func SetLoggerEnabled(enabled bool)
SetLoggerEnabled enables or disables logging.
Logs exported through ExportLog are not affected by this setting and will also include logs emitted while enabled is false.
func SetMinimumLogLevel
func SetMinimumLogLevel(level LogLevel)
SetMinimumLogLevel sets the minimum log level at which logs will be logged, provided the logger is enabled.
For example if this is set to DittoLogLevel.warning, then only logs that are logged with the LogLevelWarning or LogLevelError log levels will be shown.
Logs exported through ExportLog are not affected by this setting and include all logs at LogLevelDebug and above.
func TransactionWithResult
func TransactionWithResult[T any](store *Store, opts *TransactionOptions, fn func(*Transaction) (T, error)) (T, error)
TransactionWithResult executes a transaction and returns a value.
This is a convenience function similar to Store.Transaction, but propagates the return value of the transaction function rather than the completion action.
The transaction is committed implicitly if the function returns without error, and rolled back if an error is returned.
See Store.Transaction() for important details about transaction behavior, deadlock warnings, and mesh configuration limitations.
Note that this is a package-level function rather than a method on Store, because methods with generic type parameters are not supported in Go.
Parameters:
- store: The Store to execute the transaction on
- opts: Optional transaction configuration. Can be nil to use defaults (no hint, read-write transaction).
- fn: Function to execute within the transaction. It receives a Transaction object and should return a value and any error encountered.
Returns:
- T: The value returned from fn, or the zero value for T on error
- error: An error if the transaction fails, or any error returned from fn
func Version
func Version() string
Version returns the semantic version of the Ditto SDK.
This represents the underlying Ditto core library version, not the Go SDK wrapper version.
Types
type AWDLConfig struct { // Enabled controls whether AWDL transport is active Enabled bool `cbor:"enabled" json:"enabled"` }
AWDLConfig configures Apple Wireless Direct Link transport.
AWDL is Apple's proprietary peer-to-peer WiFi protocol used for:
- AirDrop
- AirPlay
- High-speed local transfers
Only available on iOS and macOS devices.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type Address
type Address struct { AddressType AddressType IPAddress string Port uint16 }
Address represents a peer's network address
type AddressType
type AddressType int
AddressType represents the type of address
const ( // AddressTypeIPv4 represents IPv4 addresses AddressTypeIPv4 AddressType = iota // AddressTypeIPv6 represents IPv6 addresses AddressTypeIPv6 // AddressTypeBluetooth represents Bluetooth addresses AddressTypeBluetooth )
type Attachment struct { // contains filtered or unexported fields }
Attachment represents a file attachment that can be synced via Ditto.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (a *Attachment) CopyToPath(destinationPath string) error
CopyToPath copies the attachment to a specified file path.
This method efficiently copies the attachment data to the destination path without loading the entire content into memory. The destination directory must exist, and the file will be overwritten if it already exists.
Parameters:
- destinationPath: The file path where the attachment should be copied
Returns:
- error: An error if the copy operation fails
Example:
err := attachment.CopyToPath("/path/to/destination.pdf")
if err != nil {
log.Printf("Failed to copy attachment: %v", err)
}
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (a *Attachment) CreatedAt() time.Time
CreatedAt returns when the attachment was created. This timestamp is typically stored in the attachment's metadata. If no creation time is stored, returns the current time.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (a *Attachment) Data() ([]byte, error)
Data retrieves the attachment's binary content as a byte slice.
This method loads the entire attachment into memory. For large attachments, consider using Reader() or CopyToPath() instead to avoid high memory usage.
Returns:
- []byte: The attachment's binary data
- error: An error if the data cannot be retrieved
Example:
data, err := attachment.Data()
if err != nil {
log.Printf("Failed to get attachment data: %v", err)
} else {
// Process the binary data
fmt.Printf("Attachment size: %d bytes\n", len(data))
}
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (a *Attachment) Free()
Free releases the attachment resources. This should be called when the attachment is no longer needed to free the underlying FFI resources. After calling Free, the attachment should not be used.
It is safe to call Free multiple times; subsequent calls will be no-ops.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (a *Attachment) Handle() *ffi.AttachmentHandle
Handle returns the underlying FFI attachment handle. This is primarily for internal use and should not be accessed directly in application code.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (a *Attachment) ID() string
ID returns the unique identifier of the attachment. The ID is a hex-encoded string that uniquely identifies this attachment across all peers in the Ditto network.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (a *Attachment) Len() int64
Len returns the size of the attachment in bytes. This represents the total size of the binary data.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (a *Attachment) Metadata() map[string]any
Metadata returns the attachment's metadata dictionary. Metadata can contain any JSON-serializable data that describes the attachment, such as content type, original filename, creation date, or custom attributes.
The returned map is a reference to the internal metadata. Modifications to the returned map will affect the attachment's metadata.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (a *Attachment) Path() string
Path returns the local file system path where the attachment is stored. This path is managed by Ditto and should not be modified directly. The path may be empty if the attachment was created from bytes or if it hasn't been fetched yet.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (a *Attachment) Reader() (io.ReadSeeker, error)
Reader returns an io.ReadSeeker for reading the attachment's content.
This method provides a reader that can be used to read the attachment data without loading it entirely into memory. The reader supports seeking, which allows for partial reads and repositioning within the attachment.
The caller is responsible for closing the returned reader when done.
Returns:
- io.ReadSeeker: A reader for the attachment content
- error: An error if the reader cannot be created
Example:
reader, err := attachment.Reader()
if err != nil {
log.Printf("Failed to get reader: %v", err)
return
}
defer reader.(io.Closer).Close()
// Read first 1024 bytes
buffer := make([]byte, 1024)
n, err := reader.Read(buffer)
if err != nil && err != io.EOF {
log.Printf("Failed to read: %v", err)
}
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (a *Attachment) Size() int64
Size returns the size of the attachment in bytes. This is equivalent to Len() and provided for convenience.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (a *Attachment) Token() *AttachmentToken
Token returns the attachment token that can be stored in documents. The token contains the attachment ID, size, and metadata, and is used to reference the attachment from within documents.
The token should be stored in document fields where you want to reference this When other peers sync the document, they can use the token to fetch the attachment data on-demand.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (a *Attachment) UpdatedAt() time.Time
UpdatedAt returns when the attachment was last updated. This timestamp is typically stored in the attachment's metadata. If no update time is stored, returns the current time.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type AttachmentFetchEvent struct { // Type indicates what kind of event this is Type FetchEventType // Progress indicates fetch completion (0.0 to 1.0), valid for progress events Progress float64 // BytesDownloaded is the number of bytes downloaded so far, valid for progress events BytesDownloaded int64 // TotalBytes is the total size of the attachment, valid for progress events TotalBytes int64 // Error contains failure details, valid for failed events Error error // Path is the local file path where the attachment was saved, valid for completed events Path string }
AttachmentFetchEvent represents an event that occurs during attachment fetching. Events are delivered to the callback function provided when creating a fetcher.
Different event types provide different information:
- Progress events: Include Progress, BytesDownloaded, and TotalBytes
- Completed events: Include Path to the downloaded file
- Failed events: Include Error with failure details
- Canceled events: Indicate the fetch was canceled by the user
Example handling:
func handleFetchEvent(event *AttachmentFetchEvent) {
switch event.Type {
case FetchEventTypeProgress:
percentage := event.Progress * 100
fmt.Printf("Progress: %.1f%%\n", percentage)
case FetchEventTypeCompleted:
fmt.Printf("Download completed: %s\n", event.Path)
case FetchEventTypeFailed:
fmt.Printf("Download failed: %v\n", event.Error)
case FetchEventTypeCanceled:
fmt.Println("Download canceled")
}
}
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func NewAttachmentFetchEventCompleted(path string) *AttachmentFetchEvent
NewAttachmentFetchEventCompleted creates a new completion event. This is an alias for NewCompletedEvent provided for backward compatibility. New code should use NewCompletedEvent.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func NewAttachmentFetchEventDeleted() *AttachmentFetchEvent
NewAttachmentFetchEventDeleted creates a new cancellation event. This is an alias for NewCanceledEvent provided for backward compatibility. The name "Deleted" is maintained for compatibility but actually represents cancellation. New code should use NewCanceledEvent.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func NewAttachmentFetchEventProgress(progress float64) *AttachmentFetchEvent
NewAttachmentFetchEventProgress creates a new progress event. This is an alias for NewProgressEvent provided for backward compatibility. New code should use NewProgressEvent.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func NewCanceledEvent() *AttachmentFetchEvent
NewCanceledEvent creates a new cancellation event.
Returns:
- *AttachmentFetchEvent: A cancellation event
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func NewCompletedEvent(path string) *AttachmentFetchEvent
NewCompletedEvent creates a new completion event.
Parameters:
- path: The local file system path where the attachment was saved
Returns:
- *AttachmentFetchEvent: A completion event
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func NewFailedEvent(err error) *AttachmentFetchEvent
NewFailedEvent creates a new failure event.
Parameters:
- err: The error that caused the fetch to fail
Returns:
- *AttachmentFetchEvent: A failure event
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func NewProgressEvent(progress float64) *AttachmentFetchEvent
NewProgressEvent creates a new progress event.
Parameters:
- progress: The completion percentage (0.0 to 1.0)
Returns:
- *AttachmentFetchEvent: A progress event
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (e *AttachmentFetchEvent) IsCanceled() bool
IsCanceled returns true if this is a cancellation event. Canceled events occur when the user calls Cancel() on the fetcher.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (e *AttachmentFetchEvent) IsCompleted() bool
IsCompleted returns true if this is a completion event. Completed events indicate successful download of the
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (e *AttachmentFetchEvent) IsFailed() bool
IsFailed returns true if this is a failure event. Failed events include an Error field with details about the failure.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (e *AttachmentFetchEvent) String() string
String returns a human-readable string representation of the event. Useful for logging and debugging.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type AttachmentFetchEventType = FetchEventType
AttachmentFetchEventType is an alias for FetchEventType for backward compatibility. New code should use FetchEventType.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type AttachmentFetcher struct { // contains filtered or unexported fields }
AttachmentFetcher manages the asynchronous fetching of an attachment. It provides progress updates and can be canceled if needed.
Fetchers must be started explicitly with Start() and can be canceled with Cancel(). Progress updates are delivered through the callback function provided during creation.
Thread-safety: AttachmentFetcher is thread-safe. All methods can be called concurrently from multiple goroutines.
Example usage:
fetcher := newAttachmentFetcher(dittoHandle, token, func(event *AttachmentFetchEvent) {
switch event.Type {
case FetchEventTypeProgress:
fmt.Printf("Downloaded %d of %d bytes (%.1f%%)\n",
event.BytesDownloaded, event.TotalBytes, event.Progress*100)
case FetchEventTypeCompleted:
fmt.Printf("Download complete! File at: %s\n", event.Path)
case FetchEventTypeFailed:
fmt.Printf("Download failed: %v\n", event.Error)
}
})
if err := fetcher.Start(); err != nil {
log.Fatal(err)
}
// Cancel if needed
time.Sleep(5 * time.Second)
fetcher.Cancel()
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (f *AttachmentFetcher) BytesDownloaded() int64
BytesDownloaded returns the number of bytes downloaded so far. This can be used with TotalBytes() to calculate progress or estimate remaining download time.
Thread-safe: This method can be called concurrently.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (f *AttachmentFetcher) Cancel()
Cancel stops fetching the attachment.
This method is safe to call multiple times and will gracefully stop the fetch operation if it's in progress. The callback will receive a cancellation event.
After cancellation, the fetcher cannot be restarted.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (f *AttachmentFetcher) IsCompleted() bool
IsCompleted returns true if the fetch has completed successfully. This does not include failed or canceled fetches.
Thread-safe: This method can be called concurrently.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (f *AttachmentFetcher) Progress() float64
Progress returns the current fetch progress as a value between 0.0 and 1.0.
- 0.0 means the fetch hasn't started or no data has been downloaded
- 1.0 means the fetch is complete
- Values in between represent partial completion
Thread-safe: This method can be called concurrently.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (f *AttachmentFetcher) Start() error
Start begins fetching the attachment.
Returns:
- error: An error if the fetch cannot be started (e.g., invalid token or handle)
Once started, the fetcher will download the attachment in the background and call the callback function with progress updates. The fetch continues until completion, failure, or cancellation.
Starting an already started fetcher will return an error.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (f *AttachmentFetcher) Token() *AttachmentToken
Token returns the attachment token that identifies what is being fetched. This can be useful for tracking multiple concurrent fetches.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (f *AttachmentFetcher) TotalBytes() int64
TotalBytes returns the total size of the attachment in bytes. This value is known before the download starts and comes from the token.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type AttachmentToken struct { // contains filtered or unexported fields }
AttachmentToken represents a lightweight reference to an attachment. Tokens are stored in documents to reference attachments without including the actual binary data. When a document with an attachment token is synced, the receiving peer can use the token to fetch the actual attachment data.
Tokens are immutable once created and safe for concurrent access.
Example usage:
// Create a token from an attachment
token := Token()
// Store the token in a document
doc := map[string]any{
"image": token,
"description": "Profile picture",
}
// Later, deserialize a token from a document
if tokenData, ok := doc["image"].([]byte); ok {
token, err := AttachmentTokenFromBytes(tokenData)
if err == nil {
// Use token to fetch the attachment
}
}
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func AttachmentTokenFromBytes(data []byte) (*AttachmentToken, error)
AttachmentTokenFromBytes deserializes a token from a byte array.
Parameters:
- data: The serialized token data, typically retrieved from a document
Returns:
- *AttachmentToken: The deserialized token
- error: An error if the data is invalid or deserialization fails
This function is used to reconstruct tokens from data stored in documents, allowing you to fetch the referenced attachments.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func FromString(s string) (*AttachmentToken, error)
FromString creates a token from its JSON string representation.
Parameters:
- s: A JSON string representing the token, typically from String()
Returns:
- *AttachmentToken: The deserialized token
- error: An error if the string is invalid JSON or deserialization fails
This is useful for recreating tokens from logged or transmitted string data.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func NewAttachmentToken(id string, length int64, metadata map[string]any) *AttachmentToken
NewAttachmentToken creates a new attachment token.
Parameters:
- id: The unique identifier of the attachment (hex-encoded string)
- length: The size of the attachment in bytes
- metadata: Optional metadata associated with the attachment
Returns:
- *AttachmentToken: The created token
Tokens are typically created automatically when creating attachments, but this function allows manual token creation when needed.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (t *AttachmentToken) ID() string
ID returns the unique identifier of the referenced This ID is used to fetch the actual attachment data from the Ditto network.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (t *AttachmentToken) Length() int64
Length returns the size of the referenced attachment in bytes. This can be used to display file sizes or estimate download times before actually fetching the attachment.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (t *AttachmentToken) Metadata() map[string]any
Metadata returns the metadata associated with the referenced attachment. This might include information like content type, original filename, creation date, or any custom attributes defined when the attachment was created.
The returned map is a reference to the internal metadata. Modifications will affect the token's metadata.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (t *AttachmentToken) String() string
String returns a JSON string representation of the token. This is useful for debugging or logging purposes.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (t *AttachmentToken) ToBytes() ([]byte, error)
ToBytes serializes the token to a byte array. This is the format used when storing tokens in documents.
Returns:
- []byte: The serialized token data
- error: An error if serialization fails
The returned bytes can be stored in a document and later deserialized using AttachmentTokenFromBytes.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type AttachmentTokenLike interface { // ToToken converts the implementing type to a AttachmentToken ToToken() *AttachmentToken }
AttachmentTokenLike is an interface for types that can be converted to attachment tokens. This allows for flexible token handling where different types can provide token representations.
Implement this interface on custom types that need to be used as attachment references.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type AuthenticationExpirationHandler
type AuthenticationExpirationHandler func(ditto *Ditto, timeUntilExpiration time.Duration)
AuthenticationExpirationHandler is called when authentication is required or about to expire.
See Authenticator.SetExpirationHandler()
type AuthenticationProvider
type AuthenticationProvider string
AuthenticationProvider encapsulates the authentication provider used to login.
To define a custom authentication provider, wrap the string like this:
mySpecialProvider := ditto.AuthenticationProvider("my-special-provider")
func DevelopmentAuthenticationProvider
func DevelopmentAuthenticationProvider() AuthenticationProvider
DevelopmentAuthenticationProvider returns the built-in development authentication provider to be used together with development authentication tokens.
func (AuthenticationProvider) String
func (p AuthenticationProvider) String() string
String returns the raw underlying authentication provider name as a string.
This method allows AuthenticationProvider to be used directly as a string in contexts that expect a provider name.
type AuthenticationStatus
type AuthenticationStatus struct { // IsAuthenticated is true if authenticated, otherwise false. IsAuthenticated bool // UserId is the user ID if authenticated and one was provided by the service, or otherwise an empty string. UserID string // ClientInfo returns additional information about the authenticated client. ClientInfo map[string]any }
AuthenticationStatus represents the current authentication state.
type AuthenticationStatusObservationHandler
type AuthenticationStatusObservationHandler func(status *AuthenticationStatus)
AuthenticationStatusObservationHandler is called when authentication status changes.
type AuthenticationStatusObserver
type AuthenticationStatusObserver struct { // contains filtered or unexported fields }
AuthenticationStatusObserver allows canceling a status observer.
func (*AuthenticationStatusObserver) Cancel
func (h *AuthenticationStatusObserver) Cancel()
Cancel stops observation and cleans up all associated resources.
After calling Cancel, the observer will no longer be notified of status changes.
type Authenticator
type Authenticator struct { // contains filtered or unexported fields }
Authenticator is used to authenticate with Ditto Cloud. You must set up authentication before you can start syncing.
func (*Authenticator) GetExpirationHandler
func (a *Authenticator) GetExpirationHandler() AuthenticationExpirationHandler
GetExpirationHandler returns the currently set expiration handler.
See Authenticator.SetExpirationHandler()
func (*Authenticator) Login
func (a *Authenticator) Login(token string, provider AuthenticationProvider) (clientInfoJSON string, err error)
Login logs into Ditto with a third-party token.
The login has succeeded if the returned err is nil, or has failed if it is non-nil.
The returned clientInfoJSON string will contain any JSON value returned by the auth webjook endpoint under the "clientInfo" key. This will be returned whether authentication succeeded or failed.
func (*Authenticator) LoginWithCredentials
func (a *Authenticator) LoginWithCredentials(username, password string, provider AuthenticationProvider) (err error)
LoginWithCredentials authenticates with username and password.
Returns nil on success, or an error on failure.
func (*Authenticator) Logout
func (a *Authenticator) Logout(cleanup func(*Ditto))
Logout logs out of Ditto.
This will stop sync, shut down all replication sessions, and remove any cached authentication credentials. Use the optional cleanup closure to perform any required cleanup.
Note that this does not remove any data from the store. The ∂itto instance returned in the cleanup callback will no longer be authorized for write transactions, however, data may be evicted.
If cleanup is not nil, it will be called with the relevant Ditto instance as the sole argument that allows you to perform any required cleanup of the store as part of the logout process.
func (*Authenticator) ObserveStatus
func (a *Authenticator) ObserveStatus(observer AuthenticationStatusObservationHandler) *AuthenticationStatusObserver
ObserveStatus registers an observer callback that will be called whenever authentication status changes.
Returns a AuthenticationStatusObservationHandler that needs to be held as long as you want to receive the updates. Call AuthenticationStatusObservationHandler.Cancel()
func (*Authenticator) SetExpirationHandler
func (a *Authenticator) SetExpirationHandler(handler AuthenticationExpirationHandler)
SetExpirationHandler sets the handler that will be called when authentication for this Ditto instance is about to expire.
Assign a callback function to this property to be notified before authentication expires, allowing you to login or perform other necessary actions.
Important: If the Ditto instance was initialized with DittoConfig.Connect set to DittoConfigConnectServer, this property must be set and the handler must properly authenticate when triggered.
func (*Authenticator) Status
func (a *Authenticator) Status() *AuthenticationStatus
Status returns the current authentication status.
This method never returns nil.
type BluetoothLEConfig struct { // Enabled controls whether Bluetooth LE transport is active Enabled bool `cbor:"enabled" json:"enabled"` }
BluetoothLEConfig configures Bluetooth Low Energy transport.
Bluetooth LE provides:
- Low power consumption
- Works in background on mobile devices
- Range of approximately 10-30 meters
- No pairing required
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type ConnectTransport struct { // TCPServers lists TCP server addresses to connect to (e.g., "192.168.1.100:4040") TCPServers []string `cbor:"tcp_servers" json:"tcp_servers"` // WebsocketURLs lists WebSocket endpoints for cloud sync (e.g., "wss://cloud.ditto.live") WebsocketURLs []string `cbor:"websocket_urls" json:"websocket_urls"` // RetryInterval specifies milliseconds between connection retry attempts (default: 5000) RetryInterval int `cbor:"retry_interval" json:"retry_interval"` }
ConnectTransport configures outgoing connections to Ditto Cloud or custom servers.
This enables synchronization through internet infrastructure when peer-to-peer connections are not available or sufficient.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type Connection
type Connection struct { // ID is a unique identifier for the connection. // // This ID is deterministic for any two peers and a given connection type. ID string `json:"id"` // PeerKeyString1 is the peer key of the peer at one end of the connection, as a string. // // The assignment to PeerKeyString1 and |eerKeyString2 is deterministic and stable for any two peers. PeerKeyString1 string `json:"peerKeyString1"` // PeerKeyString2 is the peer key of the peer at the other end of the connection, as a string. // // The assignment to PeerKeyString1 and PeerKeyString2 is deterministic and stable for any two peers. PeerKeyString2 string `json:"peerKeyString2"` // Type is the type of transport enabling this connection. Type ConnectionType `json:"connectionType"` }
Connection represents an active network connection between two peers in a Ditto mesh network
type ConnectionRequest
type ConnectionRequest struct { PeerKey string PeerMetadata map[string]any IdentityData map[string]any }
ConnectionRequest represents a connection request from a peer
type ConnectionRequestAuthorization
type ConnectionRequestAuthorization ffi.ConnectionRequestAuthorization
ConnectionRequestAuthorization indicates whether a connection request should be authorized.
type ConnectionRequestHandler
type ConnectionRequestHandler func(request *ConnectionRequest) ConnectionRequestAuthorization
ConnectionRequestHandler is a function that handles connection requests.
type ConnectionType
type ConnectionType string
ConnectionType is the type of Connection between two Peers signaling what transport is being used for it.
const ( // ConnectionTypeBluetooth represents Bluetooth Low Energy connections ConnectionTypeBluetooth ConnectionType = "Bluetooth" // ConnectionTypeAccessPoint represents LAN connections via WiFi/Ethernet ConnectionTypeAccessPoint ConnectionType = "AccessPoint" // ConnectionTypeP2PWiFi represents direct WiFi connections (AWDL, Wi-Fi Aware) ConnectionTypeP2PWiFi ConnectionType = "P2PWiFi" // ConnectionTypeWebSocket represents cloud or server-mediated connections ConnectionTypeWebSocket ConnectionType = "WebSocket" )
type Diff
type Diff struct { // Insertions is the set of indexes in the new array at which new items have been inserted. Insertions []int `json:"insertions" cbor:"insertions"` // Deletions is the set of indexes in the old array at which old items have been deleted. Deletions []int `json:"deletions" cbor:"deletions"` // Updates is the set of indexes in the new array at which items have been updated. Updates []int `json:"updates" cbor:"updates"` // Moves is a set of tuples each representing a move of an item from a particular index in the old // array to a particular index in the new array. Moves []Move `json:"moves" cbor:"moves"` }
Diff represents a diff between two arrays.
Create a diff between arrays of QueryResultItem using a Differ.
func (*Diff) Equal
func (d *Diff) Equal(other *Diff) bool
Equal returns true if this Diff is equal to another Diff.
func (*Diff) String
func (d *Diff) String() string
String returns a string representation of the Diff.
This is intended for use in logging and debugging.
type Differ
type Differ struct { // contains filtered or unexported fields }
Differ calculates diffs between arrays of QueryResultItem.
Use a Differ with a StoreObserver to get the diff between subsequent query results delivered by the store observer.
func NewDiffer
func NewDiffer() *Differ
NewDiffer creates a new Differ.
The caller should call Close on the Differ when it is no longer needed, to free the memory it uses.
func (*Differ) Close
func (d *Differ) Close()
Close releases all resources associated with the Differ.
After calling Close, the Differ should not be used.
func (*Differ) DiffItems
func (d *Differ) DiffItems(items []*QueryResultItem) *Diff
DiffItems calculates the diff of the provided items against the last set of items that were passed to this differ.
The returned Diff identifies changes from the old array of items to the new array of items using indices into both arrays.
Initially, the Differ has no items, so the first call to this method will always return a diff showing all items as insertions.
The identity of items is determined by their _id field.
DiffItems does not close any of the items passed into it.
If you have a QueryResult, use DiffResult instead of this method, to avoid the need to manage the lifetimes of the items.
func (*Differ) DiffResult
func (d *Differ) DiffResult(result *QueryResult) *Diff
DiffResult calculates the diff of the provided QueryResult against the last set of items that were passed to this differ.
The returned Diff identifies changes from the old array of items to the new array of items using indices into both arrays.
Initially, the Differ has no items, so the first call to this method will always return a Diff showing all items as insertions.
The identity of items is determined by their _id field.
type DiskUsage struct { // contains filtered or unexported fields }
DiskUsage provides methods to query and monitor disk space used by Ditto.
This component allows you to:
- Query current disk usage
- Monitor usage changes over time
- Identify which components use the most space
Access this via Ditto.DiskUsage().
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (d *DiskUsage) Exec() (*DiskUsageChild, error)
Exec calculates the current disk usage
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (d *DiskUsage) ExecForComponent(component FileSystemType) (*DiskUsageChild, error)
ExecForComponent calculates disk usage for a specific component
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (d *DiskUsage) RegisterObserver(callback DiskUsageCallback) *DiskUsageObserver
RegisterObserver registers a callback for disk usage changes
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type DiskUsageCallback func(usage *DiskUsageChild)
DiskUsageCallback is the function signature for disk usage change notifications.
The callback receives a DiskUsageChild structure containing the current disk usage information whenever it changes.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type DiskUsageChild struct { // Path is the relative path of this component from the root Path string `json:"path"` // SizeInBytes is the total size of this component including children SizeInBytes uint64 `json:"sizeInBytes"` // FileSystemType indicates the type of file system component (optional) FileSystemType FileSystemType `json:"fileSystemType,omitempty"` // Children contains nested components or directories Children []*DiskUsageChild `json:"children,omitempty"` // Metadata contains additional component-specific information Metadata map[string]any `json:"metadata,omitempty"` }
DiskUsageChild represents disk usage information for a component or directory.
This structure forms a tree representing the disk usage hierarchy, with each node containing its size and potentially child nodes.
Example:
usage := dittoInstance.DiskUsage()
root, err := usage.Exec()
if err == nil {
fmt.Printf("Total size: %d bytes\n", root.SizeInBytes)
for _, child := range root.Children {
fmt.Printf(" %s: %d bytes\n", child.Path, child.SizeInBytes)
}
}
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (d *DiskUsageChild) FindByPath(path string) *DiskUsageChild
FindByPath searches for a child with the given path
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (d *DiskUsageChild) GetTotalSize() uint64
GetTotalSize recursively calculates the total size including all children
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type DiskUsageObserver struct { // contains filtered or unexported fields }
DiskUsageObserver represents an active observation of disk usage changes.
Call Stop() to stop receiving updates when no longer needed.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (o *DiskUsageObserver) Cancel()
Cancel stops observing disk usage changes
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type Ditto
type Ditto struct { // contains filtered or unexported fields }
Ditto is the entry point for accessing Ditto-related functionality.
func Open
func Open(config *DittoConfig) (*Ditto, error)
Open creates and returns a new Ditto instance using the provided configuration.
This is the recommended way to initialize Ditto. The method will validate the configuration and establish the necessary internal structures.
Parameters:
- config: The configuration to initialize the new Ditto instance with
Returns:
- The newly created Ditto instance
- An error if initialization fails
Errors:
- if the chosen persistence directory is already in use by another Ditto instance
- if the passed-in DittoConfig's contents do not meet the required validation criteria
func (*Ditto) AbsolutePersistenceDirectory
func (d *Ditto) AbsolutePersistenceDirectory() string
AbsolutePersistenceDirectory returns the absolute path to the persistence directory.
This property returns the fully resolved path where Ditto stores its data, taking into account any relative paths or defaults specified in the configuration.
The value depends on what was specified in DittoConfig.PersistenceDirectory:
- Absolute path: returned unchanged
- Relative path: resolved relative to DefaultRootDirectory()
- Empty string: defaults to "{root}/ditto-{database-id}"
It is not recommended to directly read or write to this directory as its structure is managed by Ditto and may change between versions.
Returns an empty string if the instance is closed.
func (*Ditto) Auth
func (d *Ditto) Auth() *Authenticator
Auth returns the Authenticator instance for this Ditto.
The Authenticator manages authentication for server connections, including:
- Setting expiration handlers for token refresh
- Logging in with tokens or credentials
- Monitoring authentication status
Returns nil if the Ditto instance is not using a server connection (e.g., when using DittoConfigConnectSmallPeersOnly).
func (*Ditto) Close
func (d *Ditto) Close()
Close shuts down the Ditto instance and releases all resources.
This method:
- Stops all synchronization
- Cancels all active observers and subscriptions
- Closes all network connections
- Flushes pending data to disk
- Releases the database lock
After calling Close(), the Ditto instance cannot be used again. Always call Close() when done with a Ditto instance to ensure proper cleanup and to allow other processes to access the database.
Close is idempotent - calling it multiple times is safe.
func (*Ditto) Config
func (d *Ditto) Config() *DittoConfig
Config returns the configuration used to initialize this Ditto instance.
NOTE: Sensitive data such as passphrases and private keys are redacted from the returned configuration and replaced with the string "[REDACTED]".
Returns nil if any errors occur. Any error conditions would be internal errors, not expected in production code.
func (*Ditto) DatabaseID
func (d *Ditto) DatabaseID() string
DatabaseID returns the application identifier for this Ditto instance.
This is the database ID that was set when creating the Ditto configuration. It groups all peers that can synchronize with each other.
Note: In older versions of the Ditto SDK, this was named "AppID".
Returns an empty string if the instance is closed.
func (*Ditto) DeviceName
func (d *Ditto) DeviceName() string
DeviceName returns the human-readable name for this device.
When using Presence.Observe(), each remote peer is represented by a device name. By default, this is a truncated version of the device's hostname.
The device name is used for debugging and peer identification in the Ditto mesh. Names do not need to be unique among peers.
See also: SetDeviceName
func (d *Ditto) DiskUsage() *DiskUsage
DiskUsage returns the DiskUsage API for this Ditto instance
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (*Ditto) IsActivated
func (d *Ditto) IsActivated() bool
IsActivated returns whether the SDK has been activated with a valid license token.
func (*Ditto) IsClosed
func (d *Ditto) IsClosed() bool
IsClosed returns true if the Ditto instance has been closed.
Once closed, a Ditto instance cannot be reopened and all operations will return a DittoError with ErrorCodeInternal.
func (*Ditto) IsEncrypted
func (d *Ditto) IsEncrypted() bool
IsEncrypted indicates whether the Ditto data is encrypted. Returns false if the Ditto instance is closed.
func (*Ditto) Presence
func (d *Ditto) Presence() *Presence
Presence returns the Presence component for monitoring peer connections.
The Presence API allows you to:
- Observe peers in the mesh network
- Monitor connection status and quality
- Track peer metadata and capabilities
The returned Presence instance remains valid for the lifetime of the Ditto instance.
func (*Ditto) SetDeviceName
func (d *Ditto) SetDeviceName(name string)
SetDeviceName sets a custom identifier for this peer.
The device name is visible to other peers in the mesh network and helps identify devices during debugging and monitoring.
Important:
- Changes only take effect after restarting sync
- Names longer than 24 bytes will be truncated
- Names do not need to be unique
Parameters:
- name: The new device name
func (*Ditto) SetOfflineOnlyLicenseToken
func (d *Ditto) SetOfflineOnlyLicenseToken(token string) error
SetOfflineOnlyLicenseToken activates an offline Ditto instance with a license token.
You cannot sync with Ditto before activation. The offline license token is only valid for development and testing scenarios with OfflinePlayground, Manual, or SharedKey identities.
License tokens can be obtained from the Ditto portal (https://portal.ditto.live).
Parameters:
- token: The base64-encoded license token
Returns:
- nil if activation successful
- ErrDittoClosed if the instance is closed
- An error if the token is invalid or expired
func (d *Ditto) SetTransportConfig(config *TransportConfig) error
SetTransportConfig updates the transport configuration.
This method replaces the entire transport configuration with the provided one. Changes take effect immediately if sync is running, or will be applied when sync is next started.
Parameters:
- config: The new transport configuration to apply
Returns:
- nil if successful
- ErrDittoClosed if the instance is closed
- An error if the configuration is invalid or cannot be applied
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (*Ditto) SmallPeerInfo
func (d *Ditto) SmallPeerInfo() *SmallPeerInfo
SmallPeerInfo returns the SmallPeerInfo component for detailed sync information.
SmallPeerInfo provides access to detailed information about sync state, including document synchronization progress and metadata.
The returned SmallPeerInfo instance remains valid for the lifetime of the Ditto instance.
func (*Ditto) Store
func (d *Ditto) Store() *Store
Store returns the Store instance for this Ditto instance.
func (*Ditto) Sync
func (d *Ditto) Sync() *Sync
Sync returns the ditto.Sync instance for this ditto.Ditto instance.
The Sync component manages data synchronization with other peers, including:
- Starting and stopping sync
- Managing subscriptions
- Monitoring sync status
Returns nil if the Ditto instance is closed.
func (d *Ditto) TransportConfig() *TransportConfig
TransportConfig returns the current transport configuration.
The transport configuration controls how this instance discovers and connects to other peers, including:
- Peer-to-peer transports (Bluetooth LE, WiFi Direct, LAN)
- WebSocket connections
- Connection settings and limits
The returned configuration is a snapshot; modifications to it will not affect the running instance unless explicitly set via SetTransportConfig.
See also: SetTransportConfig, UpdateTransportConfig
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (d *Ditto) TransportDiagnostics() (*TransportDiagnostics, error)
TransportDiagnostics returns detailed diagnostic information about network transports.
This method provides comprehensive runtime statistics and debugging information about all configured transports, including:
- Transport enable/disable status
- Active connections and their states
- Connection durations and peer identities
- Transport-specific performance metrics
- Error conditions and warnings
- Peer discovery status
The diagnostics cover all transport types:
- Bluetooth LE: Connection count, scanning status, power state
- LAN: Network interfaces, multicast/mDNS discovery status
- P2P WiFi: AWDL/Wi-Fi Aware availability and active sessions
- WebSocket: Server connections, retry attempts, latency
This information is essential for:
- Debugging connectivity issues
- Monitoring network health
- Understanding sync performance
- Troubleshooting peer discovery problems
Returns:
- *TransportDiagnostics: Current transport status and metrics
- ErrDittoClosed if the instance is closed
- error: If diagnostics cannot be retrieved
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (d *Ditto) UpdateTransportConfig(updateFn func(*TransportConfig))
UpdateTransportConfig safely updates the transport configuration using a callback.
This method retrieves the current configuration, applies your modifications, and atomically updates the transport settings. This is the recommended way to modify transport configuration.
Parameters:
- updateFn: A function that receives the current config and modifies it
Example:
dittoInstance.UpdateTransportConfig(func(config *TransportConfig) {
// Enable only Bluetooth LE
config.PeerToPeer.BluetoothLE.Enabled = true
config.PeerToPeer.LAN.Enabled = false
config.PeerToPeer.AWDL.Enabled = false
})
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type DittoConfig
type DittoConfig struct { // DatabaseID is the unique identifier for the Ditto database. // // This must be a valid UUID string. You can find the database ID in the // Ditto portal, or provide your own if you only need to sync with // small peers only. // // Note: "Database ID" was previously referred to as "App ID" in older // versions of the Ditto SDK. DatabaseID string `cbor:"database_id" json:"databaseId"` // Connect specifies how this instance discovers and connects to peers. // This includes network settings and authentication options. Connect DittoConfigConnectUnion `cbor:"connect" json:"connect"` // PersistenceDirectory specifies where Ditto should persist data. // // Accepts: // - Absolute path: "/path/to/ditto-data" // - Relative path: "./ditto-data" (relative to DefaultRootDirectory) // - Empty string: uses default "{root}/ditto-{database-id}" // // It is not recommended to directly read or write to this directory. PersistenceDirectory string `cbor:"persistence_directory,omitempty" json:"persistenceDirectory,omitempty"` // Experimental allows setting configuration for experimental features. Experimental map[string]any `cbor:"experimental" json:"experimental"` }
DittoConfig is a configuration object for initializing a Ditto instance.
DittoConfig encapsulates all the parameters required to configure a Ditto instance, including identity, connectivity, and persistence.
func DefaultDittoConfig
func DefaultDittoConfig() *DittoConfig
DefaultDittoConfig returns a default DittoConfig instance with standard settings.
This provides a quick starting point for development, but production applications should customize the configuration as needed.
func (*DittoConfig) WithConnect
func (c *DittoConfig) WithConnect(connect DittoConfigConnect) *DittoConfig
WithConnect sets the connection configuration and returns the config for chaining.
Parameters:
- connect: The connection configuration (DittoConfigConnectServer, DittoConfigConnectSmallPeersOnly)
Returns:
- The same DittoConfig instance for chaining
func (*DittoConfig) WithDatabaseID
func (c *DittoConfig) WithDatabaseID(id string) *DittoConfig
WithDatabaseID sets the database ID and returns the config for chaining.
This is a fluent interface method that allows method chaining.
Parameters:
- id: The database ID (UUID string)
Returns:
- The same DittoConfig instance for chaining
func (*DittoConfig) WithPersistenceDirectory
func (c *DittoConfig) WithPersistenceDirectory(dir string) *DittoConfig
WithPersistenceDirectory sets the persistence directory and returns the config for chaining.
Parameters:
- dir: The directory path (absolute, relative, or empty for default)
Returns:
- The same DittoConfig instance for chaining
type DittoConfigConnect
type DittoConfigConnect interface { // contains filtered or unexported methods }
DittoConfigConnect is an interface for different connection configurations.
Implementations determine how a Ditto instance connects to other peers:
- DittoConfigConnectSmallPeersOnly: For peer-to-peer only scenarios
- DittoConfigConnectServer: For production Ditto Cloud connections
type DittoConfigConnectServer
type DittoConfigConnectServer struct { // URL is the server endpoint for cloud sync URL string `cbor:"url" json:"url"` }
DittoConfigConnectServer connects a Ditto instance to a Big Peer at the specified URL.
IMPORTANT: For sync to work with server connections, Ditto requires
- (a) an AuthenticationExpirationHandler to be set via Authenticator.SetExpirationHandler, and
- (b) that handler to properly authenticate when requested. Sync.Start will return an error if the expiration handler is nil.
type DittoConfigConnectSmallPeersOnly
type DittoConfigConnectSmallPeersOnly struct { // PrivateKey is an optional shared secret for mesh encryption. // When provided, only peers with the same key can sync together. PrivateKey []byte `cbor:"private_key,omitempty" json:"privateKey,omitempty"` }
DittoConfigConnectSmallPeersOnly restricts connectivity to small peers only, optionally using a shared secret (in the form of a private key) for authentication.
If a PrivateKey is provided, it will be used as a shared secret for authenticating peer-to-peer connections. The default value is nil, which means no encryption is used in transit.
type DittoConfigConnectType
type DittoConfigConnectType string
const ( DittoConfigConnectTypeServer DittoConfigConnectType = "server" DittoConfigConnectTypeSmallPeersOnly DittoConfigConnectType = "small_peers_only" )
type DittoConfigConnectUnion
type DittoConfigConnectUnion struct { Type DittoConfigConnectType `cbor:"type" json:"type"` *DittoConfigConnectServer `cbor:",omitempty" json:",omitempty"` *DittoConfigConnectSmallPeersOnly `cbor:",omitempty" json:",omitempty"` }
type DittoError struct { // Code is the FFI error code from dittoffi_error_code_t enumeration. Code int // Message provides a human-readable description of the error. Message string // Err is the underlying error that caused this DittoError, if any. // This allows for error wrapping and unwrapping using the standard // errors.Unwrap function. Err error }
DittoError represents an error from the Ditto SDK.
All errors that are returned by the Ditto SDK are wrapped as a DittoError. This type wraps multiple different types of error that each have an associated reason. You can access more specific information about an error by checking the error's Code value.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (*DittoError) Error
func (e *DittoError) Error() string
Error implements the error interface for DittoError.
Returns a formatted string containing both the error code and message in the format: "DittoError(code): message" If there's an underlying error, it includes that information as well.
func (*DittoError) Is
func (e *DittoError) Is(target error) bool
Is implements the errors.Is interface for DittoError.
This allows for error comparison using errors.Is, matching errors by their code rather than exact instance or message. This is useful for checking against common error conditions even when the message might differ.
Example:
err := dittoInstance.Sync().Start()
if errors.Is(err, ErrDittoClosed) {
// Handle closed instance
}
Example
ExampleDittoError_Is demonstrates how to use errors.Is with DittoError to check for specific error conditions regardless of the error message.
package main import ( "errors" "fmt" "github.com/getditto/ditto-go-sdk/v5/ditto" "github.com/getditto/ditto-go-sdk/v5/internal/ffi" ) func main() { // SDK-level errors use ErrorCodeInternal err := &ditto.DittoError{ Code: ffi.ErrorCodeInternal, Message: "The Ditto instance has been closed and cannot be used", } // Check if it's an internal error using errors.Is internalErr := &ditto.DittoError{Code: ffi.ErrorCodeInternal, Message: "Ditto instance is closed"} if errors.Is(err, internalErr) { fmt.Println("Internal SDK error") } // FFI-returned errors would have specific FFI error codes // This simulates an error that would be returned from the FFI layer ffiErr := &ditto.DittoError{ Code: ffi.ErrorCodeDqlQueryCompilation, Message: "Query syntax error at position 42", } // Check for specific FFI error code queryErr := &ditto.DittoError{Code: ffi.ErrorCodeDqlQueryCompilation, Message: "Invalid DQL query"} if errors.Is(ffiErr, queryErr) { fmt.Println("Query compilation error from FFI") } }
Output:
Internal SDK error Query compilation error from FFI
func (*DittoError) Unwrap
func (e *DittoError) Unwrap() error
Unwrap implements the errors.Unwrap interface for DittoError.
This allows for error chain inspection using errors.Unwrap, errors.As, and errors.Is with wrapped errors.
Example:
err := someOperation()
var pathErr *os.PathError
if errors.As(err, &pathErr) {
// Handle path error
}
type Document
type Document map[string]any
Document represents a document stored in a Ditto collection.
It is a map of string keys to JSON values.
type FetchCallback func(event *AttachmentFetchEvent)
FetchCallback is the function signature for attachment fetch event callbacks. This function is called whenever there is a progress update, completion, failure, or cancellation of an attachment fetch operation.
The callback is called from a background goroutine and should not perform long-running operations that could block progress updates.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type FetchEventType int
FetchEventType represents the type of fetch event. Events are delivered in sequence: multiple progress events, followed by exactly one terminal event (completed, failed, or canceled).
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
const ( // FetchEventTypeProgress indicates a fetch progress update. // These events are sent periodically during download to report progress. // // Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time. FetchEventTypeProgress FetchEventType = iota // FetchEventTypeCompleted indicates the fetch completed successfully. // The attachment is now available locally at the path specified in the event. // // Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time. FetchEventTypeCompleted // FetchEventTypeFailed indicates the fetch failed with an error. // The Error field contains details about what went wrong. // // Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time. FetchEventTypeFailed // FetchEventTypeCanceled indicates the fetch was canceled by the user. // This happens when Cancel() is called on the fetcher. // // Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time. FetchEventTypeCanceled )
type FileSystemType int
FileSystemType represents different types of file systems used by Ditto.
Ditto organizes its persistent data into different file system components, each serving a specific purpose in the synchronization and storage system.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
const ( // FileSystemRoot represents the root file system containing all Ditto data. // This includes all sub-components and is typically the persistence directory. // // Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time. FileSystemRoot FileSystemType = iota // FileSystemStore represents the main document store file system. // This contains the actual document data and indexes. // // Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time. FileSystemStore // FileSystemAuth represents the authentication file system. // This stores authentication credentials and tokens. // // Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time. FileSystemAuth // FileSystemReplication represents the replication file system. // This contains sync metadata and replication logs. // // Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time. FileSystemReplication // FileSystemAttachments represents the attachments file system. // This stores binary attachments associated with documents. // // Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time. FileSystemAttachments )
type GlobalConfig struct { // SyncGroup partitions the mesh network (0 = default group) // Devices only sync with others in the same sync group SyncGroup uint32 `cbor:"sync_group" json:"sync_group"` // RoutingHint provides a hint for connection routing optimization RoutingHint uint32 `cbor:"routing_hint" json:"routing_hint"` }
GlobalConfig contains global transport settings that affect all transports.
These settings control advanced routing and grouping behaviors.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type LANConfig struct { // Enabled controls whether LAN transport is active Enabled bool `cbor:"enabled" json:"enabled"` // MDNSEnabled allows peer discovery via mDNS/Bonjour MDNSEnabled bool `cbor:"mdns_enabled" json:"mdns_enabled"` // MulticastEnabled allows peer discovery via multicast packets MulticastEnabled bool `cbor:"multicast_enabled" json:"multicast_enabled"` }
LANConfig configures Local Area Network transport.
LAN transport enables high-speed sync between devices on the same network. It uses TCP/IP for reliable data transfer and supports both multicast discovery and mDNS (Bonjour) for finding peers.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type ListenConfig struct { // TCP configures raw TCP listening TCP ListenTCPConfig `cbor:"tcp" json:"tcp"` // HTTP configures HTTP/WebSocket listening HTTP ListenHTTPConfig `cbor:"http" json:"http"` }
ListenConfig configures this device to accept incoming connections.
This is typically used for:
- Creating a local sync server
- Bridging between network segments
- Debugging and monitoring
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type ListenHTTPConfig struct { // Enabled controls whether to listen for HTTP connections Enabled bool `cbor:"enabled" json:"enabled"` // InterfaceIP is the network interface to bind to (default: "[::]" for all interfaces) InterfaceIP string `cbor:"interface_ip" json:"interface_ip"` // Port is the HTTP port to listen on (default: 80) Port int `cbor:"port" json:"port"` // WebsocketSync enables WebSocket connections for data sync WebsocketSync bool `cbor:"websocket_sync" json:"websocket_sync"` // StaticContentPath serves static files from this directory (optional) StaticContentPath string `cbor:"static_content_path,omitempty" json:"static_content_path,omitempty"` // TLSKeyPath is the path to the TLS private key file (optional, enables HTTPS) TLSKeyPath string `cbor:"tls_key_path,omitempty" json:"tls_key_path,omitempty"` // TLSCertificatePath is the path to the TLS certificate file (optional, enables HTTPS) TLSCertificatePath string `cbor:"tls_certificate_path,omitempty" json:"tls_certificate_path,omitempty"` }
ListenHTTPConfig configures HTTP/WebSocket server listening.
This enables other devices to connect via WebSocket for synchronization and optionally serves static content for web applications.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type ListenTCPConfig struct { // Enabled controls whether to listen for TCP connections Enabled bool `cbor:"enabled" json:"enabled"` // InterfaceIP is the network interface to bind to (default: "[::]" for all interfaces) InterfaceIP string `cbor:"interface_ip" json:"interface_ip"` // Port is the TCP port to listen on (default: 4040) Port int `cbor:"port" json:"port"` }
ListenTCPConfig configures TCP server listening.
When enabled, other Ditto instances can connect to this device using the TCP transport.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type LogLevel
type LogLevel ffi.LogLevel
LogLevel represents the different log levels supported by the Ditto logger.
func GetMinimumLogLevel
func GetMinimumLogLevel() LogLevel
GetMinimumLogLevel returns the minimum log level at which logs will be logged, provided the logger is enabled.
For example if this is set to DittoLogLevel.warning, then only logs that are logged with the LogLevelWarning or LogLevelError log levels will be shown.
Logs exported through ExportLog are not affected by this setting and include all logs at LogLevelDebug and above.
func (LogLevel) String
func (l LogLevel) String() string
String returns the string representation of the LogLevel
type Move
type Move struct { // From is the index in the old array from which the item has been moved. From int `json:"from" cbor:"from"` // To is the index in the new array to which the item has been moved. To int `json:"to" cbor:"to"` }
Move represents a move of an item from a particular index in the old array to a particular index in the new array.
func (Move) String
func (m Move) String() string
String returns a string representation of the Move.
This is intended for use in logging and debugging.
type Peer
type Peer struct { // Address uniquely identifies a peer within a Ditto mesh network. // // Deprecated: use PeerKeyString instead. Address Address // PeerKeyString is a unique identifier for a given peer, equal to or derived from the cryptographic public key used to authenticate it. // // NOTE: This will be nil or empty when a peer is not updated to the latest version of the SDK. PeerKeyString string `json:"peerKeyString"` // Connections is the set of currently active connections of the peer. May be nil or empty. Connections []*Connection `json:"connections"` // DeviceName is the human-readable device name of the remote peer. // // This defaults to the hostname but can be manually set by the application developer of the other peer. It is not necessarily unique. DeviceName string `json:"deviceName"` // OS is the operating system of the remote peer. // // Note: When running on a Mac in the Mac Catalyst environment, the value returned will be iOS. OS PeerOS `json:"os,omitempty"` // IsConnectedToDittoCloud indicates whether the peer is connected to Ditto Cloud IsConnectedToDittoCloud bool `json:"isConnectedToDittoCloud"` // IsCompatible indicates whether the peer is compatible with the current peer. IsCompatible bool `json:"isCompatible"` // DittoSDKVersion is the Ditto SDK version the peer is running with. DittoSDKVersion string `json:"dittoSdkVersion"` // PeerMetadata is metadata associated with the peer, nil by default. // // Use Presence.SetPeerMetadata() Presence.SetPeerMetadataJSONData() to set this value. // // Peer metadata is dynamic and may change over the lifecycle of the DittoPresenceGraph. It may be nil or empty when // a remote peer initially appears in the presence graph and will be updated once the peer has synced its metadata // with the local peer. // // See also: Presence.SetPeerMetadata() for details on usage of metadata PeerMetadata map[string]any `json:"peerMetadata"` // IdentityServiceMetadata is metadata associated with the peer by the identity service. May be nil or empty. // // Use an authentication webhook to set this value. See Ditto’s online documentation for more information on how to // configure an authentication webhook. IdentityServiceMetadata map[string]any `json:"identityServiceMetadata"` }
Peer represents a peer in a Ditto mesh network
type PeerOS
type PeerOS string
PeerOS represents the operating system of a peer
Note: When running on a Mac in the Mac Catalyst environment, the OS is classified as iOS
const ( // PeerOSUnknown is returned when a peer's operating system has not been determined PeerOSUnknown PeerOS = "" // PeerOSGeneric represents a general other operating system PeerOSGeneric PeerOS = "Generic" // PeerOSiOS represents Apple iOS devices (iPhone, iPad) PeerOSiOS PeerOS = "iOS" // PeerOStvOS represents Apple tvOS devices (Apple TV) PeerOStvOS PeerOS = "tvOS" // PeerOSAndroid represents Android devices PeerOSAndroid PeerOS = "Android" // PeerOSLinux represents Linux systems PeerOSLinux PeerOS = "Linux" // PeerOSWindows represents Microsoft Windows systems PeerOSWindows PeerOS = "Windows" // PeerOSmacOS represents Apple macOS systems PeerOSmacOS PeerOS = "macOS" )
type PeerToPeerConfig struct { // BluetoothLE enables Bluetooth Low Energy transport (all platforms) BluetoothLE BluetoothLEConfig `cbor:"bluetooth_le" json:"bluetooth_le"` // LAN enables Local Area Network transport via TCP/IP LAN LANConfig `cbor:"lan" json:"lan"` // AWDL enables Apple Wireless Direct Link (iOS/macOS only) AWDL AWDLConfig `cbor:"awdl" json:"awdl"` // WifiAware enables Wi-Fi Aware transport (Android only) WifiAware WifiAwareConfig `cbor:"wifi_aware" json:"wifi_aware"` }
PeerToPeerConfig configures direct peer-to-peer communication transports.
These transports enable devices to sync directly without internet connectivity. Multiple transports can be enabled simultaneously for maximum connectivity.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type Presence
type Presence struct { // contains filtered or unexported fields }
Presence is the entrypoint for all actions that relate presence of other peers known by the current peer, either directly or through other peers.
Presence can be accessed from a Ditto instance via its Ditto.Presence() method.
func (*Presence) GetPeerMetadata
func (p *Presence) GetPeerMetadata() (map[string]any, error)
GetPeerMetadata gets metadata associated with the current peer.
Other peers in the same mesh can access this user-provided dictionary of metadata via the presence graph from Presence.Graph() and when evaluating connection requests using Presence.SetConnectionRequestHandler. Use SetPeerMetadata() or SetPeerMetadataJSONData() to set this value.
This is a convenience property that wraps GetPeerMetadataJSONData.
func (*Presence) GetPeerMetadataJSONData
func (p *Presence) GetPeerMetadataJSONData() ([]byte, error)
GetPeerMetadataJSONData gets metadata associated with the current peer.
Other peers in the same mesh can access this user-provided dictionary of metadata via the presence graph from Presence.Graph() and when evaluating connection requests using Presence.SetConnectionRequestHandler. Use SetPeerMetadata() or SetPeerMetadataJSONData() to set this value.
This is a convenience property that wraps GetPeerMetadataJSONData.
func (*Presence) Graph
func (p *Presence) Graph() *PresenceGraph
Graph returns the current presence graph capturing all known peers and connections between them.
func (*Presence) Observe
func (p *Presence) Observe(callback PresenceObservationHandler) *PresenceObserver
Observe requests information about Ditto peers in range of this device.
This method returns an observer which should be held as long as updates are required. Call the PresenceObserver.Stop() method to cease updates.
A newly registered observer will have a peers update delivered to it immediately. From then on it will be invoked repeatedly when Ditto devices come and go, or the active connections to them change.
func (*Presence) SetConnectionRequestHandler
func (p *Presence) SetConnectionRequestHandler(handler ConnectionRequestHandler)
SetConnectionRequestHandler registers a handler function to control which peers in a Ditto mesh can connect to the current peer.
Each peer in a Ditto mesh will attempt to connect to other peers that it can reach. By default, the mesh will try and establish connections that optimize for the best overall connectivity between peers. However, you can set this handler to assert some control over which peers you connect to.
If set, this handler is called for every incoming connection request from a remote peer and is passed the other peer’s PeerKeyString, PeerMetadata, and IdentityServiceMetadata. The handler can then accept or reject the request by returning an according DittoConnectionRequestAuthorization value. When the connection request is rejected, the remote peer may retry the connection request after a short delay.
Connection request handlers must reliably respond to requests within a short time. If a handler takes too long to respond or throws an exception, the connection request will be denied. The response currently times out after 10 seconds, but this exact value may be subject to change in future releases.
Note: The handler is called from a different thread.
func (*Presence) SetPeerMetadata
func (p *Presence) SetPeerMetadata(metadata map[string]any) error
SetPeerMetadata sets metadata associated with the current peer.
Other peers in the same mesh can access this user-provided dictionary of metadata via the presence graph from Presence.Graph() and when evaluating connection requests using Presence.SetConnectionRequestHandler. Use SetPeerMetadata() or SetPeerMetadataJSONData() to set this value.
This is a convenience property that wraps SetPeerMetadataJSONData().
func (*Presence) SetPeerMetadataJSONData
func (p *Presence) SetPeerMetadataJSONData(jsonData []byte) error
SetPeerMetadataJSONData sets metadata from JSON data
Other peers in the same mesh can access this user-provided dictionary of metadata via the presence graph from Presence.Graph() and when evaluating connection requests using Presence.SetConnectionRequestHandler. Use SetPeerMetadata() or SetPeerMetadataJSONData() to set this value.
Uses UTF-8 encoding.
type PresenceGraph
type PresenceGraph struct { // LocalPeer returns the local peer (usually the peer that is represented by the currently running Ditto instance). // The LocalPeer is the entry point, all others are remote peers known by the local peer (either directly or via other // remote peers). LocalPeer *Peer `json:"localPeer,omitempty"` // RemotePeers is all remote peers known by the localPeer, either directly or via other remote peers. RemotePeers []*Peer `json:"remotePeers,omitempty"` // AllConnectionsByID is a dictionary with all connections found in this graph by their IDs. AllConnectionsByID map[string]*Connection `json:"-"` }
PresenceGraph represents the Ditto mesh network of peers and their connections between each other.
The local peer is the entry point, all others are remote peers known by the local peer (either directly or via other remote peers).
func (*PresenceGraph) ToJSON
func (g *PresenceGraph) ToJSON() ([]byte, error)
ToJSON converts the graph to JSON
type PresenceObservationHandler
type PresenceObservationHandler func(graph *PresenceGraph)
PresenceObservationHandler is called for each peer change
type PresenceObserver
type PresenceObserver struct { // contains filtered or unexported fields }
PresenceObserver represents an active presence observation subscription.
PresenceObservers are created through Presence.Observe() and should be retained as long as updates are needed. Call Stop() to cease receiving updates
func (*PresenceObserver) Stop
func (o *PresenceObserver) Stop()
Stop terminates the observer and cleans up all associated resources.
type QueryArguments
type QueryArguments map[string]any
QueryArguments is a map of string keys to JSON values.
It is used in calls to Execute(), RegisterObserver(), and RegisterSubscription()..
type QueryExecutor
type QueryExecutor interface { // Execute executes a DQL query and returns matching items as a query result. // // The caller must close the returned QueryResult after extracting data from it. // // If multiple arguments are provided, they will be merged into a single map before being passed to the query engine. // // NOTE: Only returns results from the local store without waiting for any SyncSubscription to have // caught up with the latest changes. Only use this method if your program must proceed with immediate results. // Use a StoreObserver to receive updates to query results as soon as they have been synced to this peer. // // Parameters: // - query: A string containing a valid query expressed in DQL // - arguments: Optional variadic query arguments (dictionaries of values keyed by placeholder name without the leading ':') // // Returns an error if: // - query is not valid DQL // - arguments are not valid (contain unsupported types) // - a mutating query is attempted in a read-only transaction (Transaction only) // - a database store error occurs Execute(query string, arguments ...QueryArguments) (*QueryResult, error) }
QueryExecutor defines the interface for executing DQL queries.
This interface is implemented by Store and Transaction, allowing both to execute DQL queries with the same method signature.
type QueryResult
type QueryResult struct { // contains filtered or unexported fields }
QueryResult represents the result set from executing a DQL query.
QueryResult provides methods to access individual items, iterate through results, and retrieve metadata about query execution. Results are immutable once created.
When a QueryResult is returned from a query, the caller should extract necessary data from it and then call the Close() method to free associated resources in the underlying query engine.
func (*QueryResult) Close
func (r *QueryResult) Close()
Close releases any FFI resources associated with this result.
Always call Close when done with a QueryResult to prevent memory leaks. It's safe to call Close multiple times.
Note: This does NOT close the individual QueryResultItems. Each QueryResultItem manages its own lifecycle independently and may outlive the QueryResult. QueryResultItems will be garbage collected and finalized when no longer referenced.
func (*QueryResult) CommitID
func (r *QueryResult) CommitID() (uint64, bool)
CommitID returns the commit ID associated with this query result, if any.
This ID uniquely identifies the state of the local store after the query was executed. The commit ID is available for all query results that reflect committed data.
For write transactions, the commit ID is only available after the transaction has been successfully committed. Queries executed within an uncommitted transaction will not have a commit ID.
func (*QueryResult) Item
func (r *QueryResult) Item(i int) *QueryResultItem
Item returns the item in the result set with index i. Returns nil if index is out of bounds or the item cannot be retrieved.
func (*QueryResult) ItemCount
func (r *QueryResult) ItemCount() int
ItemCount returns the total number of items in the result set.
func (*QueryResult) Items
func (r *QueryResult) Items() iter.Seq2[int, *QueryResultItem]
Items returns an iterator of the items matching a DQL query
Each item will be automatically closed after the iteration. Note that this means references to the items should not be held. Use itemsAsSlice if you need longer-lived references to the items.
func (*QueryResult) MutatedDocumentIDs
func (r *QueryResult) MutatedDocumentIDs() []any
MutatedDocumentIDs returns the IDs of documents that were mutated locally by a mutating DQL query passed to Execute(). Empty slice if no documents have been mutated. nil if an error occurs.
NOTE: A StoreObserver can only be registered with a SELECT query, which is non-mutating, and thus the query result passed to the StoreObservationHandler always returns an empty array in that case.
IMPORTANT: The returned document IDs are not cached. Make sure to call this method once and keep the return value for as long as needed.
func (*QueryResult) Values
func (r *QueryResult) Values() []Document
Values returns the Document value for each item in the result set.
type QueryResultItem
type QueryResultItem struct { // contains filtered or unexported fields }
QueryResultItem represents a single match of a DQL query, similar to a "row" in SQL terms. It's a reference type serving as a "cursor", allowing for efficient access of the underlying data in various formats.
The Value property is lazily materialized and kept in memory until it goes out of scope. To reduce the memory footprint, structure your code such that items can be processed as a stream, i.e. one by one (or in batches) and Dematerialize() or Close() them right after use.
func (*QueryResultItem) CBORData
func (i *QueryResultItem) CBORData() []byte
CBORData returns the content of the item as CBOR data.
Returns nil on error.
Important: The returned CBOR data is not cached, make sure to call this method once and keep the returned data for as long as needed.
func (*QueryResultItem) Close
func (i *QueryResultItem) Close()
Close releases any internal resources associated with this item.
After calling Close, the item becomes invalid and should not be used. It's safe to call Close multiple times.
func (*QueryResultItem) Dematerialize
func (i *QueryResultItem) Dematerialize()
Dematerialize releases the materialized value from memory. No-op if item is not materialized.
Note: If you will not need to materialize the value again, use Close() instead to free all underlying resources.
func (*QueryResultItem) IsMaterialized
func (i *QueryResultItem) IsMaterialized() bool
IsMaterialized returns true if value is currently held materialized in memory, otherwise returns false.
See also
- Materialize()
- Dematerialize()
func (*QueryResultItem) JSONData
func (i *QueryResultItem) JSONData() []byte
JSONData returns the content of the item as JSON data containing a UTF-8 encoded string.
Important: The returned JSON data is not cached, make sure to call this method once and keep returned data for as long as needed.
func (*QueryResultItem) JSONString
func (i *QueryResultItem) JSONString() string
JSONString deserializes the item value to a JSON string.
Returns an error if the value cannot be marshaled to JSON.
func (*QueryResultItem) Materialize
func (i *QueryResultItem) Materialize()
Materialize loads the CBOR representation of the item's content, decodes it as a dictionary so it can be accessed via Value(). Keeps the dictionary in memory until Dematerialize() or Close() is called. No-op if value is already materialized.
func (*QueryResultItem) UnmarshalTo
func (i *QueryResultItem) UnmarshalTo(v any) error
UnmarshalTo decodes the query result into the value pointed to by v.
Returns an error if the result cannot be retrieved, or if there is an error decoding the result into the destination.
func (*QueryResultItem) Value
func (i *QueryResultItem) Value() Document
Value returns the content as a materialized dictionary.
The item's value is materialized on first access and subsequently on each access after performing Dematerialize(). Once materialized, the value is kept in memory until explicitly dematerialized or closed, or the item is garbage collected.
Returns nil if this QueryResultItem has been closed.
type SignalNext
type SignalNext func()
SignalNext is a function that signals the observer to deliver the next update.
This function is provided to StoreObservationHandlerWithSignalNext to control the flow of updates. Call this function when your application is ready to receive the next change notification.
type SmallPeerInfo
type SmallPeerInfo struct { // contains filtered or unexported fields }
SmallPeerInfo is the entrypoint for small peer user info collection. Small peer info consists of information gathered into a system collection on a regular interval and optionally synced to the Big Peer for device dashboard and debugging purposes.
You don't create this class directly, but can access it from a particular Ditto instance via its Ditto.SmallPeerInfo method.
func (*SmallPeerInfo) IsEnabled
func (s *SmallPeerInfo) IsEnabled() bool
IsEnabled indicates whether small peer info collection is currently enabled, defaults to `true`.
Note: whether the background ingestion process is enabled or not is a separate decision to whether this information is allowed to sync to other peers (including the big peer). This is controlled by sync scopes.
func (*SmallPeerInfo) Metadata
func (s *SmallPeerInfo) Metadata() map[string]any
Metadata Returns the JSON metadata being associated with the small peer info.
Returns:
- map[string]any: The current metadata dictionary
- an empty map if there is an error retrieving or unmarshalling the metadata or if no metadata has been set.
func (*SmallPeerInfo) MetadataJSONString
func (s *SmallPeerInfo) MetadataJSONString() string
MetadataJSONString Returns the JSON metadata being associated with the small peer info.
Returns:
- non-empty JSON string: The current metadata dictionary
- empty string if there is an error retrieving the metadata or if no metadata has been set.
func (*SmallPeerInfo) SetEnabled
func (s *SmallPeerInfo) SetEnabled(enabled bool) error
SetEnabled sets whether small peer info collection is currently enabled.
func (*SmallPeerInfo) SetMetadata
func (s *SmallPeerInfo) SetMetadata(metadata map[string]any) error
SetMetadata sets the JSON metadata to be associated with the small peer info.
The metadata is a free-form, user-provided dictionary that is serialized into JSON and is inserted into the small peer info system doc at each collection interval. The dictionary has no schema except for the following constraints:
- All contained values must be JSON serializable.
- The size of the dictionary serialized as JSON may not exceed 128 KB.
- The dictionary may only be nested up to 64 levels deep.
func (*SmallPeerInfo) SetMetadataJSONString
func (s *SmallPeerInfo) SetMetadataJSONString(jsonStr string) error
SetMetadataJSONString sets the JSON metadata to be associated with the small peer info.
The metadata is a free-form, user-provided dictionary that is serialized into JSON and is inserted into the small peer info system doc at each collection interval. The dictionary has no schema except for the following constraints:
- All contained values must be JSON serializable.
- The size of the dictionary serialized as JSON may not exceed 128 KB.
- The dictionary may only be nested up to 64 levels deep.
type Store
type Store struct { // contains filtered or unexported fields }
Store is the entrypoint for all actions that relate to data stored by Ditto.
You don't create one directly but can access it from a particular Ditto instance via its store property.
func (*Store) Execute
func (s *Store) Execute(query string, args ...QueryArguments) (*QueryResult, error)
Execute executes a DQL query and returns matching items as a query result.
The caller must close the returned QueryResult after extracting data from it.
If multiple arguments are provided, they will be merged into a single map before being passed to the query engine.
NOTE: Only returns results from the local store without waiting for any SyncSubscription to have caught up with the latest changes. Only use this method if your program must proceed with immediate results. Use a StoreObserver to receive updates to query results as soon as they have been synced to this peer.
Parameters:
- query: A string containing a valid query expressed in DQL
- args: Optional variadic query arguments (dictionaries of values keyed by placeholder name without the leading ':')
Returns an error if:
- query is not valid DQL
- arguments are not valid (contain unsupported types)
- a database store error occurs
func (s *Store) FetchAttachment(token *AttachmentToken, callback FetchCallback) (*AttachmentFetcher, error)
FetchAttachment retrieves an attachment using its token.
This method initiates the fetch of an attachment, which may need to be downloaded from other peers if not available locally. The callback is invoked with progress updates and when the fetch completes or fails.
Parameters:
- token: The attachment token obtained from a document
- callback: Function called with fetch progress events
The callback receives AttachmentFetchEvent values indicating:
- Progress: Download progress with bytes transferred
- Completed: Attachment successfully fetched
- Deleted: Attachment was deleted
Returns a AttachmentFetcher that can be used to cancel the fetch. Keep this object alive for the duration of the fetch operation.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (s *Store) NewAttachment(path string, metadata map[string]any) (*Attachment, error)
NewAttachment creates a new attachment from a file on disk.
The file at the specified path is copied into Ditto's store. The returned Attachment object can then be inserted into a document. The attachment and its metadata will be replicated to other peers.
Parameters:
- path: Absolute or relative path to the file
- metadata: Optional metadata to associate with the attachment
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (*Store) Observers
func (s *Store) Observers() []*StoreObserver
Observers returns all currently active store observers.
This method provides visibility into all observers that are currently registered and monitoring for changes to query results.
Returns:
- A slice of active StoreObserver instances
- nil if an error occurs
The returned slice is a snapshot of observers at the time of the call. Observers may be added or removed after this method returns.
The order of the values in the result is not defined, and may vary between calls. The result should be treated as an unordered set.
func (*Store) RegisterObserver
func (s *Store) RegisterObserver(query string, args QueryArguments, handler StoreObservationHandler) (*StoreObserver, error)
RegisterObserver installs and returns a store observer for a query, configuring Ditto to trigger the passed in change handler whenever documents in the local store change such that the result of the matching query changes.
The passed in query must be a SELECT query, otherwise a store error is returned.
Use a Differ to calculate a diff between subsequent results delivered to the change handler.
The first invocation of the change handler will happen shortly after this method has returned.
The observer will remain active until:
- the observer.Cancel() method is called, or
- the owning Ditto instance has shut down
Parameters:
- query: A string containing a valid SELECT query expressed in DQL
- args: A dictionary of values keyed by the placeholder name without the leading ':'. Example: QueryArguments{"mileage": 123}. Can be nil for queries without parameters.
- handler: Function called when query results change
Returns:
- An active StoreObserver for the passed in query and arguments. You'll have to keep it to be able to cancel the observation. Otherwise it will remain active until the owning Ditto object goes out of scope.
Returns an error if:
- query is not valid DQL
- query is not a SELECT query
- arguments are not valid (contain unsupported types)
Call the returned StoreObserver's Cancel() method to stop observing changes.
func (*Store) RegisterObserverWithSignalNext
func (s *Store) RegisterObserverWithSignalNext(query string, args QueryArguments, handler StoreObservationHandlerWithSignalNext) (*StoreObserver, error)
RegisterObserverWithSignalNext creates a store observer with backpressure control.
This variant of RegisterObserver provides flow control for high-frequency updates. The callback receives both the query result and a signal function that must be called when the application is ready to receive the next update. This prevents overwhelming the application with rapid changes.
The signal function should be called after processing each update to indicate readiness for the next one. The next invocation of the callback will coalesce the changes since the previous one.
After invoking the callback once, the observer will wait to deliver another callback until after you've called SignalNext.
Parameters:
- query: A SELECT query in DQL format
- args: Optional query parameter maps
- handler: Function called with results and a signal function
Use this method when:
- Query results change frequently
- Processing updates is computationally expensive
- You need to control the rate of updates
func (*Store) Transaction
func (s *Store) Transaction(opts *TransactionOptions, fn func(*Transaction) (TransactionCompletionAction, error)) (TransactionCompletionAction, error)
Transaction executes multiple DQL queries within a single atomic transaction.
This ensures that either all statements are executed successfully, or none are executed at all, providing strong consistency guarantees. Certain mesh configurations may impose limitations on these guarantees. For more details, refer to the Ditto documentation at https://ditto.live/link/sdk-latest-crud-transactions.
Transactions are initiated as read-write transactions by default, and only a single read-write transaction is being executed at any given time. Any other read-write transaction started concurrently will wait until the current transaction has been committed or rolled back. Therefore, it is crucial to make sure a transaction finishes as early as possible so other read-write transactions aren't blocked for a long time.
A transaction can also be configured to be read-only using TransactionOptions. Multiple read-only transactions can be executed concurrently. However, executing a mutating DQL statement in a read-only transaction will return an error.
If errors occur in an Execute() call within a transaction function and the error is caught and handled within the function, the transaction will continue to run and not be rolled back. When an error is returned at any point from the transaction function or while committing the transaction, the transaction is implicitly rolled back and the error is returned to the caller.
When a Ditto instance goes out of scope, it will drive all pending transactions to completion before being shut down.
Important: Calling Store.Execute() or creating a nested transaction within a transaction may lead to a deadlock.
For a complete guide on transactions, please refer to the Ditto documentation at https://ditto.live/link/sdk-latest-crud-transactions.
Parameters:
- opts: Optional transaction configuration. Can be nil to use defaults (no hint, read-write transaction).
- fn: Function to execute within the transaction. It receives a Transaction object and should return the desired completion action (commit or rollback) and any error encountered.
Returns:
- TransactionCompletionAction: The action taken (commit or rollback)
- error: An error if the transaction fails, or any error returned from fn
type StoreObservationHandler
type StoreObservationHandler func(*QueryResult)
StoreObservationHandler is the callback function invoked when query results change.
The callback receives the current QueryResult containing all documents that match the observer's query. The callback is invoked:
- Immediately after registration with the initial results
- Whenever documents matching the query are added, updated, or removed
Callbacks are executed on a separate goroutine and should be thread-safe. Long-running operations in the callback may delay subsequent updates.
type StoreObservationHandlerWithSignalNext
type StoreObservationHandlerWithSignalNext func(*QueryResult, SignalNext)
StoreObservationHandlerWithSignalNext is called when query results change with flow control.
This callback variant provides backpressure control for high-frequency updates. The callback receives both the QueryResult and a SignalNext function that must be called to indicate readiness for the next update.
type StoreObserver
type StoreObserver struct { // contains filtered or unexported fields }
StoreObserver represents an active observation of a DQL query.
A StoreObserver monitors a SELECT query and notifies when matching documents change in the local store. The observer remains active until explicitly canceled or until the Ditto instance is closed.
Observers provide real-time updates as data changes due to:
- Local modifications
- Sync updates from remote peers
- Conflict resolution
Example:
observer, err := RegisterObserver(
"SELECT * FROM tasks WHERE completed = false",
func(result *QueryResult) {
fmt.Printf("Active tasks: %d\n", result.ItemCount())
},
)
defer observer.Cancel()
Thread Safety: All StoreObserver methods are thread-safe.
func (*StoreObserver) Cancel
func (o *StoreObserver) Cancel()
Cancel stops the observer and releases its resources.
After calling Cancel, the observer will no longer receive updates and its callback will not be invoked. This method is idempotent - calling it multiple times has no additional effect.
It's recommended to call Cancel when the observer is no longer needed to free resources and prevent unnecessary processing.
func (*StoreObserver) Ditto
func (o *StoreObserver) Ditto() *Ditto
Ditto returns the Ditto instance that this store observer is registered with
func (*StoreObserver) IsCanceled
func (o *StoreObserver) IsCanceled() bool
IsCanceled returns true if the observer has been canceled.
A canceled observer no longer receives updates. An observer is considered canceled if:
- Cancel() was explicitly called
- The owning Store was closed
- The Ditto instance was shut down
func (*StoreObserver) QueryArguments
func (o *StoreObserver) QueryArguments() map[string]any
QueryArguments returns the query arguments for this observer.
Returns the map of named parameters that was provided when the observer was registered. The returned map is a copy and modifications to it do not affect the observer.
func (*StoreObserver) QueryString
func (o *StoreObserver) QueryString() string
QueryString returns the DQL query string for this observer.
This is the query that was provided when the observer was registered. The query string is immutable and does not change during the observer's lifetime.
type Sync
type Sync struct { // contains filtered or unexported fields }
Sync provides access to sync related functionality of Ditto.
func (*Sync) IsActive
func (s *Sync) IsActive() bool
IsActive returns true if synchronization is currently active.
func (*Sync) RegisterSubscription
func (s *Sync) RegisterSubscription(query string, args ...map[string]any) (*SyncSubscription, error)
RegisterSubscription installs and returns a sync subscription for a query, configuring Ditto to receive updates from other peers for documents matching that query. The passed in query must be a SELECT query, otherwise a store error is returned..
Parameters:
- query: a string containing a valid query expressed in DQL
- args: Optional query arguments (variadic for convenience)
Returns:
- An active SyncSubscription for the passed in query and arguments. The caller is responsible for keeping a reference to it and calling Cancel() when it is no longer needed. Otherwise it will remain active until the owning Ditto object is closed.
- An error if the query is invalid or registration fails
func (*Sync) Start
func (s *Sync) Start() error
Start starts the network transports. Ditto will connect to other devices.
By default Ditto will enable all peer-to-peer transport types. The default network configuration can be modified with updateTransportConfig() or replaced via the transportConfig property.
func (*Sync) Stop
func (s *Sync) Stop()
Stop stops all network transports.
You may continue to use the Ditto store locally but no data will sync to or from other devices.
func (*Sync) Subscriptions
func (s *Sync) Subscriptions() []*SyncSubscription
Subscriptions returns a snapshot of all active sync subscriptions.
The returned slice is a copy and can be safely modified without affecting the internal subscription list.
The order of the returned subscriptions is not defined, and may vary between calls. The caller should treat it as an unordered set.
Returns:
- A slice of active SyncSubscription instances
type SyncSubscription
type SyncSubscription struct { // contains filtered or unexported fields }
SyncSubscription configures Ditto to receive updates from remote peers about documents matching the subscription’s query.
Create a sync subscription by calling Sync.RegisterSubscription(). The subscription will remain active until either explicitly cancelled via SyncSubscription.Cancel() or the owning Ditto object is closed.
func (*SyncSubscription) Cancel
func (s *SyncSubscription) Cancel()
Cancel cancels the subscription
func (*SyncSubscription) Ditto
func (s *SyncSubscription) Ditto() *Ditto
Ditto returns the Ditto instance this subscription belongs to
func (*SyncSubscription) IsCancelled
func (s *SyncSubscription) IsCancelled() bool
IsCancelled returns true if the subscription has been canceled
func (*SyncSubscription) QueryArguments
func (s *SyncSubscription) QueryArguments() map[string]any
QueryArguments returns the query arguments passed when registering the subscription
func (*SyncSubscription) QueryString
func (s *SyncSubscription) QueryString() string
QueryString returns the query string passed when registering the subscription
type Transaction
type Transaction struct { // contains filtered or unexported fields }
Transaction represents an active transaction in the Ditto store.
Transactions provide atomic, isolated execution of multiple DQL operations. All changes made within a transaction are committed together, or rolled back if an error occurs or if explicitly requested.
Important: Do not call Store.Execute or start another transaction from within a transaction scope, as this will cause a deadlock.
func (*Transaction) Execute
func (t *Transaction) Execute(query string, args ...QueryArguments) (*QueryResult, error)
Execute executes a DQL query within this transaction and returns the query result.
The query executes against the current state of the transaction, including any modifications made by previous Execute calls within the same transaction.
If multiple arguments are provided, they will be merged into a single map before being passed to the query engine.
NOTE: Only returns results from the local store without waiting for any SyncSubscription to have caught up with the latest changes.
Returns an error if:
- query is not valid DQL
- arguments are not valid (contain unsupported types)
- this is a read-only transaction but a mutating query was executed
- a database store error occurs
func (*Transaction) Info
func (t *Transaction) Info() TransactionInfo
Info returns metadata about this transaction.
The returned TransactionInfo contains:
- ID: A globally unique identifier for this transaction
- Hint: An optional description provided when creating the transaction
- IsReadOnly: Whether this transaction can only perform read operations
This information is useful for debugging, monitoring, and logging transaction activity.
func (*Transaction) Store
func (t *Transaction) Store() *Store
Store returns the Store instance that this transaction belongs to.
This allows accessing the parent store's methods from within a transaction context.
type TransactionCompletionAction
type TransactionCompletionAction int
TransactionCompletionAction represents how to complete a transaction.
func (TransactionCompletionAction) String
func (a TransactionCompletionAction) String() string
String returns a string representation of the TransactionCompletionAction.
type TransactionInfo
type TransactionInfo struct { // ID is the globally unique identifier for this transaction. ID string `cbor:"id"` // Hint is an optional description provided when creating the transaction, // useful for debugging and monitoring. Hint *string `cbor:"hint,omitempty"` // IsReadOnly indicates whether this transaction can only perform read operations. // Read-only transactions can run concurrently and provide better performance. IsReadOnly bool `cbor:"is_read_only"` }
TransactionInfo contains metadata about a transaction.
type TransactionOptions
type TransactionOptions struct { // Hint provides an optional description for the transaction, // useful for debugging and monitoring. Hint string // IsReadOnly creates a read-only transaction if true. // // Read-only transactions can run concurrently and provide better performance // for queries that don't modify data. IsReadOnly bool }
TransactionOptions configures a new transaction. Can be nil to use default options (empty hint, read-write transaction).
type TransportConfig struct { // PeerToPeer configures direct device-to-device transports PeerToPeer PeerToPeerConfig `cbor:"peer_to_peer" json:"peer_to_peer"` // Connect configures outgoing connections to servers Connect ConnectTransport `cbor:"connect" json:"connect"` // Listen configures this device to accept incoming connections Listen ListenConfig `cbor:"listen" json:"listen"` // Global contains global transport settings Global GlobalConfig `cbor:"global" json:"global"` }
TransportConfig controls how Ditto connects to and communicates with other peers.
The transport system supports multiple connection methods that can work simultaneously:
- Peer-to-peer: Direct device connections via Bluetooth, WiFi Direct, LAN
- Cloud: WebSocket connections to Ditto Cloud servers
- Custom servers: TCP connections to self-hosted infrastructure
Example:
config := ditto.NewTransportConfig()
config.PeerToPeer.BluetoothLE.Enabled = true
config.PeerToPeer.LAN.Enabled = true
config.Connect.WebsocketURLs = []string{"wss://cloud.ditto.live"}
err := dittoInstance.SetTransportConfig(config)
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func NewTransportConfig() *TransportConfig
NewTransportConfig creates a new TransportConfig with safe defaults.
By default, all transports are disabled. You must explicitly enable the transports you want to use.
Common patterns:
// Enable all peer-to-peer transports
config := ditto.NewTransportConfig().EnableAllPeerToPeer()
// Enable specific transports
config := ditto.NewTransportConfig()
config.PeerToPeer.BluetoothLE.Enabled = true
config.PeerToPeer.LAN.Enabled = true
// Add cloud sync
config.AddWebsocketURL("wss://cloud.ditto.live")
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (t *TransportConfig) AddTCPServer(address string) *TransportConfig
AddTCPServer adds a TCP server address for outgoing connections.
The device will attempt to connect to this server for synchronization.
Parameters:
- address: Server address in format "host:port" (e.g., "192.168.1.100:4040")
Returns the same TransportConfig for method chaining.
Example:
config.AddTCPServer("192.168.1.100:4040").
AddTCPServer("backup.local:4040")
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (t *TransportConfig) AddWebsocketURL(url string) *TransportConfig
AddWebsocketURL adds a WebSocket URL for cloud synchronization.
Multiple URLs can be added for redundancy. Ditto will attempt to connect to all provided URLs.
Parameters:
- url: WebSocket URL (must start with ws:// or wss://)
Returns the same TransportConfig for method chaining.
Example:
config.AddWebsocketURL("wss://primary.ditto.live").
AddWebsocketURL("wss://backup.ditto.live")
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (t *TransportConfig) DisableAllPeerToPeer() *TransportConfig
DisableAllPeerToPeer disables all peer-to-peer transports.
This forces the device to only sync through cloud or custom servers. Useful for:
- Cloud-only deployments
- Debugging server connections
- Reducing battery usage on mobile devices
Returns the same TransportConfig for method chaining.
Example:
config := ditto.NewTransportConfig().
DisableAllPeerToPeer().
AddWebsocketURL("wss://cloud.ditto.live")
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (t *TransportConfig) EnableAllPeerToPeer() *TransportConfig
EnableAllPeerToPeer enables all available peer-to-peer transports.
This is a convenience method that enables:
- Bluetooth LE
- LAN (with mDNS and multicast)
- AWDL (on Apple platforms)
- Wi-Fi Aware (on Android)
Returns the same TransportConfig for method chaining.
Example:
config := ditto.NewTransportConfig().
EnableAllPeerToPeer().
AddWebsocketURL("wss://cloud.ditto.live")
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (t *TransportConfig) EnableHTTPListen(interfaceIP string, port int, enableWebsocket bool) *TransportConfig
EnableHTTPListen configures this device to accept HTTP/WebSocket connections.
This enables other devices to sync via WebSocket and optionally serves static content for web applications.
Parameters:
- interfaceIP: Network interface to bind to ("[::]" for all interfaces)
- port: HTTP port to listen on (default 80, or 443 with TLS)
- enableWebsocket: Whether to enable WebSocket sync
Returns the same TransportConfig for method chaining.
Example:
// Basic HTTP server with WebSocket sync
config.EnableHTTPListen("[::]", 8080, true)
// HTTPS server (requires separate TLS configuration)
config.EnableHTTPListen("[::]", 443, true).
SetHTTPTLS("/path/to/cert.pem", "/path/to/key.pem")
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (t *TransportConfig) EnableTCPListen(interfaceIP string, port int) *TransportConfig
EnableTCPListen configures this device to accept incoming TCP connections.
This is useful for creating a local sync server or bridge device that other peers can connect to directly.
Parameters:
- interfaceIP: Network interface to bind to ("[::]" for all interfaces)
- port: TCP port to listen on (default 4040)
Returns the same TransportConfig for method chaining.
Example:
// Listen on all interfaces, port 4040
config.EnableTCPListen("[::]", 4040)
// Listen only on specific interface
config.EnableTCPListen("192.168.1.100", 4040)
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (t *TransportConfig) SetHTTPTLS(certPath, keyPath string) *TransportConfig
SetHTTPTLS configures TLS certificates for HTTPS listening.
This enables secure WebSocket connections (wss://) to this device.
Parameters:
- certPath: Path to the TLS certificate file (PEM format)
- keyPath: Path to the TLS private key file (PEM format)
Returns the same TransportConfig for method chaining.
Example:
config.EnableHTTPListen("[::]", 443, true).
SetHTTPTLS("/etc/ssl/server.crt", "/etc/ssl/server.key")
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (t *TransportConfig) SetStaticContentPath(path string) *TransportConfig
SetStaticContentPath configures the HTTP server to serve static files.
This is useful for serving web applications that use Ditto's WebSocket sync capabilities.
Parameters:
- path: Directory path containing static files to serve
Returns the same TransportConfig for method chaining.
Example:
config.EnableHTTPListen("[::]", 8080, true).
SetStaticContentPath("/var/www/html")
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (t *TransportConfig) SetSyncGroup(group uint32) *TransportConfig
SetSyncGroup sets the sync group for mesh partitioning.
Devices only sync with others in the same sync group. This is useful for:
- Multi-tenant applications
- Testing isolated mesh networks
- Gradual rollouts
Parameters:
- group: Sync group ID (0 = default group)
Returns the same TransportConfig for method chaining.
Example:
// Isolate test devices in group 42 config.SetSyncGroup(42)
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (t *TransportConfig) SetWebsocketURLs(urls []string) *TransportConfig
SetWebsocketURLs replaces all WebSocket URLs with the provided list.
This overwrites any previously configured WebSocket URLs.
Parameters:
- urls: List of WebSocket URLs to use
Returns the same TransportConfig for method chaining.
Example:
config.SetWebsocketURLs([]string{
"wss://us-east.ditto.live",
"wss://eu-west.ditto.live",
})
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (tc *TransportConfig) ToCBOR() ([]byte, error)
ToCBOR encodes the TransportConfig to CBOR format for FFI.
This method is used internally to serialize the configuration for the Ditto core library.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type TransportDiagnostics struct { // Transports contains diagnostics for each transport type Transports []TransportSnapshot `json:"transports"` }
TransportDiagnostics provides detailed information about all transport status.
This information is useful for:
- Debugging connectivity issues
- Monitoring network health
- Understanding sync performance
Obtain diagnostics via Ditto.TransportDiagnostics().
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (td *TransportDiagnostics) ActiveTransports() int
ActiveTransports returns the number of transports that have at least one connected peer.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (td *TransportDiagnostics) TotalConnectedPeers() int
TotalConnectedPeers returns the total number of connected peers across all transports.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (td *TransportDiagnostics) TransportByType(connectionType string) *TransportSnapshot
TransportByType returns the transport snapshot for the specified connection type, or nil if no transport of that type is found.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type TransportSnapshot struct { // ConnectionType is the type of transport (e.g., "TCP", "mDNS", "Bluetooth") ConnectionType string `json:"connection_type"` // Connecting contains site IDs of peers currently connecting Connecting []int64 `json:"connecting"` // Connected contains site IDs of peers currently connected Connected []int64 `json:"connected"` // Disconnecting contains site IDs of peers currently disconnecting Disconnecting []int64 `json:"disconnecting"` // Disconnected contains site IDs of peers that have disconnected Disconnected []int64 `json:"disconnected"` }
TransportSnapshot provides diagnostic information about a specific transport.
Each transport type (TCP, mDNS, Bluetooth, etc.) has its own snapshot showing which peers are in various connection states.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (ts *TransportSnapshot) HasActivity() bool
HasActivity returns true if this transport has any peer activity (connecting, connected, or disconnecting).
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (ts *TransportSnapshot) IsActive() bool
IsActive returns true if this transport has any connected peers.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
func (ts *TransportSnapshot) TotalPeers() int
TotalPeers returns the total number of peers across all connection states.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.
type WifiAwareConfig struct { // Enabled controls whether Wi-Fi Aware transport is active Enabled bool `cbor:"enabled" json:"enabled"` }
WifiAwareConfig configures Wi-Fi Aware transport.
Wi-Fi Aware (NAN - Neighbor Awareness Networking) enables:
- Direct WiFi connections without an access point
- Low-latency discovery of nearby devices
- High-bandwidth data transfer
Only available on Android 8.0+ devices with hardware support.
Deprecated: This API is experimental. It is not supported in this preview build and may change or be removed at any time.