Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions test-app/app/src/main/assets/app/mainpage.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ require("./tests/testWorkerTerminateAfterClose");
require("./tests/testWorkerOptions");
require("./tests/testWorkerResourceLimits");
require("./tests/testWorkerNestedConsole");
require("./tests/testWorkerConcurrentStartup");
require("./tests/testMessaging");
require("./tests/testInterfaceDefaultMethods");
require("./tests/testInterfaceDefaultMethodOverrides");
Expand Down
1 change: 1 addition & 0 deletions test-app/app/src/main/assets/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"main": "boot.js",
"android": {
"v8Flags": "--expose_gc",
"codeCache": true,
"profilerOutputDir": "",
"gcThrottleTime": 500,
"memoryCheckInterval": 10,
Expand Down
608 changes: 608 additions & 0 deletions test-app/app/src/main/assets/app/tests/concurrentStartup/modA.js

Large diffs are not rendered by default.

608 changes: 608 additions & 0 deletions test-app/app/src/main/assets/app/tests/concurrentStartup/modB.js

Large diffs are not rendered by default.

608 changes: 608 additions & 0 deletions test-app/app/src/main/assets/app/tests/concurrentStartup/modC.js

Large diffs are not rendered by default.

608 changes: 608 additions & 0 deletions test-app/app/src/main/assets/app/tests/concurrentStartup/modD.js

Large diffs are not rendered by default.

608 changes: 608 additions & 0 deletions test-app/app/src/main/assets/app/tests/concurrentStartup/modE.js

Large diffs are not rendered by default.

608 changes: 608 additions & 0 deletions test-app/app/src/main/assets/app/tests/concurrentStartup/modF.js

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Entry for testWorkerConcurrentStartup: reports the fixture values it
// observed, keyed by module name. Each entry loads the modules in a
// different order, so workers starting together hit different files at once.
var values = {};
values.modA = require("./modA").value;
values.modB = require("./modB").value;
values.modC = require("./modC").value;
values.modD = require("./modD").value;
values.modE = require("./modE").value;
values.modF = require("./modF").value;

postMessage({ values: values });
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Entry for testWorkerConcurrentStartup: reports the fixture values it
// observed, keyed by module name. Each entry loads the modules in a
// different order, so workers starting together hit different files at once.
var values = {};
values.modB = require("./modB").value;
values.modC = require("./modC").value;
values.modD = require("./modD").value;
values.modE = require("./modE").value;
values.modF = require("./modF").value;
values.modA = require("./modA").value;

postMessage({ values: values });
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Entry for testWorkerConcurrentStartup: reports the fixture values it
// observed, keyed by module name. Each entry loads the modules in a
// different order, so workers starting together hit different files at once.
var values = {};
values.modC = require("./modC").value;
values.modD = require("./modD").value;
values.modE = require("./modE").value;
values.modF = require("./modF").value;
values.modA = require("./modA").value;
values.modB = require("./modB").value;

postMessage({ values: values });
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Entry for testWorkerConcurrentStartup: reports the fixture values it
// observed, keyed by module name. Each entry loads the modules in a
// different order, so workers starting together hit different files at once.
var values = {};
values.modD = require("./modD").value;
values.modE = require("./modE").value;
values.modF = require("./modF").value;
values.modA = require("./modA").value;
values.modB = require("./modB").value;
values.modC = require("./modC").value;

postMessage({ values: values });
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Entry for testWorkerConcurrentStartup: reports the fixture values it
// observed, keyed by module name. Each entry loads the modules in a
// different order, so workers starting together hit different files at once.
var values = {};
values.modE = require("./modE").value;
values.modF = require("./modF").value;
values.modA = require("./modA").value;
values.modB = require("./modB").value;
values.modC = require("./modC").value;
values.modD = require("./modD").value;

postMessage({ values: values });
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Entry for testWorkerConcurrentStartup: reports the fixture values it
// observed, keyed by module name. Each entry loads the modules in a
// different order, so workers starting together hit different files at once.
var values = {};
values.modF = require("./modF").value;
values.modA = require("./modA").value;
values.modB = require("./modB").value;
values.modC = require("./modC").value;
values.modD = require("./modD").value;
values.modE = require("./modE").value;

postMessage({ values: values });
112 changes: 112 additions & 0 deletions test-app/app/src/main/assets/app/tests/testWorkerConcurrentStartup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
// Needs "codeCache": true in the app's package.json; without it no runtime
// reads or writes the caches these specs race on.
describe("Script code caches with workers starting together", function () {
var moduleNames = ["modA", "modB", "modC", "modD", "modE", "modF"];
var entryCount = 6;
var batchSize = entryCount * 2;
var fixtureDir = __dirname + "/concurrentStartup";

var expected = {};
moduleNames.forEach(function (name) {
expected[name] = require("./concurrentStartup/" + name).value;
});

var cacheFile = function (name) {
return new java.io.File(fixtureDir, name + ".js.cache");
};

var dropCaches = function () {
moduleNames.forEach(function (name) {
cacheFile(name).delete();
});
};

// Resolves with every worker's reported values once all of them have
// reported. A worker error terminates the whole batch and rejects only
// once every worker's thread has ended (`nsworkerended`), so no worker from
// a failed batch is still writing caches when the next spec drops them.
var runBatch = function () {
return new Promise(function (resolve, reject) {
var reports = [];
var workers = [];
var ended = 0;
var failure = null;
var rejectOnceAllEnded = function () {
if (failure !== null && ended === workers.length) {
reject(failure);
}
};
for (var i = 0; i < batchSize; i++) {
(function (entry) {
var worker = new Worker("./concurrentStartup/worker" + entry + ".js");
workers.push(worker);
worker.addEventListener("nsworkerended", function () {
ended++;
rejectOnceAllEnded();
});
worker.onmessage = function (msg) {
worker.terminate();
if (failure !== null) {
return;
}
reports.push({ entry: entry, values: msg.data.values });
if (reports.length === batchSize) {
resolve(reports);
}
};
worker.onerror = function (e) {
if (failure !== null) {
return;
}
failure = new Error("worker" + entry + ": " + (e && e.message ? e.message : e));
workers.forEach(function (w) {
w.terminate();
});
Comment thread
edusperoni marked this conversation as resolved.
Resolved
rejectOnceAllEnded();
};
})(i % entryCount);
}
});
};

var expectValues = function (reports) {
expect(reports.length).toBe(batchSize);
reports.forEach(function (report) {
expect({ entry: report.entry, values: report.values })
.toEqual({ entry: report.entry, values: expected });
});
};

// A cold batch has some workers compiling and publishing a module's cache
// while others, further along their rotated load order, already consume
// it. Several rounds widen the chance of a reader overlapping a writer.
it("loads correct modules while caches are written and read concurrently", async function () {
for (var round = 0; round < 4; round++) {
dropCaches();
expectValues(await runBatch());
}
expectValues(await runBatch());
}, 120000);

it("publishes caches stamped with their source's mtime and leaves no temporaries", async function () {
dropCaches();
expectValues(await runBatch());

moduleNames.forEach(function (name) {
var cache = cacheFile(name);
var source = new java.io.File(fixtureDir, name + ".js");
expect(name + ": " + cache.exists()).toBe(name + ": true");
expect(Math.floor(cache.lastModified() / 1000))
.toBe(Math.floor(source.lastModified() / 1000));
});

var names = new java.io.File(fixtureDir).list();
var leftovers = [];
for (var i = 0; i < names.length; i++) {
if (String(names[i]).indexOf(".cache.") !== -1) {
leftovers.push(String(names[i]));
}
}
expect(leftovers).toEqual([]);
}, 60000);
});
65 changes: 55 additions & 10 deletions test-app/runtime/src/main/cpp/File.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,14 @@

#include "File.h"
#include "NativeScriptAssert.h"
#include <cerrno>
#include <climits>
#include <cstdlib>
#include <sstream>
#include <fstream>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>

using namespace std;

Expand Down Expand Up @@ -65,28 +70,68 @@ void* File::ReadBinary(const string& filePath, int& length) {
}

fseek(file, 0, SEEK_END);
length = ftell(file);
auto size = ftell(file);
if (size < 0 || size > INT_MAX) {
fclose(file);
return nullptr;
}
rewind(file);

uint8_t* data = new uint8_t[length];
fread(data, sizeof(uint8_t), length, file);
// A file truncated after the size was taken reads short. Callers hand the
// buffer to consumers that trust its length (V8 does not checksum code
// caches in release builds), so it is all of the file or nothing.
uint8_t* data = new uint8_t[size];
auto bytesRead = fread(data, sizeof(uint8_t), size, file);
fclose(file);
if (bytesRead != static_cast<size_t>(size)) {
delete[] data;
return nullptr;
}

length = static_cast<int>(size);
return data;
}

bool File::WriteBinary(const string& filePath, const void* data, int length) {
auto file = fopen(filePath.c_str(), WRITE_BINARY);
if (!file) {
bool File::WriteBinary(const string& filePath, const void* data, int length, time_t modificationTime) {
// Exclusive creation in the target's directory, so concurrent writers of
// the same path never share a temporary and rename stays on one file system.
string tempPath(filePath);
tempPath.append(".ns-XXXXXX");
int fd = mkstemp(tempPath.data());
if (fd < 0) {
return false;
}

auto writtenBytes = fwrite(data, sizeof(uint8_t), length, file);
fclose(file);
bool ok = length >= 0;
auto cursor = static_cast<const uint8_t*>(data);
size_t remaining = ok ? static_cast<size_t>(length) : 0;
while (ok && remaining > 0) {
ssize_t written = write(fd, cursor, remaining);
if (written < 0) {
ok = errno == EINTR;
continue;
}
cursor += written;
remaining -= static_cast<size_t>(written);
}

if (ok && modificationTime >= 0) {
struct timespec times[2];
times[0].tv_sec = 0;
times[0].tv_nsec = UTIME_NOW;
times[1].tv_sec = modificationTime;
times[1].tv_nsec = 0;
ok = futimens(fd, times) == 0;
}

ok = (close(fd) == 0) && ok;
ok = ok && rename(tempPath.c_str(), filePath.c_str()) == 0;
if (!ok) {
unlink(tempPath.c_str());
}

return writtenBytes == length;
return ok;
}

const char* File::WRITE_BINARY = "wb";
const char* File::READ_BINARY = "rb";
}
14 changes: 12 additions & 2 deletions test-app/runtime/src/main/cpp/File.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#ifndef JNI_FILE_H_
#define JNI_FILE_H_

#include <ctime>
#include <string>

namespace tns {
Expand All @@ -19,10 +20,19 @@ class File {
* genuinely empty — the plain overload renders both as "".
*/
static std::string ReadText(const std::string& filePath, bool& ok);
static bool WriteBinary(const std::string& filePath, const void* inData, int length);
/*
* Replaces the file atomically: readers of `filePath` see the previous
* file or the complete new one, never a partial write. A non-negative
* `modificationTime` becomes the file's mtime before it is published.
*/
static bool WriteBinary(const std::string& filePath, const void* inData, int length,
time_t modificationTime = -1);
/*
* The whole file in a buffer the caller frees with delete[], or
* nullptr (length 0) when it cannot be read in full.
*/
static void* ReadBinary(const std::string& filePath, int& length);
private:
static const char* WRITE_BINARY;
static const char* READ_BINARY;
};
}
Expand Down
20 changes: 8 additions & 12 deletions test-app/runtime/src/main/cpp/ModuleInternal.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
#include <dlfcn.h>
#include <sys/stat.h>
#include <time.h>
#include <utime.h>
#include <unistd.h>
#include <chrono>
#include <cmath>
Expand Down Expand Up @@ -1671,20 +1670,17 @@ void ModuleInternal::SaveScriptCache(const ScriptCompiler::CachedData* cache,

tns::instrumentation::Frame frame("SaveScriptCache");

int length = cache->length;
auto cachePath = path + (kind == ScriptCacheKind::Module ? ".mcache" : ".cache");
File::WriteBinary(cachePath, cache->data, length);
delete cache;
// make sure cache and js file have the same modification date
// TryLoadScriptCache only accepts a cache carrying its source's mtime, so
// the stamp is published together with the contents.
time_t sourceModifiedTime = -1;
struct stat result;
struct utimbuf new_times;
new_times.actime = time(nullptr);
new_times.modtime = time(nullptr);
if (stat(path.c_str(), &result) == 0) {
auto jsLastModifiedTime = result.st_mtime;
new_times.modtime = jsLastModifiedTime;
sourceModifiedTime = result.st_mtime;
}
utime(cachePath.c_str(), &new_times);

auto cachePath = path + (kind == ScriptCacheKind::Module ? ".mcache" : ".cache");
File::WriteBinary(cachePath, cache->data, cache->length, sourceModifiedTime);
delete cache;
}

void ModuleInternal::SaveScriptCache(const Local<Script> script, const std::string& path) {
Expand Down