Skip to content

Commit

Permalink
Update type definitions.
Browse files Browse the repository at this point in the history
  • Loading branch information
tmpfs committed Dec 6, 2024
1 parent fea1500 commit cae6416
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 180 deletions.
14 changes: 5 additions & 9 deletions crates/integration_tests/tests/ipc/local_sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,19 +77,15 @@ async fn integration_ipc_local_sync() -> Result<()> {

tokio::time::sleep(Duration::from_millis(250)).await;

// Integration mananges the accounts on the linked app
let integration = LocalIntegration::new();

// Test transport creates a IPC socket client for communication
let transport = TestLocalTransport::new(socket_name.clone()).await?;

// Integration mananges the accounts on the linked app
let integration =
LocalIntegration::new("sos-test-app", Box::new(transport));

// Prepare the local client using our test transport
let origin = Origin::new(
socket_name.to_string(),
format!("sos+ipc://{}", socket_name).parse()?,
);
let local_client =
LocalClient::new(origin, Arc::new(Mutex::new(Box::new(transport))));
let local_client = integration.client().clone();

// Prepare the linked account and add to the integration
let linked_account = LinkedAccount::new_unauthenticated(
Expand Down
4 changes: 2 additions & 2 deletions crates/ipc/src/integration/local_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ use tracing::instrument;

use bytes::Bytes;

type ClientTransport = Box<dyn LocalTransport + Send + Sync + 'static>;
pub(super) type ClientTransport =
Box<dyn LocalTransport + Send + Sync + 'static>;

/// Local client communicates with another local account
/// using a generic transport.
Expand Down Expand Up @@ -118,7 +119,6 @@ impl LocalClient {
&self,
mut response: LocalResponse,
) -> Result<Bytes> {
println!("response: {:#?}", response);
response.decompress()?;
Ok(response.body.into())
}
Expand Down
72 changes: 68 additions & 4 deletions crates/ipc/src/integration/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@
//! Typically, this would be used in the webassembly bindings
//! for a browser extension or other local integration.
use sos_sdk::prelude::{Account, AccountSwitcher};
use crate::Result;
use sos_protocol::{constants::IPC_GUI_SOCKET_NAME, Origin, RemoteSync};
use sos_sdk::prelude::{Account, AccountSwitcher, Paths, PublicIdentity};
use std::sync::Arc;
use tokio::sync::RwLock;
use tokio::sync::{Mutex, RwLock};

mod linked_account;
mod local_client;
Expand All @@ -29,21 +31,83 @@ pub type LinkedAccountSwitcher = AccountSwitcher<
/// Local app integration.
pub struct LocalIntegration {
accounts: Arc<RwLock<LinkedAccountSwitcher>>,
client: LocalClient,
}

impl LocalIntegration {
/// Create a local app integration.
pub fn new() -> Self {
pub fn new(name: &str, transport: ClientTransport) -> Self {
let url = format!("sos+ipc://{}", IPC_GUI_SOCKET_NAME);
let origin = Origin::new(
name.to_string(),
url.parse().expect("valid URL for integration origin"),
);
let transport = Arc::new(Mutex::new(transport));
let client = LocalClient::new(origin, transport);
Self {
accounts: Arc::new(RwLock::new(LinkedAccountSwitcher::new())),
client,
}
}

/// Clone of the accounts.
/// Accounts managed by this integration.
pub fn accounts(&self) -> Arc<RwLock<LinkedAccountSwitcher>> {
self.accounts.clone()
}

/// Client used to communicate with the local account.
pub fn client(&self) -> &LocalClient {
&self.client
}

/// Initialize the accounts list.
pub async fn initialize_accounts(
&mut self,
accounts: Vec<PublicIdentity>,
) -> Result<()> {
let managed_accounts = self.accounts();
let client = self.client.clone();

Paths::scaffold(None).await?;

let mut managed_accounts = managed_accounts.write().await;

for identity in accounts {
tracing::info!(address = %identity.address(), "add_account");
let account = LinkedAccount::new_unauthenticated(
*identity.address(),
client.clone(),
None,
)
.await?;

let paths = account.paths();
// tracing::info!(paths = ?paths);
paths.ensure().await?;

managed_accounts.add_account(account);
}
Ok(())
}

/// Sync the accounts data.
pub async fn sync_accounts(&mut self) -> Result<()> {
let mut accounts = self.accounts.write().await;
for account in accounts.iter_mut() {
tracing::info!(address = %account.address(), "sync_account");
let sync_result = account.sync().await;
if let Err(e) = sync_result.result {
tracing::error!(error = %e);
} else {
tracing::info!(
address = %account.address(),
"sync_account::done",
);
}
}
Ok(())
}

/*
/// Determine if a local account exists.
pub async fn local_account_exists(
Expand Down
2 changes: 0 additions & 2 deletions crates/ipc/src/local_transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,10 +262,8 @@ impl LocalResponse {
/// Decompress the response body.
pub fn decompress(&mut self) -> Result<()> {
if self.is_zlib() {
println!("decompress: {}", self.body.len());
self.body =
crate::compression::zlib::decode_all(self.body.as_slice())?;
println!("inflated : {}", self.body.len());
}
Ok(())
}
Expand Down
175 changes: 12 additions & 163 deletions packages/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,6 @@ export interface ArchiveFilter {
includeDocuments: boolean;
}

/** Qualified path to a specific secret in a target account. */
export interface QualifiedPath {
/** Account address. */
address: string;
/** Secret path. */
secretPath: SecretPath;
}

/** Target for a clipboard copy operation. */
export interface ClipboardTarget {
/** Qualified path to the secret. */
path: QualifiedPath;
}

/**
* Type of secret assigned to the secret meta data.
*
Expand Down Expand Up @@ -136,78 +122,6 @@ export interface Document {
extra: ExtraFields;
}

/** Information about a folder. */
export interface FolderInfo {
/** Name of the folder. */
name: string;
/** Folder identifier. */
folderId: string;
}

/** IPC request information. */
export type IpcRequestBody =
/**
* Probe the native bridge for aliveness.
*
* Used to test whether the executable is running
* and the native messaging API is connected.
*/
| { kind: "probe", body?: undefined }
/** Query app info. */
| { kind: "info", body?: undefined }
/** Query app status. */
| { kind: "status", body?: undefined }
/** Ping the server. */
| { kind: "ping", body?: undefined }
/** Request to open a URL. */
| { kind: "openUrl", body: string }
/** HTTP request routed to the local server. */
| { kind: "http", body: LocalRequest }
/** Request the accounts list. */
| { kind: "listAccounts", body?: undefined }
/** Request to copy to the clipboard. */
| { kind: "copy", body: ClipboardTarget }
/** Request authentication for an account. */
| { kind: "authenticate", body: {
/** Account address. */
address: string;
}}
/** Request to lock an account. */
| { kind: "lock", body: {
/** Account address. */
address?: string;
}}
/** Request to search the index. */
| { kind: "search", body: {
/** Query needle. */
needle: string;
/** Query filter. */
filter: QueryFilter;
}}
/** Request to query views in the search index. */
| { kind: "queryView", body: {
/** Document views. */
views: DocumentView[];
/** Archive filter. */
archive_filter?: ArchiveFilter;
}};

/** IPC request information. */
export interface IpcRequest {
/** Request identifier. */
id: number;
/** Request payload. */
payload: IpcRequestBody;
}

/** IPC response error. */
export interface IpcResponseError {
/** Error code. */
code: number;
/** Error message. */
message: string;
}

/**
* Request that can be sent to a local data source.
*
Expand All @@ -223,9 +137,9 @@ export interface LocalRequest {
/** Request URL. */
uri: Uri;
/** Request headers. */
headers: Record<string, string[]>;
headers?: Record<string, string[]>;
/** Request body. */
body: number[];
body?: number[];
}

/**
Expand All @@ -241,9 +155,9 @@ export interface LocalResponse {
/** Response status code. */
status: number;
/** Response headers. */
headers: Record<string, string[]>;
headers?: Record<string, string[]>;
/** Response body. */
body: number[];
body?: number[];
}

/** Public account identity information. */
Expand All @@ -263,6 +177,14 @@ export interface PublicIdentity {
label: string;
}

/** Qualified path to a specific secret in a target account. */
export interface QualifiedPath {
/** Account address. */
address: string;
/** Secret path. */
secretPath: SecretPath;
}

/** Filter for a search query. */
export interface QueryFilter {
/** List of tags. */
Expand All @@ -283,30 +205,6 @@ export interface ServiceAppInfo {
build_number: number;
}

/** Generic command outcome. */
export enum CommandOutcome {
/** Account not found. */
NotFound = "notFound",
/** Already authenticated. */
AlreadyAuthenticated = "alreadyAuthenticated",
/** Not authenticated. */
NotAuthenticated = "notAuthenticated",
/** Account was authenticated. */
Success = "success",
/** Authentication failed. */
Failed = "failed",
/** User canceled. */
Canceled = "canceled",
/** Timed out waiting for user input. */
TimedOut = "timedOut",
/** Too many attempts to authenticate. */
Exhausted = "exhausted",
/** Error attempting to get user input. */
InputError = "inputError",
/** Operation is not supported. */
Unsupported = "unsupported",
}

/** View of documents in the search index. */
export type DocumentView =
/** View all documents in the search index. */
Expand Down Expand Up @@ -350,52 +248,3 @@ export type DocumentView =
exact: boolean;
}};

/** IPC response information. */
export type IpcResponse =
/** Error response. */
| { kind: "err", body: {
/** Message identifier. */
id: number;
/** Message payload. */
payload: IpcResponseError;
}}
/** Response value. */
| { kind: "ok", body: {
/** Message identifier. */
id: number;
/** Message payload. */
payload: IpcResponseBody;
}};

/** IPC response body. */
export type IpcResponseBody =
/** Response to a probe request. */
| { kind: "probe", body?: undefined }
/** App info. */
| { kind: "info", body: ServiceAppInfo }
/**
* App status.
*
* Whether the app is running as determined
* by an active app file lock.
*/
| { kind: "status", body: boolean }
/** Reply to a ping. */
| { kind: "pong", body?: undefined }
/** Result of opening a URL. */
| { kind: "openUrl", body: boolean }
/** Result invoking the local server. */
| { kind: "http", body: LocalResponse }
/** List of accounts. */
| { kind: "accounts", body: AccountsList }
/** Copy to clipboard result. */
| { kind: "copy", body: CommandOutcome }
/** Authenticate response. */
| { kind: "authenticate", body: CommandOutcome }
/** Lock response. */
| { kind: "lock", body: CommandOutcome }
/** Search query response. */
| { kind: "search", body: SearchResults }
/** Query view response. */
| { kind: "queryView", body: SearchResults };

0 comments on commit cae6416

Please sign in to comment.