Skip to content

Commit f662731

Browse files
committed
docs and style fixes, remove traces of manifest idea
1 parent 39af37e commit f662731

File tree

7 files changed

+60
-46
lines changed

7 files changed

+60
-46
lines changed

src/lib/libfetchfs.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,11 @@ addToLibrary({
88
$FETCHFS__deps: ['$stringToUTF8OnStack', 'wasmfs_create_fetch_backend'],
99
$FETCHFS: {
1010
createBackend(opts) {
11-
return _wasmfs_create_fetch_backend(stringToUTF8OnStack(opts.base_url), opts.chunkSize | 0);
12-
}
11+
opts.base_url ??= "";
12+
return withStackSave(() => {
13+
return _wasmfs_create_fetch_backend(stringToUTF8OnStack(opts.base_url), opts.chunkSize | 0);
14+
});
15+
},
1316
},
1417
});
1518

src/lib/libwasmfs_fetch.js

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -31,25 +31,26 @@ addToLibrary({
3131
try {
3232
var u = new URL(fileUrl, self.location.origin);
3333
url = u.toString();
34-
} catch (e) {
34+
} catch (_e) {
35+
throw {status: 404};
3536
}
3637
}
3738
var chunkSize = __wasmfs_fetch_get_chunk_size(file);
38-
offset = offset || 0;
39+
offset ??= 0;
3940
len = len || chunkSize;
4041
var firstChunk = (offset / chunkSize) | 0;
4142
var lastChunk = ((offset+len) / chunkSize) | 0;
4243
if (!(file in wasmFS$JSMemoryRanges)) {
4344
var fileInfo = await fetch(url,{method:"HEAD", headers:{"Range": "bytes=0-"}});
44-
if(fileInfo.ok &&
45+
if (fileInfo.ok &&
4546
fileInfo.headers.has("Content-Length") &&
4647
fileInfo.headers.get("Accept-Ranges") == "bytes" &&
4748
(parseInt(fileInfo.headers.get("Content-Length")) > chunkSize*2)) {
4849
wasmFS$JSMemoryRanges[file] = {size:parseInt(fileInfo.headers.get("Content-Length")), chunks:[], chunkSize:chunkSize};
4950
} else {
5051
// may as well/forced to download the whole file
5152
var wholeFileReq = await fetch(url);
52-
if(!wholeFileReq.ok) {
53+
if (!wholeFileReq.ok) {
5354
throw wholeFileReq;
5455
}
5556
var wholeFileData = new Uint8Array(await wholeFileReq.arrayBuffer());
@@ -60,11 +61,11 @@ addToLibrary({
6061
}
6162
var allPresent = true;
6263
var i;
63-
if(lastChunk * chunkSize < offset+len) {
64+
if (lastChunk * chunkSize < offset+len) {
6465
lastChunk += 1;
6566
}
66-
for(i = firstChunk; i < lastChunk; i++) {
67-
if(!wasmFS$JSMemoryRanges[file].chunks[i]) {
67+
for (i = firstChunk; i < lastChunk; i++) {
68+
if (!wasmFS$JSMemoryRanges[file].chunks[i]) {
6869
allPresent = false;
6970
break;
7071
}
@@ -78,14 +79,13 @@ addToLibrary({
7879
var start = firstChunk*chunkSize;
7980
var end = lastChunk*chunkSize;
8081
var response = await fetch(url, {headers:{"Range": `bytes=${start}-${end-1}`}});
81-
if (response.ok) {
82-
var bytes = new Uint8Array(await response['arrayBuffer']());
83-
for (i = firstChunk; i < lastChunk; i++) {
84-
wasmFS$JSMemoryRanges[file].chunks[i] = bytes.slice(i*chunkSize-start,(i+1)*chunkSize-start);
85-
}
86-
} else {
82+
if (!response.ok) {
8783
throw response;
8884
}
85+
var bytes = new Uint8Array(await response['arrayBuffer']());
86+
for (i = firstChunk; i < lastChunk; i++) {
87+
wasmFS$JSMemoryRanges[file].chunks[i] = bytes.slice(i*chunkSize-start,(i+1)*chunkSize-start);
88+
}
8989
return Promise.resolve();
9090
}
9191

@@ -110,24 +110,21 @@ addToLibrary({
110110
read: async (file, buffer, length, offset) => {
111111
try {
112112
await getFileRange(file, offset || 0, length);
113-
} catch (response) {
114-
return response.status === 404 ? -{{{ cDefs.ENOENT }}} : -{{{ cDefs.EBADF }}};
113+
} catch (failedResponse) {
114+
return failedResponse.status === 404 ? -{{{ cDefs.ENOENT }}} : -{{{ cDefs.EBADF }}};
115115
}
116116
var fileInfo = wasmFS$JSMemoryRanges[file];
117117
var fileData = fileInfo.chunks;
118118
var chunkSize = fileInfo.chunkSize;
119119
var firstChunk = (offset / chunkSize) | 0;
120120
var lastChunk = ((offset+length) / chunkSize) | 0;
121-
if(offset + length > lastChunk * chunkSize) {
121+
if (offset + length > lastChunk * chunkSize) {
122122
lastChunk += 1;
123123
}
124124
var readLength = 0;
125125
for (var i = firstChunk; i < lastChunk; i++) {
126126
var chunk = fileData[i];
127127
var start = Math.max(i*chunkSize, offset);
128-
if(!chunk) {
129-
throw [fileData.length, firstChunk, lastChunk, i];
130-
}
131128
var chunkStart = i*chunkSize;
132129
var end = Math.min(chunkStart+chunkSize, offset+length);
133130
HEAPU8.set(chunk.subarray(start-chunkStart, end-chunkStart), buffer+(start-offset));
@@ -138,7 +135,7 @@ addToLibrary({
138135
getSize: async (file) => {
139136
try {
140137
await getFileRange(file, 0, 0);
141-
} catch (response) {
138+
} catch (failedResponse) {
142139
return 0;
143140
}
144141
return wasmFS$JSMemoryRanges[file].size;

system/include/emscripten/wasmfs.h

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,18 @@ typedef backend_t (*backend_constructor_t)(void*);
4848

4949
backend_t wasmfs_create_memory_backend(void);
5050

51+
// Fetch backend
52+
//
53+
// Creates a new fetchfs backend. FetchFS will backstop filesystem
54+
// reads to HTTP fetch requests, which will download just specific
55+
// ranges of the requested files. FetchFS works best when your web
56+
// server supports HTTP range requests, and it's important that those
57+
// files are not stored encrypted or compressed at rest. FetchFS by
58+
// default will dispatch HTTP requests to URLs beginning with base_url
59+
// and ending with whatever the file's path is relative to where the
60+
// fetchfs directory is mounted.
61+
//
62+
//
5163
// Note: this cannot be called on the browser main thread because it might
5264
// deadlock while waiting for its dedicated worker thread to be spawned.
5365
//
@@ -57,7 +69,9 @@ backend_t wasmfs_create_memory_backend(void);
5769
//
5870
// TODO: Add an async version of this function that will work on the main
5971
// thread.
60-
backend_t wasmfs_create_fetch_backend(const char* base_url __attribute__((nonnull)), uint32_t);
72+
//
73+
backend_t wasmfs_create_fetch_backend(const char* base_url __attribute__((nonnull)),
74+
uint32_t chunkSize);
6175

6276
backend_t wasmfs_create_node_backend(const char* root __attribute__((nonnull)));
6377

system/lib/wasmfs/backends/fetch_backend.cpp

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -21,16 +21,14 @@ class FetchBackend : public wasmfs::ProxiedAsyncJSBackend {
2121
FetchBackend(const std::string& baseUrl,
2222
uint32_t chunkSize,
2323
std::function<void(backend_t)> setupOnThread)
24-
: ProxiedAsyncJSBackend(setupOnThread), baseUrl(baseUrl), chunkSize(chunkSize)
25-
// TODO manifest
26-
{}
24+
: ProxiedAsyncJSBackend(setupOnThread), baseUrl(baseUrl), chunkSize(chunkSize) {}
2725
std::shared_ptr<DataFile> createFile(mode_t mode) override;
2826
std::shared_ptr<Directory> createDirectory(mode_t mode) override;
2927
const std::string getFileURL(const std::string& filePath);
3028
uint32_t getChunkSize();
3129
};
3230

33-
31+
3432
class FetchFile : public ProxiedAsyncJSImplFile {
3533
std::string filePath;
3634
std::string fileUrl;
@@ -81,6 +79,10 @@ class FetchDirectory : public MemoryDirectory {
8179
std::string getChildPath(const std::string& name) const {
8280
return dirPath + '/' + name;
8381
}
82+
83+
std::shared_ptr<File> getChild(const std::string& name) override {
84+
return MemoryDirectory::getChild(name);
85+
}
8486
};
8587

8688
std::shared_ptr<DataFile> FetchBackend::createFile(mode_t mode) {
@@ -92,41 +94,38 @@ std::shared_ptr<Directory> FetchBackend::createDirectory(mode_t mode) {
9294
}
9395

9496
const std::string FetchBackend::getFileURL(const std::string& filePath) {
95-
// TODO use manifest
9697
if(filePath == "") {
9798
return baseUrl;
9899
}
99100
return baseUrl + "/" + filePath;
100101
}
102+
101103
uint32_t FetchBackend::getChunkSize() {
102104
return chunkSize;
103105
}
104106

105107
extern "C" {
106-
backend_t wasmfs_create_fetch_backend(const char* base_url, uint32_t chunkSize /* TODO manifest */) {
108+
backend_t wasmfs_create_fetch_backend(const char* base_url, uint32_t chunkSize) {
107109
// ProxyWorker cannot safely be synchronously spawned from the main browser
108110
// thread. See comment in thread_utils.h for more details.
109111
assert(!emscripten_is_main_browser_thread() &&
110112
"Cannot safely create fetch backend on main browser thread");
111113
return wasmFS.addBackend(std::make_unique<FetchBackend>(
112114
base_url ? base_url : "",
113-
chunkSize != 0 ? chunkSize : DEFAULT_CHUNK_SIZE,
114-
/* TODO manifest */
115+
chunkSize ? chunkSize : DEFAULT_CHUNK_SIZE,
115116
[](backend_t backend) { _wasmfs_create_fetch_backend_js(backend); }));
116117
}
117118

118-
const char* EMSCRIPTEN_KEEPALIVE _wasmfs_fetch_get_file_path(void* ptr) {
119-
auto* file = reinterpret_cast<wasmfs::FetchFile*>(ptr);
120-
return file ? file->getPath().data() : nullptr;
121-
}
122-
const char* EMSCRIPTEN_KEEPALIVE _wasmfs_fetch_get_file_url(void* ptr) {
119+
const char* _wasmfs_fetch_get_file_url(void* ptr) {
123120
auto* file = reinterpret_cast<wasmfs::FetchFile*>(ptr);
124121
return file ? file->getURL().data() : nullptr;
125122
}
126-
uint32_t EMSCRIPTEN_KEEPALIVE _wasmfs_fetch_get_chunk_size(void* ptr) {
123+
124+
uint32_t _wasmfs_fetch_get_chunk_size(void* ptr) {
127125
auto* file = reinterpret_cast<wasmfs::FetchFile*>(ptr);
128126
return file ? file->getChunkSize() : DEFAULT_CHUNK_SIZE;
129127
}
128+
130129
}
131130

132131
} // namespace wasmfs

system/lib/wasmfs/backends/fetch_backend.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,6 @@
66
#include "wasmfs.h"
77

88
extern "C" {
9-
// See library_wasmfs_fetch.js
10-
void _wasmfs_create_fetch_backend_js(wasmfs::backend_t);
9+
// See library_wasmfs_fetch.js
10+
void _wasmfs_create_fetch_backend_js(wasmfs::backend_t);
1111
}

test/common.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2054,7 +2054,7 @@ def send_head(self):
20542054
f = open(path, 'rb')
20552055
fs = os.fstat(f.fileno())
20562056
except IOError:
2057-
self.send_error(404, "File not found: " + path)
2057+
self.send_error(404, f'File not found {path}')
20582058
return None
20592059
if self.path.endswith('.js'):
20602060
self.send_response(200)
@@ -2063,16 +2063,16 @@ def send_head(self):
20632063
self.send_header('Content-length', fs[6])
20642064
self.end_headers()
20652065
return f
2066-
elif self.headers.get("Range"):
2066+
elif self.headers.get('Range'):
20672067
self.send_response(206)
20682068
ctype = self.guess_type(path)
20692069
self.send_header('Content-Type', ctype)
2070-
pieces = self.headers.get("Range").split("=")[1].split("-")
2070+
pieces = self.headers.get('Range').split('=')[1].split('-')
20712071
start = int(pieces[0]) if pieces[0] != '' else 0
20722072
end = int(pieces[1]) if pieces[1] != '' else fs[6] - 1
20732073
end = min(fs[6] - 1, end)
20742074
length = end - start + 1
2075-
self.send_header('Content-Range', "bytes " + str(start) + "-" + str(end) + "/" + str(fs[6]))
2075+
self.send_header('Content-Range', f'bytes {start}-{end}/{fs[6]}')
20762076
self.send_header('Content-Length', str(length))
20772077
self.end_headers()
20782078
return f
@@ -2176,19 +2176,19 @@ def do_GET(self):
21762176
# Use SimpleHTTPServer default file serving operation for GET.
21772177
if DEBUG:
21782178
print('[simple HTTP serving:', unquote_plus(self.path), ']')
2179-
if self.headers.get("Range"):
2179+
if self.headers.get('Range'):
21802180
self.send_response(206)
21812181
path = self.translate_path(self.path)
21822182
data = read_binary(path)
21832183
ctype = self.guess_type(path)
21842184
self.send_header('Content-type', ctype)
2185-
pieces = self.headers.get("range").split("=")[1].split("-")
2185+
pieces = self.headers.get('Range').split('=')[1].split('-')
21862186
start = int(pieces[0]) if pieces[0] != '' else 0
21872187
end = int(pieces[1]) if pieces[1] != '' else len(data) - 1
21882188
end = min(len(data) - 1, end)
21892189
length = end - start + 1
21902190
self.send_header('Content-Length', str(length))
2191-
self.send_header('Content-Range', "bytes " + str(start) + "-" + str(end) + "/" + str(len(data)))
2191+
self.send_header('Content-Range', f'bytes {start}-{end}/{len(data)}')
21922192
self.end_headers()
21932193
self.wfile.write(data[start:end + 1])
21942194
else:

test/wasmfs/wasmfs_fetch.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
*/
77

88
#include <assert.h>
9+
#include <fcntl.h>
910
#include <dirent.h>
1011
#include <emscripten/emscripten.h>
1112
#include <emscripten/wasmfs.h>

0 commit comments

Comments
 (0)