Skip to content

Commit

Permalink
Big Rewrite to make client work.
Browse files Browse the repository at this point in the history
* Extract vocab into it's own crate
* Emit trait for records
* Strongly typed getRecord and createRecord
* Make URL params work
  • Loading branch information
aDotInTheVoid committed Aug 20, 2023
1 parent 23990a7 commit 8309315
Show file tree
Hide file tree
Showing 34 changed files with 423 additions and 147 deletions.
8 changes: 3 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,16 @@ description = "WIP ATProto SKD"

[workspace]
members = [
"lexgen"
"lexgen",
"triphosphate-vocab",
]

[dependencies]
chrono = { version = "0.4.26", features = ["serde"] }
cid = "0.10.1"
regex = "1.9.3"
anyhow = "1.0.75"
reqwest = { version = "0.11.18", features = ["json"] }
serde = { version = "=1.0.171", features = ["derive"] }
serde_json = "1.0.104"
tokio = { version = "1.29.1", features = ["rt", "macros"] }
winnow = "0.5.10"

[dev-dependencies]
anyhow = "1.0.75"
Expand Down
1 change: 0 additions & 1 deletion examples/get_record.rs

This file was deleted.

23 changes: 5 additions & 18 deletions examples/hello.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
use triphosphate::{
lex::{app::bsky::feed::Post, com::atproto::repo::create_record},
vocab::{AtIdentifier, Datetime, Nsid, StringFormat},
LexItem,
};
use triphosphate::lex::app::bsky::feed::Post;
use triphosphate_vocab::{AtIdentifier, Datetime};

#[tokio::main(flavor = "current_thread")]
async fn main() -> anyhow::Result<()> {
Expand All @@ -21,21 +18,11 @@ async fn main() -> anyhow::Result<()> {
langs: None,
reply: None,
labels: None,
text: "Hello from Triphosphate! Now contains procedures!".to_string(),
text: "Now no longer hard coding NSID's into createRecord!".to_string(),
};

let resp = create_record(
&client,
&create_record::Args {
collection: Nsid::from_str(Post::URI).unwrap(),
record: serde_json::to_value(&post)?,
repo: AtIdentifier::Did(creds.did),
validate: Some(true),
rkey: None,
swap_commit: None,
},
)
.await?;
let my_repo = AtIdentifier::Did(creds.did);
let resp = client.create_record(&post, my_repo).await?;

dbg!(resp);

Expand Down
22 changes: 22 additions & 0 deletions examples/shitpost.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use triphosphate::lex::app::bsky::feed::Post;
use triphosphate_vocab::{AtIdentifier, StringFormat};

#[tokio::main(flavor = "current_thread")]
async fn main() -> anyhow::Result<()> {
let mut client = triphosphate::client::Client::new()?;

let handle = std::env::var("ATP_USERNAME").unwrap();
let password = std::env::var("ATP_PASSWORD").unwrap();

client.login(&handle, &password).await?;

let handle = AtIdentifier::from_str("triphosphate-tests.bsky.social")?;

let p = client
.get_record::<Post>(handle, "3k5fdh2qmie2m".to_owned())
.await?;

dbg!(p);

Ok(())
}
2 changes: 1 addition & 1 deletion lexgen/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@ quote = { version = "1.0.32", default-features = false }
serde = { version = "=1.0.171", features = ["derive"] }
serde_json = "1.0.103"
syn = { version = "2.0.28", features = ["parsing"] }
triphosphate = { version = "0.0.0", path = ".." }
triphosphate-vocab = { version = "0.1.0", path = "../triphosphate-vocab" }
63 changes: 53 additions & 10 deletions lexgen/src/compiller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::{

use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote, ToTokens};
use triphosphate::vocab::StringFormat;
use triphosphate_vocab::{Nsid, StringFormat};

use crate::lexicon::{self, Array, Token, UserType, XrpcBody, XrpcBodySchema, XrpcParameters};

Expand Down Expand Up @@ -88,7 +88,7 @@ impl Compiler {

fn lower_record(&self, path: &ItemPath, r: &lexicon::Record) -> proc_macro2::TokenStream {
let obj = self.lower_object(path, &r.record, &r.description);
let nsid = triphosphate::vocab::Nsid::from_str(&self.doc.id).unwrap();
let nsid = Nsid::from_str(&self.doc.id).unwrap();

let name = path.name();
let nsid_repr = nsid.as_str();
Expand All @@ -114,7 +114,7 @@ impl Compiler {
let fields = o
.properties
.iter()
.map(|(name, prop)| self.lower_field(name, prop, o));
.map(|(name, prop)| self.lower_obj_prop(name, prop, o));

quote!(
#doc
Expand All @@ -128,7 +128,7 @@ impl Compiler {
fn lower_array(&self, path: &ItemPath, arr: &Array) -> TokenStream {
let op = &lexicon::ObjectProperty::Array(arr.clone());

let (field, desc) = FieldType::from_prop(op, &self.doc.id);
let (field, desc) = FieldType::from_obj_prop(op, &self.doc.id);

let name = path.name();

Expand Down Expand Up @@ -180,7 +180,7 @@ impl Compiler {
// TODO: Error handling.
quote! {
#docs
pub async fn #name(client: &_lex::_rt::Client, args: &_lex::#params_ty) -> ::reqwest::Result<_lex::#ret_type> {
pub async fn #name(client: &_lex::_rt::Client, args: &_lex::#params_ty) -> _lex::_rt::Result<_lex::#ret_type> {
client.do_query(#xrpc_id, args).await
}
}
Expand All @@ -204,7 +204,7 @@ impl Compiler {

quote! {
#docs
pub async fn #name(client: &_lex::_rt::Client, args: &_lex::#input_type) -> ::reqwest::Result<_lex::#output_type> {
pub async fn #name(client: &_lex::_rt::Client, args: &_lex::#input_type) -> _lex::_rt::Result<_lex::#output_type> {
client.do_procedure(#xrpc_id, args).await
}
}
Expand All @@ -216,11 +216,56 @@ impl Compiler {
path: &ItemPath,
) -> Option<ItemPath> {
if let Some(params) = params {
let object = conv::params_as_object(params.clone());
// Parameters get serialized to a query string, not json.

let params_path = path.extend("Params");

let obj = self.lower_object(&params_path, &object, &object.description);
let mut fields = Vec::new();
let mut inserters = Vec::new();
for (lex_name, prop) in &params.properties {
let ty = self.lower_param_prop(lex_name, prop, &params);

let name = ty.name();

let do_access = match &ty.ty {
FieldType::StdString => quote!(#name.clone()),
FieldType::RtType(_) => {
quote!(_lex::_rt::StringFormat::as_str(#name).to_owned())
}
_ => todo!("{ty:?}"),
};

let run_push = if ty.required {
quote!({
let #name = &self.#name;
r.push((#lex_name, #do_access));
})
} else {
quote!(if let Some(#name) = &self.#name {
r.push((#lex_name, #do_access));
} )
};

inserters.push(run_push);

fields.push(ty);
}

let n_required = params.required.len();

let obj = quote!(
pub struct Params {
#(#fields),*
}

impl _lex::_rt::AsParams for Params {
fn as_params(&self) -> Vec<(&'static str, String)> {
let mut r: Vec<(&'static str, String)> = Vec::with_capacity(#n_required); // TODO: Look at optionals.
#(#inserters)*
r
}
}
);

self.insert_item(&params_path, obj);

Expand Down Expand Up @@ -376,8 +421,6 @@ fn doc_comment(desc: &Option<String>) -> proc_macro2::TokenStream {
}
}

mod conv;

#[cfg(test)]
mod tests {

Expand Down
48 changes: 0 additions & 48 deletions lexgen/src/compiller/conv.rs

This file was deleted.

Loading

0 comments on commit 8309315

Please sign in to comment.