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
2 changes: 1 addition & 1 deletion opal.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "mistwarp-api",
"version": "2.1.0",
"version": "2.2.0",
"main": "main.osl",
"scripts": {
"dev": ["osl", "run", "main.osl"],
Expand Down
40 changes: 7 additions & 33 deletions src/admin/admin.osl
Original file line number Diff line number Diff line change
Expand Up @@ -572,14 +572,9 @@ def handleAdminStats(*serve.Context c) (
object loadsByDay = {}
object startsByDay = {}
object crashesByDay = {}
object loadTimeTotalsByDay = {}
object loadSamplesByDay = {}
object averageLoadMsByDay = {}
number totalLoads = 0
number totalStarts = 0
number totalCrashes = 0
number loadTimeTotal = 0
number loadTimeSamples = 0
number desktopLoads = 0
number touchLoads = 0
number otherLoads = 0
Expand All @@ -601,21 +596,6 @@ def handleAdminStats(*serve.Context c) (
) else (
otherLoads += 1
)
if diagnostic.loadMs.toNum() > 0 (
number loadMs = diagnostic.loadMs.toNum()
loadTimeTotal += loadMs
loadTimeSamples += 1
number previousLoadTime = 0
number previousSamples = 0
if loadTimeTotalsByDay.contains(diagnosticDay) (
previousLoadTime = loadTimeTotalsByDay[diagnosticDay].toNum()
)
if loadSamplesByDay.contains(diagnosticDay) (
previousSamples = loadSamplesByDay[diagnosticDay].toNum()
)
loadTimeTotalsByDay[diagnosticDay] = previousLoadTime + loadMs
loadSamplesByDay[diagnosticDay] = previousSamples + 1
)
) else if kind == "start" (
totalStarts += 1
number previousStarts = 0
Expand All @@ -632,15 +612,7 @@ def handleAdminStats(*serve.Context c) (
crashesByDay[diagnosticDay] = previousCrashes + 1
)
)
array loadDays = loadSamplesByDay.getKeys()
for i loadDays.len (
string loadDay = loadDays[i].toStr()
averageLoadMsByDay[loadDay] = loadTimeTotalsByDay[loadDay].toNum() / loadSamplesByDay[loadDay].toNum()
)
number averageLoadMs = 0
if loadTimeSamples > 0 (
averageLoadMs = loadTimeTotal / loadTimeSamples
)
object loadTimes = summarizeLoadTimes(diagnostics)
number totalPlaytimeMs = 0
array playtime = playtimeDocs.all()
for i playtime.len (
Expand Down Expand Up @@ -683,8 +655,9 @@ def handleAdminStats(*serve.Context c) (
totalLoads: totalLoads,
totalStarts: totalStarts,
totalCrashes: totalCrashes,
averageLoadMs: averageLoadMs,
loadTimeSamples: loadTimeSamples,
averageLoadMs: loadTimes.averageMs,
p95LoadMs: loadTimes.p95Ms,
loadTimeSamples: loadTimes.samples,
loadsByDevice: {desktop: desktopLoads, touch: touchLoads, other: otherLoads},
projectsByDay: projectsByDay,
projectUpdatesByDay: projectUpdatesByDay,
Expand All @@ -693,8 +666,9 @@ def handleAdminStats(*serve.Context c) (
loadsByDay: loadsByDay,
startsByDay: startsByDay,
crashesByDay: crashesByDay,
averageLoadMsByDay: averageLoadMsByDay,
loadSamplesByDay: loadSamplesByDay,
averageLoadMsByDay: loadTimes.averageMsByDay,
p95LoadMsByDay: loadTimes.p95MsByDay,
loadSamplesByDay: loadTimes.samplesByDay,
eventsByDay: funnelEventsByDay(since)
})
)
Expand Down
47 changes: 47 additions & 0 deletions src/community/load-times.osl
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
export {
summarizeLoadTimes
}

def summarizeLoadTimes(array diagnostics) object (
number[] values = []
number total = 0
object valuesByDay = {}
object totalsByDay = {}
for i diagnostics.len (
object diagnostic = diagnostics[i].assert(object)
number loadMs = (diagnostic.loadMs ?? 0).toNum()
if diagnostic.type.toStr() == "load" and loadMs > 0 (
string day = ((diagnostic.created ?? 0).toNum() / 86400000).toInt().toStr()
values.append(loadMs)
total += loadMs
number[] dayValues = []
number dayTotal = 0
if valuesByDay.contains(day) (
dayValues = valuesByDay[day].assert(number[])
dayTotal = totalsByDay[day].toNum()
)
dayValues.append(loadMs)
valuesByDay[day] = dayValues
totalsByDay[day] = dayTotal + loadMs
)
)
object samplesByDay = {}
object averageMsByDay = {}
object p95MsByDay = {}
array days = valuesByDay.getKeys()
for i days.len (
string day = days[i].toStr()
number[] dayValues = valuesByDay[day].assert(number[])
samplesByDay[day] = dayValues.len
averageMsByDay[day] = totalsByDay[day].toNum() / dayValues.len
p95MsByDay[day] = percentileOf(dayValues, 0.95)
)
return {
samples: values.len,
averageMs: if values.len > 0 then total / values.len else 0,
p95Ms: percentileOf(values, 0.95),
samplesByDay: samplesByDay,
averageMsByDay: averageMsByDay,
p95MsByDay: p95MsByDay
}
)
34 changes: 34 additions & 0 deletions src/community/load-times.test.osl
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import "std:testing"
import "std:crypto"
import "std:regex"
import "std:fs"
import "go:mistwarp.local/storagefs"
import "../core/utils.osl"
import "./load-times.osl"

number dayOne = 20000 * 86400000
number dayTwo = 20001 * 86400000

array diagnostics = [
{type: "load", loadMs: 600000, created: dayOne + 10},
{type: "load", loadMs: 2000, created: dayOne + 20},
{type: "load", loadMs: 3000, created: dayOne + 30},
{type: "load", loadMs: 0, created: dayOne + 40},
{type: "start", loadMs: 0, created: dayOne + 50},
{type: "load", loadMs: 4000, created: dayTwo + 10},
{type: "crash", created: dayTwo + 20}
]
object summary = summarizeLoadTimes(diagnostics)

testing.assert(summary.samples == 4, "only loads with a duration are timed samples")
testing.assert(summary.averageMs == 152250, "the average still includes the slow load")
testing.assert(summary.p95Ms == 600000, "with four samples the 95th percentile is the slowest")
testing.assert(summary.samplesByDay["20000"] == 3, "samples are grouped by UTC day")
testing.assert(summary.samplesByDay["20001"] == 1, "each day keeps its own samples")
testing.assert(summary.p95MsByDay["20000"] == 600000, "a day's 95th percentile uses that day's samples")
testing.assert(summary.p95MsByDay["20001"] == 4000, "a day with one sample reports that sample")
testing.assert(summary.averageMsByDay["20001"] == 4000, "per-day averages are kept for older clients")

object empty = summarizeLoadTimes([])
testing.assert(empty.samples == 0 and empty.averageMs == 0 and empty.p95Ms == 0, "no samples gives zeros")
testing.assert(empty.p95MsByDay.assert(object).getKeys().len == 0, "no samples gives no days")
13 changes: 2 additions & 11 deletions src/community/playtime-diagnostics.osl
Original file line number Diff line number Diff line change
Expand Up @@ -172,20 +172,11 @@ def handleGetDiagnostics(*serve.Context c) (
)
array items = diagnosticDocs.where("projectId", "==", c.param("id")).sort("created", "desc").limit(500).all()
object counts = {load: 0, start: 0, crash: 0, exit: 0}
number totalLoadMs = 0
number loadSamples = 0
for i items.len (
object item = items[i].assert(object)
string kind = item.type.toStr()
counts[kind] = counts[kind].toNum() + 1
if item.loadMs.toNum() > 0 (
totalLoadMs += item.loadMs.toNum()
loadSamples += 1
)
)
number averageLoadMs = 0
if loadSamples > 0 (
averageLoadMs = totalLoadMs / loadSamples
)
c.json(200, {ok: true, counts: counts, averageLoadMs: averageLoadMs, recent: paginate(items, 0, 50)})
object loadTimes = summarizeLoadTimes(items)
c.json(200, {ok: true, counts: counts, averageLoadMs: loadTimes.averageMs, p95LoadMs: loadTimes.p95Ms, loadSamples: loadTimes.samples, recent: paginate(items, 0, 50)})
)
10 changes: 10 additions & 0 deletions src/core/utils.osl
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export {
normalizeTag,
normalizeUsername,
paginate,
percentileOf,
randomString
}

Expand Down Expand Up @@ -69,6 +70,15 @@ def clampNumber(number value, number min, number max) number (
return value
)

def percentileOf(number[] values, number fraction) number (
if values.len == 0 (
return 0
)
number[] sorted = values.clone().sort()
number rank = clampNumber(((fraction * sorted.len) - 0.000001).ceiling(), 1, sorted.len)
return sorted[rank]
)

def paginate(array items, number offset, number limit) array (
array page = []
number count = 0
Expand Down
8 changes: 8 additions & 0 deletions src/core/utils.test.osl
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,11 @@ testing.assert(!isSafePathPart("."), "current-directory path part is unsafe")
testing.assert(!isSafePathPart(".."), "parent-directory path part is unsafe")
testing.assert(!isSafePathPart("../outside"), "forward-slash traversal is unsafe")
testing.assert(!isSafePathPart("..\\outside"), "backslash traversal is unsafe")

testing.assert(percentileOf([], 0.95) == 0, "an empty sample has a zero percentile")
testing.assert(percentileOf([4200], 0.95) == 4200, "one sample is its own percentile")
number[] loadSamples = [600000, 1000, 3000, 2000, 5000, 4000, 7000, 6000, 9000, 8000, 11000, 10000, 13000, 12000, 15000, 14000, 17000, 16000, 19000, 18000]
testing.assert(percentileOf(loadSamples, 0.95) == 19000, "the 95th percentile of twenty samples is the nineteenth smallest")
testing.assert(percentileOf(loadSamples, 0.5) == 10000, "the median of twenty samples is the tenth smallest")
testing.assert(percentileOf(loadSamples, 1) == 600000, "the 100th percentile is the largest sample")
testing.assert(loadSamples[1] == 600000, "the percentile leaves the caller's order alone")
3 changes: 2 additions & 1 deletion src/projects/project-remix.osl
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,8 @@ def finishRemix(*serve.Context c, ForkOutcome outcome) (
ok: true,
id: project.id,
projectJsonUrl: projectJsonUrlFor(project),
assetsBase: assetsBaseUrl()
assetsBase: assetsBaseUrl(),
assetsMirrorBase: assetsMirrorBaseUrl()
})
)

Expand Down
3 changes: 3 additions & 0 deletions src/projects/project-remix.test.osl
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,9 @@ def projectJsonUrlFor(object project) string (
def assetsBaseUrl() string (
return ""
)
def assetsMirrorBaseUrl() string (
return ""
)
def storageDetails(string username) object (
return {remaining: 0}
)
Expand Down
1 change: 1 addition & 0 deletions src/projects/project-response.osl
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ def projectResponse(object project,*serve.Context c) object (
repo: project.repo,
projectJsonUrl: jsonUrl,
assetsBase: assetsBaseUrl(),
assetsMirrorBase: assetsMirrorBaseUrl(),
thumbUrl: viewerThumbUrlFor(project),
cardUrl: appURL ++ "/v1/projects/" ++ project.id.toStr() ++ "/card.svg",
created: project.created,
Expand Down
22 changes: 21 additions & 1 deletion src/storage/asset-routing.osl
Original file line number Diff line number Diff line change
@@ -1,7 +1,27 @@
export {
assetNeedsUpload
assetNeedsUpload,
assetsMirrorBaseFor,
cacheControlForObjectKey,
remoteAssetRedirectCacheControl
}

string immutableAssetCacheControl = "public, max-age=31536000, immutable"
string remoteAssetRedirectCacheControl = "private, max-age=86400"

def assetsMirrorBaseFor(boolean localOnly, string r2PublicBase) string (
if localOnly or r2PublicBase == "" (
return ""
)
return r2PublicBase ++ "/assets"
)

def cacheControlForObjectKey(string key) string (
if regex.match("^assets/[a-f0-9]{32}\\.[a-z0-9]+$", key) (
return immutableAssetCacheControl
)
return ""
)

def assetUrlForLocation(string name, boolean localExists, string localAssetsBase, string r2PublicBase) string (
if localExists or r2PublicBase == "" (
return localAssetsBase ++ "/" ++ name
Expand Down
10 changes: 10 additions & 0 deletions src/storage/asset-routing.test.osl
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import "std:testing"
import "std:fs"
import "std:regex"
import "./asset-routing.osl"

testing.assert(
Expand Down Expand Up @@ -31,3 +32,12 @@ testing.assert(
assetNeedsUpload(true, true, true),
"uploads an indexed local asset when remote storage is configured"
)

testing.assert(assetsMirrorBaseFor(false, "https://mwassets.mistium.com") == "https://mwassets.mistium.com/assets", "offers the R2 asset folder as a mirror")
testing.assert(assetsMirrorBaseFor(true, "https://mwassets.mistium.com") == "", "offers no mirror when storage is local")
testing.assert(assetsMirrorBaseFor(false, "") == "", "offers no mirror without a public R2 origin")
testing.assert(cacheControlForObjectKey("assets/0123456789abcdef0123456789abcdef.png") == "public, max-age=31536000, immutable", "content-addressed assets are cached for a year")
testing.assert(cacheControlForObjectKey("project-json/0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef.json.gz") == "", "project files keep the API's own caching rules")
testing.assert(cacheControlForObjectKey("projects/p1/project.json") == "", "mutable project files are not cached as immutable")
testing.assert(cacheControlForObjectKey("assets/../secret.png") == "", "odd asset keys are not cached as immutable")
testing.assert(remoteAssetRedirectCacheControl.startsWith("private,"), "only browsers cache the R2 redirect, so a CDN cannot pin a stale route")
9 changes: 7 additions & 2 deletions src/storage/r2.osl
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export {
assetObjectKey,
assetsBaseUrl,
assetsMirrorBaseUrl,
contentTypeForExt,
copyProjectWorkspaceToPath,
copyStorageKeyToPath,
Expand Down Expand Up @@ -267,6 +268,10 @@ def assetsBaseUrl() string (
return blobBase() ++ "/assets"
)

def assetsMirrorBaseUrl() string (
return assetsMirrorBaseFor(r2Local, r2PublicBase)
)

def contentTypeForExt(string ext) string (
object types = {
"json": "application/json",
Expand Down Expand Up @@ -341,7 +346,7 @@ def r2PutEncoded(string key, BlobBody body, string contentType, string contentEn
return fs.writeFileBytes(path, body)
)
string uploadType = if contentType == "" then "application/octet-stream" else contentType
boolean stored = key != "" and r2Client.upload(key, body, {contentType: uploadType, contentEncoding: contentEncoding})
boolean stored = key != "" and r2Client.upload(key, body, {contentType: uploadType, contentEncoding: contentEncoding, cacheControl: cacheControlForObjectKey(key)})
if stored (
recordR2Stored({key: key, type: r2ObjectType(key), size: body.len})
)
Expand Down Expand Up @@ -639,7 +644,7 @@ def handleGetAssetBlob(*serve.Context c) (
string assetUrl = assetUrlForLocation(name, fs.exists(localBlobPath(key)), blobBase() ++ "/assets", remoteBase)
if assetUrl != localUrl (
c.setHeader("Location", assetUrl)
c.setHeader("Cache-Control", "no-cache")
c.setHeader("Cache-Control", remoteAssetRedirectCacheControl)
c.status(307)
return
)
Expand Down
Loading