Skip to content
This repository has been archived by the owner on Oct 31, 2023. It is now read-only.

Commit

Permalink
refactor(*): common method to get local/cached artifacts
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewtgilbride committed Nov 21, 2021
1 parent d5ff04d commit a6eb69d
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 71 deletions.
37 changes: 11 additions & 26 deletions src/claims.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
// limitations under the License.

use crate::keys::extract_keypair;
use crate::util::{cached_file, format_output, Output, OutputKind};
use crate::util::{format_output, Output, OutputKind};
use nkeys::{KeyPair, KeyPairType};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -674,33 +674,18 @@ fn sign_file(cmd: SignCommand) -> Result<String, Box<dyn ::std::error::Error>> {
async fn get_caps(
cmd: &InspectCommand,
) -> Result<Option<Token<Actor>>, Box<dyn ::std::error::Error>> {
let module_bytes = match File::open(&cmd.module) {
Ok(mut f) => {
let mut buf = Vec::new();
f.read_to_end(&mut buf).unwrap();
buf
}
Err(_) => {
if let Ok(mut from_cache) = File::open(cached_file(&cmd.module)) {
let mut buf = Vec::new();
from_cache.read_to_end(&mut buf).unwrap();
buf
} else {
crate::reg::pull_artifact(
cmd.module.to_string(),
cmd.digest.clone(),
cmd.allow_latest,
cmd.user.clone(),
cmd.password.clone(),
cmd.insecure,
)
.await?
}
}
};
let artifact_bytes = crate::reg::get_artifact(
cmd.module.to_string(),
cmd.digest.clone(),
cmd.allow_latest,
cmd.user.clone(),
cmd.password.clone(),
cmd.insecure,
)
.await?;

// Extract will return an error if it encounters an invalid hash in the claims
let claims = wascap::wasm::extract_claims(&module_bytes);
let claims = wascap::wasm::extract_claims(&artifact_bytes);
match claims {
Ok(token) => Ok(token),
Err(e) => Err(Box::new(e)),
Expand Down
44 changes: 14 additions & 30 deletions src/par.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
extern crate provider_archive;
use crate::keys::extract_keypair;
use crate::util::{cached_file, convert_error, format_output, Output, OutputKind, Result};
use crate::util::{convert_error, format_output, Output, OutputKind, Result};
use nkeys::KeyPairType;
use provider_archive::*;
use serde_json::json;
Expand Down Expand Up @@ -277,33 +277,17 @@ pub(crate) fn handle_create(cmd: CreateCommand) -> Result<String> {

/// Loads a provider archive and outputs the contents of the claims
pub(crate) async fn handle_inspect(cmd: InspectCommand) -> Result<String> {
let archive = match File::open(&cmd.archive) {
Ok(mut f) => {
let mut buf = Vec::new();
f.read_to_end(&mut buf)?;
ProviderArchive::try_load(&buf).map_err(|e| format!("{}", e))?
}
Err(_) => {
let artifact = if let Ok(mut from_cache) = File::open(cached_file(&cmd.archive)) {
let mut buf = Vec::new();
from_cache.read_to_end(&mut buf).unwrap();
buf
} else {
crate::reg::pull_artifact(
cmd.archive,
cmd.digest,
cmd.allow_latest,
cmd.user,
cmd.password,
cmd.insecure,
)
.await?
};

ProviderArchive::try_load(&artifact).map_err(|e| format!("{}", e))?
}
};
let claims = archive.claims().unwrap();
let artifact_bytes = crate::reg::get_artifact(
cmd.archive,
cmd.digest,
cmd.allow_latest,
cmd.user,
cmd.password,
cmd.insecure,
)
.await?;
let artifact = ProviderArchive::try_load(&artifact_bytes).map_err(|e| format!("{}", e))?;
let claims = artifact.claims().unwrap();
let metadata = claims.metadata.unwrap();

let output = match cmd.output.kind {
Expand All @@ -323,7 +307,7 @@ pub(crate) async fn handle_inspect(cmd: InspectCommand) -> Result<String> {
"vendor": metadata.vendor,
"ver": friendly_ver,
"rev": friendly_rev,
"targets": archive.targets()})
"targets": artifact.targets()})
)
}
OutputKind::Text => {
Expand Down Expand Up @@ -378,7 +362,7 @@ pub(crate) async fn handle_inspect(cmd: InspectCommand) -> Result<String> {
)]));

table.add_row(Row::new(vec![TableCell::new_with_alignment(
archive.targets().join("\n"),
artifact.targets().join("\n"),
2,
Alignment::Left,
)]));
Expand Down
40 changes: 40 additions & 0 deletions src/reg.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
extern crate oci_distribution;

use crate::util::{format_output, Output, OutputKind};
use log::{debug, info, warn};
use oci_distribution::client::*;
Expand All @@ -7,8 +8,10 @@ use oci_distribution::Reference;
use provider_archive::ProviderArchive;
use serde_json::json;
use spinners::{Spinner, Spinners};
use std::env::temp_dir;
use std::fs::File;
use std::io::prelude::*;
use std::path::PathBuf;
use structopt::clap::AppSettings;
use structopt::StructOpt;

Expand Down Expand Up @@ -187,6 +190,43 @@ pub(crate) async fn handle_pull(cmd: PullCommand) -> Result<String, Box<dyn ::st
))
}

/// Attempts to return a local artifact, then a cached one.
/// Falls back to pull from registry if neither is found.
pub(crate) async fn get_artifact(
url: String,
digest: Option<String>,
allow_latest: bool,
user: Option<String>,
password: Option<String>,
insecure: bool,
) -> Result<Vec<u8>, Box<dyn ::std::error::Error>> {
if let Ok(mut local_artifact) = File::open(url.clone()) {
let mut buf = Vec::new();
local_artifact.read_to_end(&mut buf)?;
Ok(buf)
} else if let Ok(mut cached_artifact) = File::open(cached_file(&url)) {
let mut buf = Vec::new();
cached_artifact.read_to_end(&mut buf)?;
Ok(buf)
} else {
pull_artifact(url.clone(), digest, allow_latest, user, password, insecure).await
}
}

fn cached_file(img: &str) -> PathBuf {
let path = temp_dir();
let path = path.join("wasmcloud_ocicache");
let _ = ::std::fs::create_dir_all(&path);
// should produce a file like wasmcloud_azurecr_io_kvcounter_v1.bin
let img = img.replace(":", "_");
let img = img.replace("/", "_");
let img = img.replace(".", "_");
let mut path = path.join(img);
path.set_extension("bin");

path
}

pub(crate) async fn pull_artifact(
url: String,
digest: Option<String>,
Expand Down
15 changes: 0 additions & 15 deletions src/util.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use nats::asynk::Connection;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::env::temp_dir;
use std::error::Error;
use std::fmt;
use std::fs::File;
Expand Down Expand Up @@ -249,17 +248,3 @@ pub(crate) async fn nats_client_from_opts(
};
Ok(nc)
}

pub(crate) fn cached_file(img: &str) -> PathBuf {
let path = temp_dir();
let path = path.join("wasmcloud_ocicache");
let _ = ::std::fs::create_dir_all(&path);
// should produce a file like wasmcloud_azurecr_io_kvcounter_v1.bin
let img = img.replace(":", "_");
let img = img.replace("/", "_");
let img = img.replace(".", "_");
let mut path = path.join(img);
path.set_extension("bin");

path
}

0 comments on commit a6eb69d

Please sign in to comment.