pub struct GuardianDB { /* private fields */ }Implementations§
Source§impl GuardianDB
impl GuardianDB
Sourcepub async fn new(
ipfs_config: Option<ClientConfig>,
options: Option<NewGuardianDBOptions>,
) -> Result<Self>
pub async fn new( ipfs_config: Option<ClientConfig>, options: Option<NewGuardianDBOptions>, ) -> Result<Self>
Construtor de alto nível que configura o Keystore e a Identidade.
Sourcepub async fn new_guardian_db(
ipfs: IpfsClient,
identity: Identity,
options: Option<NewGuardianDBOptions>,
) -> Result<Self>
pub async fn new_guardian_db( ipfs: IpfsClient, identity: Identity, options: Option<NewGuardianDBOptions>, ) -> Result<Self>
Construtor principal para uma instância de GuardianDB.
Sourcepub fn tracer(&self) -> Arc<BoxedTracer>
pub fn tracer(&self) -> Arc<BoxedTracer>
Retorna o tracer para telemetria e monitoramento.
Sourcepub fn ipfs(&self) -> &IpfsClient
pub fn ipfs(&self) -> &IpfsClient
Retorna o cliente da API do IPFS (Iroh nativo).
Sourcepub fn identity(&self) -> Identity
pub fn identity(&self) -> Identity
Retorna a identidade da instância do GuardianDB. A identidade é clonada para que o chamador possa usá-la sem manter o lock de leitura ativo.
Sourcepub fn peer_id(&self) -> PeerId
pub fn peer_id(&self) -> PeerId
Retorna o PeerId da instância do GuardianDB.
PeerId implementa o trait Copy, então o valor é copiado, o que é muito eficiente.
Sourcepub fn keystore(&self) -> Arc<RwLock<Option<Box<dyn Keystore + Send + Sync>>>> ⓘ
pub fn keystore(&self) -> Arc<RwLock<Option<Box<dyn Keystore + Send + Sync>>>> ⓘ
Retorna um clone do Arc para o Keystore, permitindo o acesso compartilhado.
O keystore é configurado durante a inicialização e pode ser usado para operações criptográficas.
Sourcepub fn close_keystore(
&self,
) -> Option<Box<dyn Fn() -> Result<()> + Send + Sync>>
pub fn close_keystore( &self, ) -> Option<Box<dyn Fn() -> Result<()> + Send + Sync>>
Retorna a função de fechamento para o Keystore, se existir.
Esta função retorna uma closure que pode ser chamada para fechar o keystore. A closure captura uma referência clonada para o campo close_keystore interno.
§Retorna
Some(closure)se uma função de fechamento foi configurada durante a inicializaçãoNonese nenhuma função de fechamento foi definida
§Alternativa
Para uma interface mais simples, use close_key_store() diretamente.
Sourcepub fn set_store(
&self,
address: String,
store: Arc<dyn Store<Error = GuardianError> + Send + Sync>,
)
pub fn set_store( &self, address: String, store: Arc<dyn Store<Error = GuardianError> + Send + Sync>, )
Adiciona ou atualiza uma store no mapa de stores gerenciadas. Esta operação adquire um lock de escrita.
Sourcepub fn delete_store(&self, address: &str)
pub fn delete_store(&self, address: &str)
Remove uma store do mapa de stores gerenciadas. Esta operação adquire um lock de escrita.
Sourcepub fn get_store(
&self,
address: &str,
) -> Option<Arc<dyn Store<Error = GuardianError> + Send + Sync>>
pub fn get_store( &self, address: &str, ) -> Option<Arc<dyn Store<Error = GuardianError> + Send + Sync>>
Busca uma store no mapa pelo seu endereço.
Retorna Some(store) se encontrada, ou None caso contrário.
Sourcepub async fn close_all_stores(&self)
pub async fn close_all_stores(&self)
Itera sobre todas as stores gerenciadas e chama o método close() de cada uma.
Clona a lista de stores para evitar manter o lock durante a chamada a close(),
prevenindo possíveis deadlocks.
Sourcepub fn close_cache(&self)
pub fn close_cache(&self)
Fecha o cache LevelDown, garantindo que todos os dados sejam persistidos e liberando os recursos associados.
Sourcepub async fn close_direct_connections(&self)
pub async fn close_direct_connections(&self)
Fecha o canal de comunicação direta e registra um erro se a operação falhar.
Sourcepub fn close_key_store(&self)
pub fn close_key_store(&self)
Executa a função de fechamento do keystore, se ela tiver sido definida. Adquire um lock de escrita para garantir que a função não seja modificada enquanto é lida e executada.
Sourcepub fn get_access_controller_type(
&self,
controller_type: &str,
) -> Option<AccessControllerConstructor>
pub fn get_access_controller_type( &self, controller_type: &str, ) -> Option<AccessControllerConstructor>
Busca um construtor de AccessController pelo seu tipo (nome).
Retorna Some(constructor) se encontrado, ou None caso contrário.
Sourcepub fn access_controller_types_names(&self) -> Vec<String>
pub fn access_controller_types_names(&self) -> Vec<String>
Retorna uma lista com os nomes de todos os tipos de AccessController registrados. Função auxiliar para debug e listagem de tipos disponíveis.
Sourcepub fn unregister_access_controller_type(&self, controller_type: &str)
pub fn unregister_access_controller_type(&self, controller_type: &str)
Remove um construtor de AccessController do mapa pelo seu tipo. Esta operação adquire um lock de escrita.
Sourcepub fn register_access_controller_type_with_name(
&self,
controller_type: &str,
constructor: AccessControllerConstructor,
) -> Result<()>
pub fn register_access_controller_type_with_name( &self, controller_type: &str, constructor: AccessControllerConstructor, ) -> Result<()>
Registra um novo tipo de AccessController. A função construtora é executada uma vez para determinar o nome do tipo.
Executa o construtor para determinar o tipo dinâmico Registra um novo tipo de AccessController com tipo explícito.
Sourcepub async fn register_access_controller_type(
&self,
constructor: AccessControllerConstructor,
) -> Result<()>
pub async fn register_access_controller_type( &self, constructor: AccessControllerConstructor, ) -> Result<()>
Método legado mantido por compatibilidade - usa tipo padrão “simple”
pub fn register_store_type( &self, store_type: String, constructor: StoreConstructor, )
Sourcepub fn unregister_store_type(&self, store_type: &str)
pub fn unregister_store_type(&self, store_type: &str)
Remove um construtor de Store do mapa pelo seu tipo.
Sourcepub fn store_types_names(&self) -> Vec<String>
pub fn store_types_names(&self) -> Vec<String>
Retorna uma lista com os nomes de todos os tipos de Store registrados.
Sourcepub fn get_store_constructor(
&self,
store_type: &str,
) -> Option<StoreConstructor>
pub fn get_store_constructor( &self, store_type: &str, ) -> Option<StoreConstructor>
Busca um construtor de Store pelo seu tipo (nome).
Retorna Some(constructor) se encontrado, ou None caso contrário.
Sourcepub async fn close(&self) -> Result<()>
pub async fn close(&self) -> Result<()>
Encerra a instância do GuardianDB, fechando todas as stores, conexões e tarefas em background.
Sourcepub async fn create(
&self,
name: &str,
store_type: &str,
options: Option<CreateDBOptions>,
) -> Result<Arc<dyn Store<Error = GuardianError> + Send + Sync>>
pub async fn create( &self, name: &str, store_type: &str, options: Option<CreateDBOptions>, ) -> Result<Arc<dyn Store<Error = GuardianError> + Send + Sync>>
Cria um novo banco de dados (store), determina seu endereço, salva localmente e o abre.
Sourcepub async fn open(
&self,
db_address: &str,
options: CreateDBOptions,
) -> Result<Arc<dyn Store<Error = GuardianError> + Send + Sync>>
pub async fn open( &self, db_address: &str, options: CreateDBOptions, ) -> Result<Arc<dyn Store<Error = GuardianError> + Send + Sync>>
Abre um banco de dados a partir de um endereço GuardianDB.
Sourcepub async fn determine_address(
&self,
name: &str,
store_type: &str,
options: Option<DetermineAddressOptions>,
) -> Result<GuardianDBAddress>
pub async fn determine_address( &self, name: &str, store_type: &str, options: Option<DetermineAddressOptions>, ) -> Result<GuardianDBAddress>
Determina o endereço de um banco de dados criando seu manifesto e salvando no IPFS.
Sourcepub async fn load_cache(
&self,
directory: &Path,
db_address: &GuardianDBAddress,
) -> Result<()>
pub async fn load_cache( &self, directory: &Path, db_address: &GuardianDBAddress, ) -> Result<()>
Carrega o cache para um determinado endereço de banco de dados.
Sourcepub async fn have_local_data(&self, db_address: &GuardianDBAddress) -> bool
pub async fn have_local_data(&self, db_address: &GuardianDBAddress) -> bool
Verifica se o manifesto de um banco de dados existe no cache local.
Sourcepub async fn add_manifest_to_cache(
&self,
directory: &Path,
db_address: &GuardianDBAddress,
) -> Result<()>
pub async fn add_manifest_to_cache( &self, directory: &Path, db_address: &GuardianDBAddress, ) -> Result<()>
Adiciona o hash do manifesto de um banco de dados ao cache local.
Sourcepub async fn create_store(
&self,
store_type: &str,
address: &GuardianDBAddress,
options: CreateDBOptions,
) -> Result<Arc<dyn Store<Error = GuardianError> + Send + Sync>>
pub async fn create_store( &self, store_type: &str, address: &GuardianDBAddress, options: CreateDBOptions, ) -> Result<Arc<dyn Store<Error = GuardianError> + Send + Sync>>
Lida com a lógica complexa de instanciar uma nova Store, incluindo a resolução do Access Controller, carregamento de cache e configuração de todas as opções.
Sourcepub async fn register_default_access_controller_types(&self) -> Result<()>
pub async fn register_default_access_controller_types(&self) -> Result<()>
Registra os construtores padrão de access controllers disponíveis
Sourcepub fn register_default_store_types(&self)
pub fn register_default_store_types(&self)
Registra os construtores padrão de stores disponíveis
Sourcepub fn event_bus(&self) -> Arc<EventBusImpl>
pub fn event_bus(&self) -> Arc<EventBusImpl>
Retorna o barramento de eventos da instância do GuardianDB.
Sourcepub async fn monitor_direct_channel(
&self,
event_bus: Arc<EventBusImpl>,
) -> Result<JoinHandle<()>>
pub async fn monitor_direct_channel( &self, event_bus: Arc<EventBusImpl>, ) -> Result<JoinHandle<()>>
Inicia uma tarefa em background para escutar eventos do pubsub e processá-los.
Sourcepub async fn handle_event_exchange_heads(
&self,
event: &MessageExchangeHeads,
store: Arc<dyn Store<Error = GuardianError> + Send + Sync>,
) -> Result<()>
pub async fn handle_event_exchange_heads( &self, event: &MessageExchangeHeads, store: Arc<dyn Store<Error = GuardianError> + Send + Sync>, ) -> Result<()>
Processa um evento de troca de “heads”, sincronizando as novas entradas com a store local.
Realiza a sincronização completa dos heads recebidos, incluindo:
- Validação de integridade dos heads
- Verificação de permissões de acesso
- Detecção de duplicatas existentes
- Sincronização efetiva com a store
- Emissão de eventos de progresso
§Argumentos
event- Evento contendo os heads a serem sincronizados e metadadosstore- Referência à store que receberá os heads
§Processamento
- Validação Básica: Verifica se os heads possuem dados válidos (hash, payload)
- Controle de Acesso: Usa o access controller da store para validar permissões
- Detecção de Duplicatas: Consulta o oplog para evitar reprocessamento
- Sincronização: Delega para o método
sync()da store que implementa a lógica completa - Eventos: Emite eventos de progresso para componentes interessados
§Performance
- O(n) onde n = número de heads recebidos
- Paralelização: Validação sequencial, mas sync em batch para eficiência
- Cache-aware: Aproveita índices existentes para detecção de duplicatas
§Erros
- Retorna erro se a sincronização da store falhar
- Heads individuais inválidos são ignorados (logged) mas não causam falha geral
Trait Implementations§
Source§impl BaseGuardianDB for GuardianDB
Implementação da trait BaseGuardianDB para GuardianDB
impl BaseGuardianDB for GuardianDB
Implementação da trait BaseGuardianDB para GuardianDB
Source§type Error = GuardianError
type Error = GuardianError
Source§fn ipfs(&self) -> Arc<IpfsClient>
fn ipfs(&self) -> Arc<IpfsClient>
Source§fn open<'life0, 'life1, 'life2, 'async_trait>(
&'life0 self,
address: &'life1 str,
options: &'life2 mut CreateDBOptions,
) -> Pin<Box<dyn Future<Output = Result<Arc<dyn Store<Error = GuardianError>>, Self::Error>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
'life2: 'async_trait,
fn open<'life0, 'life1, 'life2, 'async_trait>(
&'life0 self,
address: &'life1 str,
options: &'life2 mut CreateDBOptions,
) -> Pin<Box<dyn Future<Output = Result<Arc<dyn Store<Error = GuardianError>>, Self::Error>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
'life2: 'async_trait,
Source§fn get_store(
&self,
address: &str,
) -> Option<Arc<dyn Store<Error = GuardianError>>>
fn get_store( &self, address: &str, ) -> Option<Arc<dyn Store<Error = GuardianError>>>
Source§fn create<'life0, 'life1, 'life2, 'life3, 'async_trait>(
&'life0 self,
name: &'life1 str,
store_type: &'life2 str,
options: &'life3 mut CreateDBOptions,
) -> Pin<Box<dyn Future<Output = Result<Arc<dyn Store<Error = GuardianError>>, Self::Error>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
'life2: 'async_trait,
'life3: 'async_trait,
fn create<'life0, 'life1, 'life2, 'life3, 'async_trait>(
&'life0 self,
name: &'life1 str,
store_type: &'life2 str,
options: &'life3 mut CreateDBOptions,
) -> Pin<Box<dyn Future<Output = Result<Arc<dyn Store<Error = GuardianError>>, Self::Error>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
'life2: 'async_trait,
'life3: 'async_trait,
Source§fn determine_address<'life0, 'life1, 'life2, 'life3, 'async_trait>(
&'life0 self,
name: &'life1 str,
store_type: &'life2 str,
options: &'life3 DetermineAddressOptions,
) -> Pin<Box<dyn Future<Output = Result<Box<dyn Address>, Self::Error>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
'life2: 'async_trait,
'life3: 'async_trait,
fn determine_address<'life0, 'life1, 'life2, 'life3, 'async_trait>(
&'life0 self,
name: &'life1 str,
store_type: &'life2 str,
options: &'life3 DetermineAddressOptions,
) -> Pin<Box<dyn Future<Output = Result<Box<dyn Address>, Self::Error>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
'life2: 'async_trait,
'life3: 'async_trait,
Source§fn register_store_type(
&mut self,
store_type: &str,
constructor: StoreConstructor,
)
fn register_store_type( &mut self, store_type: &str, constructor: StoreConstructor, )
Source§fn unregister_store_type(&mut self, store_type: &str)
fn unregister_store_type(&mut self, store_type: &str)
Source§fn register_access_controller_type(
&mut self,
constructor: AccessControllerConstructor,
) -> Result<(), Self::Error>
fn register_access_controller_type( &mut self, constructor: AccessControllerConstructor, ) -> Result<(), Self::Error>
Source§fn unregister_access_controller_type(&mut self, controller_type: &str)
fn unregister_access_controller_type(&mut self, controller_type: &str)
Source§fn get_access_controller_type(
&self,
controller_type: &str,
) -> Option<AccessControllerConstructor>
fn get_access_controller_type( &self, controller_type: &str, ) -> Option<AccessControllerConstructor>
Source§fn tracer(&self) -> Arc<TracerWrapper>
fn tracer(&self) -> Arc<TracerWrapper>
Auto Trait Implementations§
impl Freeze for GuardianDB
impl !RefUnwindSafe for GuardianDB
impl Send for GuardianDB
impl Sync for GuardianDB
impl Unpin for GuardianDB
impl !UnwindSafe for GuardianDB
Blanket Implementations§
Source§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
Source§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
Source§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
Source§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> FutureExt for T
impl<T> FutureExt for T
Source§fn with_context(self, otel_cx: Context) -> WithContext<Self>
fn with_context(self, otel_cx: Context) -> WithContext<Self>
Source§fn with_current_context(self) -> WithContext<Self>
fn with_current_context(self) -> WithContext<Self>
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more