diff --git a/.gitignore b/.gitignore index c0782c3..cea9a3b 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,5 @@ main !data/agreement.json !data/agreement.md +__pycache__/ +*.pyc diff --git a/native/gitinspection/merge.go b/native/gitinspection/merge.go index a253521..d69a1cd 100644 --- a/native/gitinspection/merge.go +++ b/native/gitinspection/merge.go @@ -5,6 +5,7 @@ import ( "encoding/json" "io" "sort" + "sync" "github.com/epiclabs-io/diff3" ) @@ -26,17 +27,19 @@ type prepareMergeResult struct { Error string `json:"error,omitempty"` BaseHead string `json:"baseHead,omitempty"` AlreadyMerged bool `json:"alreadyMerged,omitempty"` + FastForward bool `json:"fastForward,omitempty"` Changes []mergeChange `json:"changes,omitempty"` Conflicts []string `json:"conflicts,omitempty"` } -func ancestorDistances(repository archive, head string) map[string]int { +func ancestorDistances(repository archive, head string) (map[string]int, bool) { distances := map[string]int{} type queuedCommit struct { oid string distance int } queue := []queuedCommit{{oid: head}} + complete := true for len(queue) > 0 && len(distances) <= maxReachable { candidate := queue[0] queue = queue[1:] @@ -45,6 +48,7 @@ func ancestorDistances(repository archive, head string) map[string]int { } commit, ok := repository.parseCommit(candidate.oid) if !ok { + complete = false continue } distances[candidate.oid] = candidate.distance @@ -52,21 +56,71 @@ func ancestorDistances(repository archive, head string) map[string]int { queue = append(queue, queuedCommit{oid: parent, distance: candidate.distance + 1}) } } - return distances + return distances, complete && len(queue) == 0 } func mergeBase(repository archive, targetHead, sourceHead string) (string, bool) { - targetAncestors := ancestorDistances(repository, targetHead) - sourceAncestors := ancestorDistances(repository, sourceHead) + return crossMergeBase(repository, targetHead, repository, sourceHead) +} + +func crossMergeBase(target archive, targetHead string, source archive, sourceHead string) (string, bool) { + base, ok, _ := walkMergeBase(target, targetHead, source, sourceHead) + return base, ok +} + +func walkMergeBase(target archive, targetHead string, source archive, sourceHead string) (string, bool, bool) { + targetAncestors, targetComplete := ancestorDistances(target, targetHead) + sourceAncestors, sourceComplete := ancestorDistances(source, sourceHead) + complete := targetComplete && sourceComplete best := "" - bestDistance := int(^uint(0) >> 1) + bestDistance := 0 + bestTargetDistance := 0 for oid, targetDistance := range targetAncestors { - if sourceDistance, common := sourceAncestors[oid]; common && targetDistance+sourceDistance < bestDistance { + sourceDistance, common := sourceAncestors[oid] + if !common { + continue + } + distance := targetDistance + sourceDistance + closer := best == "" || distance < bestDistance || + (distance == bestDistance && targetDistance < bestTargetDistance) || + (distance == bestDistance && targetDistance == bestTargetDistance && oid < best) + if closer { best = oid - bestDistance = targetDistance + sourceDistance + bestDistance = distance + bestTargetDistance = targetDistance } } - return best, best != "" + return best, best != "", complete +} + +const mergeBaseCacheLimit = 512 + +var ( + mergeBaseCacheMu sync.Mutex + mergeBaseCache = map[string]string{} + mergeBaseOrder []string +) + +func cachedMergeBase(key string) (string, bool) { + mergeBaseCacheMu.Lock() + defer mergeBaseCacheMu.Unlock() + base, ok := mergeBaseCache[key] + return base, ok +} + +func rememberMergeBase(key, base string) { + mergeBaseCacheMu.Lock() + defer mergeBaseCacheMu.Unlock() + if _, ok := mergeBaseCache[key]; ok { + mergeBaseCache[key] = base + return + } + if len(mergeBaseOrder) >= mergeBaseCacheLimit { + delete(mergeBaseCache, mergeBaseOrder[0]) + mergeBaseOrder = mergeBaseOrder[1:] + } + mergeBaseCache[key] = base + mergeBaseOrder = append(mergeBaseOrder, key) } func filesAtCommit(repository archive, sha string) (map[string]gitFile, bool) { @@ -110,6 +164,15 @@ func PrepareMerge(targetPath, targetHead, sourcePath, sourceHead, baseHead strin return prepareMergeResult{Error: "source workspace archive is unavailable"} } defer sourceReader.Close() + return prepareArchiveMerge(target, targetHead, source, sourceHead, baseHead, mergeLabels{ours: "target", theirs: "pull request"}) +} + +type mergeLabels struct { + ours string + theirs string +} + +func prepareArchiveMerge(target archive, targetHead string, source archive, sourceHead, baseHead string, labels mergeLabels) prepareMergeResult { baseFiles, ok := filesAtCommit(target, baseHead) if !ok { return prepareMergeResult{Error: "pull request base is unavailable"} @@ -168,7 +231,7 @@ func PrepareMerge(targetPath, targetHead, sourcePath, sourceHead, baseHead strin result.Conflicts = append(result.Conflicts, path) continue } - merged, mergeErr := diff3.Merge(bytes.NewReader(oursContent), bytes.NewReader(baseContent), bytes.NewReader(theirsContent), true, "target", "pull request") + merged, mergeErr := diff3.Merge(bytes.NewReader(oursContent), bytes.NewReader(baseContent), bytes.NewReader(theirsContent), true, labels.ours, labels.theirs) if mergeErr != nil { return prepareMergeResult{Error: "could not merge text file"} } @@ -213,3 +276,68 @@ func PrepareBranchMergeJSON(path, targetHead, sourceHead string) string { encoded, _ := json.Marshal(PrepareBranchMerge(path, targetHead, sourceHead)) return string(encoded) } + +func PrepareRemixMerge(targetPath, targetHead, sourcePath, sourceHead, oursLabel, theirsLabel string) prepareMergeResult { + releaseSlot := acquireInspectionSlot() + defer releaseSlot() + targetReader, target, err := openArchive(targetPath) + if err != nil { + return prepareMergeResult{Error: "target workspace archive is unavailable"} + } + defer targetReader.Close() + sourceReader, source, err := openArchive(sourcePath) + if err != nil { + return prepareMergeResult{Error: "source workspace archive is unavailable"} + } + defer sourceReader.Close() + baseHead, ok := crossMergeBase(target, targetHead, source, sourceHead) + if !ok { + return prepareMergeResult{Error: "the two projects do not share a common commit"} + } + if baseHead == sourceHead { + return prepareMergeResult{OK: true, BaseHead: baseHead, AlreadyMerged: true, Changes: []mergeChange{}, Conflicts: []string{}} + } + result := prepareArchiveMerge(target, targetHead, source, sourceHead, baseHead, mergeLabels{ours: oursLabel, theirs: theirsLabel}) + result.BaseHead = baseHead + result.FastForward = result.OK && baseHead == targetHead + return result +} + +func PrepareRemixMergeJSON(targetPath, targetHead, sourcePath, sourceHead, oursLabel, theirsLabel string) string { + encoded, _ := json.Marshal(PrepareRemixMerge(targetPath, targetHead, sourcePath, sourceHead, oursLabel, theirsLabel)) + return string(encoded) +} + +func RemixMergeBase(targetPath, targetHead, sourcePath, sourceHead string) string { + if len(targetHead) != 40 || len(sourceHead) != 40 { + return failure("both heads are required") + } + releaseSlot := acquireInspectionSlot() + defer releaseSlot() + targetShared, err := acquireSharedArchive(targetPath) + if err != nil { + return failure("target workspace archive is unavailable") + } + defer targetShared.release() + sourceShared, err := acquireSharedArchive(sourcePath) + if err != nil { + return failure("source workspace archive is unavailable") + } + defer sourceShared.release() + key := targetHead + ":" + sourceHead + if baseHead, ok := cachedMergeBase(key); ok { + _, inTarget := targetShared.archive.parseCommit(baseHead) + _, inSource := sourceShared.archive.parseCommit(baseHead) + if inTarget && inSource { + return encode(map[string]any{"ok": true, "base": baseHead}, "could not encode merge base") + } + } + baseHead, ok, complete := walkMergeBase(targetShared.archive, targetHead, sourceShared.archive, sourceHead) + if !ok { + return failure("the two projects do not share a common commit") + } + if complete { + rememberMergeBase(key, baseHead) + } + return encode(map[string]any{"ok": true, "base": baseHead}, "could not encode merge base") +} diff --git a/native/gitinspection/remix_merge_test.go b/native/gitinspection/remix_merge_test.go new file mode 100644 index 0000000..f04c9c1 --- /dev/null +++ b/native/gitinspection/remix_merge_test.go @@ -0,0 +1,236 @@ +package gitinspection + +import ( + "strings" + "testing" +) + +func (r *testRepository) mergeCommit(tree, message string, parents ...string) string { + body := "tree " + tree + "\n" + for _, parent := range parents { + body += "parent " + parent + "\n" + } + body += "author Mist 1724976000 +0000\n" + body += "committer Mist 1724976000 +0000\n\n" + message + "\n" + return r.object("commit", []byte(body)) +} + +func (r *testRepository) copyFrom(other *testRepository) { + for oid, object := range other.objects { + r.objects[oid] = object + } +} + +func (r *testRepository) fileCommit(content, parent, message string) string { + blob := r.object("blob", []byte(content)) + return r.commit(r.tree("main.fractch", blob), parent, message) +} + +func TestPrepareRemixMergeBringsOriginalChangesIntoRemix(t *testing.T) { + original := newTestRepository() + base := original.fileCommit("one\ntwo\nthree\n", "", "Base") + upstream := original.fileCommit("one\ntwo\nTHREE\n", base, "Upstream") + + remix := newTestRepository() + remix.copyFrom(original) + delete(remix.objects, upstream) + own := remix.fileCommit("ONE\ntwo\nthree\n", base, "Remix") + + result := PrepareRemixMerge(remix.write(t), own, original.write(t), upstream, "this remix", "original") + if !result.OK || result.BaseHead != base || result.AlreadyMerged || result.FastForward || len(result.Conflicts) != 0 || len(result.Changes) != 1 { + t.Fatalf("unexpected remix merge result: %#v", result) + } + content := string(result.Changes[0].Content) + if !strings.Contains(content, "ONE") || !strings.Contains(content, "THREE") { + t.Fatalf("both edits were not merged: %q", content) + } +} + +func TestPrepareRemixMergeMarksFastForward(t *testing.T) { + original := newTestRepository() + base := original.fileCommit("one\n", "", "Base") + remix := newTestRepository() + remix.copyFrom(original) + upstream := original.fileCommit("two\n", base, "Upstream") + + result := PrepareRemixMerge(remix.write(t), base, original.write(t), upstream, "this remix", "original") + if !result.OK || !result.FastForward || result.AlreadyMerged || len(result.Changes) != 1 || string(result.Changes[0].Content) != "two\n" { + t.Fatalf("expected a fast-forward result: %#v", result) + } +} + +func TestPrepareRemixMergeDetectsAlreadyMerged(t *testing.T) { + original := newTestRepository() + base := original.fileCommit("one\n", "", "Base") + upstream := original.fileCommit("two\n", base, "Upstream") + remix := newTestRepository() + remix.copyFrom(original) + own := remix.fileCommit("three\n", upstream, "Remix") + + result := PrepareRemixMerge(remix.write(t), own, original.write(t), upstream, "this remix", "original") + if !result.OK || !result.AlreadyMerged || result.BaseHead != upstream { + t.Fatalf("expected an already-merged result: %#v", result) + } +} + +func TestPrepareRemixMergeRejectsUnrelatedHistory(t *testing.T) { + original := newTestRepository() + upstream := original.fileCommit("one\n", "", "Original") + remix := newTestRepository() + own := remix.fileCommit("one\n", "", "Unrelated") + + result := PrepareRemixMerge(remix.write(t), own, original.write(t), upstream, "this remix", "original") + if result.OK || result.Error == "" { + t.Fatalf("unrelated histories should not merge: %#v", result) + } +} + +func TestRepairedRemixMergesThroughReconnectedBase(t *testing.T) { + original := newTestRepository() + base := original.fileCommit("one\ntwo\nthree\n", "", "Initial version") + upstream := original.fileCommit("one\ntwo\nTHREE\n", base, "fixed space bug") + + remix := newTestRepository() + root := remix.fileCommit("one\ntwo\nthree\n", "", "Remix initial version") + own := remix.fileCommit("ONE\ntwo\nthree\n", root, "game save data") + remix.copyFrom(original) + delete(remix.objects, upstream) + ownTree := remix.tree("main.fractch", remix.object("blob", []byte("ONE\ntwo\nthree\n"))) + repaired := remix.mergeCommit(ownTree, "Reconnect recorded remix parent history", own, base) + originalPath := original.write(t) + remixPath := remix.write(t) + + decoded := decodeResult(t, RemixMergeBase(originalPath, upstream, remixPath, repaired)) + if decoded["ok"] != true || decoded["base"] != base { + t.Fatalf("expected the reconnected base, got %#v", decoded) + } + result := PrepareRemixMerge(originalPath, upstream, remixPath, repaired, "target", "pull request") + if !result.OK || result.BaseHead != base || len(result.Changes) != 1 || len(result.Conflicts) != 0 { + t.Fatalf("unexpected pull merge result: %#v", result) + } + content := string(result.Changes[0].Content) + if !strings.Contains(content, "ONE") || !strings.Contains(content, "THREE") { + t.Fatalf("the remix change was not merged: %q", content) + } + stale := PrepareRemixMerge(originalPath, upstream, remixPath, root, "target", "pull request") + if stale.OK { + t.Fatalf("the unconnected remix root should not merge: %#v", stale) + } +} + +func TestRemixMergeBaseRejectsMissingHeads(t *testing.T) { + original := newTestRepository() + head := original.fileCommit("one\n", "", "Base") + path := original.write(t) + decoded := decodeResult(t, RemixMergeBase(path, "", path, head)) + if decoded["ok"] != false { + t.Fatalf("a missing head should fail: %#v", decoded) + } +} + +func TestPrepareRemixMergeLabelsConflicts(t *testing.T) { + original := newTestRepository() + base := original.fileCommit("one\nmove 10\nthree\n", "", "Base") + upstream := original.fileCommit("one\nmove 20\nthree\n", base, "Upstream") + remix := newTestRepository() + remix.copyFrom(original) + delete(remix.objects, upstream) + own := remix.fileCommit("one\nmove 5\nthree\n", base, "Remix") + + result := PrepareRemixMerge(remix.write(t), own, original.write(t), upstream, "this remix", "original") + if !result.OK || len(result.Conflicts) != 1 { + t.Fatalf("expected one conflict: %#v", result) + } + content := string(result.Changes[0].Content) + if !strings.Contains(content, "<<<<<<< this remix") || !strings.Contains(content, ">>>>>>> original") { + t.Fatalf("conflict markers are not labelled: %q", content) + } +} + +func TestCrossMergeBaseBreaksTiesTheSameWayEveryTime(t *testing.T) { + repo := newTestRepository() + root := repo.fileCommit("root\n", "", "Root") + left := repo.fileCommit("left\n", root, "Left") + right := repo.fileCommit("right\n", root, "Right") + leftTree := repo.tree("main.fractch", repo.object("blob", []byte("left merge\n"))) + rightTree := repo.tree("main.fractch", repo.object("blob", []byte("right merge\n"))) + targetHead := repo.mergeCommit(leftTree, "Target merge", left, right) + sourceHead := repo.mergeCommit(rightTree, "Source merge", right, left) + path := repo.write(t) + reader, archive, err := openArchive(path) + if err != nil { + t.Fatal(err) + } + defer reader.Close() + want := left + if right < left { + want = right + } + for attempt := 0; attempt < 50; attempt++ { + base, ok := crossMergeBase(archive, targetHead, archive, sourceHead) + if !ok || base != want { + t.Fatalf("attempt %d chose %s, want %s", attempt, base, want) + } + } +} + +func TestRemixMergeBaseIsRememberedForTheSameHeads(t *testing.T) { + original := newTestRepository() + base := original.fileCommit("one\n", "", "Base") + upstream := original.fileCommit("two\n", base, "Upstream") + remix := newTestRepository() + remix.copyFrom(original) + delete(remix.objects, upstream) + own := remix.fileCommit("mine\n", base, "Remix") + + remixPath := remix.write(t) + originalPath := original.write(t) + first := RemixMergeBase(remixPath, own, originalPath, upstream) + if !strings.Contains(first, base) { + t.Fatalf("unexpected merge base: %s", first) + } + if cached, ok := cachedMergeBase(own + ":" + upstream); !ok || cached != base { + t.Fatalf("merge base was not remembered: %q %v", cached, ok) + } + if again := RemixMergeBase(remixPath, own, originalPath, upstream); again != first { + t.Fatalf("cached lookup changed the answer: %s", again) + } + missingHead := strings.Repeat("e", 40) + rememberMergeBase(own+":"+missingHead, strings.Repeat("f", 40)) + if stale := RemixMergeBase(remixPath, own, originalPath, missingHead); strings.Contains(stale, `"ok":true`) { + t.Fatalf("a cached base missing from the archives was trusted: %s", stale) + } + mergeBaseCacheMu.Lock() + mergeBaseCache[own+":"+upstream] = strings.Repeat("f", 40) + mergeBaseCacheMu.Unlock() + if healed := RemixMergeBase(remixPath, own, originalPath, upstream); !strings.Contains(healed, base) { + t.Fatalf("a stale cached base changed the answer: %s", healed) + } + if cached, _ := cachedMergeBase(own + ":" + upstream); cached != base { + t.Fatalf("a stale cached base was not replaced: %q", cached) + } + + root := original.fileCommit("zero\n", "", "Root") + side := original.fileCommit("side\n", root, "Side") + middle := original.fileCommit("mid\n", root, "Middle") + tip := original.fileCommit("tip\n", middle, "Tip") + fork := newTestRepository() + fork.copyFrom(original) + forkCommit := fork.fileCommit("fork\n", middle, "Fork") + mergeCommit := original.mergeCommit(original.tree("main.fractch", original.object("blob", []byte("merged\n"))), "Merge", tip, side) + partial := newTestRepository() + partial.copyFrom(original) + delete(partial.objects, middle) + partialPath := partial.write(t) + forkPath := fork.write(t) + if fallback := RemixMergeBase(partialPath, mergeCommit, forkPath, forkCommit); !strings.Contains(fallback, root) { + t.Fatalf("expected fallback base %s, got %s", root, fallback) + } + if cached, ok := cachedMergeBase(mergeCommit + ":" + forkCommit); ok { + t.Fatalf("truncated walk should not be cached, got %q", cached) + } + repairedPath := original.write(t) + if repaired := RemixMergeBase(repairedPath, mergeCommit, forkPath, forkCommit); !strings.Contains(repaired, middle) { + t.Fatalf("repaired archive kept truncated base: %s (want %s)", repaired, middle) + } +} diff --git a/opal.json b/opal.json index 31d2c54..bfd38cd 100644 --- a/opal.json +++ b/opal.json @@ -1,6 +1,6 @@ { "name": "mistwarp-api", - "version": "1.6.0", + "version": "1.7.0", "main": "main.osl", "scripts": { "dev": ["osl", "run", "main.osl"], diff --git a/scripts/__pycache__/check_conventions.cpython-314.pyc b/scripts/__pycache__/check_conventions.cpython-314.pyc deleted file mode 100644 index 2aa9485..0000000 Binary files a/scripts/__pycache__/check_conventions.cpython-314.pyc and /dev/null differ diff --git a/scripts/__pycache__/refund_project_sales.cpython-314.pyc b/scripts/__pycache__/refund_project_sales.cpython-314.pyc deleted file mode 100644 index f3ce77e..0000000 Binary files a/scripts/__pycache__/refund_project_sales.cpython-314.pyc and /dev/null differ diff --git a/scripts/__pycache__/refund_project_sales.cpython-38.pyc b/scripts/__pycache__/refund_project_sales.cpython-38.pyc deleted file mode 100644 index aac556f..0000000 Binary files a/scripts/__pycache__/refund_project_sales.cpython-38.pyc and /dev/null differ diff --git a/scripts/__pycache__/test_project_sales_api.cpython-314.pyc b/scripts/__pycache__/test_project_sales_api.cpython-314.pyc deleted file mode 100644 index 6750867..0000000 Binary files a/scripts/__pycache__/test_project_sales_api.cpython-314.pyc and /dev/null differ diff --git a/scripts/__pycache__/test_refund_project_sales.cpython-314.pyc b/scripts/__pycache__/test_refund_project_sales.cpython-314.pyc deleted file mode 100644 index 90a181e..0000000 Binary files a/scripts/__pycache__/test_refund_project_sales.cpython-314.pyc and /dev/null differ diff --git a/scripts/__pycache__/test_refund_project_sales.cpython-38.pyc b/scripts/__pycache__/test_refund_project_sales.cpython-38.pyc deleted file mode 100644 index bb8ec7a..0000000 Binary files a/scripts/__pycache__/test_refund_project_sales.cpython-38.pyc and /dev/null differ diff --git a/scripts/e2e_smoke.py b/scripts/e2e_smoke.py index d6a310f..d7f0f0f 100644 --- a/scripts/e2e_smoke.py +++ b/scripts/e2e_smoke.py @@ -1,4 +1,5 @@ import argparse +import base64 import concurrent.futures import difflib import gzip @@ -40,6 +41,7 @@ SLOW_LEDGER_USERS = {"u_lena"} ROTUR_DELAY = 4 EXPECTED_ERRORS = {"patch team unknown user", "patch transfer unknown", "patch team rotur unavailable", "patch transfer rotur unavailable", "upload unsaved first save of the day", "upload extension store failure", "upload extension store failure with history", "upload json store failure", "upload metadata save failure"} +CHECK_STEPS = {"sync pull reads stay inside the pull", "sync pull hides remix commits when seeInside is off", "sync merged pull reads stay inside the pull", "sync pull already merged completes even if base branch was renamed", "sync pull follows the remix", "sync prepared heads", "sync result", "sync pull diff uses the live base", "sync pull merge result", "sync remix is dirty", "sync refusals are enforced", "sync dirty refusals are enforced"} SCOPED_SESSIONS = {"sam_editor": ("sam", "editor")} VOLATILE_NAMES = {"token", "viewKey", "expires", "created", "edited", "firstSeen", "historyBytes"} UNORDERED = {"largest"} @@ -394,7 +396,7 @@ def commit(self, tree, parents, message): lines += [b"author " + SMOKE_AUTHOR, b"committer " + SMOKE_AUTHOR] return self.add("commit", b"\n".join(lines) + b"\n\n" + message.encode() + b"\n") - def archive(self, head, delta, extra=None): + def archive(self, head, delta, extra=None, worktree=None): refs = dict(self.refs) if not delta else {} refs[self.branch] = head manifest = self.metadata(head, delta) @@ -409,6 +411,8 @@ def archive(self, head, delta, extra=None): objects = dict(self.added) if delta else dict(self.objects, **self.added) for oid, compressed in sorted(objects.items()): archive.writestr(".git/objects/%s/%s" % (oid[:2], oid[2:]), compressed) + for name, content in sorted((worktree or {}).items()): + archive.writestr(name, content) return buffer.getvalue() def metadata(self, head, delta): @@ -963,6 +967,230 @@ def upload(): }}) +def history_commit(server, ids, alias, who, name, content): + history = History(raw_get(server, "/v1/projects/%s/workspace.mwp" % real_id(ids, alias), who)) + tree = history.tree_with(history.tree_of(history.head()), name, content.encode()) + head = history.commit(tree, [history.head()], "Change " + name) + return head, history.archive(head, False), json.dumps(history.metadata(head, False)) + + +def project_head(server, ids, alias, who): + project = server.call("GET", "/v1/projects/" + real_id(ids, alias), who)[1] + return str(project.get("gitHead") or (project.get("project") or {}).get("gitHead") or ""), project.get("remixFrom") or (project.get("project") or {}).get("remixFrom") or {} + + +def synced_tree(server, ids, alias, who, head, merge): + history = History(raw_get(server, "/v1/projects/%s/workspace.mwp" % real_id(ids, alias), who)) + files = history.files(history.tree_of(head)) + for change in merge.get("changes") or []: + if change.get("deleted"): + files.pop(change["path"], None) + else: + files[change["path"]] = base64.b64decode(change.get("content") or "") + return zip_files(files) + + +def remix_sync_flow(server, step, steps, ids): + plain = sb3_archive(project_with_costumes([])) + status, created = step("sync original create", "POST", "/v1/projects", "sam", {"title": "Sync original"}) + ids[str(created.get("id", "")) if isinstance(created, dict) else ""] = "" + original = "/v1/projects/" + step("sync original first save", "POST", original + "/upload", "sam", form=({}, {"project": plain})) + step("sync original share", "POST", original + "/visibility", "sam", {"visibility": "public"}) + status, remixed = step("sync remix create", "POST", original + "/remix", "alice", {}) + ids[str(remixed.get("id", "") or (remixed.get("project") or {}).get("id", "")) if isinstance(remixed, dict) else ""] = "" + remix = "/v1/projects/" + step("sync with nothing new", "POST", remix + "/remix/sync", "alice", {}) + + upstream, archive, metadata = history_commit(server, ids, "", "sam", "original-notes.txt", "from the original") + step("sync original change", "POST", original + "/upload", "sam", form=({"git": metadata}, {"project": plain, "workspace": archive})) + first, archive, metadata = history_commit(server, ids, "", "alice", "remix-notes.txt", "first remix change") + step("sync remix change", "POST", remix + "/upload", "alice", form=({"git": metadata}, {"project": plain, "workspace": archive})) + status, pull = step("sync remix pull", "POST", original + "/pulls", "alice", {"sourceProjectId": real_id(ids, ""), "title": "Remix notes", "body": ""}) + pull_path = original + "/pulls/" + str(((pull.get("pull") or {}).get("index", "")) if isinstance(pull, dict) else "") + second, archive, metadata = history_commit(server, ids, "", "alice", "remix-notes.txt", "second remix change") + step("sync remix second change", "POST", remix + "/upload", "alice", form=({"git": metadata}, {"project": plain, "workspace": archive})) + status, opened = step("sync pull after a new remix commit", "GET", pull_path, "sam") + status, diff = step("sync pull diff after a new remix commit", "GET", pull_path + "/diff?view=changes", "sam") + status, remix_project = server.call("GET", "/v1/projects/" + real_id(ids, ""), "alice")[:2] + remix_from = remix_project.get("remixFrom") or (remix_project.get("project") or {}).get("remixFrom") or {} + steps.append({"step": "sync pull follows the remix", "status": 0, "body": { + "pullHeadIsLatest": (opened.get("pull") or {}).get("headCommit") == second, + "diffHeadIsLatest": ((diff.get("pull") or {}).get("headCommit") == second) if isinstance(diff, dict) else False, + "firstWasRecorded": (pull.get("pull") or {}).get("headCommit") == first, + "ahead": remix_from.get("ahead"), "behind": remix_from.get("behind"), + }}) + + stranger_status, _ = step("sync by a stranger", "POST", remix + "/remix/sync", "bob", {}) + not_remix_status, _ = step("sync a project that is not a remix", "POST", original + "/remix/sync", "sam", {}) + signed_out_status, _ = step("sync signed out", "POST", remix + "/remix/sync", None, {}) + status, prepared = step("sync prepare", "POST", remix + "/remix/sync", "alice", {}) + merge = prepared.get("merge") or {} if isinstance(prepared, dict) else {} + steps.append({"step": "sync prepared heads", "status": 0, "body": { + "sourceIsOriginal": prepared.get("sourceHead") == upstream, "targetIsRemix": prepared.get("expectedHead") == second, + "paths": sorted(change.get("path") for change in merge.get("changes") or []), + }}) + tree = synced_tree(server, ids, "", "alice", second, merge) + no_head_status, no_head_body = step("sync upload without the remix head", "POST", remix + "/upload", "alice", form=({"syncHead": upstream}, {"project": plain, "mergeTree": tree})) + moved_orig_status, moved_orig_body = step("sync upload with a moved original", "POST", remix + "/upload", "alice", form=({"syncHead": ZERO_HEAD, "expectedHead": second}, {"project": plain, "mergeTree": tree})) + stranger_up_status, _ = step("sync upload by a stranger", "POST", remix + "/upload", "bob", form=({"syncHead": upstream, "expectedHead": second}, {"project": plain, "mergeTree": tree})) + with_pull_status, _ = step("sync upload with a pull", "POST", remix + "/upload", "alice", form=({"syncHead": upstream, "expectedHead": second, "pullId": "1"}, {"project": plain, "mergeTree": tree})) + steps.append({"step": "sync refusals are enforced", "status": 0, "body": { + "strangerSyncRefused": stranger_status == 404, + "notRemixNotFound": not_remix_status == 404, + "signedOutUnauthorized": signed_out_status == 401, + "missingExpectedHeadConflict": no_head_status == 409 and isinstance(no_head_body, dict) and no_head_body.get("code") == "head_changed", + "movedOriginalConflict": moved_orig_status == 409 and isinstance(moved_orig_body, dict) and moved_orig_body.get("code") == "original_changed", + "strangerUploadForbidden": stranger_up_status == 403, + "combinedPullBadRequest": with_pull_status == 400, + }}) + step("sync upload", "POST", remix + "/upload", "alice", form=({"syncHead": upstream, "expectedHead": second}, {"project": plain, "mergeTree": tree})) + synced, remix_from = project_head(server, ids, "", "alice") + history = History(raw_get(server, "/v1/projects/%s/workspace.mwp" % real_id(ids, ""), "alice")) + parents = [line.decode()[len("parent "):] for line in history.read(synced)[1].split(b"\n") if line.startswith(b"parent ")] + message = history.read(synced)[1].split(b"\n\n", 1)[1].decode().strip() + files = history.files(history.tree_of(synced)) + steps.append({"step": "sync result", "status": 0, "body": { + "parentsAreRemixThenOriginal": parents == [second, upstream], "message": message, + "hasOriginalFile": files.get("original-notes.txt") == b"from the original", + "keepsRemixFile": files.get("remix-notes.txt") == b"second remix change", + "ahead": remix_from.get("ahead"), "behind": remix_from.get("behind"), + }}) + step("sync again", "POST", remix + "/remix/sync", "alice", {}) + status, synced_diff = step("sync pull diff after syncing", "GET", pull_path + "/diff?view=changes", "sam") + synced_diff_pull = (synced_diff.get("pull") or {}) if isinstance(synced_diff, dict) else {} + steps.append({"step": "sync pull diff uses the live base", "status": 0, "body": { + "baseIsOriginalHead": synced_diff_pull.get("baseCommit") == upstream, + "baseMovedFromRecorded": synced_diff_pull.get("baseCommit") != (pull.get("pull") or {}).get("baseCommit"), + "headIsSynced": synced_diff_pull.get("headCommit") == synced, + }}) + + pull_index = str((pull.get("pull") or {}).get("index", "")) if isinstance(pull, dict) else "" + remix_id, original_id = real_id(ids, ""), real_id(ids, "") + + def pull_read(sha, who): + path = "/v1/projects/%s/commits/%s/file?path=remix-notes.txt&pull=%s&pullTarget=%s" % (remix_id, sha, pull_index, original_id) + return server.call("GET", path, who)[0] + + def pull_archive(who): + return server.call("GET", "/v1/projects/%s/workspace.mwp?pull=%s" % (remix_id, pull_index), who)[0] + + steps.append({"step": "sync pull reads stay inside the pull", "status": 0, "body": { + "recordedHeadReadable": pull_read(first, None) == 200, + "liveHeadReadable": pull_read(synced, None) == 200, + "archiveRefusedSignedOut": pull_archive(None) == 404, + "archiveRefusedToOtherViewers": pull_archive("bob") == 404, + "archiveAllowedToTheOwner": pull_archive("sam") == 200, + }}) + + hide_status = server.call("PUT", "/v1/projects/" + remix_id, "alice", {"seeInside": False})[0] + timeline_status, hidden_timeline = server.call("GET", "/v1/projects/%s/pulls/%s/timeline" % (original_id, pull_index), None)[:2] + diff_status = server.call("GET", "/v1/projects/%s/pulls/%s/diff?view=changes" % (original_id, pull_index), "sam")[0] + pull_merge_hidden_status = server.call("POST", "/v1/projects/%s/pulls/%s/merge" % (original_id, pull_index), "sam", {})[0] + pull_upload_hidden_status = server.form( + "/v1/projects/%s/upload" % original_id, "sam", + {"pullId": str(pull_index), "expectedHead": project_head(server, ids, "", "sam")[0], "mergeSourceHead": synced}, + {"project": plain, "mergeTree": zip_files({"original-notes.txt": b"x"})}, + )[0] + file_hidden_status = pull_read(synced, None) + unhide_status = server.call("PUT", "/v1/projects/" + remix_id, "alice", {"seeInside": True})[0] + steps.append({"step": "sync pull hides remix commits when seeInside is off", "status": 0, "body": { + "hideOk": hide_status == 200, + "unhideOk": unhide_status == 200, + "timelineOk": timeline_status == 200, + "commitsHidden": isinstance(hidden_timeline, dict) and hidden_timeline.get("commits") == [], + "targetCommitsHidden": isinstance(hidden_timeline, dict) and hidden_timeline.get("targetCommits") == [], + "diffForbidden": diff_status == 403, + "mergeForbidden": pull_merge_hidden_status == 403, + "uploadForbidden": pull_upload_hidden_status == 403, + "fileHidden": file_hidden_status == 404, + }}) + + status, merged = step("sync pull merge after syncing", "POST", pull_path + "/merge", "sam", {}) + status, closed = step("sync pull after merging", "GET", pull_path, "sam") + original_head = project_head(server, ids, "", "sam")[0] + steps.append({"step": "sync pull merge result", "status": 0, "body": { + "fastForwarded": isinstance(merged, dict) and merged.get("merged") is True, + "recordsMergedHead": (closed.get("pull") or {}).get("headCommit") == synced, + "originalHasRemixFile": History(raw_get(server, "/v1/projects/%s/workspace.mwp" % real_id(ids, ""), "sam")).files( + History(raw_get(server, "/v1/projects/%s/workspace.mwp" % real_id(ids, ""), "sam")).tree_of(original_head)).get("remix-notes.txt") == b"second remix change", + }}) + steps.append({"step": "sync merged pull reads stay inside the pull", "status": 0, "body": { + "mergedHeadReadable": pull_read(synced, None) == 200, + "otherRemixCommitRefused": pull_read(second, None) == 404, + }}) + + already_pull_status, already_pull = server.call("POST", "/v1/projects/%s/pulls" % original_id, "alice", {"sourceProjectId": remix_id, "title": "Already in target", "body": ""})[:2] + already_pull_idx = str(((already_pull.get("pull") or {}).get("index", "")) if isinstance(already_pull, dict) else "") + rename_out_status = server.call("PATCH", "/v1/projects/%s/branches" % original_id, "sam", {"branch": "main", "name": "release"})[0] + already_merge_status, already_merged = server.call("POST", "/v1/projects/%s/pulls/%s/merge" % (original_id, already_pull_idx), "sam", {})[:2] + rename_back_status = server.call("PATCH", "/v1/projects/%s/branches" % original_id, "sam", {"branch": "release", "name": "main"})[0] + + already_dirty_pull_status, already_dirty_pull = server.call("POST", "/v1/projects/%s/pulls" % original_id, "alice", {"sourceProjectId": remix_id, "title": "Already in dirty target", "body": ""})[:2] + already_dirty_pull_idx = str(((already_dirty_pull.get("pull") or {}).get("index", "")) if isinstance(already_dirty_pull, dict) else "") + orig_history = History(raw_get(server, "/v1/projects/%s/workspace.mwp" % real_id(ids, ""), "sam")) + orig_worktree = dict(orig_history.files(orig_history.tree_of(orig_history.head())), **{"original-notes.txt": b"dirty target worktree"}) + orig_dirty_manifest = dict(orig_history.metadata(orig_history.head(), False), worktree=True) + server.form("/v1/projects/%s/upload" % original_id, "sam", {"git": json.dumps(orig_dirty_manifest)}, { + "project": plain, "workspace": orig_history.archive(orig_history.head(), False, {"worktree": True}, orig_worktree), + }) + already_dirty_merge_status, already_dirty_merged = server.call("POST", "/v1/projects/%s/pulls/%s/merge" % (original_id, already_dirty_pull_idx), "sam", {})[:2] + + _, remix_third_archive, remix_third_meta = history_commit(server, ids, "", "alice", "remix-notes.txt", "third remix change") + server.form("/v1/projects/%s/upload" % remix_id, "alice", {"git": remix_third_meta}, {"project": plain, "workspace": remix_third_archive}) + unmerged_pull_status, unmerged_pull = server.call("POST", "/v1/projects/%s/pulls" % original_id, "alice", {"sourceProjectId": remix_id, "title": "Not in target", "body": ""})[:2] + unmerged_pull_idx = str(((unmerged_pull.get("pull") or {}).get("index", "")) if isinstance(unmerged_pull, dict) else "") + dirty_pull_merge_status, dirty_pull_merge_body = server.call("POST", "/v1/projects/%s/pulls/%s/merge" % (original_id, unmerged_pull_idx), "sam", {})[:2] + dirty_pull_upload_status, dirty_pull_upload_body = server.form( + "/v1/projects/%s/upload" % original_id, "sam", + {"pullId": unmerged_pull_idx, "expectedHead": orig_history.head(), "mergeSourceHead": project_head(server, ids, "", "alice")[0]}, + {"project": plain, "mergeTree": zip_files({"original-notes.txt": b"x"})}, + )[:2] + + upstream, archive, metadata = history_commit(server, ids, "", "sam", "original-notes.txt", "second original change") + step("sync original second change", "POST", original + "/upload", "sam", form=({"git": metadata}, {"project": plain, "workspace": archive})) + server.call("PATCH", "/v1/projects/%s/branches" % original_id, "sam", {"branch": "main", "name": "release"}) + missing_branch_status, missing_branch_body = server.call("POST", "/v1/projects/%s/pulls/%s/merge" % (original_id, unmerged_pull_idx), "sam", {})[:2] + server.call("PATCH", "/v1/projects/%s/branches" % original_id, "sam", {"branch": "release", "name": "main"}) + steps.append({"step": "sync pull already merged completes even if base branch was renamed", "status": 0, "body": { + "opened": already_pull_status == 201 and bool(already_pull_idx), + "renamed": rename_out_status == 200 and rename_back_status == 200, + "completed": already_merge_status == 200 and isinstance(already_merged, dict) and already_merged.get("merged") is True and already_merged.get("alreadyMerged") is True, + "completedWhenTargetDirty": already_dirty_pull_status == 201 and already_dirty_merge_status == 200 and isinstance(already_dirty_merged, dict) and already_dirty_merged.get("merged") is True and already_dirty_merged.get("alreadyMerged") is True, + "unmergedRefusedWhenBranchMissing": missing_branch_status == 409 and isinstance(missing_branch_body, dict) and missing_branch_body.get("code") == "target_branch_missing" and missing_branch_body.get("branch") == "main", + "unmergedRefusedWhenTargetDirty": dirty_pull_merge_status == 409 and isinstance(dirty_pull_merge_body, dict) and dirty_pull_merge_body.get("code") == "uncommitted_changes", + "uploadRefusedWhenTargetDirty": dirty_pull_upload_status == 409 and isinstance(dirty_pull_upload_body, dict) and dirty_pull_upload_body.get("code") == "uncommitted_changes", + }}) + head = project_head(server, ids, "", "alice")[0] + server.call("POST", "/v1/projects/%s/publish" % remix_id, "alice", {}) + public_stranger_sync_status = server.call("POST", "/v1/projects/%s/remix/sync" % remix_id, "bob", {})[0] + server.call("POST", "/v1/projects/%s/unpublish" % original_id, "sam", {}) + closed_original_sync_status = server.call("POST", "/v1/projects/%s/remix/sync" % remix_id, "alice", {})[0] + closed_original_upload_status, closed_original_upload_body = step( + "sync upload when original source is closed", "POST", remix + "/upload", "alice", + form=({"syncHead": upstream, "expectedHead": head}, {"project": plain, "mergeTree": zip_files({"original-notes.txt": b"x"})}), + ) + server.call("POST", "/v1/projects/%s/publish" % original_id, "sam", {}) + + history = History(raw_get(server, "/v1/projects/%s/workspace.mwp" % real_id(ids, ""), "alice")) + worktree = dict(history.files(history.tree_of(history.head())), **{"remix-notes.txt": b"not committed yet"}) + manifest = dict(history.metadata(history.head(), False), worktree=True) + step("sync remix save without a commit", "POST", remix + "/upload", "alice", form=({"git": json.dumps(manifest)}, { + "project": plain, "workspace": history.archive(history.head(), False, {"worktree": True}, worktree), + })) + status, commits = step("sync remix uncommitted state", "GET", remix + "/commits", "alice") + steps.append({"step": "sync remix is dirty", "status": 0, "body": {"uncommitted": bool(isinstance(commits, dict) and commits.get("uncommitted"))}}) + dirty_sync_status, dirty_sync_body = step("sync with uncommitted changes", "POST", remix + "/remix/sync", "alice", {}) + dirty_upload_status, dirty_upload_body = step("sync upload with uncommitted changes", "POST", remix + "/upload", "alice", form=({"syncHead": upstream, "expectedHead": head}, {"project": plain, "mergeTree": zip_files({"original-notes.txt": b"x"})})) + steps.append({"step": "sync dirty refusals are enforced", "status": 0, "body": { + "prepareRefused": dirty_sync_status == 409 and isinstance(dirty_sync_body, dict) and dirty_sync_body.get("code") == "uncommitted_changes", + "uploadRefused": dirty_upload_status == 409 and isinstance(dirty_upload_body, dict) and dirty_upload_body.get("code") == "uncommitted_changes", + "publicStrangerSyncForbidden": public_stranger_sync_status == 403, + "closedOriginalSyncForbidden": closed_original_sync_status == 403, + "closedOriginalUploadForbidden": closed_original_upload_status == 403 and isinstance(closed_original_upload_body, dict) and "original" in str(closed_original_upload_body.get("error", "")), + }}) + + def normalize(value, ids, key="", parent=""): if isinstance(value, dict): return {("" if HEX.match(k) else k): normalize(v, ids, k, key) for k, v in sorted(value.items())} @@ -1060,6 +1288,7 @@ def step(name, method, path, who=None, body=None, upload=None, headers=(), form= slow_rotur_flow(server, step, steps, ids) slow_ledger_flow(server, step, steps, ids) locks_flow(server, step, steps, ids) + remix_sync_flow(server, step, steps, ids) time.sleep(1.5) for real, alias in list(ids.items()): if alias in ("", "", ""): @@ -1092,7 +1321,14 @@ def main(): with open(os.path.join(args.out, os.path.basename(binary) + ".json"), "w") as handle: handle.write(text) failures = [s for s in steps if s["status"] >= 500 and s["step"] not in EXPECTED_ERRORS] - print("%s: %d steps, %d server errors" % (binary, len(steps), len(failures))) + failed_checks = [s for s in steps if s["step"] in CHECK_STEPS and any(value is False for value in (s.get("body") or {}).values())] + missing_checks = CHECK_STEPS - {s["step"] for s in steps} + print("%s: %d steps, %d server errors, %d failed checks" % (binary, len(steps), len(failures), len(failed_checks) + len(missing_checks))) + for record in failed_checks: + print(" check failed: %s %s" % (record["step"], json.dumps(record.get("body"), sort_keys=True))) + for name in sorted(missing_checks): + print(" check missing: %s" % name) + failures = failures + failed_checks + [{"step": name} for name in missing_checks] for record in steps: print(" %3d %s" % (record["status"], record["step"])) broken = broken or bool(failures) diff --git a/src/git/pull-metadata.osl b/src/git/pull-metadata.osl index 7cab885..2d016f4 100644 --- a/src/git/pull-metadata.osl +++ b/src/git/pull-metadata.osl @@ -1,5 +1,6 @@ export { - canonicalHistoryHead + canonicalHistoryHead, + pullPreparedSourceHead } def storedPullCommentCount(object pull) number ( @@ -101,3 +102,58 @@ def canonicalHistoryHead(object metadata) string ( ) return "" ) + +def pullTargetBranchRefusalCode(string targetBranch, string currentBranch, array branchNames) string ( + if targetBranch == "" or targetBranch == currentBranch or branchNames.len == 0 ( + return "" + ) + for i branchNames.len ( + if branchNames[i].toStr() == targetBranch ( + return "target_branch_changed" + ) + ) + return "target_branch_missing" +) + +def pullCommitRecordedFor(object pull, boolean isTarget, boolean isSource, string sha) boolean ( + if sha == "" ( + return false + ) + if isTarget and ((pull.baseCommit ?? "").toStr() == sha or (pull.targetHead ?? "").toStr() == sha) ( + return true + ) + return isSource and ((pull.headCommit ?? "").toStr() == sha or (pull.preparedSourceHead ?? "").toStr() == sha) +) + +def pullPreparedSourceHead(object pull) string ( + string prepared = (pull.preparedSourceHead ?? "").toStr() + return if prepared != "" then prepared else (pull.headCommit ?? "").toStr() +) + +def pullSourceBranch(object pull, array branchNames) string ( + string recorded = (pull.sourceBranch ?? "").toStr() + if recorded != "" ( + return recorded + ) + if branchNames.len == 0 ( + return "main" + ) + if branchNames.len == 1 ( + return branchNames[1].toStr() + ) + return "" +) + +def livePullHeadFrom(object pull, string sourceBranch, string branchHead, string currentBranch, string currentHead) string ( + string stored = (pull.headCommit ?? "").toStr() + if (pull.state ?? "").toStr() != "open" or sourceBranch == "" ( + return stored + ) + if branchHead != "" ( + return branchHead + ) + if currentHead != "" and sourceBranch == currentBranch ( + return currentHead + ) + return stored +) diff --git a/src/git/pull-metadata.test.osl b/src/git/pull-metadata.test.osl index ea0a724..8c52921 100644 --- a/src/git/pull-metadata.test.osl +++ b/src/git/pull-metadata.test.osl @@ -23,3 +23,37 @@ object staleProject = { testing.assert(canonicalHistoryHead(staleProject) == branchHead, "the current branch tip wins over a stale stored head") testing.assert(canonicalHistoryHead({head: staleHead, branch: "main", graph: {branchLogs: [{branch: "main", oids: [branchHead]}]}}) == branchHead, "uploaded history uses its branch tip") testing.assert(canonicalHistoryHead({gitHead: staleHead}) == staleHead, "stored heads remain the fallback without branch metadata") + +object openPull = {state: "open", headCommit: staleHead, sourceBranch: "main"} +testing.assert(livePullHeadFrom(openPull, "main", branchHead, "main", branchHead) == branchHead, "open pulls follow the source branch tip") +testing.assert(livePullHeadFrom(openPull, "main", "", "main", branchHead) == branchHead, "open pulls fall back to the current head of the same branch") +testing.assert(livePullHeadFrom(openPull, "main", "", "other", branchHead) == staleHead, "a missing source branch keeps the recorded head") +testing.assert(livePullHeadFrom({state: "merged", headCommit: staleHead, sourceBranch: "main"}, "main", branchHead, "main", branchHead) == staleHead, "merged pulls keep the head they merged") +testing.assert(livePullHeadFrom({state: "closed", headCommit: staleHead}, "main", branchHead, "main", branchHead) == staleHead, "closed pulls keep their recorded head") +testing.assert(livePullHeadFrom(openPull, "", branchHead, "main", branchHead) == staleHead, "an unknown source branch keeps the recorded head") + +object legacyPull = {state: "open", headCommit: staleHead} +testing.assert(pullSourceBranch(openPull, ["main", "dev"]) == "main", "pulls name the branch they were opened from") +testing.assert(pullSourceBranch({state: "open", sourceBranch: "dev"}, ["main", "dev"]) == "dev", "pulls from another branch follow that branch") +testing.assert(pullSourceBranch(legacyPull, ["dev"]) == "dev", "legacy pulls from a one-branch remix follow that branch") +testing.assert(pullSourceBranch(legacyPull, []) == "main", "legacy pulls from a remix without branch metadata follow main") +testing.assert(pullSourceBranch(legacyPull, ["main", "dev"]) == "", "legacy pulls from a remix with several branches keep the recorded head") + +testing.assert(pullTargetBranchRefusalCode("main", "main", ["main", "dev"]) == "", "a project on the target branch can merge") +testing.assert(pullTargetBranchRefusalCode("dev", "main", ["main", "dev"]) == "target_branch_changed", "a project on another branch must switch first") +testing.assert(pullTargetBranchRefusalCode("dev", "main", ["main"]) == "target_branch_missing", "a deleted target branch stops the merge") +testing.assert(pullTargetBranchRefusalCode("dev", "main", []) == "", "projects without branch metadata merge as before") +testing.assert(pullTargetBranchRefusalCode("", "main", ["main"]) == "", "pulls without a recorded target branch merge as before") +testing.assert(pullPreparedSourceHead({headCommit: staleHead, preparedSourceHead: branchHead}) == branchHead, "older clients merge the head the server last prepared") +testing.assert(pullPreparedSourceHead({headCommit: staleHead}) == staleHead, "without a prepared head the recorded head is used") +testing.assert(pullPreparedSourceHead({headCommit: staleHead, preparedSourceHead: ""}) == staleHead, "an empty prepared head falls back to the recorded head") + +object readablePull = {baseCommit: "1" * 40, targetHead: "2" * 40, headCommit: "3" * 40, preparedSourceHead: "4" * 40} +testing.assert(pullCommitRecordedFor(readablePull, true, false, "1" * 40), "the target side serves the recorded base") +testing.assert(pullCommitRecordedFor(readablePull, true, false, "2" * 40), "the target side serves the recorded target head") +testing.assert(!pullCommitRecordedFor(readablePull, true, false, "3" * 40), "the target side does not serve the source head") +testing.assert(pullCommitRecordedFor(readablePull, false, true, "3" * 40), "the source side serves the recorded head") +testing.assert(pullCommitRecordedFor(readablePull, false, true, "4" * 40), "the source side serves the prepared head") +testing.assert(!pullCommitRecordedFor(readablePull, false, true, "1" * 40), "the source side does not serve the target base") +testing.assert(!pullCommitRecordedFor(readablePull, true, true, "5" * 40), "any other commit is not served") +testing.assert(!pullCommitRecordedFor({}, true, true, ""), "an empty sha is never served") diff --git a/src/git/pulls.osl b/src/git/pulls.osl index 82e62c0..505e796 100644 --- a/src/git/pulls.osl +++ b/src/git/pulls.osl @@ -1,7 +1,10 @@ export { canAccessPullWorkspace, + canInspectPullWithSource, completeNativePull, createNativePull, + livePullHead, + pullTargetBranchRefusal, projectBranchHead, projectGitHead, projectHasWorkspace, @@ -17,6 +20,57 @@ def projectHasWorkspace(object project) boolean ( return projectWorkspaceKeys(project).len > 0 and projectGitHead(project) != "" ) +def projectBranchNames(object project) array ( + object graph = projectVersionHistory(project).graph.assertElse(object, {}) + return if graph.contains("branches") then graph.branches.assertElse(array, []) else [] +) + +def livePullHead(object pull, object source) string ( + string sourceBranch = pullSourceBranch(pull, projectBranchNames(source)) + string currentBranch = if source.contains("gitBranch") and source.gitBranch != null and source.gitBranch.toStr() != "" then source.gitBranch.toStr() else "main" + string branchHead = if sourceBranch == "" then "" else projectBranchHead(source, sourceBranch) + return livePullHeadFrom(pull, sourceBranch, branchHead, currentBranch, projectGitHead(source)) +) + +def pullTargetBranch(object pull) string ( + return (pull.targetBranch ?? "").toStr() +) + +def pullTargetHead(object pull, object target) string ( + string branch = pullTargetBranch(pull) + string branchHead = if branch == "" then "" else projectBranchHead(target, branch) + if branchHead != "" ( + return branchHead + ) + if pullTargetBranchRefusalCode(branch, projectCurrentBranch(target), projectBranchNames(target)) == "target_branch_missing" ( + return "" + ) + return projectGitHead(target) +) + +def livePullBase(object pull, string targetWorkspacePath, string targetHead, string sourceWorkspacePath, string sourceHead) string ( + string stored = (pull.baseCommit ?? "").toStr() + if (pull.state ?? "").toStr() != "open" or targetHead == "" or sourceHead == "" ( + return stored + ) + auto parsed = json.parse(gitinspection.RemixMergeBase(targetWorkspacePath, targetHead, sourceWorkspacePath, sourceHead), {type: "object"}) + if parsed.isErr() ( + return stored + ) + object found = parsed.unwrap().assert(object) + if found.ok != true ( + return stored + ) + return (found.base ?? stored).toStr() +) + +def livePullResponse(object pull, string baseCommit, string headCommit) object ( + object response = pullResponse(pull) + response.baseCommit = baseCommit + response.headCommit = headCommit + return response +) + def pullDocument(string targetId, string index) object ( return (pullDocs.findById(targetId ++ ":" ++ index) ?? {}) ) @@ -89,12 +143,11 @@ def pullResponse(object pull) object ( } ) -def isPullSourceOwner(object pull,*serve.Context c) boolean ( +def isPullSourceOwnerWithSource(object pull, object source,*serve.Context c) boolean ( if !contextBool(c, "authenticated") ( return false ) - auto sourceResult = loadProject(pull.sourceProjectId.toStr()) - if sourceResult.ok and projectRole(sourceResult.project.assert(object), contextString(c, "username")) == "owner" ( + if source.len > 0 and projectRole(source, contextString(c, "username")) == "owner" ( return true ) return identityMatches( @@ -105,16 +158,28 @@ def isPullSourceOwner(object pull,*serve.Context c) boolean ( ) ) +def isPullSourceOwner(object pull,*serve.Context c) boolean ( + if !contextBool(c, "authenticated") ( + return false + ) + auto sourceResult = loadProject(pull.sourceProjectId.toStr()) + object source = if sourceResult.ok then sourceResult.project.assert(object) else {} + return isPullSourceOwnerWithSource(pull, source, c) +) + +def canClosePullWithSource(object pull, object target, object source,*serve.Context c) boolean ( + return canEditProject(target, c) or isPullSourceOwnerWithSource(pull, source, c) +) + def canClosePull(object pull, object target,*serve.Context c) boolean ( return canEditProject(target, c) or isPullSourceOwner(pull, c) ) -def canInspectPull(object pull, object target,*serve.Context c) boolean ( +def canInspectPullWithSource(object pull, object target, object source,*serve.Context c) boolean ( if !sourcePolicyAllowsViewer(target, c) or projectHiddenFrom(target, c) ( return false ) - auto sourceResult = loadProject(pull.sourceProjectId.toStr()) - if !sourceResult.ok or !sourcePolicyAllowsViewer(sourceResult.project.assert(object), c) or projectHiddenFrom(sourceResult.project.assert(object), c) ( + if source.len == 0 or !sourcePolicyAllowsViewer(source, c) or projectHiddenFrom(source, c) ( return false ) if canSeeInsideProject(target, c) ( @@ -123,7 +188,13 @@ def canInspectPull(object pull, object target,*serve.Context c) boolean ( if !contextBool(c, "authenticated") ( return false ) - return canEditProject(target, c) or isPullSourceOwner(pull, c) + return canEditProject(target, c) or isPullSourceOwnerWithSource(pull, source, c) +) + +def canInspectPull(object pull, object target,*serve.Context c) boolean ( + auto sourceResult = loadProject(pull.sourceProjectId.toStr()) + object source = if sourceResult.ok then sourceResult.project.assert(object) else {} + return canInspectPullWithSource(pull, target, source, c) ) def createNativePull(*serve.Context c, object target, object source, string title, string description, string bountyId) object ( @@ -477,6 +548,8 @@ def handleCreatePull(*serve.Context c) ( ) def handleGetPull(*serve.Context c) ( + c.setHeader("Cache-Control", "private, no-store") + c.setHeader("CDN-Cache-Control", "private, no-store") object pull = pullDocument(c.param("id"), c.param("index")) if pull.len == 0 ( c.notFound("pull request not found") @@ -489,8 +562,14 @@ def handleGetPull(*serve.Context c) ( ) object response = pullResponse(pull) object target = targetResult.project.assert(object) - response.canClose = canClosePull(pull, target, c) - response.canInspect = canInspectPull(pull, target, c) + auto sourceResult = loadProject(pull.sourceProjectId.toStr()) + object source = if sourceResult.ok then sourceResult.project.assert(object) else {} + response.canClose = canClosePullWithSource(pull, target, source, c) + response.canInspect = canInspectPullWithSource(pull, target, source, c) + response.baseBranchMissing = pullTargetBranchRefusalCode(pullTargetBranch(pull), projectCurrentBranch(target), projectBranchNames(target)) == "target_branch_missing" + if response.canInspect == true and source.len > 0 ( + response.headCommit = livePullHead(pull, source) + ) response.canMerge = canEditProject(target, c) and response.canInspect == true c.json(200, {ok: true, pull: response}) ) @@ -515,10 +594,14 @@ def handleGetPullTimeline(*serve.Context c) ( for i comments.len ( comments[i] = commentResponse(comments[i].assert(object), contextString(c, "username")) ) - array targetHistory = projectVersionHistory(target).commits.assert(array) - array sourceCommits = commitsAfter(projectVersionHistory(source).commits.assert(array), pull.baseCommit.toStr(), pull.created.toNum()) - sourceCommits = commitsNotIn(sourceCommits, targetHistory) - array targetCommits = commitsAfter(targetHistory, pull.targetHead.toStr(), pull.created.toNum()) + array sourceCommits = [] + array targetCommits = [] + if canInspectPullWithSource(pull, target, source, c) ( + array targetHistory = projectVersionHistory(target).commits.assert(array) + sourceCommits = commitsAfter(projectVersionHistory(source).commits.assert(array), pull.baseCommit.toStr(), pull.created.toNum()) + sourceCommits = commitsNotIn(sourceCommits, targetHistory) + targetCommits = commitsAfter(targetHistory, pull.targetHead.toStr(), pull.created.toNum()) + ) c.json(200, { ok: true, comments: comments, @@ -641,7 +724,7 @@ def handleEditPullComment(*serve.Context c) ( ) def canAccessPullWorkspace(object project, string pullIndex,*serve.Context c) boolean ( - if !sourcePolicyAllowsViewer(project, c) ( + if !sourcePolicyAllowsViewer(project, c) or !contextBool(c, "authenticated") ( return false ) array matches = [] @@ -658,15 +741,26 @@ def canAccessPullWorkspace(object project, string pullIndex,*serve.Context c) bo ) for i matches.len ( object pull = matches[i].assert(object) - boolean related = pull.sourceProjectId.toStr() == project.id.toStr() or pull.targetProjectId.toStr() == project.id.toStr() - if related ( - auto targetResult = loadProject(pull.targetProjectId.toStr()) - if targetResult.ok ( - object target = targetResult.project.assert(object) - if canInspectPull(pull, target, c) ( - return true + boolean isTarget = pull.targetProjectId.toStr() == project.id.toStr() + boolean isSource = pull.sourceProjectId.toStr() == project.id.toStr() + if isTarget or isSource ( + object target = project + boolean targetOk = true + if !isTarget ( + auto targetResult = loadProject(pull.targetProjectId.toStr()) + targetOk = targetResult.ok + if targetOk ( + target = targetResult.project.assert(object) ) ) + object source = project + if !isSource ( + auto sourceResult = loadProject(pull.sourceProjectId.toStr()) + source = if sourceResult.ok then sourceResult.project.assert(object) else {} + ) + if targetOk and canInspectPullWithSource(pull, target, source, c) and (canEditProject(target, c) or isPullSourceOwnerWithSource(pull, source, c)) ( + return true + ) ) ) return false @@ -680,17 +774,49 @@ def canAccessPullProjectCommit(object project, string targetId, string pullIndex if pull.len == 0 ( return false ) - boolean matchingTarget = pull.targetProjectId.toStr() == project.id.toStr() and (pull.baseCommit.toStr() == sha or pull.targetHead.toStr() == sha or projectRecordsCommit(project, sha)) - boolean matchingSource = pull.sourceProjectId.toStr() == project.id.toStr() and (pull.headCommit.toStr() == sha or projectRecordsCommit(project, sha)) - if !matchingTarget and !matchingSource ( + boolean isTarget = pull.targetProjectId.toStr() == project.id.toStr() + boolean isSource = pull.sourceProjectId.toStr() == project.id.toStr() + if !isTarget and !isSource ( return false ) - auto targetResult = loadProject(pull.targetProjectId.toStr()) - if !targetResult.ok ( + object target = project + if !isTarget ( + auto targetResult = loadProject(pull.targetProjectId.toStr()) + if !targetResult.ok ( + return false + ) + target = targetResult.project.assert(object) + ) + object source = project + if !isSource ( + auto sourceResult = loadProject(pull.sourceProjectId.toStr()) + if !sourceResult.ok ( + return false + ) + source = sourceResult.project.assert(object) + ) + if !canInspectPullWithSource(pull, target, source, c) ( return false ) - object target = targetResult.project.assert(object) - return canInspectPull(pull, target, c) + if pullCommitRecordedFor(pull, isTarget, isSource, sha) ( + return true + ) + if isSource ( + return livePullHead(pull, source) == sha + ) + return isLivePullBase(pull, target, source, sha) +) + +def isLivePullBase(object pull, object target, object source, string sha) boolean ( + if (pull.state ?? "").toStr() != "open" ( + return false + ) + string targetWorkspacePath = cachedProjectWorkspacePath(target) + string sourceWorkspacePath = cachedProjectWorkspacePath(source) + if targetWorkspacePath == "" or sourceWorkspacePath == "" ( + return false + ) + return livePullBase(pull, targetWorkspacePath, pullTargetHead(pull, target), sourceWorkspacePath, livePullHead(pull, source)) == sha ) def pullInspectionJSON(string view, string inline, string targetWorkspacePath, string baseCommit, string sourceWorkspacePath, string headCommit) string ( @@ -719,7 +845,7 @@ def handleGetPullDiff(*serve.Context c) ( ) object target = targetResult.project.assert(object) object source = sourceResult.project.assert(object) - if !canInspectPull(pull, target, c) ( + if !canInspectPullWithSource(pull, target, source, c) ( c.forbidden("only the fork owner and project maintainers can inspect this pull request") return ) @@ -729,8 +855,8 @@ def handleGetPullDiff(*serve.Context c) ( c.internalError("could not assemble pull request history") return ) - string baseCommit = pull.baseCommit.toStr() - string headCommit = pull.headCommit.toStr() + string headCommit = livePullHead(pull, source) + string baseCommit = livePullBase(pull, targetWorkspacePath, pullTargetHead(pull, target), sourceWorkspacePath, headCommit) string inspectionJson = pullInspectionJSON((c.query("view") ?? ""), (c.query("inline") ?? ""), targetWorkspacePath, baseCommit, sourceWorkspacePath, headCommit) auto parsedInspection = json.parse(inspectionJson, {type: "object"}) if parsedInspection.isErr() ( @@ -745,7 +871,7 @@ def handleGetPullDiff(*serve.Context c) ( string suffix = "?pull=" ++ pull.index.toStr() c.json(200, { ok: true, - pull: pullResponse(pull), + pull: livePullResponse(pull, baseCommit, headCommit), inspection: inspection, targetProjectId: target.id, sourceProjectId: source.id, @@ -755,6 +881,14 @@ def handleGetPullDiff(*serve.Context c) ( }) ) +def pullMergeRefusesBeforePrepare(object branchRefusal) boolean ( + return branchRefusal.len > 0 and (branchRefusal.code ?? "").toStr() != "target_branch_missing" +) + +def pullMergeAlreadyMerged(object prepared) boolean ( + return prepared.ok == true and (prepared.alreadyMerged ?? false) == true +) + def handleMergePull(*serve.Context c) ( object pull = pullDocument(c.param("id"), c.param("index")) if pull.len == 0 or pull.state.toStr() != "open" ( @@ -773,28 +907,48 @@ def handleMergePull(*serve.Context c) ( return ) object source = sourceResult.project.assert(object) - if !canInspectPull(pull, target, c) ( + if !canInspectPullWithSource(pull, target, source, c) ( c.forbidden("project source is restricted to its owner") return ) string currentTargetHead = projectGitHead(target) - string currentSourceHead = projectGitHead(source) - if currentTargetHead == pull.baseCommit.toStr() and currentSourceHead == pull.headCommit.toStr() ( - string targetWorkspacePath = cachedProjectWorkspacePath(target) - string sourceWorkspacePath = cachedProjectWorkspacePath(source) - if targetWorkspacePath == "" or sourceWorkspacePath == "" ( - c.internalError("could not assemble pull request history") - return - ) - string baseCommit = pull.baseCommit.toStr() - string headCommit = pull.headCommit.toStr() - string inspectionJson = gitinspection.CompareArchivesJSON(targetWorkspacePath, baseCommit, sourceWorkspacePath, headCommit) - auto parsedInspection = json.parse(inspectionJson, {type: "object"}) - if parsedInspection.isErr() or parsedInspection.unwrap().assert(object).ok != true ( - c.json(409, {ok: false, error: "the pull request history is unavailable", code: "pull_history_unavailable"}) + object branchRefusal = pullTargetBranchRefusal(pull, target) + if pullMergeRefusesBeforePrepare(branchRefusal) ( + c.json(409, branchRefusal) + return + ) + string sourceHead = livePullHead(pull, source) + string targetWorkspacePath = cachedProjectWorkspacePath(target) + string sourceWorkspacePath = cachedProjectWorkspacePath(source) + if targetWorkspacePath == "" or sourceWorkspacePath == "" ( + if branchRefusal.len > 0 ( + c.json(409, branchRefusal) return ) - object merged = fastForwardPullLocked(c, pull, target, source, targetWorkspacePath, sourceWorkspacePath, currentTargetHead, currentSourceHead) + c.internalError("could not assemble pull request history") + return + ) + object prepared = preparePullMerge(pull, targetWorkspacePath, currentTargetHead, sourceWorkspacePath, sourceHead) + if pullMergeAlreadyMerged(prepared) ( + closeAlreadyMergedPullLocked(c, pull, target.id.toStr(), currentTargetHead, sourceHead) + return + ) + if branchRefusal.len > 0 ( + c.json(409, branchRefusal) + return + ) + if prepared.ok != true ( + c.json(409, {ok: false, error: prepared.error.toStr(), code: "pull_merge_unavailable"}) + return + ) + object merge = prepared + if projectUncommittedSummary(target).len > 0 ( + c.json(409, {ok: false, error: "Commit the changes saved in this project before merging this pull request.", code: "uncommitted_changes"}) + return + ) + boolean sourceClean = projectUncommittedSummary(source).len == 0 + if (merge.fastForward ?? false) == true and sourceClean and sourceHead == projectGitHead(source) ( + object merged = fastForwardPullLocked(c, pull, target, source, targetWorkspacePath, sourceWorkspacePath, currentTargetHead, sourceHead) if merged.ok != true ( return ) @@ -811,34 +965,92 @@ def handleMergePull(*serve.Context c) ( removeProjectStorageKeyIfOrphaned(previousWorkspaceKey, target.id.toStr(), true) ) ) - c.json(200, {ok: true, merged: true, fastForward: false, pull: pullResponse(pullDocument(target.id.toStr(), pull.index.toStr())), head: projectGitHead(target)}) - return - ) - string targetWorkspacePath = cachedProjectWorkspacePath(target) - string sourceWorkspacePath = cachedProjectWorkspacePath(source) - if targetWorkspacePath == "" or sourceWorkspacePath == "" ( - c.internalError("could not assemble pull request history") - return - ) - string sourceHead = pull.headCommit.toStr() - string baseHead = pull.baseCommit.toStr() - string mergeJson = gitinspection.PrepareMergeJSON(targetWorkspacePath, currentTargetHead, sourceWorkspacePath, sourceHead, baseHead) - auto parsedMerge = json.parse(mergeJson, {type: "object"}) - if parsedMerge.isErr() or parsedMerge.unwrap().assert(object).ok != true ( - c.json(409, {ok: false, error: "the pull request could not be merged on the server", code: "pull_merge_unavailable"}) + c.json(200, {ok: true, merged: true, fastForward: true, pull: pullResponse(pullDocument(target.id.toStr(), pull.index.toStr())), head: projectGitHead(target)}) return ) + recordPreparedPullHead(target.id.toStr(), pull.index.toStr(), sourceHead) c.json(200, { ok: true, merged: false, - pull: pullResponse(pull), - merge: parsedMerge.unwrap(), + pull: livePullResponse(pull, (merge.baseHead ?? pull.baseCommit ?? "").toStr(), sourceHead), + merge: merge, expectedHead: currentTargetHead, + sourceHead: sourceHead, targetProjectId: target.id, sourceProjectId: source.id }) ) +def projectCurrentBranch(object project) string ( + return if project.contains("gitBranch") and project.gitBranch != null and project.gitBranch.toStr() != "" then project.gitBranch.toStr() else "main" +) + +def pullTargetBranchRefusal(object pull, object target) object ( + string targetBranch = pullTargetBranch(pull) + string code = pullTargetBranchRefusalCode(targetBranch, projectCurrentBranch(target), projectBranchNames(target)) + if code == "target_branch_changed" ( + return {ok: false, error: "Switch this project to the " ++ targetBranch ++ " branch before merging this pull request.", code: code, branch: targetBranch} + ) + if code == "target_branch_missing" ( + return {ok: false, error: "This pull request targets the " ++ targetBranch ++ " branch, which no longer exists.", code: code, branch: targetBranch} + ) + return {} +) + +def recordPreparedPullHead(string targetId, string pullIndex, string sourceHead) ( + string saveLock = "project-history-" ++ targetId + sync.lock(saveLock) + defer sync.unlock(saveLock) + string pullLock = "pull-comment-count:" ++ targetId ++ ":" ++ pullIndex + sync.lock(pullLock) + defer sync.unlock(pullLock) + object latest = pullDocument(targetId, pullIndex) + if latest.len == 0 or (latest.state ?? "").toStr() != "open" or (latest.preparedSourceHead ?? "").toStr() == sourceHead ( + return + ) + latest.preparedSourceHead = sourceHead + putDocument(pullDocs, latest["_id"].toStr(), latest) +) + +def closeAlreadyMergedPullLocked(*serve.Context c, object pull, string targetId, string expectedHead, string sourceHead) ( + string saveLock = "project-history-" ++ targetId + sync.lock(saveLock) + defer sync.unlock(saveLock) + auto latestResult = loadProject(targetId) + if !latestResult.ok or projectGitHead(latestResult.project.assert(object)) != expectedHead ( + c.json(409, {ok: false, error: "This project changed while the merge was processing. Merge again to include the latest changes.", code: "head_changed"}) + return + ) + object latest = latestResult.project.assert(object) + if !completeNativePull(latest, pull.index.toStr(), expectedHead, sourceHead, canEditProject(latest, c)) ( + if (pullDocument(targetId, pull.index.toStr()).state ?? "").toStr() == "open" ( + c.internalError("these changes are already in this project, but the pull request could not be closed") + return + ) + c.json(409, {ok: false, error: "the pull request is no longer open", code: "pull_not_open"}) + return + ) + c.json(200, {ok: true, merged: true, alreadyMerged: true, pull: pullResponse(pullDocument(targetId, pull.index.toStr())), head: expectedHead}) +) + +def preparePullMerge(object pull, string targetWorkspacePath, string targetHead, string sourceWorkspacePath, string sourceHead) object ( + string fallback = "the pull request could not be merged on the server" + auto parsed = json.parse(gitinspection.PrepareRemixMergeJSON(targetWorkspacePath, targetHead, sourceWorkspacePath, sourceHead, "target", "pull request"), {type: "object"}) + if !parsed.isErr() and parsed.unwrap().assert(object).ok == true ( + return parsed.unwrap().assert(object) + ) + string failureMessage = if parsed.isErr() then fallback else (parsed.unwrap().assert(object).error ?? fallback).toStr() + string storedBase = (pull.baseCommit ?? "").toStr() + if !validGitObjectId(storedBase) ( + return {ok: false, error: failureMessage} + ) + auto storedParsed = json.parse(gitinspection.PrepareMergeJSON(targetWorkspacePath, targetHead, sourceWorkspacePath, sourceHead, storedBase), {type: "object"}) + if storedParsed.isErr() or storedParsed.unwrap().assert(object).ok != true ( + return {ok: false, error: failureMessage} + ) + return storedParsed.unwrap().assert(object) +) + def fastForwardPullLocked(*serve.Context c, object pull, object target, object source, string targetWorkspacePath, string sourceWorkspacePath, string currentTargetHead, string currentSourceHead) object ( string lockName = "project-history-" ++ target.id.toStr() sync.lock(lockName) @@ -851,6 +1063,10 @@ def fastForwardPullLocked(*serve.Context c, object pull, object target, object s ) target = latestTargetResult.project.assert(object) source = latestSourceResult.project.assert(object) + if projectUncommittedSummary(target).len > 0 or projectUncommittedSummary(source).len > 0 ( + c.json(409, {ok: false, error: "Commit the changes saved in this project before merging this pull request.", code: "uncommitted_changes"}) + return {ok: false} + ) object sourceJsonSnapshot = ensureProjectJsonSnapshot(source) if !sourceJsonSnapshot.ok ( c.internalError("could not prepare the source project") @@ -938,7 +1154,7 @@ def fastForwardPullLocked(*serve.Context c, object pull, object target, object s ) upsertIndexEntry(target) storageSettleProject(target) - if !completeNativePull(target, pull.index.toStr(), currentTargetHead, contextString(c, "username")) ( + if !completeNativePull(target, pull.index.toStr(), currentTargetHead, currentSourceHead, canEditProject(target, c)) ( c.internalError("the project merged, but the pull request could not be closed") return {ok: false} ) @@ -961,34 +1177,65 @@ def handleClosePull(*serve.Context c) ( c.forbidden("only the fork owner and project maintainers can close this pull request") return ) - pull.state = "closed" - pull.updated = timestamp - if !putDocument(pullDocs, pull["_id"].toStr(), pull) ( + object closed = closePullLocked(target.id.toStr(), pull.index.toStr()) + if (closed.writeFailed ?? false) == true ( c.internalError("could not close pull request") return ) - object response = pullResponse(pull) + if closed.len == 0 ( + c.json(409, {ok: false, error: "the pull request is no longer open", code: "pull_not_open"}) + return + ) + object response = pullResponse(closed) response.canClose = true response.canMerge = canEditProject(target, c) c.json(200, {ok: true, pull: response}) ) -def completeNativePull(object project, string pullIndex, string expectedHead, string username) boolean ( - object pull = pullDocument(project.id.toStr(), pullIndex) - if pull.len == 0 or pull.state.toStr() != "open" ( - return false +def closePullLocked(string targetId, string pullIndex) object ( + string pullLock = "pull-comment-count:" ++ targetId ++ ":" ++ pullIndex + sync.lock(pullLock) + defer sync.unlock(pullLock) + object latest = pullDocument(targetId, pullIndex) + if latest.len == 0 or (latest.state ?? "").toStr() != "open" ( + return {} ) - string role = projectRole(project, username) - if role != "owner" and role != "maintainer" ( - return false + latest.state = "closed" + latest.updated = timestamp + if !putDocument(pullDocs, latest["_id"].toStr(), latest) ( + return {writeFailed: true} ) - if expectedHead == "" ( - return false + return latest +) + +def markPullMergedLocked(object project, string pullIndex, string mergedHead) object ( + string pullLock = "pull-comment-count:" ++ project.id.toStr() ++ ":" ++ pullIndex + sync.lock(pullLock) + defer sync.unlock(pullLock) + object pull = pullDocument(project.id.toStr(), pullIndex) + if pull.len == 0 or (pull.state ?? "").toStr() != "open" ( + return {} ) pull.state = "merged" pull.mergedCommit = projectGitHead(project) + if mergedHead != "" ( + pull.headCommit = mergedHead + ) pull.updated = timestamp - putDocument(pullDocs, pull["_id"].toStr(), pull) + if !putDocument(pullDocs, pull["_id"].toStr(), pull) ( + return {} + ) + return pull +) + +def completeNativePull(object project, string pullIndex, string expectedHead, string mergedHead, boolean canMerge) boolean ( + if !canMerge or expectedHead == "" ( + return false + ) + object pull = markPullMergedLocked(project, pullIndex, mergedHead) + if pull.len == 0 ( + return false + ) number acceptedChanges = 0 if project.contains("acceptedChanges") and project.acceptedChanges != null ( diff --git a/src/git/pulls.test.osl b/src/git/pulls.test.osl index 83a7025..c365856 100644 --- a/src/git/pulls.test.osl +++ b/src/git/pulls.test.osl @@ -36,6 +36,18 @@ def lockIsFree(string lockName) boolean ( def canonicalHistoryHead(object project) string ( return (project.gitHead ?? "").toStr() ) +def livePullHeadFrom(object pull, string sourceBranch, string branchHead, string currentBranch, string currentHead) string ( + return (pull.headCommit ?? "").toStr() +) +def pullTargetBranchRefusalCode(string targetBranch, string currentBranch, array branchNames) string ( + return "" +) +def pullCommitRecordedFor(object pull, boolean isTarget, boolean isSource, string sha) boolean ( + return false +) +def pullSourceBranch(object pull, array branchNames) string ( + return (pull.sourceBranch ?? "main").toStr() +) def storedPullCommentCount(object pull) number ( return if pull.contains("commentCount") then pull.commentCount.toNum() else -1 ) @@ -170,9 +182,6 @@ def ensureProjectJsonSnapshot(object project) object ( def ensureProjectWorkspaceSnapshots(object project) object ( return {} ) -def projectRecordsCommit(object project, string sha) boolean ( - return false -) def projectSizeBytes(object project) number ( return 0 ) @@ -218,6 +227,38 @@ testing.assert(try(countCreated()).isErr() and lockIsFree("pull-comment-count:p1 testing.assert(try(countDeleted()).isErr() and lockIsFree("pull-comment-count:p1:1"), "the comment count lock is released when counting a deleted comment throws") failing = false +string pullBaseA = "a" * 40 +string pullBaseB = "b" * 40 +object closedForBase = {state: "closed", baseCommit: pullBaseA} +testing.assert(livePullBase(closedForBase, "", pullBaseB, "", pullBaseB) == pullBaseA, "closed pulls keep their recorded base") +testing.assert(livePullBase({state: "open", baseCommit: pullBaseA}, "", "", "", pullBaseB) == pullBaseA, "a missing target head keeps the recorded base") +testing.assert(livePullBase({state: "open", baseCommit: pullBaseA}, tmpDir ++ "none.mwp", pullBaseB, tmpDir ++ "none.mwp", pullBaseB) == pullBaseA, "unreadable histories keep the recorded base") +testing.assert(livePullBase({state: "open"}, "", "", "", "") == "", "a pull without a base reports none rather than null") + +object openForMerge = {"_id": "p9:1", targetProjectId: "p9", index: 1, state: "open", headCommit: pullBaseA, sourceOwner: "mist"} +void putDocument(pullDocs, "p9:1", openForMerge) +recordPreparedPullHead("p9", "1", pullBaseB) +testing.assert(pullDocument("p9", "1").preparedSourceHead == pullBaseB and lockIsFree("project-history-p9"), "a prepared merge records the remix head it used") +testing.assert(!completeNativePull({id: "p9", gitHead: pullBaseB}, "1", pullBaseA, pullBaseB, false), "only people who can edit the project can complete a pull") +testing.assert(completeNativePull({id: "p9", gitHead: pullBaseB}, "1", pullBaseA, pullBaseB, true), "an editor completes the pull") +object mergedPull = pullDocument("p9", "1") +testing.assert(mergedPull.state == "merged" and mergedPull.headCommit == pullBaseB and mergedPull.mergedCommit == pullBaseB and lockIsFree("pull-comment-count:p9:1"), "a completed pull records the merged remix head and the merge commit") +testing.assert(!completeNativePull({id: "p9", gitHead: pullBaseB}, "1", pullBaseA, pullBaseB, true), "a pull is only completed once") +testing.assert(closePullLocked("p9", "1").len == 0 and pullDocument("p9", "1").state == "merged" and lockIsFree("pull-comment-count:p9:1"), "closing a merged pull leaves it merged") +object openToClose = {"_id": "p9:2", targetProjectId: "p9", index: 2, state: "open", headCommit: pullBaseA} +void putDocument(pullDocs, "p9:2", openToClose) +testing.assert(closePullLocked("p9", "2").state == "closed" and pullDocument("p9", "2").state == "closed" and lockIsFree("pull-comment-count:p9:2"), "an open pull closes") +testing.assert(!completeNativePull({id: "p9", gitHead: pullBaseB}, "2", pullBaseA, pullBaseB, true), "a closed pull cannot be merged") +recordPreparedPullHead("p9", "1", pullBaseA) +testing.assert(pullDocument("p9", "1").preparedSourceHead == pullBaseB, "a merged pull keeps its prepared head") + +testing.assert(!pullMergeRefusesBeforePrepare({}), "an empty target branch refusal allows preparePullMerge") +testing.assert(pullMergeRefusesBeforePrepare({code: "target_branch_changed"}), "target_branch_changed refuses before preparePullMerge") +testing.assert(!pullMergeRefusesBeforePrepare({code: "target_branch_missing"}), "target_branch_missing defers refusal until after preparePullMerge checks alreadyMerged") +testing.assert(pullMergeAlreadyMerged({ok: true, alreadyMerged: true}), "an already-merged preparation is recognized") +testing.assert(!pullMergeAlreadyMerged({ok: true, alreadyMerged: false}), "a non-merged preparation is not treated as already merged") +testing.assert(!pullMergeAlreadyMerged({ok: false, alreadyMerged: true}), "a failed preparation is not treated as already merged") + def handleTestMerge(*serve.Context c) ( void fastForwardPullLocked(c, {index: 1}, {id: "p1"}, {id: "p2"}, "", "", "h1", "h2") ) diff --git a/src/git/remix-sync.osl b/src/git/remix-sync.osl new file mode 100644 index 0000000..5c914a5 --- /dev/null +++ b/src/git/remix-sync.osl @@ -0,0 +1,81 @@ +export { + canSyncRemixFrom, + loadRemixSyncOriginal, + remixHasUncommittedChanges +} + +def remixHasUncommittedChanges(object project) boolean ( + return projectUncommittedSummary(project).len > 0 +) + +def loadRemixSyncOriginal(object project) object? ( + string parentId = if project.contains("remixParent") and project.remixParent != null then project.remixParent.toStr() else "" + if parentId == "" or parentId == project.id.toStr() ( + return null + ) + auto parentResult = loadProject(parentId) + if !parentResult.ok ( + return null + ) + return parentResult.project.assert(object) +) + +def canSyncRemixFrom(object project, object original,*serve.Context c) boolean ( + if !canEditProject(project, c) or !canSeeInsideProject(project, c) ( + return false + ) + return canViewProject(original, c) and canSeeInsideProject(original, c) +) + +def handlePrepareRemixSync(*serve.Context c) ( + c.setHeader("Cache-Control", "private, no-store") + c.setHeader("CDN-Cache-Control", "private, no-store") + auto res = loadProject(c.param("id")) + if !res.ok or !canViewProject(res.project.assert(object), c) ( + c.notFound("project not found") + return + ) + object project = res.project.assert(object) + object? original = loadRemixSyncOriginal(project) + if original == null ( + c.notFound("this project is not a remix of a project that still exists") + return + ) + if !canSyncRemixFrom(project, original, c) ( + c.forbidden("only the remix's maintainers can sync it, and only while they can see inside the original") + return + ) + string projectHead = projectGitHead(project) + string originalHead = projectGitHead(original) + if projectHead == "" or originalHead == "" ( + c.json(409, {ok: false, error: "both projects need MistWarp history before they can be synced", code: "sync_history_unavailable"}) + return + ) + if remixHasUncommittedChanges(project) ( + c.json(409, {ok: false, error: "commit the changes saved in this remix before syncing it with the original", code: "uncommitted_changes"}) + return + ) + string projectWorkspacePath = cachedProjectWorkspacePath(project) + string originalWorkspacePath = cachedProjectWorkspacePath(original) + if projectWorkspacePath == "" or originalWorkspacePath == "" ( + c.internalError("could not assemble project history") + return + ) + string mergeJson = gitinspection.PrepareRemixMergeJSON(projectWorkspacePath, projectHead, originalWorkspacePath, originalHead, "this remix", "original") + auto parsedMerge = json.parse(mergeJson, {type: "object"}) + if parsedMerge.isErr() or parsedMerge.unwrap().assert(object).ok != true ( + string message = if parsedMerge.isErr() then "could not prepare the sync" else (parsedMerge.unwrap().assert(object).error ?? "could not prepare the sync").toStr() + c.json(409, {ok: false, error: message, code: "sync_unavailable"}) + return + ) + c.json(200, { + ok: true, + merge: parsedMerge.unwrap(), + targetProjectId: project.id, + sourceProjectId: original.id, + sourceTitle: original.title, + sourceHead: originalHead, + targetHead: projectHead, + expectedHead: projectHead + }) +) diff --git a/src/git/remix-sync.test.osl b/src/git/remix-sync.test.osl new file mode 100644 index 0000000..fc53f48 --- /dev/null +++ b/src/git/remix-sync.test.osl @@ -0,0 +1,88 @@ +import "std:testing" +import "std:json" +import "std:requests" +import "std:serve" +import "std:thread" +import "go:mistwarp.local/gitinspection" + +object projects = { + plain: {id: "plain", viewable: true, editable: true, seeInside: true, gitHead: "h-plain"}, + orphan: {id: "orphan", remixParent: "gone", viewable: true, editable: true, seeInside: true, gitHead: "h-orphan"}, + hidden: {id: "hidden", remixParent: "original", viewable: false, editable: true, seeInside: true, gitHead: "h-hidden"}, + viewer: {id: "viewer", remixParent: "original", viewable: true, editable: false, seeInside: true, gitHead: "h-viewer"}, + locked: {id: "locked", remixParent: "secret", viewable: true, editable: true, seeInside: true, gitHead: "h-locked"}, + fresh: {id: "fresh", remixParent: "original", viewable: true, editable: true, seeInside: true, gitHead: ""}, + dirty: {id: "dirty", remixParent: "original", viewable: true, editable: true, seeInside: true, gitHead: "h-dirty", uncommitted: {files: 2}}, + clean: {id: "clean", remixParent: "original", viewable: true, editable: true, seeInside: true, gitHead: "h-clean"}, + self: {id: "self", remixParent: "self", viewable: true, editable: true, seeInside: true, gitHead: "h-self"}, + original: {id: "original", title: "Space Cat", viewable: true, editable: false, seeInside: true, gitHead: "h-original"}, + secret: {id: "secret", title: "Secret", viewable: true, editable: false, seeInside: false, gitHead: "h-secret"} +} + +def loadProject(string id) object ( + if !projects.contains(id) ( + return {ok: false, missing: true} + ) + return {ok: true, project: projects[id]} +) +def canViewProject(object project,*serve.Context c) boolean ( + return project.viewable == true +) +def canEditProject(object project,*serve.Context c) boolean ( + return project.editable == true +) +def canSeeInsideProject(object project,*serve.Context c) boolean ( + return project.seeInside == true +) +def projectUncommittedSummary(object project) object ( + return (project.uncommitted ?? {}).assertElse(object, {}) +) +def projectGitHead(object project) string ( + return (project.gitHead ?? "").toStr() +) +def cachedProjectWorkspacePath(object project) string ( + return "" +) + +import "./remix-sync.osl" + +testing.assert(loadRemixSyncOriginal(projects.plain) == null, "a project that is not a remix has no original") +testing.assert(loadRemixSyncOriginal(projects.orphan) == null, "a remix of a deleted project has no original") +testing.assert(loadRemixSyncOriginal(projects.self) == null, "a project cannot be its own original") +testing.assert(loadRemixSyncOriginal(projects.clean).id == "original", "a remix loads its original") +testing.assert(remixHasUncommittedChanges(projects.dirty) and !remixHasUncommittedChanges(projects.clean), "uncommitted changes are detected") + +*serve.Router app = serve.new() +app.POST("/projects/:id/remix/sync", handlePrepareRemixSync) +app.GET("/ready", def(*serve.Context c) -> ( + c.json(200, {ok: true}) +)) +def runApp() ( + app.run(":18363") +) +thread.new(runApp) +string base = "http://127.0.0.1:18363" +for i 50 ( + if requests.get(base ++ "/ready").isOk() ( + break + ) + wait 0.1 +) + +def syncResponse(string id) object ( + object response = requests.post(base ++ "/projects/" ++ id ++ "/remix/sync", {body: "{}"}).unwrapOr({status: 0, body: "{}"}) + object body = json.parse(response.body.toStr(), {type: "object"}).unwrapOr({}).assertElse(object, {}) + return {status: response.status.toNum(), code: (body.code ?? "").toStr()} +) + +testing.assert(syncResponse("missing").status == 404, "a missing project cannot sync") +testing.assert(syncResponse("hidden").status == 404, "a project the viewer cannot see answers as missing") +testing.assert(syncResponse("plain").status == 404, "a project that is not a remix cannot sync") +testing.assert(syncResponse("orphan").status == 404, "a remix of a deleted project cannot sync") +testing.assert(syncResponse("viewer").status == 403, "only maintainers of the remix can sync it") +testing.assert(syncResponse("locked").status == 403, "a remix cannot pull in an original the viewer cannot see inside") +object fresh = syncResponse("fresh") +testing.assert(fresh.status == 409 and fresh.code == "sync_history_unavailable", "a remix without history cannot sync") +object dirty = syncResponse("dirty") +testing.assert(dirty.status == 409 and dirty.code == "uncommitted_changes", "a remix with uncommitted changes cannot sync") +testing.assert(syncResponse("clean").status == 500, "a clean remix reaches the history merge") diff --git a/src/git/routes.osl b/src/git/routes.osl index ef9ed2e..686ab7c 100644 --- a/src/git/routes.osl +++ b/src/git/routes.osl @@ -11,6 +11,7 @@ def registerGitRoutes(*serve.Router api) ( api.PATCH("/projects/:id/branches", requireAuth, handleRenameProjectBranch) api.DELETE("/projects/:id/branches", requireAuth, handleDeleteProjectBranch) api.POST("/projects/:id/branches/merge", requireAuth, handlePrepareBranchMerge) + api.POST("/projects/:id/remix/sync", requireAuth, handlePrepareRemixSync) api.GET("/projects/:id/commits/:sha", handleGetCommitInspection) api.GET("/projects/:id/commits/:sha/changes", handleGetCommitChanges) diff --git a/src/projects/project-upload-history.osl b/src/projects/project-upload-history.osl index 6a594a7..cdfaf20 100644 --- a/src/projects/project-upload-history.osl +++ b/src/projects/project-upload-history.osl @@ -75,7 +75,15 @@ def unchangedVersionCheck(object project, UploadRequest request, UploadHistory h return noRefusal() ) -def createMergeCommit(object project, UploadRequest request, UploadHistory history, UploadArchive archive, string uploader) Refusal ( +def createMergeCommit(*serve.Context c, object project, UploadRequest request, UploadHistory history, UploadArchive archive, string uploader) Refusal ( + Refusal syncTree = remixSyncTreeRefusal(request, history) + if isRefused(syncTree) ( + return syncTree + ) + Refusal pullShape = pullUploadShapeRefusal(request, history) + if isRefused(pullShape) ( + return pullShape + ) if !needsMergeCommit(request, history) ( return noRefusal() ) @@ -83,24 +91,56 @@ def createMergeCommit(object project, UploadRequest request, UploadHistory histo object mergeSource = project string mergeSourceHead = request.mergeSourceHead string mergeTargetHead = request.mergeTargetHead + string mergeMessage = mergeCommitMessage(request, branchMerge) if branchMerge ( Refusal branchChanged = branchMergeRefusal(request, projectBranchHead(project, request.mergeSourceBranch), projectBranchHead(project, request.mergeTargetBranch)) if isRefused(branchChanged) ( return branchChanged ) history.baseHead = mergeTargetHead + ) else if isRemixSync(request) ( + object? loadedOriginal = loadRemixSyncOriginal(project) + object original = if loadedOriginal != null then loadedOriginal else {} + Refusal syncRefusal = remixSyncMergeRefusal(request, loadedOriginal != null, loadedOriginal != null and canSyncRemixFrom(project, original, c), projectGitHead(original)) + if isRefused(syncRefusal) ( + return syncRefusal + ) + mergeSource = original + mergeSourceHead = request.syncHead + mergeTargetHead = history.currentHead + mergeMessage = remixSyncCommitMessage((original.title ?? "").toStr()) ) else ( object mergePull = pullDocument(project.id.toStr(), request.pullId) Refusal pullClosed = pullMergeRefusal(request, mergePull, project.id.toStr()) if isRefused(pullClosed) ( return pullClosed ) + Refusal pullHead = pullExpectedHeadRefusal(request) + if isRefused(pullHead) ( + return pullHead + ) + if projectUncommittedSummary(project).len > 0 ( + return refuseWithBody(409, {ok: false, error: "Commit the changes saved in this project before merging this pull request.", code: "uncommitted_changes"}) + ) auto mergeSourceResult = loadProject(mergePull.sourceProjectId.toStr()) if !mergeSourceResult.ok ( return refuse(404, "merge source project not found") ) mergeSource = mergeSourceResult.project.assert(object) - mergeSourceHead = mergePull.headCommit.toStr() + if !canInspectPullWithSource(mergePull, project, mergeSource, c) ( + return refuse(403, "source code is not visible") + ) + object branchRefusal = pullTargetBranchRefusal(mergePull, project) + if branchRefusal.len > 0 ( + return refuseWithBody(409, branchRefusal) + ) + string liveSourceHead = livePullHead(mergePull, mergeSource) + Refusal sourceMoved = pullSourceHeadRefusal(request, liveSourceHead, pullPreparedSourceHead(mergePull)) + if isRefused(sourceMoved) ( + return sourceMoved + ) + mergeSourceHead = liveSourceHead + request.mergedPullHead = liveSourceHead mergeTargetHead = history.currentHead ) if !isSafeHistoryArchive(history.mergeTree, archive, false) ( @@ -118,7 +158,7 @@ def createMergeCommit(object project, UploadRequest request, UploadHistory histo number mergeTimestamp = timestamp string mergeJson = "" if mergeReady ( - mergeJson = gitinspection.CreateMergeArchiveJSON(mergeTargetPath, mergeTargetHead, mergeSourcePath, mergeSourceHead, mergeTreePath, mergeDeltaPath, identity.projectId, identity.remixParent, identity.baseCommit, mergeBranch, uploader, mergeCommitMessage(request, branchMerge), mergeTimestamp / 1000) + mergeJson = gitinspection.CreateMergeArchiveJSON(mergeTargetPath, mergeTargetHead, mergeSourcePath, mergeSourceHead, mergeTreePath, mergeDeltaPath, identity.projectId, identity.remixParent, identity.baseCommit, mergeBranch, uploader, mergeMessage, mergeTimestamp / 1000) ) object merged = parsedGeneratedHistory(mergeJson) if !mergeReady or merged.len == 0 ( diff --git a/src/projects/project-upload-policy.osl b/src/projects/project-upload-policy.osl index 549e6fe..2d51a2b 100644 --- a/src/projects/project-upload-policy.osl +++ b/src/projects/project-upload-policy.osl @@ -11,6 +11,8 @@ class UploadRequest ( string mergeTargetBranch = "" string mergeSourceHead = "" string mergeTargetHead = "" + string syncHead = "" + string mergedPullHead = "" string git = "" string extensions = "" string workspaceToken = "" @@ -46,7 +48,7 @@ def liveContributorRefusal(UploadRequest request, boolean canEdit) Refusal ( if canEdit ( return noRefusal() ) - if request.expectedEdited == "" or request.restoreCommit != "" or request.pullId != "" or request.mergeSourceBranch != "" or request.replaceHistory ( + if request.expectedEdited == "" or request.restoreCommit != "" or request.pullId != "" or request.mergeSourceBranch != "" or request.syncHead != "" or request.replaceHistory ( return refuse(403, "live contributors can save the current project; history and publishing require a maintainer") ) return noRefusal() @@ -59,7 +61,7 @@ def staleUploadRefusal(UploadRequest request, object project, string currentHead if request.expectedHead != "" and request.expectedHead != currentHead ( return refuseWithBody(409, {ok: false, error: "the project changed while you were merging", code: "head_changed", currentHead: currentHead}) ) - if request.replaceHistory and (request.expectedHead != currentHead or request.restoreCommit != "" or request.pullId != "" or request.mergeSourceBranch != "") ( + if request.replaceHistory and (request.expectedHead != currentHead or request.restoreCommit != "" or request.pullId != "" or request.mergeSourceBranch != "" or request.syncHead != "") ( return refuseWithBody(409, {ok: false, error: "history replacement requires the current saved head and a full workspace", code: "head_changed"}) ) return noRefusal() @@ -135,6 +137,74 @@ def branchMergeRefusal(UploadRequest request, string latestSourceHead, string la return noRefusal() ) +def isRemixSync(UploadRequest request) boolean ( + return request.syncHead != "" +) + +def remixSyncRequestRefusal(UploadRequest request) Refusal ( + if !isRemixSync(request) ( + return noRefusal() + ) + if request.pullId != "" or request.mergeSourceBranch != "" or request.restoreCommit != "" or request.replaceHistory ( + return refuse(400, "a sync with the original project cannot be combined with another merge") + ) + if request.expectedHead == "" ( + return refuseWithBody(409, {ok: false, error: "refresh the project before syncing it with the original", code: "head_changed"}) + ) + return noRefusal() +) + +def remixSyncTreeRefusal(UploadRequest request, UploadHistory history) Refusal ( + if isRemixSync(request) and (!history.hasMergeTree or history.hasWorkspace) ( + return refuse(400, "a sync with the original project needs the merged project tree") + ) + return noRefusal() +) + +def pullUploadShapeRefusal(UploadRequest request, UploadHistory history) Refusal ( + if request.pullId != "" and (!history.hasMergeTree or history.hasWorkspace or request.restoreCommit != "" or request.mergeSourceBranch != "" or request.mergeTargetBranch != "") ( + return refuse(400, "a pull request merge needs the merged project tree and nothing else") + ) + return noRefusal() +) + +def pullExpectedHeadRefusal(UploadRequest request) Refusal ( + if request.pullId != "" and request.expectedHead == "" ( + return refuseWithBody(409, {ok: false, error: "refresh the project before merging this pull request", code: "head_changed"}) + ) + return noRefusal() +) + +def remixSyncHeadRefusal(UploadRequest request, string latestOriginalHead) Refusal ( + if latestOriginalHead == "" or latestOriginalHead != request.syncHead ( + return refuseWithBody(409, {ok: false, error: "the original project changed while this sync was processing", code: "original_changed"}) + ) + return noRefusal() +) + +def remixSyncMergeRefusal(UploadRequest request, boolean originalFound, boolean canSync, string latestOriginalHead) Refusal ( + if !originalFound ( + return refuse(404, "the original project was not found") + ) + if !canSync ( + return refuse(403, "only the remix's maintainers can sync it, and only while they can see inside the original") + ) + return remixSyncHeadRefusal(request, latestOriginalHead) +) + +def remixSyncCommitMessage(string originalTitle) string ( + string title = originalTitle.strip() + return if title == "" then "Merge changes from the original project" else "Merge changes from " ++ title +) + +def pullSourceHeadRefusal(UploadRequest request, string liveSourceHead, string recordedHead) Refusal ( + string preparedHead = if request.mergeSourceHead != "" then request.mergeSourceHead else recordedHead + if liveSourceHead == "" or preparedHead != liveSourceHead ( + return refuseWithBody(409, {ok: false, error: "the remix changed while this merge was processing", code: "pull_head_changed"}) + ) + return noRefusal() +) + def pullMergeRefusal(UploadRequest request, object pull, string projectId) Refusal ( if request.pullId == "" or pull.len == 0 or pull.state.toStr() != "open" or pull.targetProjectId.toStr() != projectId ( return refuseWithBody(409, {ok: false, error: "the pull request is no longer open", code: "pull_not_open"}) diff --git a/src/projects/project-upload-policy.test.osl b/src/projects/project-upload-policy.test.osl index 1c85dbe..36a7e71 100644 --- a/src/projects/project-upload-policy.test.osl +++ b/src/projects/project-upload-policy.test.osl @@ -125,6 +125,63 @@ testing.assert(isRefused(pullMergeRefusal(branch, openPull, "p2")), "a pull into testing.assert(isRefused(pullMergeRefusal(branch, {}, "p1")), "a missing pull cannot merge") testing.assert(isRefused(pullMergeRefusal(request(), openPull, "p1")), "a merge without a pull id or branches is refused") +UploadRequest pullFromRemix = request() +pullFromRemix.pullId = "1" +testing.assert(!isRefused(pullSourceHeadRefusal(pullFromRemix, headB, headB)), "older clients that send no remix head merge the recorded head") +testing.assert(pullSourceHeadRefusal(pullFromRemix, headB, headA).body.code == "pull_head_changed", "older clients cannot merge a remix that moved past the recorded head") +pullFromRemix.mergeSourceHead = headB +testing.assert(!isRefused(pullSourceHeadRefusal(pullFromRemix, headB, headA)), "the remix head the merge was prepared from can merge") +testing.assert(pullSourceHeadRefusal(pullFromRemix, headA, headA).body.code == "pull_head_changed", "a remix that moved after preparing stops the merge") +testing.assert(isRefused(pullSourceHeadRefusal(pullFromRemix, "", headB)), "a remix with no head cannot merge") + +UploadRequest sync = request() +testing.assert(!isRemixSync(sync) and !isRefused(remixSyncRequestRefusal(sync)), "ordinary saves are not syncs") +sync.syncHead = headB +testing.assert(isRemixSync(sync), "an original head makes a sync with the original") +testing.assert(remixSyncRequestRefusal(sync).body.code == "head_changed", "a sync must name the remix head it was prepared from") +sync.expectedHead = headA +testing.assert(!isRefused(remixSyncRequestRefusal(sync)), "a sync with both heads can continue") +testing.assert(liveContributorRefusal(sync, false).status == 403, "live contributors cannot sync a remix") +testing.assert(!isRefused(liveContributorRefusal(sync, true)), "maintainers can sync a remix") +testing.assert(!isRefused(remixSyncHeadRefusal(sync, headB)), "an unchanged original head can sync") +testing.assert(remixSyncHeadRefusal(sync, headA).body.code == "original_changed", "a moved original head stops the sync") +testing.assert(isRefused(remixSyncHeadRefusal(sync, "")), "an original without history stops the sync") +testing.assert(remixSyncMergeRefusal(sync, false, false, "").status == 404, "a missing original refuses the post-body merge check with 404") +testing.assert(remixSyncMergeRefusal(sync, true, false, headB).status == 403, "an original whose source became hidden while the upload streamed refuses the post-body merge check with 403") +testing.assert(remixSyncMergeRefusal(sync, true, true, headA).body.code == "original_changed", "an original that moved while the upload streamed refuses the post-body merge check with 409 original_changed") +testing.assert(!isRefused(remixSyncMergeRefusal(sync, true, true, headB)), "a visible, unchanged original passes the post-body merge check") +UploadHistory syncWithTree = newUploadHistory(sync, headA) +syncWithTree.hasMergeTree = true +testing.assert(!isRefused(remixSyncTreeRefusal(sync, syncWithTree)), "a sync carrying the merged tree can continue") +testing.assert(remixSyncTreeRefusal(sync, newUploadHistory(sync, headA)).status == 400, "a sync without the merged tree is refused") +testing.assert(!isRefused(remixSyncTreeRefusal(request(), newUploadHistory(request(), headA))), "ordinary saves need no merged tree") +UploadRequest pullUpload = request() +pullUpload.pullId = "4" +UploadHistory pullTree = newUploadHistory(pullUpload, headA) +pullTree.hasMergeTree = true +testing.assert(pullExpectedHeadRefusal(pullUpload).body.code == "head_changed", "a pull merge must name the target head it was prepared from") +pullUpload.expectedHead = headA +testing.assert(!isRefused(pullExpectedHeadRefusal(pullUpload)), "a pull merge naming the target head can continue") +testing.assert(!isRefused(pullUploadShapeRefusal(pullUpload, pullTree)), "a pull merge with only the merged tree can continue") +testing.assert(pullUploadShapeRefusal(pullUpload, newUploadHistory(pullUpload, headA)).status == 400, "a pull merge without the merged tree is refused") +UploadHistory pullWithWorkspace = newUploadHistory(pullUpload, headA) +pullWithWorkspace.hasMergeTree = true +pullWithWorkspace.hasWorkspace = true +testing.assert(pullUploadShapeRefusal(pullUpload, pullWithWorkspace).status == 400, "a pull merge that also carries a workspace is refused") +testing.assert(!isRefused(pullUploadShapeRefusal(request(), newUploadHistory(request(), headA))), "ordinary saves are not pull merges") +UploadRequest syncAndPull = request() +syncAndPull.syncHead = headB +syncAndPull.expectedHead = headA +syncAndPull.pullId = "3" +testing.assert(remixSyncRequestRefusal(syncAndPull).status == 400, "a sync cannot also merge a pull request") +UploadRequest syncAndReplace = request() +syncAndReplace.syncHead = headB +syncAndReplace.expectedHead = headA +syncAndReplace.replaceHistory = true +testing.assert(isRefused(remixSyncRequestRefusal(syncAndReplace)) and isRefused(staleUploadRefusal(syncAndReplace, {edited: 1}, headA)), "a sync cannot replace history") +testing.assert(remixSyncCommitMessage("Meowing Simulator") == "Merge changes from Meowing Simulator", "sync commits name the original") +testing.assert(remixSyncCommitMessage(" ") == "Merge changes from the original project", "untitled originals get a generic message") + HistoryIdentity fresh = historyIdentity({id: "p1", remixParent: null}) testing.assert(fresh.projectId == "p1" and fresh.remixParent == "" and fresh.baseCommit == "" and fresh.branch == "main", "missing identity fields fall back") HistoryIdentity forked = historyIdentity({id: "p2", remixParent: "p1", remixBaseCommit: headA, gitBranch: "dev"}) diff --git a/src/projects/project-upload-publish.osl b/src/projects/project-upload-publish.osl index 4f866df..14d8a7a 100644 --- a/src/projects/project-upload-publish.osl +++ b/src/projects/project-upload-publish.osl @@ -118,8 +118,8 @@ def projectWithUploadHistory(object project) object ( return generatedHistory.project.assert(object) ) -def completeUploadPull(object project, UploadRequest request, string username) Refusal ( - if request.pullId != "" and !completeNativePull(project, request.pullId, request.expectedHead, username) ( +def completeUploadPull(object project, UploadRequest request, boolean canMerge) Refusal ( + if request.pullId != "" and !completeNativePull(project, request.pullId, request.expectedHead, request.mergedPullHead, canMerge) ( return refuseWithBody(409, {ok: false, error: "the project saved, but the pull request could not be closed", code: "pull_not_closed"}) ) return noRefusal() diff --git a/src/projects/project-upload-publish.test.osl b/src/projects/project-upload-publish.test.osl index aff5c9c..af9c022 100644 --- a/src/projects/project-upload-publish.test.osl +++ b/src/projects/project-upload-publish.test.osl @@ -84,7 +84,7 @@ def projectHasWorkspace(object project) boolean ( def ensureUploadedProjectHistory(object project) object ( return {ok: true, project: project} ) -def completeNativePull(object project, string pullIndex, string expectedHead, string username) boolean ( +def completeNativePull(object project, string pullIndex, string expectedHead, string mergedHead, boolean canMerge) boolean ( return true ) def projectGitHead(object project) string ( diff --git a/src/projects/project-upload-receive.osl b/src/projects/project-upload-receive.osl index 35e532e..df2f48c 100644 --- a/src/projects/project-upload-receive.osl +++ b/src/projects/project-upload-receive.osl @@ -36,6 +36,7 @@ def readUploadRequest(*serve.Context c) UploadRequest ( request.mergeTargetBranch = uploadFormValue(c, "mergeTargetBranch") request.mergeSourceHead = uploadFormValue(c, "mergeSourceHead") request.mergeTargetHead = uploadFormValue(c, "mergeTargetHead") + request.syncHead = uploadFormValue(c, "syncHead") request.git = (c.formValue("git") ?? "") request.extensions = (c.formValue("extensions") ?? "") request.workspaceToken = (c.formValue("workspaceToken") ?? "") diff --git a/src/projects/project-upload.osl b/src/projects/project-upload.osl index ed564fd..1fff723 100644 --- a/src/projects/project-upload.osl +++ b/src/projects/project-upload.osl @@ -37,6 +37,23 @@ def handleCheckProjectAssets(*serve.Context c) ( c.json(200, {ok: true, missing: missing}) ) +def remixSyncAccessRefusal(*serve.Context c, object project, UploadRequest request) Refusal ( + if !isRemixSync(request) ( + return noRefusal() + ) + object? original = loadRemixSyncOriginal(project) + if original == null ( + return refuse(404, "the original project was not found") + ) + if !canSyncRemixFrom(project, original, c) ( + return refuse(403, "only the remix's maintainers can sync it, and only while they can see inside the original") + ) + if remixHasUncommittedChanges(project) ( + return refuseWithBody(409, {ok: false, error: "commit the changes saved in this remix before syncing it with the original", code: "uncommitted_changes"}) + ) + return noRefusal() +) + def handleUploadProject(*serve.Context c) ( runLocked(projectSaveLock(c.param("id")), def() -> ( handleUploadProjectLocked(c) @@ -55,7 +72,9 @@ def handleUploadProjectLocked(*serve.Context c) ( if refused(c, editorReplaceRefusal(c, request, project)) return UploadHistory history = newUploadHistory(request, projectGitHead(project)) if refused(c, liveContributorRefusal(request, canEditProject(project, c))) return + if refused(c, remixSyncRequestRefusal(request)) return if refused(c, staleUploadRefusal(request, project, history.currentHead)) return + if refused(c, remixSyncAccessRefusal(c, project, request)) return if refused(c, readUploadGitMetadata(history, projectHasWorkspace(project))) return if refused(c, restoreCommitRefusal(request)) return @@ -72,7 +91,7 @@ def handleUploadProjectLocked(*serve.Context c) ( if refused(c, archive.discardOn(unchangedVersionCheck(project, request, history, archive))) return object extensionResult = collectProjectExtensions(archive.extractDir ++ "/project.json", request.extensions) if refused(c, archive.discardOn(extensionRefusal(extensionResult))) return - if refused(c, archive.discardOn(createMergeCommit(project, request, history, archive, uploader))) return + if refused(c, archive.discardOn(createMergeCommit(c, project, request, history, archive, uploader))) return if refused(c, archive.discardOn(createRestoreCommit(project, request, history, archive, uploader))) return if refused(c, archive.discardOn(checkGeneratedHistory(project, history))) return @@ -103,7 +122,7 @@ def handleUploadProjectLocked(*serve.Context c) ( archive.discard() project = projectWithUploadHistory(project) - if refused(c, completeUploadPull(project, request, contextString(c, "username"))) return + if refused(c, completeUploadPull(project, request, canEditProject(project, c))) return c.json(200, uploadResponse(project, uploadResult)) )