sync

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2025 License: MIT Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ErrTypeNetwork            = "network"
	ErrTypeIntegrityFailure   = "integrity_failure"
	ErrTypeAuthFailure        = "auth_failure"
	ErrTypeQuotaExceeded      = "quota_exceeded"
	ErrTypeCorruption         = "corruption"
	ErrTypeHashMismatch       = "hash_mismatch"
	ErrTypeInvalidChecksum    = "invalid_checksum"
	ErrTypeTimeout            = "timeout"
	ErrTypeStorageUnavailable = "storage_unavailable"
	ErrTypeInvalidResponse    = "invalid_response"
	ErrTypeConflictResolution = "conflict_resolution"
	ErrTypeResourceExhausted  = "resource_exhausted"
)

Sync error types

View Source
const (
	CodeNetworkTimeout     = "NET_TIMEOUT"
	CodeNetworkUnreachable = "NET_UNREACHABLE"
	CodeAuthTokenExpired   = "AUTH_TOKEN_EXPIRED"
	CodeAuthInvalidCreds   = "AUTH_INVALID_CREDS"
	CodeQuotaRecordsLimit  = "QUOTA_RECORDS_LIMIT"
	CodeQuotaStorageLimit  = "QUOTA_STORAGE_LIMIT"
	CodeIntegrityHashFail  = "INTEGRITY_HASH_FAIL"
	CodeIntegrityCorrupted = "INTEGRITY_CORRUPTED"
	CodeStorageLocked      = "STORAGE_LOCKED"
	CodeStorageCorrupted   = "STORAGE_CORRUPTED"
	CodeServerError        = "SERVER_ERROR"
	CodeInvalidPayload     = "INVALID_PAYLOAD"
)

Sync error codes

View Source
const (
	RecoveryTypeRetry              = "retry"
	RecoveryTypeReauthenticate     = "reauthenticate"
	RecoveryTypeRebuildCache       = "rebuild_cache"
	RecoveryTypeValidateStorage    = "validate_storage"
	RecoveryTypeFullResync         = "full_resync"
	RecoveryTypeManualIntervention = "manual_intervention"
)

Recovery action types

View Source
const (
	IntegrityStatusPerfect   = "perfect"
	IntegrityStatusNeedSync  = "needs_sync"
	IntegrityStatusConflicts = "has_conflicts"
	IntegrityStatusCorrupted = "corrupted"
)

IntegrityStatus constants

View Source
const (
	SyncTypeFull        = "full"
	SyncTypeIncremental = "incremental"
	SyncTypeRecovery    = "recovery"
)

SyncType constants

View Source
const (
	MaxBatchRetries = 5
	BatchSize       = 1000
	LockTimeout     = time.Hour
)

Batch update constants

Variables

This section is empty.

Functions

This section is empty.

Types

type AuthResponse

type AuthResponse struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresAt    int64  `json:"expires_at"`
	UserID       string `json:"user_id"`
	DeviceID     string `json:"device_id"`
}

type BatchEvaluationConfig added in v0.4.0

type BatchEvaluationConfig struct {
	BatchSize   int
	WorkerCount int
	MaxMemoryMB int
}

BatchEvaluationConfig configures batch processing parameters

type BatchEvaluationResult added in v0.4.0

type BatchEvaluationResult struct {
	ProcessedCommands int           `json:"processed_commands"`
	UpdatedCommands   int           `json:"updated_commands"`
	Duration          time.Duration `json:"duration"`
	MemoryUsedMB      int           `json:"memory_used_mb"`
}

BatchEvaluationResult contains results of batch re-evaluation

type BatchMetadata

type BatchMetadata struct {
	BatchNumber    int  `json:"batch_number"`
	TotalBatches   int  `json:"total_batches"`
	IsLastBatch    bool `json:"is_last_batch"`
	RecordsInBatch int  `json:"records_in_batch"`
}

BatchMetadata contains metadata about the batch

type BatchUpdateRequest

type BatchUpdateRequest struct {
	DeviceID      string         `json:"device_id"`
	Records       []RecordUpdate `json:"records"`
	BatchMetadata BatchMetadata  `json:"batch_metadata"`
}

BatchUpdateRequest represents a batch of records to update remotely

type BatchUpdateResponse

type BatchUpdateResponse struct {
	Success        bool   `json:"success"`
	ProcessedCount int    `json:"processed_count"`
	FailedCount    int    `json:"failed_count"`
	Message        string `json:"message,omitempty"`
}

BatchUpdateResponse represents the response from batch update

type CleanupRequest

type CleanupRequest struct {
	RetentionDays int `json:"retention_days"`
}

type CleanupResponse

type CleanupResponse struct {
	Success      bool   `json:"success"`
	DeletedCount int    `json:"deleted_count"`
	Message      string `json:"message"`
}

type ConflictInfo

type ConflictInfo struct {
	LocalHash  string `json:"local_hash"`
	RemoteHash string `json:"remote_hash"`
	Resolution string `json:"resolution"`
	Timestamp  int64  `json:"timestamp"`
}

type ConflictResolutionStrategy

type ConflictResolutionStrategy int

ConflictResolutionStrategy defines how conflicts should be resolved

const (
	ResolutionServerDecides ConflictResolutionStrategy = iota
	ResolutionLocalWins
	ResolutionRemoteWins
	ResolutionMerge
)

type ConflictResolver

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

func NewConflictResolver

func NewConflictResolver() *ConflictResolver

func (*ConflictResolver) DetectLocalConflicts

func (cr *ConflictResolver) DetectLocalConflicts(localRecords []*storage.CommandRecord, remoteHashes []string) []ConflictResult

DetectLocalConflicts identifies potential conflicts before upload

func (*ConflictResolver) GetConflictStatistics

func (cr *ConflictResolver) GetConflictStatistics(conflicts []ConflictInfo) map[string]int

GetConflictStatistics returns statistics about conflict resolution

func (*ConflictResolver) ProcessServerConflicts

func (cr *ConflictResolver) ProcessServerConflicts(conflicts []ConflictInfo, storage StorageInterface) error

ProcessServerConflicts handles conflict resolution decisions from server

func (*ConflictResolver) ResolveConflictLocally

func (cr *ConflictResolver) ResolveConflictLocally(local, remote *storage.CommandRecord, strategy ConflictResolutionStrategy) (*storage.CommandRecord, error)

ResolveConflictLocally applies local conflict resolution strategy

func (*ConflictResolver) ValidateConflictResolution

func (cr *ConflictResolver) ValidateConflictResolution(conflict ConflictInfo) error

ValidateConflictResolution checks if a conflict resolution is valid

type ConflictResult

type ConflictResult struct {
	Resolution  string `json:"resolution"`
	LocalHash   string `json:"local_hash"`
	RemoteHash  string `json:"remote_hash"`
	WinningHash string `json:"winning_hash"`
	ResolvedAt  int64  `json:"resolved_at"`
}

ConflictResult contains the outcome of conflict resolution

type DeleteAccountRequest

type DeleteAccountRequest struct {
	Confirmation string `json:"confirmation"`
}

type DeleteAccountResponse

type DeleteAccountResponse struct {
	Success   bool   `json:"success"`
	Message   string `json:"message"`
	DeletedAt string `json:"deleted_at"`
}

type DeleteDeviceResponse

type DeleteDeviceResponse struct {
	Success        bool   `json:"success"`
	Message        string `json:"message"`
	RecordsDeleted int    `json:"records_deleted"`
}

type DetailedHealthResponse

type DetailedHealthResponse struct {
	Status    string `json:"status"`
	Timestamp string `json:"timestamp"`
	Version   string `json:"version"`
	Uptime    string `json:"uptime"`
	Database  struct {
		Status            string `json:"status"`
		MaxOpenConns      int    `json:"max_open_conns"`
		OpenConns         int    `json:"open_conns"`
		InUse             int    `json:"in_use"`
		Idle              int    `json:"idle"`
		WaitCount         int64  `json:"wait_count"`
		WaitDuration      string `json:"wait_duration"`
		MaxIdleClosed     int64  `json:"max_idle_closed"`
		MaxIdleTimeClosed int64  `json:"max_idle_time_closed"`
		MaxLifetimeClosed int64  `json:"max_lifetime_closed"`
	} `json:"database"`
	System struct {
		StartTime     string  `json:"start_time"`
		UptimeSeconds float64 `json:"uptime_seconds"`
	} `json:"system"`
}

type Device added in v0.4.0

type Device struct {
	DeviceID  string `json:"device_id"`
	Hostname  string `json:"hostname"`
	Platform  string `json:"platform"`
	LastSeen  int64  `json:"last_seen"`
	IsActive  bool   `json:"is_active"`
	Alias     string `json:"alias,omitempty"`
	IsEnabled bool   `json:"is_enabled"`
	IsCurrent bool   `json:"is_current"`
	UpdatedAt int64  `json:"updated_at"`
}

Device represents a device with its alias information

type DeviceAliasManager added in v0.4.0

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

DeviceAliasManager handles device aliases and management

func NewDeviceAliasManager added in v0.4.0

func NewDeviceAliasManager(storage *securestorage.SecureStorage, cfg *config.Config) *DeviceAliasManager

NewDeviceAliasManager creates a new device alias manager

func (*DeviceAliasManager) DeactivateDevice added in v0.4.0

func (dam *DeviceAliasManager) DeactivateDevice(deviceID string) error

DeactivateDevice marks a device as inactive

func (*DeviceAliasManager) GetCurrentDeviceID added in v0.4.0

func (dam *DeviceAliasManager) GetCurrentDeviceID() (string, error)

GetCurrentDeviceID returns the current device's ID

func (*DeviceAliasManager) GetDeviceAlias added in v0.4.0

func (dam *DeviceAliasManager) GetDeviceAlias(deviceID string) (string, error)

GetDeviceAlias returns the alias for a device if it exists

func (*DeviceAliasManager) GetDevices added in v0.4.0

func (dam *DeviceAliasManager) GetDevices() ([]Device, error)

GetDevices returns all devices with their alias information

func (*DeviceAliasManager) ReactivateDevice added in v0.4.0

func (dam *DeviceAliasManager) ReactivateDevice(deviceID string) error

ReactivateDevice marks a device as active

func (*DeviceAliasManager) RemoveDeviceAlias added in v0.4.0

func (dam *DeviceAliasManager) RemoveDeviceAlias(deviceID string) error

RemoveDeviceAlias removes an alias for a device

func (*DeviceAliasManager) ResolveAlias added in v0.4.0

func (dam *DeviceAliasManager) ResolveAlias(aliasOrID string) (string, error)

ResolveAlias resolves an alias or device ID to a device ID

func (*DeviceAliasManager) SetDeviceAlias added in v0.4.0

func (dam *DeviceAliasManager) SetDeviceAlias(deviceID, alias string) error

SetDeviceAlias sets an alias for a device

func (*DeviceAliasManager) UpdateDevicesList added in v0.4.0

func (dam *DeviceAliasManager) UpdateDevicesList(devices []ServerDevice) error

UpdateDevicesList updates the local device list from server data

type DeviceInfo

type DeviceInfo struct {
	DeviceID  string `json:"device_id"`
	Hostname  string `json:"hostname"`
	Platform  string `json:"platform"`
	UserAgent string `json:"user_agent"`
	CreatedAt int64  `json:"created_at"`
}

DeviceInfo contains information about this device

type DeviceManager

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

DeviceManager handles device identification

func NewDeviceManager

func NewDeviceManager(cfg *config.Config) *DeviceManager

NewDeviceManager creates a new device manager

func (*DeviceManager) ClearDeviceID

func (dm *DeviceManager) ClearDeviceID() error

ClearDeviceID removes the stored device ID

func (*DeviceManager) GetDeviceID

func (dm *DeviceManager) GetDeviceID() (string, error)

GetDeviceID returns the device ID, generating one if it doesn't exist

func (*DeviceManager) GetDeviceInfo

func (dm *DeviceManager) GetDeviceInfo() (*DeviceInfo, error)

GetDeviceInfo returns comprehensive device information

func (*DeviceManager) RegenerateDeviceID

func (dm *DeviceManager) RegenerateDeviceID() (string, error)

RegenerateDeviceID creates a new device ID and saves it

type DeviceRegistration

type DeviceRegistration struct {
	DeviceID   string `json:"device_id"`
	DeviceName string `json:"device_name"`
	Hostname   string `json:"hostname"`
	Platform   string `json:"platform"`
	UserAgent  string `json:"user_agent"`
}

type DevicesResponse

type DevicesResponse struct {
	Devices []ServerDevice `json:"devices"`
}

type ErrorClassifier

type ErrorClassifier struct{}

ErrorClassifier helps classify and handle different types of errors

func NewErrorClassifier

func NewErrorClassifier() *ErrorClassifier

NewErrorClassifier creates a new error classifier

func (*ErrorClassifier) ClassifyError

func (ec *ErrorClassifier) ClassifyError(err error) *SyncError

ClassifyError analyzes an error and returns an appropriate SyncError

type HashCompression

type HashCompression struct {
	Enabled        bool    `json:"enabled"`
	Algorithm      string  `json:"algorithm"`
	Ratio          float64 `json:"ratio"`
	OriginalSize   int64   `json:"original_size"`
	CompressedSize int64   `json:"compressed_size"`
}

HashCompression contains methods for compressing hash collections

type HashGenerator

type HashGenerator struct{}

HashGenerator creates deterministic hashes for command records

func NewHashGenerator

func NewHashGenerator() *HashGenerator

NewHashGenerator creates a new hash generator

func (*HashGenerator) CompareRecords

func (hg *HashGenerator) CompareRecords(r1, r2 *storage.CommandRecord) bool

CompareRecords checks if two records represent the same command execution

func (*HashGenerator) GenerateRecordHash

func (hg *HashGenerator) GenerateRecordHash(record *storage.CommandRecord) string

GenerateRecordHash creates a deterministic hash for conflict detection

type HealthResponse

type HealthResponse struct {
	Status    string `json:"status"`
	Timestamp string `json:"timestamp"`
	Version   string `json:"version"`
	Database  string `json:"database"`
	Uptime    string `json:"uptime"`
}

Health endpoint types

type JWTToken

type JWTToken struct {
	AccessToken string `json:"access_token"`
	ExpiresAt   int64  `json:"expires_at"`
	UserID      string `json:"user_id"`
	DeviceID    string `json:"device_id"`
	IssuedAt    int64  `json:"issued_at"`
	TokenType   string `json:"token_type"`
}

type LocalIntegrityState

type LocalIntegrityState struct {
	RecordCount     int      `json:"record_count"`
	AllHashes       []string `json:"all_hashes"`
	HashChecksum    string   `json:"hash_checksum"`
	LatestTimestamp int64    `json:"latest_timestamp"`
	OldestTimestamp int64    `json:"oldest_timestamp"`
}

LocalIntegrityState contains the complete local state for integrity verification

type LockInfo

type LockInfo struct {
	UserID    string `json:"user_id"`
	DeviceID  string `json:"device_id"`
	ExpiresAt int64  `json:"expires_at"`
	CreatedAt int64  `json:"created_at"`
}

LockInfo contains details about the password change lock

type LoginRequest

type LoginRequest struct {
	Email    string             `json:"email"`
	Password string             `json:"password"`
	Device   DeviceRegistration `json:"device"`
}

type LoginResponse

type LoginResponse struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresAt    int64  `json:"expires_at"`
	UserID       string `json:"user_id"`
	DeviceID     string `json:"device_id"`
}

type LogoutRequest

type LogoutRequest struct {
	DeviceID string `json:"device_id"`
}

type MissingRecord

type MissingRecord struct {
	RecordHash       string                `json:"record_hash"`
	EncryptedPayload []byte                `json:"encrypted_payload"`
	TimestampMs      int64                 `json:"timestamp_ms"`
	Hostname         string                `json:"hostname"`
	SessionID        string                `json:"session_id"`
	Metadata         MissingRecordMetadata `json:"metadata"`
}

MissingRecord represents a record that the client is missing

type MissingRecordMetadata

type MissingRecordMetadata struct {
	DeviceOrigin string `json:"device_origin"`
	SyncPriority int    `json:"sync_priority"`
}

MissingRecordMetadata contains additional metadata for missing records

type PasswordChangeLockStatus

type PasswordChangeLockStatus struct {
	IsLocked   bool     `json:"is_locked"`
	CanProceed bool     `json:"can_proceed"`
	LockInfo   LockInfo `json:"lock_info"`
	Reason     string   `json:"reason,omitempty"`
}

PasswordChangeLockStatus represents the response from lock status endpoint

type PasswordChangeUI

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

PasswordChangeUI handles user interactions for password change recovery

func NewPasswordChangeUI

func NewPasswordChangeUI() *PasswordChangeUI

NewPasswordChangeUI creates a new password change UI handler

func (*PasswordChangeUI) ClearLine

func (ui *PasswordChangeUI) ClearLine()

ClearLine clears the current line in terminal

func (*PasswordChangeUI) ConfirmDataPreservation

func (ui *PasswordChangeUI) ConfirmDataPreservation() (bool, error)

ConfirmDataPreservation explains data preservation to user

func (*PasswordChangeUI) PromptForEmail

func (ui *PasswordChangeUI) PromptForEmail() (string, error)

PromptForEmail prompts the user for their email address

func (*PasswordChangeUI) PromptForNewPassword

func (ui *PasswordChangeUI) PromptForNewPassword() (string, error)

PromptForNewPassword securely prompts the user for their new password

func (*PasswordChangeUI) PromptForPasswordChangeConfirmation

func (ui *PasswordChangeUI) PromptForPasswordChangeConfirmation() (bool, error)

PromptForPasswordChangeConfirmation asks user if they want to proceed with password change recovery

func (*PasswordChangeUI) PromptRetry

func (ui *PasswordChangeUI) PromptRetry(err error, operation string) (bool, error)

PromptRetry asks if user wants to retry after an error

func (*PasswordChangeUI) ShowError

func (ui *PasswordChangeUI) ShowError(err error)

ShowError displays an error message with formatting

func (*PasswordChangeUI) ShowRecoveryComplete

func (ui *PasswordChangeUI) ShowRecoveryComplete(stats RecoveryStats)

ShowRecoveryComplete displays completion message with summary

func (*PasswordChangeUI) ShowRecoveryProgress

func (ui *PasswordChangeUI) ShowRecoveryProgress(step string, message string)

ShowRecoveryProgress displays progress indicators during recovery

func (*PasswordChangeUI) ShowRecoverySteps

func (ui *PasswordChangeUI) ShowRecoverySteps()

ShowRecoverySteps shows what will happen during recovery

func (*PasswordChangeUI) ShowSuccess

func (ui *PasswordChangeUI) ShowSuccess(message string)

ShowSuccess displays a success message

func (*PasswordChangeUI) ShowThinkingIndicator

func (ui *PasswordChangeUI) ShowThinkingIndicator(message string, done <-chan bool)

ShowThinkingIndicator shows a simple thinking animation

func (*PasswordChangeUI) ShowWarning

func (ui *PasswordChangeUI) ShowWarning(message string)

ShowWarning displays a warning message

type PerfectSyncRequest

type PerfectSyncRequest struct {
	DeviceID        string              `json:"device_id"`
	SyncSessionID   string              `json:"sync_session_id"`
	LocalState      LocalIntegrityState `json:"local_state"`
	RequestMetadata RequestMetadata     `json:"request_metadata"`
}

PerfectSyncRequest represents the request payload for integrity verification

type PerfectSyncResponse

type PerfectSyncResponse struct {
	SyncSessionID   string         `json:"sync_session_id"`
	IntegrityStatus string         `json:"integrity_status"`
	ServerState     ServerState    `json:"server_state"`
	SyncActions     SyncActions    `json:"sync_actions"`
	Statistics      SyncStatistics `json:"statistics"`
}

PerfectSyncResponse represents the response from integrity verification

type PerformanceOptions

type PerformanceOptions struct {
	BatchSize               int           `json:"batch_size"`
	MaxHashesPerRequest     int           `json:"max_hashes_per_request"`
	HashCollectionTimeout   time.Duration `json:"hash_collection_timeout"`
	NetworkTimeout          time.Duration `json:"network_timeout"`
	EnableCompression       bool          `json:"enable_compression"`
	ParallelProcessing      bool          `json:"parallel_processing"`
	MaxConcurrentOperations int           `json:"max_concurrent_operations"`
}

PerformanceOptions contains options for optimizing Perfect Sync performance

type ProgressBar

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

ProgressBar represents a simple text-based progress bar

func NewProgressBar

func NewProgressBar(total int, label string) *ProgressBar

NewProgressBar creates a new progress bar

func (*ProgressBar) Finish

func (pb *ProgressBar) Finish()

Finish completes the progress bar

func (*ProgressBar) Update

func (pb *ProgressBar) Update(current int)

Update updates the progress bar

type RecordUpdate

type RecordUpdate struct {
	RecordHash          string `json:"record_hash"`
	NewEncryptedPayload string `json:"new_encrypted_payload"`
	UpdateReason        string `json:"update_reason"`
}

RecordUpdate represents a single record update

type RecoveryAction

type RecoveryAction struct {
	Type        string `json:"type"`
	Description string `json:"description"`
	Command     string `json:"command,omitempty"`
	Automatic   bool   `json:"automatic"`
}

RecoveryAction represents an action to take when recovering from sync errors

type RecoveryManager

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

RecoveryManager provides recovery suggestions for different error types

func NewRecoveryManager

func NewRecoveryManager() *RecoveryManager

NewRecoveryManager creates a new recovery manager

func (*RecoveryManager) GetRecoveryActions

func (rm *RecoveryManager) GetRecoveryActions(err error) []RecoveryAction

GetRecoveryActions returns suggested recovery actions for an error

type RecoveryStats

type RecoveryStats struct {
	CommandsPreserved   int
	CommandsReencrypted int
	CommandsSynced      int
	Duration            time.Duration
	StartTime           time.Time
	EndTime             time.Time
}

RecoveryStats contains statistics about the recovery operation

func NewRecoveryStats

func NewRecoveryStats() *RecoveryStats

NewRecoveryStats creates a new recovery stats tracker

func (*RecoveryStats) Complete

func (rs *RecoveryStats) Complete()

Complete marks the recovery as completed and calculates duration

type RecoveryStrategy

type RecoveryStrategy struct {
	MaxRetries        int           `json:"max_retries"`
	BackoffMultiplier float64       `json:"backoff_multiplier"`
	InitialDelay      time.Duration `json:"initial_delay"`
	MaxDelay          time.Duration `json:"max_delay"`
	RetryableErrors   []string      `json:"retryable_errors"`
}

RecoveryStrategy defines how to handle different types of sync failures

type RefreshRequest

type RefreshRequest struct {
	RefreshToken string `json:"refresh_token"`
}

type RegisterRequest

type RegisterRequest struct {
	Email           string             `json:"email"`
	Password        string             `json:"password"`
	ConfirmPassword string             `json:"confirm_password"`
	Device          DeviceRegistration `json:"device"`
}

Auth endpoint types

type RegisterResponse

type RegisterResponse struct {
	UserID      string `json:"user_id"`
	Email       string `json:"email"`
	AccessToken string `json:"access_token"`
	ExpiresAt   int64  `json:"expires_at"`
	DeviceID    string `json:"device_id"`
}

type RemoteAuthenticator

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

func NewRemoteAuthenticator

func NewRemoteAuthenticator(cfg *config.Config, localAuth *auth.AuthManager) *RemoteAuthenticator

func (*RemoteAuthenticator) Authenticate

func (ra *RemoteAuthenticator) Authenticate(email, password string) error

func (*RemoteAuthenticator) AuthenticateWithDerivedKey

func (ra *RemoteAuthenticator) AuthenticateWithDerivedKey(email string, remoteAuthKey []byte) error

AuthenticateWithDerivedKey authenticates using pre-derived remote auth key (for existing users)

func (*RemoteAuthenticator) CancelSubscription

func (ra *RemoteAuthenticator) CancelSubscription() (*SubscriptionCancelResponse, error)

CancelSubscription cancels the user's premium subscription

func (*RemoteAuthenticator) ChangePassword

func (ra *RemoteAuthenticator) ChangePassword(currentRemoteKey, newRemoteKey []byte) error

ChangePassword changes the remote password

func (*RemoteAuthenticator) GetDeviceID

func (ra *RemoteAuthenticator) GetDeviceID() (string, error)

func (*RemoteAuthenticator) GetStoredEmail

func (ra *RemoteAuthenticator) GetStoredEmail() (string, error)

GetStoredEmail retrieves the email address from stored credentials or config

func (*RemoteAuthenticator) GetTokenExpiryTime

func (ra *RemoteAuthenticator) GetTokenExpiryTime() (time.Time, error)

func (*RemoteAuthenticator) GetUserID

func (ra *RemoteAuthenticator) GetUserID() (string, error)

func (*RemoteAuthenticator) GetValidToken

func (ra *RemoteAuthenticator) GetValidToken() (string, error)

func (*RemoteAuthenticator) IsAuthenticated

func (ra *RemoteAuthenticator) IsAuthenticated() bool

IsAuthenticated checks if the user is authenticated with valid tokens

func (*RemoteAuthenticator) IsServerAuthenticated

func (ra *RemoteAuthenticator) IsServerAuthenticated() bool

IsServerAuthenticated validates the token against the server

func (*RemoteAuthenticator) Logout

func (ra *RemoteAuthenticator) Logout() error

func (*RemoteAuthenticator) RefreshToken

func (ra *RemoteAuthenticator) RefreshToken() error

func (*RemoteAuthenticator) RegisterWithDerivedKey

func (ra *RemoteAuthenticator) RegisterWithDerivedKey(email string, remoteKey []byte) (*RegisterResponse, error)

RegisterWithDerivedKey registers a new account using derived key subset

func (*RemoteAuthenticator) TestConnection

func (ra *RemoteAuthenticator) TestConnection() error

func (*RemoteAuthenticator) ValidateTokenWithServer

func (ra *RemoteAuthenticator) ValidateTokenWithServer() error

ValidateTokenWithServer calls the server's token validation endpoint

type RequestMetadata

type RequestMetadata struct {
	ClientVersion string `json:"client_version"`
	SyncType      string `json:"sync_type"`
	Compression   bool   `json:"compression"`
}

RequestMetadata contains metadata about the sync request

type RetryStrategy

type RetryStrategy struct {
	MaxRetries        int
	InitialDelay      time.Duration
	MaxDelay          time.Duration
	BackoffMultiplier float64
	RetryableErrors   map[string]bool
}

RetryStrategy defines how to handle retries for different error types

func DefaultRetryStrategy

func DefaultRetryStrategy() *RetryStrategy

DefaultRetryStrategy returns a sensible default retry strategy

func (*RetryStrategy) GetDelay

func (rs *RetryStrategy) GetDelay(attempt int) time.Duration

GetDelay calculates the delay before the next retry attempt

func (*RetryStrategy) ShouldRetry

func (rs *RetryStrategy) ShouldRetry(err *SyncError, attempt int) bool

ShouldRetry determines if an error should be retried

type RuleCondition added in v0.4.0

type RuleCondition struct {
	Type     string `json:"type"`     // "tag", "working_dir", "command_pattern"
	Operator string `json:"operator"` // "equals", "contains", "starts_with", "regex"
	Value    string `json:"value"`
	Negate   bool   `json:"negate,omitempty"`
}

RuleCondition represents conditions for rule application (for future phases)

type RuleConflict added in v0.4.0

type RuleConflict struct {
	ConflictingRules []SyncRule `json:"conflicting_rules"`
	ConflictType     string     `json:"conflict_type"`
	DeviceID         string     `json:"device_id"`
	Description      string     `json:"description"`
}

RuleConflict represents a conflict between rules

type RuleEngine added in v0.4.0

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

RuleEngine handles rule evaluation and target device determination

func NewRuleEngine added in v0.4.0

func NewRuleEngine(rulesManager *RulesManager, deviceAliasManager *DeviceAliasManager) *RuleEngine

NewRuleEngine creates a new rule engine

func (*RuleEngine) AutoResolveConflicts added in v0.4.0

func (re *RuleEngine) AutoResolveConflicts() (int, error)

AutoResolveConflicts automatically resolves conflicts by keeping newer rules

func (*RuleEngine) DetectRuleConflicts added in v0.4.0

func (re *RuleEngine) DetectRuleConflicts() ([]RuleConflict, error)

DetectRuleConflicts analyzes all rules and detects conflicts

func (*RuleEngine) EvaluateRules added in v0.4.0

func (re *RuleEngine) EvaluateRules(record *storage.CommandRecord) (*RuleEvaluationResult, error)

EvaluateRules evaluates all applicable rules for a command and returns target devices

func (*RuleEngine) GetDefaultTargets added in v0.4.0

func (re *RuleEngine) GetDefaultTargets() (*RuleEvaluationResult, error)

GetDefaultTargets returns the default sync behavior (all active devices)

func (*RuleEngine) GetEvaluationDiagnostics added in v0.4.0

func (re *RuleEngine) GetEvaluationDiagnostics() (map[string]interface{}, error)

GetEvaluationDiagnostics returns detailed diagnostic information about rule evaluation

func (*RuleEngine) GetRuleEvaluationStats added in v0.4.0

func (re *RuleEngine) GetRuleEvaluationStats() (map[string]interface{}, error)

GetRuleEvaluationStats returns statistics about rule evaluation efficiency

func (*RuleEngine) GetTargetDevicesForCurrentDevice added in v0.4.0

func (re *RuleEngine) GetTargetDevicesForCurrentDevice() ([]string, error)

GetTargetDevicesForCurrentDevice returns devices that the current device should sync to

func (*RuleEngine) ReEvaluateAllUnsyncedCommands added in v0.4.0

func (re *RuleEngine) ReEvaluateAllUnsyncedCommands() (*BatchEvaluationResult, error)

ReEvaluateAllUnsyncedCommands re-evaluates rules for all unsynced commands with parallel processing

func (*RuleEngine) ReEvaluateAllUnsyncedCommandsWithConfig added in v0.4.0

func (re *RuleEngine) ReEvaluateAllUnsyncedCommandsWithConfig(config *BatchEvaluationConfig) (*BatchEvaluationResult, error)

ReEvaluateAllUnsyncedCommandsWithConfig re-evaluates rules with custom configuration

func (*RuleEngine) ResolveConflict added in v0.4.0

func (re *RuleEngine) ResolveConflict(conflict RuleConflict, keepRuleID string) error

ResolveConflict resolves a conflict by deleting the older conflicting rule

func (*RuleEngine) SimulateRuleEvaluation added in v0.4.0

func (re *RuleEngine) SimulateRuleEvaluation(command, workingDir string, tags []string) (*RuleEvaluationResult, error)

SimulateRuleEvaluation simulates rule evaluation for a given command string

func (*RuleEngine) TestRuleEvaluationForAllDevices added in v0.4.0

func (re *RuleEngine) TestRuleEvaluationForAllDevices(command string) (map[string]*RuleEvaluationResult, error)

TestRuleEvaluationForAllDevices tests rule evaluation against all known devices

func (*RuleEngine) ValidateRuleLogic added in v0.4.0

func (re *RuleEngine) ValidateRuleLogic() ([]string, error)

ValidateRuleLogic checks for potential rule conflicts or issues

type RuleEvaluationResult added in v0.4.0

type RuleEvaluationResult struct {
	TargetDevices []string `json:"target_devices"`
	RulesApplied  []string `json:"rules_applied"`
	DefaultUsed   bool     `json:"default_used"`
	Explanation   string   `json:"explanation,omitempty"`
}

RuleEvaluationResult contains the result of rule evaluation

type RuleSummary added in v0.4.0

type RuleSummary struct {
	TotalRules  int `json:"total_rules"`
	ActiveRules int `json:"active_rules"`
	AllowRules  int `json:"allow_rules"`
	DenyRules   int `json:"deny_rules"`
}

RuleSummary provides an overview of rules

type RulesManager added in v0.4.0

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

RulesManager handles sync rule creation, storage, and management

func NewRulesManager added in v0.4.0

func NewRulesManager(storage *securestorage.SecureStorage, cfg *config.Config, deviceAliasManager *DeviceAliasManager) *RulesManager

NewRulesManager creates a new rules manager

func (*RulesManager) CreateAllowRule added in v0.4.0

func (rm *RulesManager) CreateAllowRule(deviceAliasOrID string) error

CreateAllowRule creates a simple allow rule for a device

func (*RulesManager) CreateConditionalAllowRule added in v0.4.0

func (rm *RulesManager) CreateConditionalAllowRule(deviceAliasOrID string, conditions []RuleCondition) error

CreateConditionalAllowRule creates an allow rule with specific conditions

func (*RulesManager) CreateConditionalDenyRule added in v0.4.0

func (rm *RulesManager) CreateConditionalDenyRule(deviceAliasOrID string, conditions []RuleCondition) error

CreateConditionalDenyRule creates a deny rule with specific conditions

func (*RulesManager) CreateDenyRule added in v0.4.0

func (rm *RulesManager) CreateDenyRule(deviceAliasOrID string) error

CreateDenyRule creates a simple deny rule for a device

func (*RulesManager) CreateDirectoryRule added in v0.4.0

func (rm *RulesManager) CreateDirectoryRule(deviceAliasOrID, directory string, allow bool) error

CreateDirectoryRule creates a rule based on working directory

func (*RulesManager) CreatePatternRule added in v0.4.0

func (rm *RulesManager) CreatePatternRule(deviceAliasOrID, pattern string, allow bool) error

CreatePatternRule creates a rule based on command pattern

func (*RulesManager) CreateRule added in v0.4.0

func (rm *RulesManager) CreateRule(rule *SyncRule) error

CreateRule creates a new sync rule

func (*RulesManager) CreateTagRule added in v0.4.0

func (rm *RulesManager) CreateTagRule(deviceAliasOrID, tag string, allow bool) error

CreateTagRule creates a rule based on command tags

func (*RulesManager) CreateTimeRule added in v0.4.0

func (rm *RulesManager) CreateTimeRule(deviceAliasOrID, timeCondition string, allow bool) error

CreateTimeRule creates a rule based on time constraints

func (*RulesManager) DeleteRule added in v0.4.0

func (rm *RulesManager) DeleteRule(ruleID string) error

DeleteRule deletes a rule by ID

func (*RulesManager) ForceReEvaluation added in v0.4.0

func (rm *RulesManager) ForceReEvaluation() error

ForceReEvaluation forces re-evaluation of all commands for testing purposes

func (*RulesManager) GetActiveRules added in v0.4.0

func (rm *RulesManager) GetActiveRules() ([]SyncRule, error)

GetActiveRules returns only active rules

func (*RulesManager) GetRule added in v0.4.0

func (rm *RulesManager) GetRule(ruleID string) (*SyncRule, error)

GetRule returns a specific rule by ID

func (*RulesManager) GetRulesForDevice added in v0.4.0

func (rm *RulesManager) GetRulesForDevice(deviceID string) ([]SyncRule, error)

GetRulesForDevice returns all rules that apply to a specific device

func (*RulesManager) GetRulesSummary added in v0.4.0

func (rm *RulesManager) GetRulesSummary() (*RuleSummary, error)

GetRulesSummary returns a summary of all rules

func (*RulesManager) HasRules added in v0.4.0

func (rm *RulesManager) HasRules() (bool, error)

HasRules returns true if any rules exist in the system

func (*RulesManager) ListRules added in v0.4.0

func (rm *RulesManager) ListRules() ([]SyncRule, error)

ListRules returns all sync rules

func (*RulesManager) ToggleRule added in v0.4.0

func (rm *RulesManager) ToggleRule(ruleID string, active bool) error

ToggleRule enables or disables a rule

func (*RulesManager) UpdateRule added in v0.4.0

func (rm *RulesManager) UpdateRule(rule *SyncRule) error

UpdateRule updates an existing rule

type ServerDevice added in v0.4.0

type ServerDevice struct {
	DeviceID string `json:"device_id"`
	Hostname string `json:"hostname"`
	Platform string `json:"platform"`
	LastSeen string `json:"last_seen"`
	IsActive bool   `json:"is_active"`
}

type ServerErrorResponse

type ServerErrorResponse struct {
	Error   string                 `json:"error"`
	Message string                 `json:"message"`
	Code    string                 `json:"code"`
	Details map[string]interface{} `json:"details,omitempty"`
}

type ServerPasswordChangeRequest

type ServerPasswordChangeRequest struct {
	CurrentPassword string `json:"current_password"`
	NewPassword     string `json:"new_password"`
	ConfirmPassword string `json:"confirm_password"`
}

ServerPasswordChangeRequest represents the request to change password on server

type ServerPasswordChangeResponse

type ServerPasswordChangeResponse struct {
	Success   bool   `json:"success"`
	Message   string `json:"message"`
	Timestamp int64  `json:"timestamp"`
}

ServerPasswordChangeResponse represents the response from server password change

type ServerState

type ServerState struct {
	TotalRecordsForUser int64  `json:"total_records_for_user"`
	HashChecksum        string `json:"hash_checksum"`
	LatestTimestamp     int64  `json:"latest_timestamp"`
}

ServerState contains the server's state information

type StorageInterface

type StorageInterface interface {
	MarkRecordSyncedByHash(hash string) error
	MarkConflictResolvedByHash(hash string) error
	GetRecordByHash(hash string) (*storage.CommandRecord, error)
	UpdateRecord(record *storage.CommandRecord) error
}

StorageInterface defines operations needed by conflict resolver

type StoredCredentials

type StoredCredentials struct {
	AccessToken  []byte `json:"access_token"`  // Encrypted access token
	RefreshToken []byte `json:"refresh_token"` // Encrypted refresh token
	ExpiresAt    int64  `json:"expires_at"`    // Access token expiry
	UserID       string `json:"user_id"`
	DeviceID     string `json:"device_id"`
	Version      int    `json:"version"` // For future migrations
}

type SubscriptionCancelResponse

type SubscriptionCancelResponse struct {
	Success       bool   `json:"success"`
	Message       string `json:"message"`
	CancelledAt   string `json:"cancelled_at"`
	EffectiveDate string `json:"effective_date"`
	AccessInfo    string `json:"access_info"`
}

SubscriptionCancelResponse represents the API response for subscription cancellation

type SuccessResponse

type SuccessResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
}

Generic response types

type SyncActions

type SyncActions struct {
	MissingRecords   []MissingRecord `json:"missing_records"`
	OrphanedHashes   []string        `json:"orphaned_hashes"`
	ConflictedHashes []string        `json:"conflicted_hashes"`
}

SyncActions contains the actions needed to achieve perfect sync

type SyncClient

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

func NewSyncClient

func NewSyncClient(cfg *config.Config, remoteAuth *RemoteAuthenticator) *SyncClient

func (*SyncClient) BatchUpdateRecords

func (sc *SyncClient) BatchUpdateRecords(request *BatchUpdateRequest) error

BatchUpdateRecords uploads a batch of re-encrypted records during password change

func (*SyncClient) ChangeServerPassword

func (sc *SyncClient) ChangeServerPassword(currentPasswordHex, newPasswordHex string) (*ServerPasswordChangeResponse, error)

ChangeServerPassword changes password on server and acquires password change lock

func (*SyncClient) CleanupOldRecords

func (sc *SyncClient) CleanupOldRecords(retentionDays int) (*CleanupResponse, error)

func (*SyncClient) DeleteAccount

func (sc *SyncClient) DeleteAccount() (*DeleteAccountResponse, error)

func (*SyncClient) DeleteDevice

func (sc *SyncClient) DeleteDevice(deviceID string) (*DeleteDeviceResponse, error)

func (*SyncClient) DetailedHealth

func (sc *SyncClient) DetailedHealth() (*DetailedHealthResponse, error)

func (*SyncClient) DownloadRecords

func (sc *SyncClient) DownloadRecords(deviceID string, since int64, limit int, includeDeleted bool) (*SyncDownloadResponse, error)

func (*SyncClient) GetDevices added in v0.4.0

func (sc *SyncClient) GetDevices() ([]ServerDevice, error)

GetDevices fetches the list of devices for the current user

func (*SyncClient) GetPasswordChangeLockStatus

func (sc *SyncClient) GetPasswordChangeLockStatus() (*PasswordChangeLockStatus, error)

GetPasswordChangeLockStatus checks the status of password change lock

func (*SyncClient) GetSyncStatus

func (sc *SyncClient) GetSyncStatus(deviceID string) (*SyncStatusResponse, error)

func (*SyncClient) GetUserDevices

func (sc *SyncClient) GetUserDevices() (*DevicesResponse, error)

func (*SyncClient) GetUserProfile

func (sc *SyncClient) GetUserProfile() (*UserProfile, error)

User management endpoints

func (*SyncClient) Health

func (sc *SyncClient) Health() (*HealthResponse, error)

Health endpoints

func (*SyncClient) Login

func (sc *SyncClient) Login(email, password string, device DeviceRegistration) (*LoginResponse, error)

func (*SyncClient) Logout

func (sc *SyncClient) Logout(deviceID string) error

func (*SyncClient) RefreshToken

func (sc *SyncClient) RefreshToken(refreshToken string) (*LoginResponse, error)

func (*SyncClient) Register

func (sc *SyncClient) Register(email, password, confirmPassword string, device DeviceRegistration) (*RegisterResponse, error)

Auth endpoints

func (*SyncClient) UpdateUserProfile

func (sc *SyncClient) UpdateUserProfile(email string) (*UserProfile, error)

func (*SyncClient) UploadRecords

func (sc *SyncClient) UploadRecords(records []SyncRecord, deviceID string, metadata SyncMetadata) (*SyncUploadResponse, error)

Sync endpoints

func (*SyncClient) VerifyIntegrity

func (sc *SyncClient) VerifyIntegrity(request *PerfectSyncRequest) (*PerfectSyncResponse, error)

VerifyIntegrity performs Perfect Sync integrity verification with the server

type SyncDownloadResponse

type SyncDownloadResponse struct {
	Records       []SyncRecord `json:"records"`
	HasMore       bool         `json:"has_more"`
	NextTimestamp int64        `json:"next_timestamp,omitempty"`
	TotalCount    int          `json:"total_count"`
	SyncSessionID string       `json:"sync_session_id"`
}

type SyncError

type SyncError struct {
	Type        string            `json:"type"`
	Message     string            `json:"message"`
	Code        string            `json:"code"`
	Recoverable bool              `json:"recoverable"`
	RetryAfter  time.Time         `json:"retry_after,omitempty"`
	Context     map[string]string `json:"context,omitempty"`
	Cause       error             `json:"-"`
}

SyncError represents a comprehensive sync error with context and recovery information

func NewAuthError

func NewAuthError(message string, cause error) *SyncError

NewAuthError creates an authentication-related sync error

func NewCorruptionError

func NewCorruptionError(message string, cause error) *SyncError

NewCorruptionError creates a corruption-related sync error

func NewIntegrityError

func NewIntegrityError(message string, cause error) *SyncError

NewIntegrityError creates an integrity-related sync error

func NewNetworkError

func NewNetworkError(message string, cause error) *SyncError

NewNetworkError creates a network-related sync error

func NewQuotaError

func NewQuotaError(message string, cause error) *SyncError

NewQuotaError creates a quota-related sync error

func NewSyncError

func NewSyncError(errType, message, code string, recoverable bool, cause error) *SyncError

NewSyncError creates a new sync error with the given parameters

func (*SyncError) AddContext

func (e *SyncError) AddContext(key, value string) *SyncError

AddContext adds contextual information to the error

func (*SyncError) Error

func (e *SyncError) Error() string

Error implements the error interface

func (*SyncError) IsRetryable

func (e *SyncError) IsRetryable() bool

IsRetryable returns true if the error can be retried

func (*SyncError) Unwrap

func (e *SyncError) Unwrap() error

Unwrap returns the underlying error for error unwrapping

func (*SyncError) WithRetryAfter

func (e *SyncError) WithRetryAfter(retryAfter time.Time) *SyncError

WithRetryAfter sets the retry time for the error

type SyncMetadata

type SyncMetadata struct {
	ClientVersion    string `json:"client_version"`
	LastSyncTime     int64  `json:"last_sync_time"`
	TotalRecordCount int    `json:"total_record_count"`
}

type SyncMetrics

type SyncMetrics struct {
	IntegritySyncDuration  time.Duration `json:"integrity_sync_duration"`
	HashCollectionDuration time.Duration `json:"hash_collection_duration"`
	NetworkRequestDuration time.Duration `json:"network_request_duration"`
	RecordsDownloaded      int64         `json:"records_downloaded"`
	RecordsUploaded        int64         `json:"records_uploaded"`
	IntegrityScore         float64       `json:"integrity_score"`
	RequestSizeBytes       int64         `json:"request_size_bytes"`
	ResponseSizeBytes      int64         `json:"response_size_bytes"`
	HashesProcessed        int64         `json:"hashes_processed"`
	ConflictsResolved      int64         `json:"conflicts_resolved"`
	ErrorsEncountered      int64         `json:"errors_encountered"`
}

SyncMetrics contains detailed metrics for Perfect Sync operations

type SyncRecord

type SyncRecord struct {
	RecordHash       string   `json:"record_hash"`
	EncryptedPayload []byte   `json:"encrypted_payload"`
	TimestampMs      int64    `json:"timestamp_ms"`
	Hostname         string   `json:"hostname"`
	SessionID        string   `json:"session_id"`
	TargetDevices    []string `json:"target_devices,omitempty"` // Routing metadata
}

type SyncRule added in v0.4.0

type SyncRule struct {
	ID           string          `json:"id"`
	Name         string          `json:"name"`
	Description  string          `json:"description,omitempty"`
	Action       string          `json:"action"`        // "allow" or "deny"
	TargetDevice string          `json:"target_device"` // Device ID (not alias)
	Conditions   []RuleCondition `json:"conditions,omitempty"`
	Active       bool            `json:"active"`
	CreatedAt    int64           `json:"created_at"`
	UpdatedAt    int64           `json:"updated_at"`
}

SyncRule represents a sync rule configuration

type SyncService

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

func NewSyncService

func NewSyncService(cfg *config.Config, storage *securestorage.SecureStorage, localAuth *auth.AuthManager) *SyncService

func (*SyncService) ApplySyncActions

func (s *SyncService) ApplySyncActions(actions SyncActions) error

ApplySyncActions processes the sync actions returned by the server

func (*SyncService) Authenticate

func (s *SyncService) Authenticate(email, password string) error

func (*SyncService) BatchReencryptRecords

func (s *SyncService) BatchReencryptRecords(newKey []byte) (string, error)

BatchReencryptRecords re-encrypts all records with new key and saves to staging

func (*SyncService) BatchUpdateRemoteRecords

func (s *SyncService) BatchUpdateRemoteRecords(stagingPath string) error

BatchUpdateRemoteRecords uploads re-encrypted records in batches during password change

func (*SyncService) BuildLocalIntegrityState

func (s *SyncService) BuildLocalIntegrityState() (*LocalIntegrityState, error)

BuildLocalIntegrityState collects all local record hashes and metadata

func (*SyncService) CleanupStagingArea

func (s *SyncService) CleanupStagingArea(stagingPath string) error

CleanupStagingArea removes the staging file and directory (public method)

func (*SyncService) Close

func (s *SyncService) Close() error

func (*SyncService) CreateStagingArea

func (s *SyncService) CreateStagingArea() (string, error)

CreateStagingArea creates a temporary directory for storing re-encrypted records

func (*SyncService) DivideToBatches

func (s *SyncService) DivideToBatches(records []RecordUpdate, batchSize int) [][]RecordUpdate

DivideToBatches splits records into batches of specified size

func (*SyncService) DownloadNewRecords

func (s *SyncService) DownloadNewRecords() error

func (*SyncService) GetDeviceAliasManager added in v0.4.0

func (s *SyncService) GetDeviceAliasManager() *DeviceAliasManager

GetDeviceAliasManager returns the device alias manager

func (*SyncService) GetRemoteAuth

func (s *SyncService) GetRemoteAuth() *RemoteAuthenticator

func (*SyncService) GetRuleEngine added in v0.4.0

func (s *SyncService) GetRuleEngine() *RuleEngine

GetRuleEngine returns the rule engine

func (*SyncService) GetRulesManager added in v0.4.0

func (s *SyncService) GetRulesManager() *RulesManager

GetRulesManager returns the rules manager

func (*SyncService) GetSyncStats

func (s *SyncService) GetSyncStats() SyncStats

func (*SyncService) Initialize

func (s *SyncService) Initialize() error

func (*SyncService) IsEnabled

func (s *SyncService) IsEnabled() bool

func (*SyncService) IsRunning

func (s *SyncService) IsRunning() bool

func (*SyncService) LoadFromStaging

func (s *SyncService) LoadFromStaging(stagingPath string) ([]RecordUpdate, error)

LoadFromStaging loads re-encrypted records from the staging area

func (*SyncService) Logout

func (s *SyncService) Logout() error

func (*SyncService) PerformIntegritySync

func (s *SyncService) PerformIntegritySync() error

PerformIntegritySync performs Perfect Sync using hash-based integrity verification with comprehensive error handling

func (*SyncService) PerformSync

func (s *SyncService) PerformSync() error

func (*SyncService) SaveToStaging

func (s *SyncService) SaveToStaging(stagingPath string, records []RecordUpdate) error

SaveToStaging saves re-encrypted records to the staging area

func (*SyncService) SyncNow

func (s *SyncService) SyncNow() error

SyncNow performs a full synchronization to ensure local and remote data match

func (*SyncService) TestConnection

func (s *SyncService) TestConnection() error

func (*SyncService) UploadNewRecords

func (s *SyncService) UploadNewRecords() error

func (*SyncService) VerifyIntegrity

func (s *SyncService) VerifyIntegrity() (*PerfectSyncResponse, error)

VerifyIntegrity performs Perfect Sync integrity verification with the server

type SyncStatistics

type SyncStatistics struct {
	RecordsToDownload int     `json:"records_to_download"`
	RecordsToRemove   int     `json:"records_to_remove"`
	PerfectMatches    int     `json:"perfect_matches"`
	IntegrityScore    float64 `json:"integrity_score"`
}

SyncStatistics contains metrics about the sync operation

type SyncStats

type SyncStats struct {
	LastSyncTime      int64         `json:"last_sync_time"`
	TotalUploaded     int64         `json:"total_uploaded"`
	TotalDownloaded   int64         `json:"total_downloaded"`
	ConflictsResolved int64         `json:"conflicts_resolved"`
	LastSyncDuration  time.Duration `json:"last_sync_duration"`
	ErrorCount        int64         `json:"error_count"`
	IsAuthenticated   bool          `json:"is_authenticated"`
}

type SyncStatusResponse

type SyncStatusResponse struct {
	LastSyncTime   int64 `json:"last_sync_time"`
	TotalRecords   int   `json:"total_records"`
	PendingUploads int   `json:"pending_uploads"`
	RecentSessions []struct {
		ID                string `json:"id"`
		StartedAt         string `json:"started_at"`
		CompletedAt       string `json:"completed_at"`
		RecordsUploaded   int    `json:"records_uploaded"`
		RecordsDownloaded int    `json:"records_downloaded"`
		ConflictsResolved int    `json:"conflicts_resolved"`
		Status            string `json:"status"`
	} `json:"recent_sessions"`
	DeviceCount int   `json:"device_count"`
	StorageUsed int64 `json:"storage_used"`
}

type SyncUploadRequest

type SyncUploadRequest struct {
	DeviceID string       `json:"device_id"`
	Records  []SyncRecord `json:"records"`
	Metadata SyncMetadata `json:"metadata"`
}

Sync endpoint types

type SyncUploadResponse

type SyncUploadResponse struct {
	Success        bool   `json:"success"`
	ProcessedCount int    `json:"processed_count"`
	DuplicateCount int    `json:"duplicate_count"`
	ErrorCount     int    `json:"error_count"`
	Conflicts      int    `json:"conflicts,omitempty"`
	SyncSessionID  string `json:"sync_session_id"`
}

type TokenManager

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

func NewTokenManager

func NewTokenManager(cfg *config.Config) *TokenManager

func (*TokenManager) ClearToken

func (tm *TokenManager) ClearToken() error

func (*TokenManager) CreateTokenFromAuth

func (tm *TokenManager) CreateTokenFromAuth(auth *AuthResponse) *JWTToken

func (*TokenManager) GetDeviceID

func (tm *TokenManager) GetDeviceID() string

func (*TokenManager) GetTimeUntilExpiry

func (tm *TokenManager) GetTimeUntilExpiry() (time.Duration, error)

func (*TokenManager) GetTokenAge

func (tm *TokenManager) GetTokenAge() (time.Duration, error)

func (*TokenManager) GetTokenInfo

func (tm *TokenManager) GetTokenInfo() (*JWTToken, error)

func (*TokenManager) GetUserID

func (tm *TokenManager) GetUserID() string

func (*TokenManager) GetValidToken

func (tm *TokenManager) GetValidToken() (string, error)

func (*TokenManager) IsExpiringSoon

func (tm *TokenManager) IsExpiringSoon(threshold time.Duration) bool

func (*TokenManager) IsTokenValid

func (tm *TokenManager) IsTokenValid() bool

func (*TokenManager) LoadToken

func (tm *TokenManager) LoadToken() error

func (*TokenManager) SaveToken

func (tm *TokenManager) SaveToken(token *JWTToken) error

func (*TokenManager) ValidateTokenStructure

func (tm *TokenManager) ValidateTokenStructure() error

type TokenValidationResponse

type TokenValidationResponse struct {
	Valid     bool   `json:"valid"`
	Message   string `json:"message"`
	ExpiresAt int64  `json:"expires_at,omitempty"`
	Error     string `json:"error,omitempty"`
}

type UpdateProfileRequest

type UpdateProfileRequest struct {
	Email string `json:"email,omitempty"`
}

type UserDevice

type UserDevice struct {
	ID          string `json:"id"`
	DeviceID    string `json:"device_id"`
	DeviceName  string `json:"device_name"`
	Hostname    string `json:"hostname"`
	Platform    string `json:"platform"`
	LastSeen    string `json:"last_seen"`
	CreatedAt   string `json:"created_at"`
	RecordCount int    `json:"record_count"`
	IsActive    bool   `json:"is_active"`
}

type UserProfile

type UserProfile struct {
	UserID      string `json:"user_id"`
	Email       string `json:"email"`
	CreatedAt   string `json:"created_at"`
	LastLogin   string `json:"last_login"`
	DeviceCount int    `json:"device_count"`
	RecordCount int    `json:"record_count"`
	StorageUsed int64  `json:"storage_used"`
	IsActive    bool   `json:"is_active"`
}

User management types

Jump to

Keyboard shortcuts

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