1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
use std::fmt::Write;
use std::str::FromStr;

use js_sys::ArrayBuffer;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
use web_sys::{
    Request,
    RequestInit,
    RequestMode,
    Response,
};

use super::*;


const ATTRIBUTES_FILE: &str = "attributes.json";


#[wasm_bindgen]
#[derive(Clone)]
pub struct N5HTTPFetch {
    base_path: String,
}

impl N5HTTPFetch {
    fn fetch(&self, path_name: &str) -> JsFuture {
        let mut request_options = RequestInit::new();
        request_options.method("GET");
        request_options.mode(RequestMode::Cors);

        let req = Request::new_with_str_and_init(
            &format!("{}/{}", &self.base_path, path_name),
            &request_options).unwrap();

        let req_promise = web_sys::window().unwrap().fetch_with_request(&req);

        JsFuture::from(req_promise)
    }

    fn fetch_json(&self, path_name: &str) -> impl Future<Item = JsValue, Error = JsValue> {
        self.fetch(path_name).and_then(|resp_value| {
            assert!(resp_value.is_instance_of::<Response>());
            let resp: Response = resp_value.dyn_into()?;

            resp.json()
        }).and_then(|json_value: Promise| {
            JsFuture::from(json_value)
        })
    }

    fn get_attributes(&self, path_name: &str) -> impl Future<Item = serde_json::Value, Error = Error> {
        let path = if path_name.is_empty() { ATTRIBUTES_FILE.to_owned() }
            else { format!("{}/{}", path_name, ATTRIBUTES_FILE) };
        let to_return = self
            .fetch_json(&path)
            .map(|json| json.into_serde().unwrap());

        map_future_error_rust(to_return)
    }

    fn relative_block_path(&self, path_name: &str, grid_position: &[i64]) -> String {
        let mut block_path = String::new();
        for coord in grid_position {
            write!(block_path, "/{}", coord).unwrap();
        }

        format!("{}{}", path_name, block_path)
    }
}

#[wasm_bindgen]
impl N5HTTPFetch {
    pub fn open(base_path: &str) -> Promise {
        let reader = N5HTTPFetch {
            base_path: base_path.into(),
        };

        let to_return = N5AsyncReader::get_version(&reader).and_then(|version| {

            if !n5::VERSION.is_compatible(&version) {
                return future::err(Error::new(ErrorKind::Other, "TODO: Incompatible version"))
            }

            future::ok(JsValue::from(reader))
        });

        future_to_promise(map_future_error_wasm(to_return))
    }
}

/// Delegations to expose N5PromiseReader trait to WASM.
#[wasm_bindgen]
impl N5HTTPFetch {
    pub fn get_version(&self) -> Promise {
        N5PromiseReader::get_version(self)
    }

    pub fn get_dataset_attributes(&self, path_name: &str) -> Promise {
        N5PromiseReader::get_dataset_attributes(self, path_name)
    }

    pub fn exists(&self, path_name: &str) -> Promise {
        N5PromiseReader::exists(self, path_name)
    }

    pub fn dataset_exists(&self, path_name: &str) -> Promise {
        N5PromiseReader::dataset_exists(self, path_name)
    }

    pub fn read_block(
        &self,
        path_name: &str,
        data_attrs: &wrapped::DatasetAttributes,
        grid_position: Vec<i64>
    ) -> Promise {
        N5PromiseReader::read_block(self, path_name, data_attrs, grid_position)
    }

    pub fn list_attributes(&self, path_name: &str) -> Promise {
        N5PromiseReader::list_attributes(self, path_name)
    }

    pub fn block_etag(
        &self,
        path_name: &str,
        data_attrs: &wrapped::DatasetAttributes,
        grid_position: Vec<i64>
    ) -> Promise {
        N5PromiseEtagReader::block_etag(
            self, path_name, data_attrs, grid_position)
    }

    pub fn read_block_with_etag(
        &self,
        path_name: &str,
        data_attrs: &wrapped::DatasetAttributes,
        grid_position: Vec<i64>
    ) -> Promise {
        N5PromiseEtagReader::read_block_with_etag(
            self, path_name, data_attrs, grid_position)
    }
}

impl N5AsyncReader for N5HTTPFetch {
    fn get_version(&self) -> Box<Future<Item = n5::Version, Error = Error>> {
        let to_return = self.get_attributes("").map(|attr| {
            n5::Version::from_str(attr
                    .get(n5::VERSION_ATTRIBUTE_KEY)
                    .unwrap()
                    .as_str().unwrap_or("")
                ).unwrap()
        });

        Box::new(to_return)
    }

    fn get_dataset_attributes(&self, path_name: &str) ->
            Box<Future<Item = n5::DatasetAttributes, Error = Error>> {

        let path = if path_name.is_empty() { ATTRIBUTES_FILE.to_owned() }
            else { format!("{}/{}", path_name, ATTRIBUTES_FILE) };
        let to_return = self
            .fetch_json(&path)
            .map(|json| { json.into_serde().unwrap() });

        Box::new(map_future_error_rust(to_return))
    }

    fn exists(&self, path_name: &str) -> Box<Future<Item = bool, Error = Error>> {
        let to_return = self.fetch(path_name).and_then(|resp_value| {
            assert!(resp_value.is_instance_of::<Response>());
            let resp: Response = resp_value.dyn_into().unwrap();

            future::ok(resp.ok())
        });

        Box::new(map_future_error_rust(to_return))
    }

    fn read_block<T>(
        &self,
        path_name: &str,
        data_attrs: &DatasetAttributes,
        grid_position: Vec<i64>
    ) -> Box<Future<Item = Option<VecDataBlock<T>>, Error = Error>>
            where DataType: n5::DataBlockCreator<T>,
                  VecDataBlock<T>: DataBlock<T>,
                  T: Clone + 'static {

        Box::new(N5AsyncEtagReader::read_block_with_etag(
                self, path_name, data_attrs, grid_position)
            .map(|maybe_block| maybe_block.map(|(block, _etag)| block)))
    }

    fn list(&self, _path_name: &str) -> Box<Future<Item = Vec<String>, Error = Error>> {
        // TODO: Not implemented because remote paths are not listable.
        unimplemented!()
    }

    fn list_attributes(
        &self,
        path_name: &str,
    ) -> Box<Future<Item = serde_json::Value, Error = Error>> {

        Box::new(self.get_attributes(path_name))
    }
}

impl N5AsyncEtagReader for N5HTTPFetch {
    fn block_etag(
        &self,
        path_name: &str,
        _data_attrs: &DatasetAttributes,
        grid_position: Vec<i64>
    ) -> Box<Future<Item = Option<String>, Error = Error>> {
        let mut request_options = RequestInit::new();
        request_options.method("HEAD");
        request_options.mode(RequestMode::Cors);

        let block_path = self.relative_block_path(path_name, &grid_position);

        let req = Request::new_with_str_and_init(
            &format!("{}/{}", &self.base_path, block_path),
            &request_options).unwrap();

        let req_promise = web_sys::window().unwrap().fetch_with_request(&req);

        let f = JsFuture::from(req_promise)
            .map(|resp_value| {
                assert!(resp_value.is_instance_of::<Response>());
                let resp: Response = resp_value.dyn_into().unwrap();

                if resp.ok() {
                    resp.headers().get("ETag").unwrap_or(None)
                } else {
                    None
                }
            });

        Box::new(map_future_error_rust(f))
    }

    fn read_block_with_etag<T>(
        &self,
        path_name: &str,
        data_attrs: &DatasetAttributes,
        grid_position: Vec<i64>
    ) -> Box<Future<Item = Option<(VecDataBlock<T>, Option<String>)>, Error = Error>>
            where DataType: n5::DataBlockCreator<T>,
                  VecDataBlock<T>: DataBlock<T>,
                  T: Clone + 'static {

        let da2 = data_attrs.clone();

        let block_path = self.relative_block_path(path_name, &grid_position);

        let f = self.fetch(&block_path).and_then(|resp_value| {
            assert!(resp_value.is_instance_of::<Response>());
            let resp: Response = resp_value.dyn_into().unwrap();

            if resp.ok() {
                let etag: Option<String> = resp.headers().get("ETag").unwrap_or(None);
                let to_return = JsFuture::from(resp.array_buffer().unwrap())
                    .map(move |arrbuff_value| {
                        assert!(arrbuff_value.is_instance_of::<ArrayBuffer>());
                        let typebuff: js_sys::Uint8Array = js_sys::Uint8Array::new(&arrbuff_value);

                        let mut buff: Vec<u8> = vec![0; typebuff.length() as usize];
                        typebuff.copy_to(buff.as_mut_slice());

                        Some((<n5::DefaultBlock as n5::DefaultBlockReader<T, &[u8]>>::read_block(
                            &buff,
                            &da2,
                            grid_position).unwrap(),
                            etag))
                    });
                future::Either::A(to_return)
            } else  {
                future::Either::B(future::ok(None))
            }
        });

        Box::new(map_future_error_rust(f))
    }
}