Skip to content
Open
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 .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ jobs:

- name: Install OSL
env:
OSL_COMMIT: aeb83e39b3f5638e4a366c4d9c6fa881f630e72c
OSL_COMMIT: f5e02b2e086ac7f7fb1d42a8215de47314660c73
run: |
mkdir -p "$HOME/.local/bin"
git clone --filter=blob:none https://git.rotur.dev/osl/.go /tmp/osl-source
Expand Down
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# AGENTS.md

mistwarp-api is the OSL backend behind https://api.mistwarp.org/v1, for the MistWarp community site and editor (scratch-gui). It needs OSL 6.1. Community data is in SQLite (`data/community.db`), other state is JSON under `data/`, and project files are in Cloudflare R2.
mistwarp-api is the OSL backend behind https://api.mistwarp.org/v1, for the MistWarp community site and editor (scratch-gui). It needs OSL 24.0.1. Community data is in SQLite (`data/community.db`), other state is JSON under `data/`, and project files are in Cloudflare R2.

## Where code goes

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ It runs at `https://api.mistwarp.org/v1`. The editor and community site are [scr

## Getting started

You need OSL 6.1.
You need OSL 24.0.1.

```sh
cp .env.example .env
Expand Down
5 changes: 3 additions & 2 deletions main.osl
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ import "./src/community"
import "./src/admin"
import "./src/classroom"

*ws.Server gameRealtimeSocket = ws.New()
*ws.Server siteRealtimeSocket = ws.New()

ensureDirectories()
string thumbnailSecret = loadThumbnailSecret(thumbnailSecretFile)
void initCommunityDatabase() catch (err) (
Expand Down Expand Up @@ -120,8 +123,6 @@ thread.new(developmentFeedLoop)
thread.new(vanityLapseLoop)

*serve.Router app = serve.new()
*ws.Server gameRealtimeSocket = ws.New()
*ws.Server siteRealtimeSocket = ws.New()

app.bodyLimit(maxAppRequestBytes)
app.use(realtimeUpgradeGuard)
Expand Down
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": "1.7.0",
"version": "1.7.1",
"main": "main.osl",
"scripts": {
"dev": ["osl", "run", "main.osl"],
Expand Down
2 changes: 1 addition & 1 deletion src/admin/admin-users.osl
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def unindexComment(string key, string cid) (

def migrateCommentIndex() boolean (
string migrationId = "migration:comment-index-v1"
if (diagnosticDocs.findById(migrationId) ?? {}).len > 0 (
if (diagnosticDocs.findById(migrationId).unwrap() ?? {}).len > 0 (
return true
)
array files = fs.readDir(commentsDir).unwrapOr([])
Expand Down
4 changes: 2 additions & 2 deletions src/admin/errors.osl
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,7 @@ def handleAdminResolveSiteError(*serve.Context c) (
def resolveSiteErrorLocked(*serve.Context c, string id, boolean resolved) object (
sync.lock("site-errors")
defer sync.unlock("site-errors")
object entry = (errorDocs.findById(id) ?? {})
object entry = (errorDocs.findById(id).unwrap() ?? {})
if entry.len == 0 (
c.notFound("error not found")
return {found: false}
Expand Down Expand Up @@ -369,7 +369,7 @@ def handleAdminDeleteSiteError(*serve.Context c) (
c.badRequest("error id is required")
return
)
if (errorDocs.findById(id) ?? {}).len == 0 (
if (errorDocs.findById(id).unwrap() ?? {}).len == 0 (
c.notFound("error not found")
return
)
Expand Down
18 changes: 9 additions & 9 deletions src/admin/errors.test.osl
Original file line number Diff line number Diff line change
Expand Up @@ -76,15 +76,15 @@ testing.assert(scrubbed.resolved == true and scrubbed.kind == "react" and scrubb

errorDocs.insertOne({_id: "legacy", message: "m", url: "https://mistwarp.org/users/mist", username: "mist", userAgent: "x", projectId: "p1", created: timestamp, resolved: false})
pruneSiteErrors()
object legacy = errorDocs.findById("legacy") ?? {}
object legacy = errorDocs.findById("legacy").unwrap() ?? {}
testing.assert(legacy.len > 0 and !legacy.contains("username") and legacy.url == "https://mistwarp.org/users/:id", "the sweep scrubs reports stored before this change")
void deleteAllSiteErrors()

for i 250 (
errorDocs.insertOne({_id: "e" ++ i.toStr(), resolved: i % 2 == 0, created: i})
)
testing.assert(deleteAllSiteErrors() == 250, "deletes beyond the 200-entry response limit")
testing.assert(errorDocs.count({}) == 0, "deletes both open and resolved errors")
testing.assert(errorDocs.count({}).unwrap() == 0, "deletes both open and resolved errors")
testing.assert(deleteAllSiteErrors() == 0, "deleting an empty collection succeeds")
testing.assert(siteErrorCutoff(100 * 86400000) == 93 * 86400000, "reports are kept for 7 days")

Expand All @@ -93,20 +93,20 @@ errorDocs.insertOne({_id: "old", resolved: false, created: now - (8 * 86400000)}
errorDocs.insertOne({_id: "edge", resolved: true, created: now - (6 * 86400000)})
errorDocs.insertOne({_id: "new", resolved: false, created: now})
sweepSiteErrors()
testing.assert((errorDocs.findById("old") ?? {}).len == 0, "the sweep deletes reports older than 7 days, resolved or not")
testing.assert((errorDocs.findById("edge") ?? {}).len > 0, "the sweep keeps reports younger than 7 days")
testing.assert((errorDocs.findById("new") ?? {}).len > 0, "the sweep keeps new reports")
testing.assert((errorDocs.findById("old").unwrap() ?? {}).len == 0, "the sweep deletes reports older than 7 days, resolved or not")
testing.assert((errorDocs.findById("edge").unwrap() ?? {}).len > 0, "the sweep keeps reports younger than 7 days")
testing.assert((errorDocs.findById("new").unwrap() ?? {}).len > 0, "the sweep keeps new reports")
testing.assert(deleteAllSiteErrors() == 2, "only the expired report was swept")

for i 1005 (
errorDocs.insertOne({_id: "c" ++ i.toStr(), resolved: false, created: (now - 1005) + i})
)
errorDocs.insertOne({_id: "stale", resolved: false, created: now - (200 * 86400000)})
pruneSiteErrors()
testing.assert(errorDocs.count({}) == 1000, "pruning keeps the newest 1000 reports")
testing.assert((errorDocs.findById("stale") ?? {}).len == 0, "pruning drops expired reports too")
testing.assert((errorDocs.findById("c1") ?? {}).len == 0, "pruning drops the oldest reports beyond the cap")
testing.assert((errorDocs.findById("c1005") ?? {}).len > 0, "pruning keeps the newest report")
testing.assert(errorDocs.count({}).unwrap() == 1000, "pruning keeps the newest 1000 reports")
testing.assert((errorDocs.findById("stale").unwrap() ?? {}).len == 0, "pruning drops expired reports too")
testing.assert((errorDocs.findById("c1").unwrap() ?? {}).len == 0, "pruning drops the oldest reports beyond the cap")
testing.assert((errorDocs.findById("c1005").unwrap() ?? {}).len > 0, "pruning keeps the newest report")
void deleteAllSiteErrors()
testing.assert(sweepSiteErrors(), "a sweep that works reports success")
testDb.close()
Expand Down
2 changes: 1 addition & 1 deletion src/admin/funnel-events.osl
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ def recordFunnelEvent(string key, number now) (
string id = "funnel:" ++ funnelDayKey(now)
sync.lock("funnel-events")
defer sync.unlock("funnel-events")
object doc = funnelDocs.findById(id) ?? {}
object doc = funnelDocs.findById(id).unwrap() ?? {}
object counts = {}
if doc.contains("counts") and doc.counts != null (
counts = doc.counts.assert(object)
Expand Down
2 changes: 1 addition & 1 deletion src/admin/project-moderation.osl
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ def handleListShadowBans(*serve.Context c) (
for i projectIds.len (
string id = projectIds[i].toStr()
object entry = projects[id].assertElse(object, {})
object indexed = (projectSearchDocs.findById(id) ?? {})
object indexed = (projectSearchDocs.findById(id).unwrap() ?? {})
projectRows.append({
id: id,
title: if indexed.len > 0 then indexed.title else entry.title ?? "",
Expand Down
2 changes: 1 addition & 1 deletion src/auth/agreement.osl
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def saveAgreement(object data) boolean (
bool ok = writeFile(agreementMetaPath(), data)
data.text = text
if text != "" (
if !fs.writeFile(agreementTextPath(), text) (
if !fs.writeFile(agreementTextPath(), text).isOk() (
ok = false
)
)
Expand Down
4 changes: 2 additions & 2 deletions src/auth/auth.osl
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def deleteSession(string token) boolean (
return false
)
sessionCache.delete(token)
return fs.remove(sessionsDir ++ token ++ ".json")
return fs.remove(sessionsDir ++ token ++ ".json").isOk()
)

def cleanupExpiredSessions() (
Expand Down Expand Up @@ -318,7 +318,7 @@ def externalDependency(string url) object (

def handleDependencyHealth(*serve.Context c) (
string probePath = tmpDir ++ "health-" ++ randomString(8)
boolean storageOk = fs.writeFile(probePath, "ok")
boolean storageOk = fs.writeFile(probePath, "ok").isOk()
if storageOk (
storageOk = fs.readFile(probePath).unwrapOr("") == "ok"
void fs.remove(probePath)
Expand Down
8 changes: 4 additions & 4 deletions src/auth/user-identity.osl
Original file line number Diff line number Diff line change
Expand Up @@ -502,13 +502,13 @@ def ensureUserIdentity(string userId, string username) (
userIdsCache.set("username:" ++ normalizeUsername(username), userId)
)

number roturRequestTimeoutSeconds = 10
number roturRequestTimeoutMs = 10000

def roturServiceOptions() object (
if mistwarpRoturToken == "" (
return {timeout: roturRequestTimeoutSeconds}
return {timeout: roturRequestTimeoutMs}
)
return {headers: {"Authorization": "Bearer " ++ mistwarpRoturToken}, timeout: roturRequestTimeoutSeconds}
return {headers: {"Authorization": "Bearer " ++ mistwarpRoturToken}, timeout: roturRequestTimeoutMs}
)

def refreshUsernameForId(string userId) string (
Expand Down Expand Up @@ -885,7 +885,7 @@ def reconcileDeletedUsers() (
)
)
)
ids = ids.filter((any id) boolean -> !isStudentUserId(id.toStr()))
ids = ids.filter(def(any id) boolean -> !isStudentUserId(id.toStr()))
if ids.len == 0 (
return
)
Expand Down
2 changes: 1 addition & 1 deletion src/classroom/classroom-billing-policy.osl
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def stripeSignatureValid(string header, string payload, string secret, number no
return false
)
string expected = crypto.hmac("sha256", secret, signedAt.toInt().toStr() ++ "." ++ payload)
array signatures = parts.v1.assert(array)
array signatures = parts.v1
for i signatures.len (
if crypto.constantTimeCompare(expected, signatures[i].toStr()) (
return true
Expand Down
14 changes: 7 additions & 7 deletions src/classroom/classroom-billing.osl
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ def stripeBillingConfigured() boolean (

def stripeRequest(string path, array fields) object (
object resp = requests.post("https://api.stripe.com/v1" ++ path, {
timeoutMs: 15000,
timeout: 15000,
headers: {
"Authorization": "Bearer " ++ stripeSecretKey,
"Content-Type": "application/x-www-form-urlencoded"
Expand All @@ -28,7 +28,7 @@ def stripeRequest(string path, array fields) object (
)

def classroomBillingInfo(string userId) object (
object stored = (classroomPlanDocs.findById(userId) ?? {})
object stored = (classroomPlanDocs.findById(userId).unwrap() ?? {})
boolean schoolManaged = schoolForTeacher(userId).len > 0
return {
available: stripeBillingConfigured() and !schoolManaged,
Expand Down Expand Up @@ -62,7 +62,7 @@ def startClassroomTrialLocked(*serve.Context c, string userId) boolean (
string lockName = "classroom-plan-" ++ userId
sync.lock(lockName)
defer sync.unlock(lockName)
object stored = (classroomPlanDocs.findById(userId) ?? {})
object stored = (classroomPlanDocs.findById(userId).unwrap() ?? {})
if !classroomTrialAvailable(stored, false, timestamp) (
c.json(409, {ok: false, code: "trial_unavailable", error: "The free trial is for teachers who have not had a Classroom plan before."})
return false
Expand All @@ -85,7 +85,7 @@ def handleClassroomCheckout(*serve.Context c) (
return
)
string userId = contextString(c, "userId")
object stored = (classroomPlanDocs.findById(userId) ?? {})
object stored = (classroomPlanDocs.findById(userId).unwrap() ?? {})
if classroomSubscriptionActive((stored.stripeStatus ?? "").toStr()) (
c.json(409, {ok: false, code: "already_subscribed", error: "You already have a Classroom subscription. Manage it from billing."})
return
Expand Down Expand Up @@ -128,7 +128,7 @@ def handleClassroomBillingPortal(*serve.Context c) (
c.json(503, {ok: false, code: "billing_unavailable", error: "Online payment is not set up yet. Contact MistWarp support to change your plan."})
return
)
object stored = (classroomPlanDocs.findById(contextString(c, "userId")) ?? {})
object stored = (classroomPlanDocs.findById(contextString(c, "userId")).unwrap() ?? {})
string customerId = (stored.stripeCustomerId ?? "").toStr()
if customerId == "" (
c.json(404, {ok: false, code: "no_billing_account", error: "You have not bought a plan online yet."})
Expand All @@ -146,7 +146,7 @@ def storeStripePlan(string userId, object update, number eventCreated) (
string lockName = "classroom-plan-" ++ userId
sync.lock(lockName)
defer sync.unlock(lockName)
object stored = (classroomPlanDocs.findById(userId) ?? {})
object stored = (classroomPlanDocs.findById(userId).unwrap() ?? {})
if stored.len == 0 (
stored = {_id: userId}
)
Expand All @@ -168,7 +168,7 @@ def applyStripeSubscription(object subscription, number eventCreated, boolean de
return
)
string subscriptionId = (subscription.id ?? "").toStr()
if !stripeEventMayChangePlan((classroomPlanDocs.findById(userId) ?? {}), subscriptionId) (
if !stripeEventMayChangePlan((classroomPlanDocs.findById(userId).unwrap() ?? {}), subscriptionId) (
return
)
object plan = classroomPlanFromSubscription(subscription, [stripeSeatPackPrice, stripeSeatPackPriceYearly])
Expand Down
8 changes: 4 additions & 4 deletions src/classroom/classroom-groups.osl
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def groupForSubmission(object submission) object (
if groupId == "" (
return {}
)
object group = (classroomGroupDocs.findById(groupId) ?? {})
object group = (classroomGroupDocs.findById(groupId).unwrap() ?? {})
if group.len == 0 (
return {}
)
Expand Down Expand Up @@ -103,14 +103,14 @@ def handleCreateClassGroup(*serve.Context c) (
object assignment = {}
string assignmentId = (body.assignmentId ?? "").toStr()
if assignmentId != "" (
assignment = (assignmentDocs.findById(assignmentId) ?? {})
assignment = (assignmentDocs.findById(assignmentId).unwrap() ?? {})
if assignment.len == 0 or assignment.classId.toStr() != classId (
c.badRequest("choose an assignment from this class")
return
)
for i students.len (
object student = students[i].assert(object)
if (submissionDocs.findById(assignmentId ++ ":" ++ student["_id"].toStr()) ?? {}).len > 0 (
if (submissionDocs.findById(assignmentId ++ ":" ++ student["_id"].toStr()).unwrap() ?? {}).len > 0 (
c.json(409, {ok: false, code: "already_started", error: student.displayName.toStr() ++ " has already started this assignment on their own."})
return
)
Expand Down Expand Up @@ -184,7 +184,7 @@ def handleDeleteClassGroup(*serve.Context c) (
if classDoc.len == 0 (
return
)
object group = (classroomGroupDocs.findById(c.param("gid")) ?? {})
object group = (classroomGroupDocs.findById(c.param("gid")).unwrap() ?? {})
if group.len == 0 or group.classId.toStr() != classDoc["_id"].toStr() (
c.notFound("group not found")
return
Expand Down
8 changes: 4 additions & 4 deletions src/classroom/classroom-legal.osl
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ export {
}

def classroomTermsRecord(string userId) object (
return (classroomTermsDocs.findById(userId) ?? {})
return (classroomTermsDocs.findById(userId).unwrap() ?? {})
)

def classroomTermsStatus(string userId) object (
Expand Down Expand Up @@ -87,7 +87,7 @@ def studentExportRow(object student) object (
lastLoginAt: student.lastLoginAt ?? 0,
failedLogins: student.failedLogins ?? 0,
lockedUntil: student.lockedUntil ?? 0,
projects: ownerIndexEntries(student.username.toStr(), true).map((any entry) any -> {id: entry.id, title: entry.title, created: entry.created ?? 0, edited: entry.edited})
projects: ownerIndexEntries(student.username.toStr(), true).map(def(any entry) any -> {id: entry.id, title: entry.title, created: entry.created ?? 0, edited: entry.edited})
}
)

Expand Down Expand Up @@ -158,7 +158,7 @@ def handleExportClassStudent(*serve.Context c) (
submissions: submissionDocs.where("studentId", "==", studentId).all(),
groups: groups,
activity: activity,
pendingRelease: classroomClaimDocs.where("studentId", "==", studentId).all().map((any claim) any -> {createdAt: claim.createdAt, expiresAt: claim.expiresAt})
pendingRelease: classroomClaimDocs.where("studentId", "==", studentId).all().map(def(any claim) any -> {createdAt: claim.createdAt, expiresAt: claim.expiresAt})
})
)

Expand Down Expand Up @@ -229,7 +229,7 @@ def handleAdminPurgeClassroom(*serve.Context c) (
string target = ""
string schoolId = (body.schoolId ?? "").toStr()
if schoolId != "" (
object school = (schoolDocs.findById(schoolId) ?? {})
object school = (schoolDocs.findById(schoolId).unwrap() ?? {})
if school.len == 0 (
c.badRequest("school not found")
return
Expand Down
6 changes: 3 additions & 3 deletions src/classroom/classroom-policy.osl
Original file line number Diff line number Diff line change
Expand Up @@ -294,16 +294,16 @@ def classAfterTeacherErased(object classDoc, string userId) object (
object successor = kept[1].assertElse(object, {})
next.ownerId = (successor.userId ?? "").toStr()
next.owner = (successor.username ?? "").toStr()
kept = kept.filter((any teacher) boolean -> (teacher.assertElse(object, {}).userId ?? "").toStr() != next.ownerId)
kept = kept.filter(def(any teacher) boolean -> (teacher.assertElse(object, {}).userId ?? "").toStr() != next.ownerId)
)
next.coTeachers = kept
return next
)

def schoolAfterTeacherErased(object school, string userId) object (
object next = school.clone()
array teachers = (school.teacherIds ?? []).assertElse(array, []).filter((any id) boolean -> id.toStr() != userId)
array admins = (school.adminIds ?? []).assertElse(array, []).filter((any id) boolean -> id.toStr() != userId)
array teachers = (school.teacherIds ?? []).assertElse(array, []).filter(def(any id) boolean -> id.toStr() != userId)
array admins = (school.adminIds ?? []).assertElse(array, []).filter(def(any id) boolean -> id.toStr() != userId)
if admins.len == 0 and teachers.len > 0 (
admins.append(teachers[1].toStr())
)
Expand Down
2 changes: 1 addition & 1 deletion src/classroom/classroom-present.osl
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export {
number classroomPresentationLifetimeMs = 14400000

def activePresentationForProject(string projectId) object (
object presentation = (classroomPresentationDocs.findById(projectId) ?? {})
object presentation = (classroomPresentationDocs.findById(projectId).unwrap() ?? {})
if presentation.len == 0 or (presentation.expiresAt ?? 0).toNum() <= timestamp (
return {}
)
Expand Down
Loading
Loading