4 Commits

Author SHA1 Message Date
b67a67d809 fix: bump version 2025-08-13 11:38:09 +10:00
87b19a5c8c fix: test 2025-08-13 11:37:41 +10:00
dc3a420986 feat: performance improvements, fix zip 2025-08-13 11:35:50 +10:00
1665033fd9 test: add subdir tests 2025-07-18 22:46:42 +10:00
13 changed files with 521 additions and 224 deletions

27
Cargo.lock generated
View File

@ -153,6 +153,15 @@ dependencies = [
"unicode-segmentation", "unicode-segmentation",
] ]
[[package]]
name = "crc32fast"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
dependencies = [
"cfg-if",
]
[[package]] [[package]]
name = "ctor" name = "ctor"
version = "0.4.2" version = "0.4.2"
@ -227,6 +236,8 @@ dependencies = [
name = "droplet" name = "droplet"
version = "0.7.0" version = "0.7.0"
dependencies = [ dependencies = [
"dyn-clone",
"flate2",
"hex", "hex",
"md5", "md5",
"napi", "napi",
@ -261,6 +272,22 @@ version = "0.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7454e41ff9012c00d53cf7f475c5e3afa3b91b7c90568495495e8d9bf47a1055" checksum = "7454e41ff9012c00d53cf7f475c5e3afa3b91b7c90568495495e8d9bf47a1055"
[[package]]
name = "dyn-clone"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
[[package]]
name = "flate2"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a3d7db9596fecd151c5f638c0ee5d5bd487b6e0ea232e5dc96d5250f6f94b1d"
dependencies = [
"crc32fast",
"miniz_oxide",
]
[[package]] [[package]]
name = "futures-core" name = "futures-core"
version = "0.3.31" version = "0.3.31"

View File

@ -25,6 +25,8 @@ ring = "0.17.14"
tokio = { version = "1.45.1", features = ["fs", "io-util"] } tokio = { version = "1.45.1", features = ["fs", "io-util"] }
tokio-util = { version = "0.7.15", features = ["codec"] } tokio-util = { version = "0.7.15", features = ["codec"] }
rawzip = "0.3.0" rawzip = "0.3.0"
dyn-clone = "1.0.20"
flate2 = "1.1.2"
[package.metadata.patch] [package.metadata.patch]
crates = ["rawzip"] crates = ["rawzip"]

View File

@ -2,7 +2,7 @@ import test from "ava";
import fs from "node:fs"; import fs from "node:fs";
import path from "path"; import path from "path";
import { generateManifest, listFiles } from "../index.js"; import { DropletHandler, generateManifest } from "../index.js";
test("numerous small file", async (t) => { test("numerous small file", async (t) => {
// Setup test dir // Setup test dir
@ -18,9 +18,12 @@ test("numerous small file", async (t) => {
fs.writeFileSync(fileName, i.toString()); fs.writeFileSync(fileName, i.toString());
} }
const dropletHandler = new DropletHandler();
const manifest = JSON.parse( const manifest = JSON.parse(
await new Promise((r, e) => await new Promise((r, e) =>
generateManifest( generateManifest(
dropletHandler,
dirName, dirName,
(_, __) => {}, (_, __) => {},
(_, __) => {}, (_, __) => {},
@ -56,7 +59,6 @@ test("numerous small file", async (t) => {
test.skip("performance test", async (t) => { test.skip("performance test", async (t) => {
t.timeout(5 * 60 * 1000); t.timeout(5 * 60 * 1000);
return t.pass();
const dirName = "./.test/pt"; const dirName = "./.test/pt";
if (fs.existsSync(dirName)) fs.rmSync(dirName, { recursive: true }); if (fs.existsSync(dirName)) fs.rmSync(dirName, { recursive: true });
fs.mkdirSync(dirName, { recursive: true }); fs.mkdirSync(dirName, { recursive: true });
@ -73,9 +75,12 @@ test.skip("performance test", async (t) => {
randomStream.on("end", r); randomStream.on("end", r);
}); });
const dropletHandler = new DropletHandler();
const start = Date.now(); const start = Date.now();
await new Promise((r, e) => await new Promise((r, e) =>
generateManifest( generateManifest(
dropletHandler,
dirName, dirName,
(_, __) => {}, (_, __) => {},
(_, __) => {}, (_, __) => {},

View File

@ -2,7 +2,7 @@ import test from "ava";
import fs from "node:fs"; import fs from "node:fs";
import path from "path"; import path from "path";
import droplet, { generateManifest } from "../index.js"; import droplet, { DropletHandler, generateManifest } from "../index.js";
test("check alt thread util", async (t) => { test("check alt thread util", async (t) => {
let endtime1, endtime2; let endtime1, endtime2;
@ -23,6 +23,28 @@ test("check alt thread util", async (t) => {
t.pass(); t.pass();
}); });
test("list files", async (t) => {
const dirName = "./.listfiles";
if (fs.existsSync(dirName)) fs.rmSync(dirName, { recursive: true });
fs.mkdirSync(dirName, { recursive: true });
fs.mkdirSync(dirName + "/subdir", { recursive: true });
fs.mkdirSync(dirName + "/subddir", { recursive: true });
fs.writeFileSync(dirName + "/root.txt", "root");
fs.writeFileSync(dirName + "/subdir/one.txt", "the first subdir");
fs.writeFileSync(dirName + "/subddir/two.txt", "the second");
const dropletHandler = new DropletHandler();
const files = dropletHandler.listFiles(dirName);
t.assert(
files.sort().join("\n"),
["root.txt", "subddir/two.txt", "subdir/one.txt"].join("\n")
);
fs.rmSync(dirName, { recursive: true });
});
test("read file", async (t) => { test("read file", async (t) => {
const dirName = "./.test2"; const dirName = "./.test2";
if (fs.existsSync(dirName)) fs.rmSync(dirName, { recursive: true }); if (fs.existsSync(dirName)) fs.rmSync(dirName, { recursive: true });
@ -32,11 +54,13 @@ test("read file", async (t) => {
fs.writeFileSync(dirName + "/TESTFILE", testString); fs.writeFileSync(dirName + "/TESTFILE", testString);
const stream = droplet.readFile(dirName, "TESTFILE"); const dropletHandler = new DropletHandler();
const stream = dropletHandler.readFile(dirName, "TESTFILE");
let finalString = ""; let finalString = "";
for await (const chunk of stream) { for await (const chunk of stream.getStream()) {
// Do something with each 'chunk' // Do something with each 'chunk'
finalString += String.fromCharCode.apply(null, chunk); finalString += String.fromCharCode.apply(null, chunk);
} }
@ -53,11 +77,12 @@ test("read file offset", async (t) => {
const testString = "0123456789"; const testString = "0123456789";
fs.writeFileSync(dirName + "/TESTFILE", testString); fs.writeFileSync(dirName + "/TESTFILE", testString);
const stream = droplet.readFile(dirName, "TESTFILE", BigInt(1), BigInt(4)); const dropletHandler = new DropletHandler();
const stream = dropletHandler.readFile(dirName, "TESTFILE", BigInt(1), BigInt(4));
let finalString = ""; let finalString = "";
for await (const chunk of stream) { for await (const chunk of stream.getStream()) {
// Do something with each 'chunk' // Do something with each 'chunk'
finalString += String.fromCharCode.apply(null, chunk); finalString += String.fromCharCode.apply(null, chunk);
} }
@ -73,9 +98,13 @@ test("read file offset", async (t) => {
test("zip file reader", async (t) => { test("zip file reader", async (t) => {
return t.pass(); return t.pass();
t.timeout(10_000);
const dropletHandler = new DropletHandler();
const manifest = JSON.parse( const manifest = JSON.parse(
await new Promise((r, e) => await new Promise((r, e) =>
generateManifest( generateManifest(
dropletHandler,
"./assets/TheGame.zip", "./assets/TheGame.zip",
(_, __) => {}, (_, __) => {},
(_, __) => {}, (_, __) => {},
@ -84,17 +113,20 @@ test("zip file reader", async (t) => {
) )
); );
console.log(manifest); const stream = dropletHandler.readFile(
"./assets/TheGame.zip",
"setup.exe",
BigInt(10),
BigInt(20)
);
return t.pass();
const stream = droplet.readFile("./assets/TheGame.zip", "TheGame/setup.exe");
let finalString; let finalString = "";
for await (const chunk of stream) { for await (const chunk of stream.getStream()) {
console.log(`read chunk ${chunk}`);
// Do something with each 'chunk' // Do something with each 'chunk'
finalString += String.fromCharCode.apply(null, chunk); finalString = String.fromCharCode.apply(null, chunk);
if(finalString.length > 100) break;
} }
console.log(finalString); t.pass();
}); });

View File

@ -1,3 +1,3 @@
dd if=/dev/random of=./setup.exe bs=1024 count=1000000 yes "droplet is awesome" | dd of=./setup.exe bs=1024 count=1000000
zip TheGame.zip setup.exe zip TheGame.zip setup.exe
rm setup.exe rm setup.exe

28
index.d.ts vendored
View File

@ -1,24 +1,28 @@
/* auto-generated by NAPI-RS */ /* auto-generated by NAPI-RS */
/* eslint-disable */ /* eslint-disable */
/**
* Persistent object so we can cache things between commands
*/
export declare class DropletHandler {
constructor()
hasBackendForPath(path: string): boolean
listFiles(path: string): Array<string>
peekFile(path: string, subPath: string): bigint
readFile(path: string, subPath: string, start?: bigint | undefined | null, end?: bigint | undefined | null): JsDropStreamable
}
export declare class JsDropStreamable {
getStream(): any
}
export declare function callAltThreadFunc(tsfn: ((err: Error | null, ) => any)): void export declare function callAltThreadFunc(tsfn: ((err: Error | null, ) => any)): void
export declare function generateClientCertificate(clientId: string, clientName: string, rootCa: string, rootCaPrivate: string): Array<string> export declare function generateClientCertificate(clientId: string, clientName: string, rootCa: string, rootCaPrivate: string): Array<string>
export declare function generateManifest(dir: string, progressSfn: ((err: Error | null, arg: number) => any), logSfn: ((err: Error | null, arg: string) => any), callbackSfn: ((err: Error | null, arg: string) => any)): void export declare function generateManifest(dropletHandler: DropletHandler, dir: string, progressSfn: ((err: Error | null, arg: number) => any), logSfn: ((err: Error | null, arg: string) => any), callbackSfn: ((err: Error | null, arg: string) => any)): void
export declare function generateRootCa(): Array<string> export declare function generateRootCa(): Array<string>
export declare function hasBackendForPath(path: string): boolean
export declare function listFiles(path: string): Array<string>
/**
* This is inefficient, but is used in attempt to keep the interface simple
*/
export declare function peekFile(path: string, subPath: string): bigint
export declare function readFile(path: string, subPath: string, start?: bigint | undefined | null, end?: bigint | undefined | null): ReadableStream<Buffer> | null
export declare function signNonce(privateKey: string, nonce: string): string export declare function signNonce(privateKey: string, nonce: string): string
export declare function verifyClientCertificate(clientCert: string, rootCa: string): boolean export declare function verifyClientCertificate(clientCert: string, rootCa: string): boolean

View File

@ -376,14 +376,12 @@ if (!nativeBinding) {
} }
module.exports = nativeBinding module.exports = nativeBinding
module.exports.DropletHandler = nativeBinding.DropletHandler
module.exports.JsDropStreamable = nativeBinding.JsDropStreamable
module.exports.callAltThreadFunc = nativeBinding.callAltThreadFunc module.exports.callAltThreadFunc = nativeBinding.callAltThreadFunc
module.exports.generateClientCertificate = nativeBinding.generateClientCertificate module.exports.generateClientCertificate = nativeBinding.generateClientCertificate
module.exports.generateManifest = nativeBinding.generateManifest module.exports.generateManifest = nativeBinding.generateManifest
module.exports.generateRootCa = nativeBinding.generateRootCa module.exports.generateRootCa = nativeBinding.generateRootCa
module.exports.hasBackendForPath = nativeBinding.hasBackendForPath
module.exports.listFiles = nativeBinding.listFiles
module.exports.peekFile = nativeBinding.peekFile
module.exports.readFile = nativeBinding.readFile
module.exports.signNonce = nativeBinding.signNonce module.exports.signNonce = nativeBinding.signNonce
module.exports.verifyClientCertificate = nativeBinding.verifyClientCertificate module.exports.verifyClientCertificate = nativeBinding.verifyClientCertificate
module.exports.verifyNonce = nativeBinding.verifyNonce module.exports.verifyNonce = nativeBinding.verifyNonce

View File

@ -1,6 +1,6 @@
{ {
"name": "@drop-oss/droplet", "name": "@drop-oss/droplet",
"version": "1.6.0", "version": "2.0.1",
"main": "index.js", "main": "index.js",
"types": "index.d.ts", "types": "index.d.ts",
"napi": { "napi": {
@ -27,7 +27,14 @@
"ava": "^6.2.0" "ava": "^6.2.0"
}, },
"ava": { "ava": {
"timeout": "3m" "timeout": "3m",
"extensions": [
"cjs",
"mjs",
"js",
"ts",
"mts"
]
}, },
"engines": { "engines": {
"node": ">= 10" "node": ">= 10"
@ -44,5 +51,8 @@
"packageManager": "yarn@4.7.0", "packageManager": "yarn@4.7.0",
"repository": { "repository": {
"url": "git+https://github.com/Drop-OSS/droplet.git" "url": "git+https://github.com/Drop-OSS/droplet.git"
},
"dependencies": {
"tsimp": "^2.0.12"
} }
} }

View File

@ -13,8 +13,7 @@ use napi::{
use serde_json::json; use serde_json::json;
use uuid::Uuid; use uuid::Uuid;
use crate::version::utils::create_backend_for_path; use crate::version::{types::VersionBackend, utils::DropletHandler};
const CHUNK_SIZE: usize = 1024 * 1024 * 64; const CHUNK_SIZE: usize = 1024 * 1024 * 64;
@ -36,15 +35,18 @@ pub fn call_alt_thread_func(tsfn: Arc<ThreadsafeFunction<()>>) -> Result<(), Str
} }
#[napi] #[napi]
pub fn generate_manifest( pub fn generate_manifest<'a>(
droplet_handler: &mut DropletHandler,
dir: String, dir: String,
progress_sfn: ThreadsafeFunction<i32>, progress_sfn: ThreadsafeFunction<i32>,
log_sfn: ThreadsafeFunction<String>, log_sfn: ThreadsafeFunction<String>,
callback_sfn: ThreadsafeFunction<String>, callback_sfn: ThreadsafeFunction<String>,
) -> Result<(), String> { ) -> Result<()> {
let backend: &mut Box<dyn VersionBackend + Send> =
droplet_handler.create_backend_for_path(dir).ok_or(napi::Error::from_reason("Could not create backend for path."))?;
let backend: &'static mut Box<dyn VersionBackend + Send> =
unsafe { std::mem::transmute(backend) };
thread::spawn(move || { thread::spawn(move || {
let base_dir = Path::new(&dir);
let mut backend = create_backend_for_path(base_dir).unwrap();
let files = backend.list_files(); let files = backend.list_files();
// Filepath to chunk data // Filepath to chunk data
@ -54,7 +56,7 @@ pub fn generate_manifest(
let mut i: i32 = 0; let mut i: i32 = 0;
for version_file in files { for version_file in files {
let raw_reader= backend.reader(&version_file).unwrap(); let raw_reader = backend.reader(&version_file).unwrap();
let mut reader = BufReader::with_capacity(CHUNK_SIZE, raw_reader); let mut reader = BufReader::with_capacity(CHUNK_SIZE, raw_reader);
let mut chunk_data = ChunkData { let mut chunk_data = ChunkData {

View File

@ -1,24 +1,34 @@
use core::arch;
#[cfg(unix)] #[cfg(unix)]
use std::os::unix::fs::PermissionsExt; use std::os::unix::fs::PermissionsExt;
use std::{ use std::{
fs::File, fs::{self, metadata, File},
io::{self, Read, Seek}, io::{self, Read, Sink},
path::PathBuf, path::{Path, PathBuf},
pin::Pin,
rc::Rc,
sync::Arc, sync::Arc,
}; };
use flate2::read::DeflateDecoder;
use rawzip::{ use rawzip::{
FileReader, ReaderAt, ZipArchive, ZipArchiveEntryWayfinder, ZipEntry, RECOMMENDED_BUFFER_SIZE, FileReader, ZipArchive, ZipArchiveEntryWayfinder, ZipEntry, ZipReader, RECOMMENDED_BUFFER_SIZE,
}; };
use crate::version::{ use crate::version::types::{MinimumFileObject, Skippable, VersionBackend, VersionFile};
types::{MinimumFileObject, Skippable, VersionBackend, VersionFile},
utils::_list_files,
};
pub fn _list_files(vec: &mut Vec<PathBuf>, path: &Path) {
if metadata(path).unwrap().is_dir() {
let paths = fs::read_dir(path).unwrap();
for path_result in paths {
let full_path = path_result.unwrap().path();
if metadata(&full_path).unwrap().is_dir() {
_list_files(vec, &full_path);
} else {
vec.push(full_path);
}
}
}
}
#[derive(Clone)]
pub struct PathVersionBackend { pub struct PathVersionBackend {
pub base_dir: PathBuf, pub base_dir: PathBuf,
} }
@ -30,8 +40,31 @@ impl VersionBackend for PathVersionBackend {
let mut results = Vec::new(); let mut results = Vec::new();
for pathbuf in vec.iter() { for pathbuf in vec.iter() {
let file = File::open(pathbuf.clone()).unwrap();
let relative = pathbuf.strip_prefix(self.base_dir.clone()).unwrap(); let relative = pathbuf.strip_prefix(self.base_dir.clone()).unwrap();
results.push(
self
.peek_file(relative.to_str().unwrap().to_owned())
.unwrap(),
);
}
results
}
fn reader(&mut self, file: &VersionFile) -> Option<Box<dyn MinimumFileObject + 'static>> {
let file = File::open(self.base_dir.join(file.relative_filename.clone())).ok()?;
return Some(Box::new(file));
}
fn peek_file(&mut self, sub_path: String) -> Option<VersionFile> {
let pathbuf = self.base_dir.join(sub_path.clone());
if !pathbuf.exists() {
return None;
};
let file = File::open(pathbuf.clone()).unwrap();
let metadata = file.try_clone().unwrap().metadata().unwrap(); let metadata = file.try_clone().unwrap().metadata().unwrap();
let permission_object = metadata.permissions(); let permission_object = metadata.permissions();
let permissions = { let permissions = {
@ -47,23 +80,15 @@ impl VersionBackend for PathVersionBackend {
perm perm
}; };
results.push(VersionFile { Some(VersionFile {
relative_filename: relative.to_string_lossy().to_string(), relative_filename: sub_path,
permission: permissions, permission: permissions,
size: metadata.len(), size: metadata.len(),
}); })
}
results
}
fn reader(&mut self, file: &VersionFile) -> Option<Box<(dyn MinimumFileObject + 'static)>> {
let file = File::open(self.base_dir.join(file.relative_filename.clone())).ok()?;
return Some(Box::new(file));
} }
} }
#[derive(Clone)]
pub struct ZipVersionBackend { pub struct ZipVersionBackend {
archive: Arc<ZipArchive<FileReader>>, archive: Arc<ZipArchive<FileReader>>,
} }
@ -75,46 +100,51 @@ impl ZipVersionBackend {
} }
} }
pub fn new_entry( pub fn new_entry<'archive>(
&self, &self,
entry: ZipEntry<'_, FileReader>, entry: ZipEntry<'archive, FileReader>,
wayfinder: ZipArchiveEntryWayfinder, ) -> ZipFileWrapper<'archive> {
) -> ZipFileWrapper { let deflater = DeflateDecoder::new(entry.reader());
let (offset, end_offset) = entry.compressed_data_range(); ZipFileWrapper { reader: deflater }
ZipFileWrapper {
archive: self.archive.clone(),
wayfinder,
offset,
end_offset,
}
} }
} }
pub struct ZipFileWrapper { pub struct ZipFileWrapper<'archive> {
pub archive: Arc<ZipArchive<FileReader>>, reader: DeflateDecoder<ZipReader<'archive, FileReader>>,
wayfinder: ZipArchiveEntryWayfinder,
offset: u64,
end_offset: u64,
} }
impl Read for ZipFileWrapper { impl<'a> Read for ZipFileWrapper<'a> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let read_size = buf.len().min((self.end_offset - self.offset) as usize); let read = self.reader.read(buf)?;
let read = self
.archive
.get_ref()
.read_at(&mut buf[..read_size], self.offset)?;
self.offset += read as u64;
Ok(read) Ok(read)
} }
} }
impl Skippable for ZipFileWrapper { impl<'a> Skippable for ZipFileWrapper<'a> {
fn skip(&mut self, amount: u64) { fn skip(&mut self, amount: u64) {
self.offset += amount; io::copy(&mut self.reader.by_ref().take(amount), &mut Sink::default()).unwrap();
} }
} }
impl MinimumFileObject for ZipFileWrapper {} impl<'a> MinimumFileObject for ZipFileWrapper<'a> {}
impl ZipVersionBackend {
fn find_wayfinder(&mut self, filename: &str) -> Option<ZipArchiveEntryWayfinder> {
let read_buffer = &mut [0u8; RECOMMENDED_BUFFER_SIZE];
let mut entries = self.archive.entries(read_buffer);
let entry = loop {
if let Some(v) = entries.next_entry().unwrap() {
if v.file_path().try_normalize().unwrap().as_ref() == filename {
break Some(v);
}
} else {
break None;
}
}?;
let wayfinder = entry.wayfinder();
Some(wayfinder)
}
}
impl VersionBackend for ZipVersionBackend { impl VersionBackend for ZipVersionBackend {
fn list_files(&mut self) -> Vec<VersionFile> { fn list_files(&mut self) -> Vec<VersionFile> {
let mut results = Vec::new(); let mut results = Vec::new();
@ -133,24 +163,22 @@ impl VersionBackend for ZipVersionBackend {
results results
} }
fn reader(&mut self, file: &VersionFile) -> Option<Box<(dyn MinimumFileObject)>> { fn reader(&mut self, file: &VersionFile) -> Option<Box<dyn MinimumFileObject + '_>> {
let read_buffer = &mut [0u8; RECOMMENDED_BUFFER_SIZE]; let wayfinder = self.find_wayfinder(&file.relative_filename)?;
let mut entries = self.archive.entries(read_buffer);
let entry = loop {
if let Some(v) = entries.next_entry().unwrap() {
if v.file_path().try_normalize().unwrap().as_ref() == &file.relative_filename {
break Some(v);
}
} else {
break None;
}
}?;
let wayfinder = entry.wayfinder();
let local_entry = self.archive.get_entry(wayfinder).unwrap(); let local_entry = self.archive.get_entry(wayfinder).unwrap();
let wrapper = self.new_entry(local_entry, wayfinder); let wrapper = self.new_entry(local_entry);
Some(Box::new(wrapper)) Some(Box::new(wrapper))
} }
fn peek_file(&mut self, sub_path: String) -> Option<VersionFile> {
let entry = self.find_wayfinder(&sub_path)?;
Some(VersionFile {
relative_filename: sub_path,
permission: 0,
size: entry.uncompressed_size_hint(),
})
}
} }

View File

@ -1,7 +1,9 @@
use std::{ use std::{
fmt::Debug, io::{Read, Seek, SeekFrom} fmt::Debug,
io::{Read, Seek, SeekFrom},
}; };
use dyn_clone::DynClone;
use tokio::io::{self, AsyncRead}; use tokio::io::{self, AsyncRead};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@ -27,12 +29,11 @@ pub trait MinimumFileObject: Read + Send + Skippable {}
impl<T: Read + Send + Seek> MinimumFileObject for T {} impl<T: Read + Send + Seek> MinimumFileObject for T {}
// Intentionally not a generic, because of types in read_file // Intentionally not a generic, because of types in read_file
pub struct ReadToAsyncRead { pub struct ReadToAsyncRead<'a> {
pub inner: Box<(dyn Read + Send)>, pub inner: Box<dyn Read + Send + 'a>,
pub backend: Box<(dyn VersionBackend + Send)>,
} }
impl AsyncRead for ReadToAsyncRead { impl<'a> AsyncRead for ReadToAsyncRead<'a> {
fn poll_read( fn poll_read(
mut self: std::pin::Pin<&mut Self>, mut self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>, _cx: &mut std::task::Context<'_>,
@ -40,13 +41,16 @@ impl AsyncRead for ReadToAsyncRead {
) -> std::task::Poll<io::Result<()>> { ) -> std::task::Poll<io::Result<()>> {
let mut read_buf = [0u8; 8192]; let mut read_buf = [0u8; 8192];
let var_name = self.inner.read(&mut read_buf).unwrap(); let var_name = self.inner.read(&mut read_buf).unwrap();
let amount = var_name; let amount = var_name.min(buf.remaining());
buf.put_slice(&read_buf[0..amount]); buf.put_slice(&read_buf[0..amount]);
std::task::Poll::Ready(Ok(())) std::task::Poll::Ready(Ok(()))
} }
} }
pub trait VersionBackend { pub trait VersionBackend: DynClone {
fn list_files(&mut self) -> Vec<VersionFile>; fn list_files(&mut self) -> Vec<VersionFile>;
fn reader(&mut self, file: &VersionFile) -> Option<Box<(dyn MinimumFileObject)>>; fn peek_file(&mut self, sub_path: String) -> Option<VersionFile>;
fn reader(&mut self, file: &VersionFile) -> Option<Box<dyn MinimumFileObject + '_>>;
} }
dyn_clone::clone_trait_object!(VersionBackend);

View File

@ -1,10 +1,6 @@
use std::{ use std::{collections::HashMap, fs::File, io::Read, path::Path};
fs::{self, metadata, File},
io::Read,
path::{Path, PathBuf},
};
use napi::{bindgen_prelude::*, tokio_stream::StreamExt}; use napi::{bindgen_prelude::*, sys::napi_value__, tokio_stream::StreamExt};
use tokio_util::codec::{BytesCodec, FramedRead}; use tokio_util::codec::{BytesCodec, FramedRead};
use crate::version::{ use crate::version::{
@ -12,90 +8,115 @@ use crate::version::{
types::{ReadToAsyncRead, VersionBackend, VersionFile}, types::{ReadToAsyncRead, VersionBackend, VersionFile},
}; };
pub fn _list_files(vec: &mut Vec<PathBuf>, path: &Path) { /**
if metadata(path).unwrap().is_dir() { * Append new backends here
let paths = fs::read_dir(path).unwrap(); */
for path_result in paths { pub fn create_backend_constructor<'a>(
let full_path = path_result.unwrap().path(); path: &Path,
if metadata(&full_path).unwrap().is_dir() { ) -> Option<Box<dyn FnOnce() -> Box<dyn VersionBackend + Send + 'a>>> {
_list_files(vec, &full_path); if !path.exists() {
} else { return None;
vec.push(full_path);
} }
}
}
}
pub fn create_backend_for_path<'a>(path: &Path) -> Option<Box<(dyn VersionBackend + Send + 'a)>> {
let is_directory = path.is_dir(); let is_directory = path.is_dir();
if is_directory { if is_directory {
return Some(Box::new(PathVersionBackend { let base_dir = path.to_path_buf();
base_dir: path.to_path_buf(), return Some(Box::new(move || Box::new(PathVersionBackend { base_dir })));
}));
}; };
if path.to_string_lossy().ends_with(".zip") { if path.to_string_lossy().ends_with(".zip") {
let f = File::open(path.to_path_buf()).unwrap(); let f = File::open(path.to_path_buf()).unwrap();
return Some(Box::new(ZipVersionBackend::new(f))); return Some(Box::new(|| Box::new(ZipVersionBackend::new(f))));
} }
None None
} }
/**
* Persistent object so we can cache things between commands
*/
#[napi(js_name = "DropletHandler")]
pub struct DropletHandler<'a> {
backend_cache: HashMap<String, Box<dyn VersionBackend + Send + 'a>>,
}
#[napi] #[napi]
pub fn has_backend_for_path(path: String) -> bool { impl<'a> DropletHandler<'a> {
#[napi(constructor)]
pub fn new() -> Self {
DropletHandler {
backend_cache: HashMap::new(),
}
}
pub fn create_backend_for_path(
&mut self,
path: String,
) -> Option<&mut Box<dyn VersionBackend + Send + 'a>> {
let fs_path = Path::new(&path);
let constructor = create_backend_constructor(fs_path)?;
let existing_backend = self.backend_cache.entry(path).or_insert_with(|| {
let backend = constructor();
backend
});
Some(existing_backend)
}
#[napi]
pub fn has_backend_for_path(&self, path: String) -> bool {
let path = Path::new(&path); let path = Path::new(&path);
let has_backend = create_backend_for_path(path).is_some(); let has_backend = create_backend_constructor(path).is_some();
has_backend has_backend
} }
#[napi] #[napi]
pub fn list_files(path: String) -> Result<Vec<String>> { pub fn list_files(&mut self, path: String) -> Result<Vec<String>> {
let path = Path::new(&path); let backend = self
let mut backend = .create_backend_for_path(path)
create_backend_for_path(path).ok_or(napi::Error::from_reason("No backend for path"))?; .ok_or(napi::Error::from_reason("No backend for path"))?;
let files = backend.list_files(); let files = backend.list_files();
Ok(files.into_iter().map(|e| e.relative_filename).collect()) Ok(files.into_iter().map(|e| e.relative_filename).collect())
} }
/** #[napi]
* This is inefficient, but is used in attempt to keep the interface simple pub fn peek_file(&mut self, path: String, sub_path: String) -> Result<u64> {
*/ let backend = self
#[napi] .create_backend_for_path(path)
pub fn peek_file(path: String, sub_path: String) -> Result<u64> { .ok_or(napi::Error::from_reason("No backend for path"))?;
let path = Path::new(&path);
let mut backend =
create_backend_for_path(path).ok_or(napi::Error::from_reason("No backend for path"))?;
let files = backend.list_files();
let file = files let file = backend
.iter() .peek_file(sub_path)
.find(|e| e.relative_filename == sub_path)
.ok_or(napi::Error::from_reason("Can't find file to peek"))?; .ok_or(napi::Error::from_reason("Can't find file to peek"))?;
return Ok(file.size.try_into().unwrap());
}
#[napi] return Ok(file.size.try_into().unwrap());
pub fn read_file( }
#[napi]
pub fn read_file(
&mut self,
reference: Reference<DropletHandler<'static>>,
path: String, path: String,
sub_path: String, sub_path: String,
env: &Env, env: Env,
start: Option<BigInt>, start: Option<BigInt>,
end: Option<BigInt>, end: Option<BigInt>,
) -> Option<ReadableStream<'_, BufferSlice<'_>>> { ) -> Result<JsDropStreamable> {
let path = Path::new(&path); let stream = reference.share_with(env, |handler| {
let mut backend = create_backend_for_path(path).unwrap(); let backend = handler
.create_backend_for_path(path)
.ok_or(napi::Error::from_reason("Failed to create backend."))?;
let version_file = VersionFile { let version_file = VersionFile {
relative_filename: sub_path, relative_filename: sub_path,
permission: 0, // Shouldn't matter permission: 0, // Shouldn't matter
size: 0, // Shouldn't matter size: 0, // Shouldn't matter
}; };
// Use `?` operator for cleaner error propagation from `Option` // Use `?` operator for cleaner error propagation from `Option`
let mut reader = backend.reader(&version_file)?; let mut reader = backend.reader(&version_file).ok_or(napi::Error::from_reason("Failed to create reader."))?;
// Skip the 'start' amount of bytes without seek
if let Some(skip) = start.clone() { if let Some(skip) = start.clone() {
reader.skip(skip.get_u64().1.into()); reader.skip(skip.get_u64().1.into());
// io::copy(&mut reader.by_ref().take(skip.into()), &mut io::sink()).unwrap(); // io::copy(&mut reader.by_ref().take(skip.into()), &mut io::sink()).unwrap();
@ -105,13 +126,9 @@ pub fn read_file(
let amount = limit.get_u64().1 - start.map_or(Some(0), |v| Some(v.get_u64().1)).unwrap(); let amount = limit.get_u64().1 - start.map_or(Some(0), |v| Some(v.get_u64().1)).unwrap();
ReadToAsyncRead { ReadToAsyncRead {
inner: Box::new(reader.take(amount.into())), inner: Box::new(reader.take(amount.into())),
backend,
} }
} else { } else {
ReadToAsyncRead { ReadToAsyncRead { inner: reader }
inner: reader,
backend,
}
}; };
// Create a FramedRead stream with BytesCodec for chunking // Create a FramedRead stream with BytesCodec for chunking
@ -127,5 +144,24 @@ pub fn read_file(
// Create the napi-rs ReadableStream from the tokio_stream::Stream // Create the napi-rs ReadableStream from the tokio_stream::Stream
// The unwrap() here means if stream creation fails, it will panic. // The unwrap() here means if stream creation fails, it will panic.
// For a production system, consider returning Result<Option<...>> and handling this. // For a production system, consider returning Result<Option<...>> and handling this.
Some(ReadableStream::create_with_stream_bytes(env, stream).unwrap()) Ok(ReadableStream::create_with_stream_bytes(&env, stream).unwrap())
})?;
Ok(JsDropStreamable {
inner: stream,
})
}
}
#[napi]
pub struct JsDropStreamable {
inner: SharedReference<DropletHandler<'static>, ReadableStream<'static, BufferSlice<'static>>>,
}
#[napi]
impl JsDropStreamable {
#[napi]
pub fn get_stream(&self) -> *mut napi_value__ {
self.inner.raw()
}
} }

151
yarn.lock
View File

@ -12,6 +12,7 @@ __metadata:
"@napi-rs/cli": "npm:3.0.0-alpha.91" "@napi-rs/cli": "npm:3.0.0-alpha.91"
"@types/node": "npm:^22.13.10" "@types/node": "npm:^22.13.10"
ava: "npm:^6.2.0" ava: "npm:^6.2.0"
tsimp: "npm:^2.0.12"
languageName: unknown languageName: unknown
linkType: soft linkType: soft
@ -268,6 +269,38 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@isaacs/balanced-match@npm:^4.0.1":
version: 4.0.1
resolution: "@isaacs/balanced-match@npm:4.0.1"
checksum: 10c0/7da011805b259ec5c955f01cee903da72ad97c5e6f01ca96197267d3f33103d5b2f8a1af192140f3aa64526c593c8d098ae366c2b11f7f17645d12387c2fd420
languageName: node
linkType: hard
"@isaacs/brace-expansion@npm:^5.0.0":
version: 5.0.0
resolution: "@isaacs/brace-expansion@npm:5.0.0"
dependencies:
"@isaacs/balanced-match": "npm:^4.0.1"
checksum: 10c0/b4d4812f4be53afc2c5b6c545001ff7a4659af68d4484804e9d514e183d20269bb81def8682c01a22b17c4d6aed14292c8494f7d2ac664e547101c1a905aa977
languageName: node
linkType: hard
"@isaacs/cached@npm:^1.0.1":
version: 1.0.1
resolution: "@isaacs/cached@npm:1.0.1"
dependencies:
"@isaacs/catcher": "npm:^1.0.0"
checksum: 10c0/1c15dc2a60873f2c73f4b04ed59ecfc8d9679976ff09af1b5b45e7273a590a4f86a339cc4c785c2d22309277ca47293611af20dd7d41550cdcfb53e06a04ac65
languageName: node
linkType: hard
"@isaacs/catcher@npm:^1.0.0, @isaacs/catcher@npm:^1.0.4":
version: 1.0.4
resolution: "@isaacs/catcher@npm:1.0.4"
checksum: 10c0/d8b77e2c6b84a6301d390d0b2badea1b4a321f2e8ba662645b045efc42f20a54a6c760f3181fab4ed0d90da58f2cb084a93490a892c53b4da21ec05278b8ba4f
languageName: node
linkType: hard
"@isaacs/cliui@npm:^8.0.2": "@isaacs/cliui@npm:^8.0.2":
version: 8.0.2 version: 8.0.2
resolution: "@isaacs/cliui@npm:8.0.2" resolution: "@isaacs/cliui@npm:8.0.2"
@ -1756,7 +1789,7 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"foreground-child@npm:^3.1.0": "foreground-child@npm:^3.1.0, foreground-child@npm:^3.1.1, foreground-child@npm:^3.3.1":
version: 3.3.1 version: 3.3.1
resolution: "foreground-child@npm:3.3.1" resolution: "foreground-child@npm:3.3.1"
dependencies: dependencies:
@ -1812,6 +1845,22 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"glob@npm:^11.0.0":
version: 11.0.3
resolution: "glob@npm:11.0.3"
dependencies:
foreground-child: "npm:^3.3.1"
jackspeak: "npm:^4.1.1"
minimatch: "npm:^10.0.3"
minipass: "npm:^7.1.2"
package-json-from-dist: "npm:^1.0.0"
path-scurry: "npm:^2.0.0"
bin:
glob: dist/esm/bin.mjs
checksum: 10c0/7d24457549ec2903920dfa3d8e76850e7c02aa709122f0164b240c712f5455c0b457e6f2a1eee39344c6148e39895be8094ae8cfef7ccc3296ed30bce250c661
languageName: node
linkType: hard
"glob@npm:^7.1.3": "glob@npm:^7.1.3":
version: 7.2.3 version: 7.2.3
resolution: "glob@npm:7.2.3" resolution: "glob@npm:7.2.3"
@ -1996,6 +2045,15 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"jackspeak@npm:^4.1.1":
version: 4.1.1
resolution: "jackspeak@npm:4.1.1"
dependencies:
"@isaacs/cliui": "npm:^8.0.2"
checksum: 10c0/84ec4f8e21d6514db24737d9caf65361511f75e5e424980eebca4199f400874f45e562ac20fa8aeb1dd20ca2f3f81f0788b6e9c3e64d216a5794fd6f30e0e042
languageName: node
linkType: hard
"js-string-escape@npm:^1.0.1": "js-string-escape@npm:^1.0.1":
version: 1.0.1 version: 1.0.1
resolution: "js-string-escape@npm:1.0.1" resolution: "js-string-escape@npm:1.0.1"
@ -2063,6 +2121,13 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"lru-cache@npm:^11.0.0":
version: 11.1.0
resolution: "lru-cache@npm:11.1.0"
checksum: 10c0/85c312f7113f65fae6a62de7985348649937eb34fb3d212811acbf6704dc322a421788aca253b62838f1f07049a84cc513d88f494e373d3756514ad263670a64
languageName: node
linkType: hard
"matcher@npm:^5.0.0": "matcher@npm:^5.0.0":
version: 5.0.0 version: 5.0.0
resolution: "matcher@npm:5.0.0" resolution: "matcher@npm:5.0.0"
@ -2114,6 +2179,15 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"minimatch@npm:^10.0.3":
version: 10.0.3
resolution: "minimatch@npm:10.0.3"
dependencies:
"@isaacs/brace-expansion": "npm:^5.0.0"
checksum: 10c0/e43e4a905c5d70ac4cec8530ceaeccb9c544b1ba8ac45238e2a78121a01c17ff0c373346472d221872563204eabe929ad02669bb575cb1f0cc30facab369f70f
languageName: node
linkType: hard
"minimatch@npm:^3.1.1": "minimatch@npm:^3.1.1":
version: 3.1.2 version: 3.1.2
resolution: "minimatch@npm:3.1.2" resolution: "minimatch@npm:3.1.2"
@ -2311,6 +2385,16 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"path-scurry@npm:^2.0.0":
version: 2.0.0
resolution: "path-scurry@npm:2.0.0"
dependencies:
lru-cache: "npm:^11.0.0"
minipass: "npm:^7.1.2"
checksum: 10c0/3da4adedaa8e7ef8d6dc4f35a0ff8f05a9b4d8365f2b28047752b62d4c1ad73eec21e37b1579ef2d075920157856a3b52ae8309c480a6f1a8bbe06ff8e52b33c
languageName: node
linkType: hard
"path-type@npm:^6.0.0": "path-type@npm:^6.0.0":
version: 6.0.0 version: 6.0.0
resolution: "path-type@npm:6.0.0" resolution: "path-type@npm:6.0.0"
@ -2332,6 +2416,13 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"pirates@npm:^4.0.6":
version: 4.0.7
resolution: "pirates@npm:4.0.7"
checksum: 10c0/a51f108dd811beb779d58a76864bbd49e239fa40c7984cd11596c75a121a8cc789f1c8971d8bb15f0dbf9d48b76c05bb62fcbce840f89b688c0fa64b37e8478a
languageName: node
linkType: hard
"plur@npm:^5.1.0": "plur@npm:^5.1.0":
version: 5.1.0 version: 5.1.0
resolution: "plur@npm:5.1.0" resolution: "plur@npm:5.1.0"
@ -2398,6 +2489,18 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"rimraf@npm:^6.0.1":
version: 6.0.1
resolution: "rimraf@npm:6.0.1"
dependencies:
glob: "npm:^11.0.0"
package-json-from-dist: "npm:^1.0.0"
bin:
rimraf: dist/esm/bin.mjs
checksum: 10c0/b30b6b072771f0d1e73b4ca5f37bb2944ee09375be9db5f558fcd3310000d29dfcfa93cf7734d75295ad5a7486dc8e40f63089ced1722a664539ffc0c3ece8c6
languageName: node
linkType: hard
"run-parallel@npm:^1.1.9": "run-parallel@npm:^1.1.9":
version: 1.2.0 version: 1.2.0
resolution: "run-parallel@npm:1.2.0" resolution: "run-parallel@npm:1.2.0"
@ -2481,6 +2584,24 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"sock-daemon@npm:^1.4.2":
version: 1.4.2
resolution: "sock-daemon@npm:1.4.2"
dependencies:
rimraf: "npm:^5.0.5"
signal-exit: "npm:^4.1.0"
socket-post-message: "npm:^1.0.3"
checksum: 10c0/1b5e0b02fdd8cd5454fc7de80557c11aac5d88085d0cee80ead08b8f4df5e3c0a4b50ebb2ae2113dab94f36dc88b5d3b7d4b1c2c8e53bbcfbddfc741abf3bd00
languageName: node
linkType: hard
"socket-post-message@npm:^1.0.3":
version: 1.0.3
resolution: "socket-post-message@npm:1.0.3"
checksum: 10c0/d3ffb51dad97754856aaa6709e036196f4b8b674f00366b71591ead122bcdbc073827f67d17c8b03c9a28c921b2c7cb277c581f6ca318d472034eae7afc169d1
languageName: node
linkType: hard
"sprintf-js@npm:~1.0.2": "sprintf-js@npm:~1.0.2":
version: 1.0.3 version: 1.0.3
resolution: "sprintf-js@npm:1.0.3" resolution: "sprintf-js@npm:1.0.3"
@ -2613,6 +2734,27 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"tsimp@npm:^2.0.12":
version: 2.0.12
resolution: "tsimp@npm:2.0.12"
dependencies:
"@isaacs/cached": "npm:^1.0.1"
"@isaacs/catcher": "npm:^1.0.4"
foreground-child: "npm:^3.1.1"
mkdirp: "npm:^3.0.1"
pirates: "npm:^4.0.6"
rimraf: "npm:^6.0.1"
signal-exit: "npm:^4.1.0"
sock-daemon: "npm:^1.4.2"
walk-up-path: "npm:^4.0.0"
peerDependencies:
typescript: ^5.1.0
bin:
tsimp: dist/esm/bin.mjs
checksum: 10c0/c56c03a6a4df3ab5ebcefcc0b473992cbb7150173c331be6bda01670d5ae3965e65f30c42757cd391100a1c21485e167a05a350d875f41826b35c45008e5fac8
languageName: node
linkType: hard
"tslib@npm:^2.4.0": "tslib@npm:^2.4.0":
version: 2.8.1 version: 2.8.1
resolution: "tslib@npm:2.8.1" resolution: "tslib@npm:2.8.1"
@ -2669,6 +2811,13 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"walk-up-path@npm:^4.0.0":
version: 4.0.0
resolution: "walk-up-path@npm:4.0.0"
checksum: 10c0/fabe344f91387d1d41df230af962ef18bf703dd4178006d55cd6412caacd187b54440002d4d53a982d4f7f0455567dcffb6d3884533c8b2268928eca3ebd8a19
languageName: node
linkType: hard
"wasm-sjlj@npm:^1.0.6": "wasm-sjlj@npm:^1.0.6":
version: 1.0.6 version: 1.0.6
resolution: "wasm-sjlj@npm:1.0.6" resolution: "wasm-sjlj@npm:1.0.6"