GuardianDB

Struct GuardianDB 

Source
pub struct GuardianDB { /* private fields */ }

Implementations§

Source§

impl GuardianDB

Source

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.

Source

pub async fn new_guardian_db( ipfs: IpfsClient, identity: Identity, options: Option<NewGuardianDBOptions>, ) -> Result<Self>

Construtor principal para uma instância de GuardianDB.

Source

pub fn tracer(&self) -> Arc<BoxedTracer>

Retorna o tracer para telemetria e monitoramento.

Source

pub fn span(&self) -> &Span

Retorna uma referência ao span de tracing para instrumentação

Source

pub fn ipfs(&self) -> &IpfsClient

Retorna o cliente da API do IPFS (Iroh nativo).

Source

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.

Source

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.

Source

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.

Source

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ção
  • None se nenhuma função de fechamento foi definida
§Alternativa

Para uma interface mais simples, use close_key_store() diretamente.

Source

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.

Source

pub fn delete_store(&self, address: &str)

Remove uma store do mapa de stores gerenciadas. Esta operação adquire um lock de escrita.

Source

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.

Source

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.

Source

pub fn close_cache(&self)

Fecha o cache LevelDown, garantindo que todos os dados sejam persistidos e liberando os recursos associados.

Source

pub async fn close_direct_connections(&self)

Fecha o canal de comunicação direta e registra um erro se a operação falhar.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub async fn register_access_controller_type( &self, constructor: AccessControllerConstructor, ) -> Result<()>

Método legado mantido por compatibilidade - usa tipo padrão “simple”

Source

pub fn register_store_type( &self, store_type: String, constructor: StoreConstructor, )

Source

pub fn unregister_store_type(&self, store_type: &str)

Remove um construtor de Store do mapa pelo seu tipo.

Source

pub fn store_types_names(&self) -> Vec<String>

Retorna uma lista com os nomes de todos os tipos de Store registrados.

Source

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.

Source

pub async fn close(&self) -> Result<()>

Encerra a instância do GuardianDB, fechando todas as stores, conexões e tarefas em background.

Source

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.

Source

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.

Source

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.

Source

pub async fn load_cache( &self, directory: &Path, db_address: &GuardianDBAddress, ) -> Result<()>

Carrega o cache para um determinado endereço de banco de dados.

Source

pub async fn have_local_data(&self, db_address: &GuardianDBAddress) -> bool

Verifica se o manifesto de um banco de dados existe no cache local.

Source

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.

Source

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.

Source

pub async fn register_default_access_controller_types(&self) -> Result<()>

Registra os construtores padrão de access controllers disponíveis

Source

pub fn register_default_store_types(&self)

Registra os construtores padrão de stores disponíveis

Source

pub fn event_bus(&self) -> Arc<EventBusImpl>

Retorna o barramento de eventos da instância do GuardianDB.

Source

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.

Source

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:

  1. Validação de integridade dos heads
  2. Verificação de permissões de acesso
  3. Detecção de duplicatas existentes
  4. Sincronização efetiva com a store
  5. Emissão de eventos de progresso
§Argumentos
  • event - Evento contendo os heads a serem sincronizados e metadados
  • store - Referência à store que receberá os heads
§Processamento
  1. Validação Básica: Verifica se os heads possuem dados válidos (hash, payload)
  2. Controle de Acesso: Usa o access controller da store para validar permissões
  3. Detecção de Duplicatas: Consulta o oplog para evitar reprocessamento
  4. Sincronização: Delega para o método sync() da store que implementa a lógica completa
  5. 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

Source§

type Error = GuardianError

Define um tipo de erro associado para flexibilidade na implementação.
Source§

fn ipfs(&self) -> Arc<IpfsClient>

Retorna a instância da API do IPFS.
Source§

fn identity(&self) -> Arc<Identity>

Retorna a identidade utilizada pelo GuardianDB.
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,

Cria ou abre uma store com o endereço e opções fornecidos.
Source§

fn get_store( &self, address: &str, ) -> Option<Arc<dyn Store<Error = GuardianError>>>

Retorna uma instância da store se ela já estiver aberta.
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,

Cria uma nova store com o nome, tipo e opções fornecidos.
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,

Determina o endereço de um banco de dados com base nos seus parâmetros.
Source§

fn register_store_type( &mut self, store_type: &str, constructor: StoreConstructor, )

Registra um novo tipo de Store.
Source§

fn unregister_store_type(&mut self, store_type: &str)

Desregistra um tipo de Store.
Source§

fn register_access_controller_type( &mut self, constructor: AccessControllerConstructor, ) -> Result<(), Self::Error>

Registra um novo tipo de Access Controller.
Source§

fn unregister_access_controller_type(&mut self, controller_type: &str)

Desregistra um tipo de Access Controller.
Source§

fn get_access_controller_type( &self, controller_type: &str, ) -> Option<AccessControllerConstructor>

Obtém um construtor de Access Controller pelo seu tipo.
Source§

fn event_bus(&self) -> EventBus

Retorna o barramento de eventos.
Source§

fn span(&self) -> &Span

Retorna o span para tracing.
Source§

fn tracer(&self) -> Arc<TracerWrapper>

Retorna o tracer para telemetria.
Source§

impl Drop for GuardianDB

Implementação do Drop trait para garantir cleanup seguro do GuardianDB

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CompatExt for T

Source§

fn compat(self) -> Compat<T>

Applies the Compat adapter by value. Read more
Source§

fn compat_ref(&self) -> Compat<&T>

Applies the Compat adapter by shared reference. Read more
Source§

fn compat_mut(&mut self) -> Compat<&mut T>

Applies the Compat adapter by mutable reference. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> References<RawCodec> for T

Source§

fn references<R, E>(_c: RawCodec, _r: &mut R, _set: &mut E) -> Result<(), Error>
where R: Read, E: Extend<Cid<64>>,

Scrape the references from an impl Read. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more