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
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
const axios = require('axios');
const YAML = require('yaml');

const fs = require('node:fs');
const path_ = require('node:path');
const url = require('node:url');
const https = require('node:https');
const Assert = require('./Assert');
const log_error = require('./log_error');

module.exports = class TestSDK {
    constructor (conf, context, options = {}) {
        this.conf = conf;
        this.context = context;
        this.options = options;

        this.default_cwd = path_.posix.join('/', context.mountpoint.path, conf.username, 'api_test');
        this.cwd = this.default_cwd;

        this.httpsAgent = new https.Agent({
            rejectUnauthorized: false
        })
        const url_origin = new url.URL(conf.api_url).origin;
        this.headers_ = {
            'Origin': url_origin,
            'Authorization': `Bearer ${conf.auth_token}`
        };

        this.installAPIMethodShorthands_();

        this.assert = new Assert();

        this.sdks = {};

        this.results = [];
        this.failCount = 0;
        this.caseCount = 0;
        this.nameStack = [];

        this.packageResults = [];

        this.benchmarkResults = [];
    }

    async init_working_directory () {
        try {
            await this.delete(this.default_cwd, { recursive: true });
        } catch (e) {
            // ignore
        }
        try {
            await this.mkdir(this.default_cwd, { overwrite: true, create_missing_parents: true });
            await this.cd(this.default_cwd);
        } catch (e) {
            console.log('error during working directory initialization: ', e.message);
            process.exit(1);
        }
    }

    async get_sdk (name) {
        return await this.sdks[name].create();
    }

    // === test related methods ===

    async runTestPackage (testDefinition) {
        // display the fs provider name in the test results
        const settings = this.context.mountpoint?.provider;

        this.nameStack.push(testDefinition.name);
        const packageResult = {
            settings,
            name: testDefinition.name,
            failCount: 0,
            caseCount: 0,
            start: Date.now(),
        };
        this.packageResults.push(packageResult);
        const imported = {};
        for ( const key of Object.keys(testDefinition.import ?? {}) ) {
            imported[key] = this.sdks[key];
        }
        try {
            await testDefinition.do(this, imported);
        } finally {
            packageResult.end = Date.now();
            packageResult.duration = (packageResult.end - packageResult.start) / 1000; // Convert to seconds
        }
        this.nameStack.pop();
    }

    async runBenchmark (benchDefinition) {
        const strid = '' +
            '\x1B[35;1m[bench]\x1B[0m' +
            this.nameStack.join(` \x1B[36;1m->\x1B[0m `);
        process.stdout.write(strid + ' ... \n');

        this.resetCwd();

        this.nameStack.push(benchDefinition.name);
        const start = Date.now();
        let duration = null;
        try {
            const res = await benchDefinition.do(this);
            if ( res?.duration ) {
                duration = res.duration;
            }
        } catch (e) {
            // we don't tolerate errors at the moment
            console.error(e);
            throw e;
        }

        if ( ! duration ) {
            // if the bench definition doesn't return the duration, we calculate it here
            duration = Date.now() - start;
        }

        const results = {
            name: benchDefinition.name,
            description: benchDefinition.description,
            duration: Date.now() - start,
            fs_provider: this.context.mountpoint?.provider || 'unknown',
        };

        console.log(`duration: ${(results.duration / 1000).toFixed(2)}s`);

        this.benchmarkResults.push(results);

        this.nameStack.pop();
    }

    recordResult (result) {
        const pkg = this.packageResults[this.packageResults.length - 1];
        this.caseCount++;
        pkg.caseCount++;
        if ( ! result.success ) {
            this.failCount++;
            pkg.failCount++;
        }
        this.results.push(result);
    }

    async case (id, fn) {
        this.nameStack.push(id);

        // Always reset cwd at the beginning of a test suite to prevent it 
        // from affected by others.
        if (this.nameStack.length === 1) {
            this.resetCwd();
        }

        const tabs = Array(this.nameStack.length - 2).fill('  ').join('');
        const strid = tabs + this.nameStack.join(` \x1B[36;1m->\x1B[0m `);
        process.stdout.write(strid + ' ... \n');

        try {
            await fn(this.context);
        } catch (e) {
            process.stdout.write(`${tabs}...\x1B[31;1m[FAIL]\x1B[0m\n`);
            this.recordResult({
                strid,
                e,
                success: false,
            });
            log_error(e);
            
            // Check if we should stop on failure
            if (this.options.stopOnFailure) {
                console.log('\x1B[31;1m[STOPPING] Test execution stopped due to failure and --stop-on-failure flag\x1B[0m');
                process.exit(1);
            }
            
            return;
        } finally {
            this.nameStack.pop();
        }

        process.stdout.write(`${tabs}...\x1B[32;1m[PASS]\x1B[0m\n`);
        this.recordResult({
            strid,
            success: true
        });
    }

    quirk (msg) {
        console.log(`\x1B[33;1mignoring known quirk: ${msg}\x1B[0m`);
    }

    // === information display methods ===

    printTestResults () {
        console.log(`\n\x1B[33;1m=== Test Results ===\x1B[0m`);

        let tbl = {};
        for ( const pkg of this.packageResults ) {
            tbl[pkg.name] = {
                settings: pkg.settings,
                passed: pkg.caseCount - pkg.failCount,
                failed: pkg.failCount,
                total: pkg.caseCount,
            }
        }
        console.table(tbl);

        process.stdout.write(`\x1B[36;1m${this.caseCount} tests were run\x1B[0m - `);
        if ( this.failCount > 0 ) {
            console.log(`\x1B[31;1m✖ ${this.failCount} tests failed!\x1B[0m`);
        } else {
            console.log(`\x1B[32;1m✔ All tests passed!\x1B[0m`)
        }
    }

    printBenchmarkResults () {
        console.log(`\n\x1B[33;1m=== Benchmark Results ===\x1B[0m`);

        let tbl = {};
        for ( const bench of this.benchmarkResults ) {
            tbl[bench.name] = {
                'duration (ms)': bench.duration,
            }
        }
        console.table(tbl);
    }

    // === path related methods ===

    cd (path) {
        if ( path.startsWith('/') ) {
            this.cwd = path;
        } else {
            this.cwd = path_.posix.join(this.cwd, path);
        }
    }

    resetCwd () {
        this.cwd = this.default_cwd;
    }

    resolve (path) {
        if ( path.startsWith('$') ) return path;
        if ( path.startsWith('/') ) return path;
        return path_.posix.join(this.cwd, path);
    }

    // === API calls ===

    installAPIMethodShorthands_ () {
        const p = this.resolve.bind(this);
        this.read = async path => {
            const res = await this.get('read', { path: p(path) });
            return res.data;
        }
        this.mkdir = async (path, opts) => {
            const res = await this.post('mkdir', {
                path: p(path),
                ...(opts ?? {})
            });
            return res.data;
        };
        // parent + path format: {"parent": "/foo", "path":"bar", args...}
        // this is used by puter-js (puter.fs.mkdir("/foo/bar"))
        this.mkdir_v2 = async (parent, path, opts) => {
            const res = await this.post('mkdir', {
                parent: p(parent),
                path: path, // "path" arg should remain relative in this api
                ...(opts ?? {})
            });
            return res.data;
        }
        this.write = async (path, bin, params) => {
            path = p(path);
            params = params ?? {};
            let mime = 'text/plain';
            if ( params.hasOwnProperty('mime') ) {
                mime = params.mime;
                delete params.mime;
            }
            let name = path_.posix.basename(path);
            path = path_.posix.dirname(path);
            params.path = path;
            const res = await this.upload('write', name, mime, bin, params);
            return res.data;
        }
        this.stat = async (path, params) => {
            path = p(path);
            const res = await this.post('stat', { ...params, path });
            return res.data;
        }
        this.stat_uuid = async (uuid, params) => {
            // for stat(uuid) api:
            // - use "uid" for "uuid"
            // - there have to be a "subject" field which is the same as "uid"
            const res = await this.post('stat', { ...params, uid: uuid, subject: uuid });
            return res.data;
        }
        this.statu = async (uid, params) => {
            const res = await this.post('stat', { ...params, uid });
            return res.data;
        }
        this.readdir = async (path, params) => {
            path = p(path);
            const res = await this.post('readdir', {
                ...params,
                path
            })
            return res.data;
        }
        this.delete = async (path, params) => {
            path = p(path);
            const res = await this.post('delete', {
                ...params,
                paths: [path]
            });
            return res.data;
        }
        this.move = async (src, dst, params = {}) => {
            src = p(src);
            dst = p(dst);
            const destination = path_.dirname(dst);
            const source = src;
            const new_name = path_.basename(dst);
            console.log('move', { destination, source, new_name });
            const res = await this.post('move', {
                ...params,
                destination,
                source,
                new_name,
            });
            return res.data;
        }
    }

    getURL (...path) {
        const apiURL = new url.URL(this.conf.api_url);
        apiURL.pathname = path_.posix.join(
            apiURL.pathname,
            ...path
        );
        return apiURL.href;
    };

    // === HTTP methods ===

    get (ep, params) {
        return axios.request({
            httpsAgent: this.httpsAgent,
            method: 'get',
            url: this.getURL(ep),
            params,
            headers: {
                ...this.headers_
            }
        });
    }

    post (ep, params) {
        return axios.request({
            httpsAgent: this.httpsAgent,
            method: 'post',
            url: this.getURL(ep),
            data: params,
            headers: {
                ...this.headers_,
                'Content-Type': 'application/json',
            }
        })
    }

    upload (ep, name, mime, bin, params) {
        const adapt_file = (bin, mime) => {
            if ( typeof bin === 'string' ) {
                return new Blob([bin], { type: mime });
            }
            return bin;
        };
        const fd = new FormData();
        for ( const k in params ) fd.append(k, params[k]);
        const blob = adapt_file(bin, mime);
        fd.append('size', blob.size);
        fd.append('file', adapt_file(bin, mime), name)
        return axios.request({
            httpsAgent: this.httpsAgent,
            method: 'post',
            url: this.getURL(ep),
            data: fd,
            headers: {
                ...this.headers_,
                'Content-Type': 'multipart/form-data'
            },
        });
    }

    async batch (ep, ops, bins) {
        const adapt_file = (bin, mime) => {
            if ( typeof bin === 'string' ) {
                return new Blob([bin], { type: mime });
            }
            return bin;
        };
        const fd = new FormData();

        fd.append('original_client_socket_id', '');
        fd.append('socket_id', '');
        fd.append('operation_id', '');

        let fileI = 0;
        for ( let i=0 ; i < ops.length ; i++ ) {
            const op = ops[i];

            fd.append('operation', JSON.stringify(op));
        }

        const files = [];

        for ( let i=0 ; i < ops.length ; i++ ) {
            const op = ops[i];

            if ( op.op === 'mkdir' ) continue;
            if ( op.op === 'mktree' ) continue;

            let mime = op.mime ?? 'text/plain';
            const file = adapt_file(bins[fileI++], mime);
            fd.append('fileinfo', JSON.stringify({
                size: file.size,
                name: op.name,
                mime,
            }));
            files.push({
                op, file,
            })

            delete op.name;
        }

        for ( const file of files ) {
            const { op, file: blob } = file;
            fd.append('file', blob, op.name);
        }

        const res = await axios.request({
            httpsAgent: this.httpsAgent,
            method: 'post',
            url: this.getURL(ep),
            data: fd,
            headers: {
                ...this.headers_,
                'Content-Type': 'multipart/form-data'
            },
        });
        return res.data.results;
    }

    batch_json (ep, ops, bins) {
        return axios.request({
            httpsAgent: this.httpsAgent,
            method: 'post',
            url: this.getURL(ep),
            data: ops,
            headers: {
                ...this.headers_,
                'Content-Type': 'application/json',
            },
        });
    }
}