Zhang-Wei (Discord, v0.1.1318, 102 skills) saw every sync fail with "GitHub sync: HTTP 422: Sorry, the file is too large to be processed" on magpie/magpie.magpie-backup; the last backup that went up was about 19 MB. The Contents API's PUT refuses files well under the 100 MB a blob can hold. A repository with commits is now written through the Git Data API: the ref's head, the file's version at that head (it must still be the one sync read, or errChanged), a base64 blob, a tree on the head's tree, a commit with the head as its parent, and a ref update without force. Still one commit per write or removal, and the version is the blob SHA as before. A ref update that is not a fast-forward is built again on the new head (the blob is kept), up to three times, then errChanged; if the new head changed the backup it is errChanged at once, so another computer's backup goes through the normal merge. A branch deleted meanwhile is an error, not created. Usage files and their removal take the same path. An empty repository has no head to build on, so its first write still goes through the Contents API (one commit, unchanged). If that is refused as too large (422 "too large" or 413), a short README.md in magpie's folder makes the first commit and the backup follows as the second. Reading was already right for large files: the object media type gives encoding "none" over 1 MB and bytes() downloads by blob SHA; the new test covers it at 21 MB. The fixture now serves the Git Data API (blobs, commits, trees, a fast-forward-only ref update) and refuses a Contents PUT over contentsLimit with GitHub's 422 text. docs/subsystems/sync-backup.md says how writes go and names the new tests. Record for this push: 13 commits on origin/mainca4a1cde0, head tree539c84e92. Go 1.26.8, sandbox HOME, GOMODCACHE/GOCACHE pinned. The full Go run and vet were at tree d6393dfc8, the same Go code as this head: only app.js comments (cut under the core script budget) and one ja string changed after it. - gofmt -l: nothing. go build ./...; go vet ./... (darwin), GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: clean. - go test -timeout 45m ./..., through tee, one suite on the machine: 68 packages ok. The one red was internal/gui's TestCoreScriptBudget: app.js 1,335,314 > 1,335,000, since main grew app.js under the stack. The autoscroll commit's own comments were cut (to 1,334,629) rather than the budget raised, and go test -count=1 ./internal/gui is ok at this head (113s). Packages the run took from Go's test cache had the same inputs. - GUI: the 18 files this stack touches or names, both engines, 202 of 204 pass (tree068acf128, this push less the last commit). The two reds: gui-ja, red on main sincec2636b7b5and fixed by this push's last commit (gui-ja and i18n-keys 6 of 6 there), and usage-fold's chromium "several accounts" (#2163, red on main the same way). - internal/davsync and internal/cli ok, the GitHub large-backup tests and TestGitHubCmd among them. - s3-sync.test.cjs (WebKit en) is red alone on main too: #2448, the header over the form's tick. This commit doesn't touch the GUI. The whole GUI suite ran at 1c1fc7183 (this stack's first 12 commits on0ddcf28a1): 11713 of 11769 pass. Each of the 21 red files was then run alone at the stack and at origin/main8278fd9b0. Eight are red the same way on main: plugin-card-update (#3079), quota-count-wrap and quota-name-translated (#2228), s3-sync (#2448), usage-agents-hide (#2276), usage-checkin (#3091), usage-fold's chromium "several accounts" (#2163), usage-ledger (#3104). The other 13 pass alone on both and were red only under that run's load (50 to 335): currency #3101, plugin-github #3218, provider-fetch-again #3292, rest-try-now #2564, routing-auto-reset #3293, routing-keys-fold #1612, routing-steady #1804, routing-wb-restricted #1905, sessions-folder-delete #2218, sessions-manage #3294, switch-only #3295, text-size #1866, usage-pack #3296. Red on the old github.go (the new tests with the old code): TestGitHubLargeBackup and TestGitHubEmptyRepositoryLargeBackup fail with "HTTP 422: Sorry, the file is too large to be processed", TestGitHubRemote too at its 1.26 MB put, and TestGitHubBranchMovedMeanwhile's three subtests fail. Broken by hand on the new code, each red: - version check at the head skipped: TestGitHubRemote, LargeBackup's stale put, BranchMovedMeanwhile/the_backup - no rebuild on a non-fast-forward: BranchMovedMeanwhile/another_file and /the_backup - large read by base64 only: TestGitHubRemote, TestGitHubLargeBackup - no README initialization: TestGitHubEmptyRepositoryLargeBackup (409) Not tried against the real GitHub API: the fixture follows GitHub's documented Git Data API, and GitHub's exact Contents API size limit is not documented.
620 lines
20 KiB
Go
620 lines
20 KiB
Go
package davsync
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha1"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
pathpkg "path"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const githubMaxFile = 64 << 20
|
|
|
|
type github struct {
|
|
repo, prefix, branch, token string
|
|
ready bool
|
|
empty bool
|
|
client *http.Client
|
|
}
|
|
|
|
// newGitHub accepts github://owner/repo/prefix. Only GitHub's API receives
|
|
// the token; neither a download URL nor a configurable host is followed.
|
|
func newGitHub(c Config) (*github, error) {
|
|
u, err := url.Parse(strings.TrimSpace(c.URL))
|
|
if err != nil || !strings.EqualFold(u.Scheme, "github") || u.Host == "" ||
|
|
u.User != nil || u.Port() != "" || u.RawQuery != "" || u.Fragment != "" {
|
|
return nil, errors.New("GitHub sync needs an address like github://owner/repo or github://owner/repo/folder")
|
|
}
|
|
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
|
|
valid := func(s string) bool {
|
|
if s == "" || s == "." || s == ".." {
|
|
return false
|
|
}
|
|
for _, ch := range s {
|
|
if ch != '-' && ch != '_' && ch != '.' && (ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z') && (ch < '0' || ch > '9') {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
if !valid(u.Host) || !valid(parts[0]) {
|
|
return nil, errors.New("GitHub sync needs a repository in owner/repo form")
|
|
}
|
|
for _, p := range parts[1:] {
|
|
if p == "" || p == "." || p == ".." || strings.ContainsAny(p, "\\\x00\r\n") {
|
|
return nil, errors.New("the GitHub folder must be a relative path without empty, . or .. components")
|
|
}
|
|
}
|
|
branch := strings.TrimSpace(c.Branch)
|
|
if strings.ContainsAny(branch, "\x00\r\n") || strings.Contains(branch, "..") {
|
|
return nil, errors.New("the GitHub branch contains invalid characters")
|
|
}
|
|
if strings.ContainsAny(c.Password, " \t\r\n") {
|
|
return nil, errors.New("the GitHub branch or token contains invalid whitespace")
|
|
}
|
|
client := *syncClient
|
|
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
|
|
if req.URL.Scheme != "https" || req.URL.Host != "api.github.com" {
|
|
return errors.New("GitHub sync refused a redirect outside api.github.com")
|
|
}
|
|
if len(via) >= 10 {
|
|
return errors.New("GitHub sync stopped after too many redirects")
|
|
}
|
|
return nil
|
|
}
|
|
return &github{repo: u.Host + "/" + parts[0], prefix: strings.Join(parts[1:], "/"),
|
|
branch: branch, token: c.Password, client: &client}, nil
|
|
}
|
|
|
|
// send calls the repository's API; a non-empty ref reads at that branch or
|
|
// commit.
|
|
func (g *github) send(ctx context.Context, method, apiPath string, body []byte, accept string, ref string) (*http.Response, error) {
|
|
u := &url.URL{Scheme: "https", Host: "api.github.com", Path: "/repos/" + g.repo}
|
|
if apiPath != "" {
|
|
u.Path += "/" + apiPath
|
|
}
|
|
if ref != "" {
|
|
q := url.Values{"ref": {ref}}
|
|
u.RawQuery = q.Encode()
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, method, u.String(), bytes.NewReader(body))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
req.Header.Set("Authorization", "Bearer "+g.token)
|
|
req.Header.Set("Accept", accept)
|
|
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
|
|
req.Header.Set("User-Agent", "magpie-sync")
|
|
if body != nil {
|
|
req.Header.Set("Content-Type", "application/json")
|
|
}
|
|
return g.client.Do(req)
|
|
}
|
|
|
|
func githubError(res *http.Response) error {
|
|
if err := limited("GitHub", res.StatusCode, res.Header); err != nil {
|
|
return err
|
|
}
|
|
if res.StatusCode == http.StatusForbidden && (res.Header.Get("X-RateLimit-Remaining") == "0" || res.Header.Get("Retry-After") != "") {
|
|
after := retryAfter(res.Header.Get("Retry-After"))
|
|
if after == 0 {
|
|
if until, err := strconv.ParseInt(res.Header.Get("X-RateLimit-Reset"), 10, 64); err == nil {
|
|
after = max(time.Until(time.Unix(until, 0)), 0)
|
|
}
|
|
}
|
|
return &rateLimited{kind: "GitHub", status: res.StatusCode, after: after}
|
|
}
|
|
var e struct{ Message string }
|
|
json.NewDecoder(io.LimitReader(res.Body, 64<<10)).Decode(&e)
|
|
switch res.StatusCode {
|
|
case http.StatusUnauthorized:
|
|
return errors.New("GitHub refused the sync token (HTTP 401): check that it has not expired or been revoked")
|
|
case http.StatusForbidden:
|
|
return fmt.Errorf("GitHub refused access (HTTP 403): the sync token needs Contents read and write permission; check repository rules too: %s", e.Message)
|
|
case http.StatusNotFound:
|
|
return errors.New("GitHub could not find the repository or branch (HTTP 404): check the name and the token's repository access")
|
|
}
|
|
return fmt.Errorf("GitHub sync: HTTP %d: %s", res.StatusCode, e.Message)
|
|
}
|
|
|
|
// prepare distinguishes a missing file from an inaccessible repository or
|
|
// branch before the sync considers creating its first backup.
|
|
func (g *github) prepare(ctx context.Context) error {
|
|
if g.ready {
|
|
return nil
|
|
}
|
|
res, err := g.send(ctx, http.MethodGet, "", nil, "application/vnd.github+json", "")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if res.StatusCode != http.StatusOK {
|
|
defer res.Body.Close()
|
|
return githubError(res)
|
|
}
|
|
var repo struct {
|
|
DefaultBranch string `json:"default_branch"`
|
|
Private *bool `json:"private"`
|
|
}
|
|
err = json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&repo)
|
|
res.Body.Close()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// A public repository hands every version of the sealed backup, its
|
|
// whole commit history, to anyone, to guess the passphrase at leisure.
|
|
if repo.Private == nil || !*repo.Private {
|
|
return fmt.Errorf("the GitHub repository %s is public, or GitHub didn't say it is private: anyone could download every version of the sealed backup from its history. Make it private, or use a private repository", g.repo)
|
|
}
|
|
if g.branch == "" {
|
|
g.branch = repo.DefaultBranch
|
|
}
|
|
if g.branch == "" {
|
|
return errors.New("the GitHub repository has no default branch: create an initial commit first")
|
|
}
|
|
res, err = g.send(ctx, http.MethodGet, "git/ref/heads/"+g.branch, nil, "application/vnd.github+json", "")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer res.Body.Close()
|
|
if res.StatusCode == http.StatusConflict {
|
|
body, err := io.ReadAll(io.LimitReader(res.Body, 64<<10))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var failure struct{ Message string }
|
|
if json.Unmarshal(body, &failure) != nil || failure.Message != "Git Repository is empty." {
|
|
res.Body = io.NopCloser(bytes.NewReader(body))
|
|
return githubError(res)
|
|
}
|
|
if g.branch != repo.DefaultBranch {
|
|
return errors.New("The GitHub repository is empty: leave Branch empty or use its default branch for the first sync")
|
|
}
|
|
g.empty = true
|
|
} else if res.StatusCode != http.StatusOK {
|
|
return githubError(res)
|
|
}
|
|
g.ready = true
|
|
return nil
|
|
}
|
|
|
|
type githubContent struct {
|
|
Type string `json:"type"`
|
|
Name string `json:"name"`
|
|
SHA string `json:"sha"`
|
|
Size int64 `json:"size"`
|
|
Encoding string `json:"encoding"`
|
|
Content string `json:"content"`
|
|
}
|
|
|
|
func (g *github) at(name string) string {
|
|
return pathpkg.Join(g.prefix, folder, name)
|
|
}
|
|
|
|
func (g *github) content(ctx context.Context, name string) (*githubContent, error) {
|
|
if err := g.prepare(ctx); err != nil {
|
|
return nil, err
|
|
}
|
|
return g.contentAt(ctx, name, g.branch)
|
|
}
|
|
|
|
// contentAt reads a file's metadata at a branch or commit. The object media
|
|
// type answers for files up to 100 MB; over 1 MB its content is empty and
|
|
// bytes downloads the blob instead.
|
|
func (g *github) contentAt(ctx context.Context, name, ref string) (*githubContent, error) {
|
|
res, err := g.send(ctx, http.MethodGet, "contents/"+g.at(name), nil, "application/vnd.github.object+json", ref)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer res.Body.Close()
|
|
if res.StatusCode == http.StatusNotFound {
|
|
return nil, nil
|
|
}
|
|
if res.StatusCode != http.StatusOK {
|
|
return nil, githubError(res)
|
|
}
|
|
var c githubContent
|
|
if err := json.NewDecoder(io.LimitReader(res.Body, 90<<20)).Decode(&c); err != nil {
|
|
return nil, err
|
|
}
|
|
if c.Type != "file" || c.SHA == "" || c.Size < 0 || c.Size > githubMaxFile {
|
|
return nil, errors.New("GitHub sync needs a regular file no larger than 64 MiB")
|
|
}
|
|
g.empty = false
|
|
return &c, nil
|
|
}
|
|
|
|
func (g *github) bytes(ctx context.Context, c *githubContent) ([]byte, error) {
|
|
if c.Encoding == "base64" {
|
|
b, err := base64.StdEncoding.DecodeString(c.Content)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("decoding GitHub's file: %w", err)
|
|
}
|
|
if int64(len(b)) != c.Size {
|
|
return nil, errors.New("GitHub returned an incomplete file")
|
|
}
|
|
return b, nil
|
|
}
|
|
if c.Encoding != "none" {
|
|
return nil, fmt.Errorf("GitHub returned an unsupported file encoding %q", c.Encoding)
|
|
}
|
|
// The blob SHA pins the download to the metadata read above, even if
|
|
// another computer commits a new backup while the download is starting.
|
|
res, err := g.send(ctx, http.MethodGet, "git/blobs/"+c.SHA, nil, "application/vnd.github.raw+json", "")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer res.Body.Close()
|
|
if res.StatusCode != http.StatusOK {
|
|
return nil, githubError(res)
|
|
}
|
|
b, err := io.ReadAll(io.LimitReader(res.Body, githubMaxFile+1))
|
|
if err == nil && int64(len(b)) != c.Size {
|
|
err = errors.New("GitHub returned an incomplete or oversized file")
|
|
}
|
|
return b, err
|
|
}
|
|
|
|
func (g *github) get(ctx context.Context, have version) ([]byte, version, error) {
|
|
c, err := g.content(ctx, file)
|
|
if err != nil || c == nil {
|
|
return nil, version{}, err
|
|
}
|
|
v := version{ETag: c.SHA}
|
|
if have.ETag == c.SHA {
|
|
return nil, v, errNotModified
|
|
}
|
|
b, err := g.bytes(ctx, c)
|
|
return b, v, err
|
|
}
|
|
|
|
// errTooLarge is the Contents API refusing a file it won't process, which
|
|
// it does well under the 100 MB a blob can hold (a 19 MB backup passed and a
|
|
// larger one didn't, on Discord).
|
|
var errTooLarge = errors.New("GitHub's Contents API refused the file as too large")
|
|
|
|
// errBehind is a ref update that is no longer a fast-forward: another commit
|
|
// reached the branch after its head was read.
|
|
var errBehind = errors.New("the GitHub branch moved meanwhile")
|
|
|
|
// commit writes or removes one file in one commit. A repository with
|
|
// commits goes through the Git Data API (blob, tree, commit, ref), which
|
|
// takes files up to 100 MB, where the Contents API refuses large ones (HTTP
|
|
// 422 "the file is too large to be processed"). An empty repository has no
|
|
// branch to build on, so its first write goes through the Contents API,
|
|
// which creates the default branch.
|
|
func (g *github) commit(ctx context.Context, name string, data []byte, sha string, remove bool) (version, error) {
|
|
if len(data) > githubMaxFile {
|
|
return version{}, errors.New("the GitHub sync file exceeds 64 MiB")
|
|
}
|
|
if err := g.prepare(ctx); err != nil {
|
|
return version{}, err
|
|
}
|
|
if g.empty {
|
|
v, err := g.contents(ctx, name, data, sha, remove)
|
|
if !errors.Is(err, errTooLarge) {
|
|
return v, err
|
|
}
|
|
// Too large for the Contents API: give the repository a first
|
|
// commit of its own, then build the file's commit on it.
|
|
if err := g.initialize(ctx); err != nil {
|
|
return version{}, err
|
|
}
|
|
}
|
|
blob := ""
|
|
for try := 0; ; try++ {
|
|
v, err := g.gitCommit(ctx, name, data, sha, remove, &blob)
|
|
if !errors.Is(err, errBehind) {
|
|
return v, err
|
|
}
|
|
// A commit that touched other files (another computer's usage)
|
|
// is built on again; gitCommit returns errChanged if it touched
|
|
// this file.
|
|
if try == 3 {
|
|
return version{}, errChanged
|
|
}
|
|
}
|
|
}
|
|
|
|
// githubJSON sends in as JSON and decodes a 2xx reply into out. Any other
|
|
// status is returned as the response, its body readable, for the caller to
|
|
// judge.
|
|
func (g *github) githubJSON(ctx context.Context, method, apiPath string, in, out any) (*http.Response, error) {
|
|
var body []byte
|
|
if in != nil {
|
|
var err error
|
|
if body, err = json.Marshal(in); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
res, err := g.send(ctx, method, apiPath, body, "application/vnd.github+json", "")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if res.StatusCode < 200 || res.StatusCode > 299 {
|
|
b, err := io.ReadAll(io.LimitReader(res.Body, 64<<10))
|
|
res.Body.Close()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
res.Body = io.NopCloser(bytes.NewReader(b))
|
|
return res, nil
|
|
}
|
|
defer res.Body.Close()
|
|
if err := json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(out); err != nil {
|
|
return nil, fmt.Errorf("reading GitHub's reply to %s %s: %w", method, apiPath, err)
|
|
}
|
|
return nil, nil
|
|
}
|
|
|
|
// gitCommit builds one commit on the branch's head that writes data (or
|
|
// removes the file) and moves the branch to it. The file must still be at
|
|
// sha in that head, so another computer's backup is never written over;
|
|
// the ref update without force refuses a head that moved after it was read.
|
|
// blob carries the uploaded blob's SHA across retries.
|
|
func (g *github) gitCommit(ctx context.Context, name string, data []byte, sha string, remove bool, blob *string) (version, error) {
|
|
var ref struct {
|
|
Object struct {
|
|
SHA string `json:"sha"`
|
|
} `json:"object"`
|
|
}
|
|
if res, err := g.githubJSON(ctx, http.MethodGet, "git/ref/heads/"+g.branch, nil, &ref); err != nil {
|
|
return version{}, err
|
|
} else if res != nil {
|
|
return version{}, githubError(res)
|
|
}
|
|
head := ref.Object.SHA
|
|
if head == "" {
|
|
return version{}, errors.New("GitHub did not return the branch's head commit")
|
|
}
|
|
c, err := g.contentAt(ctx, name, head)
|
|
if err != nil {
|
|
return version{}, err
|
|
}
|
|
if c != nil && c.SHA != sha || c == nil && sha != "" {
|
|
return version{}, errChanged
|
|
}
|
|
if !remove && *blob == "" {
|
|
var out struct {
|
|
SHA string `json:"sha"`
|
|
}
|
|
in := map[string]string{"content": base64.StdEncoding.EncodeToString(data), "encoding": "base64"}
|
|
if res, err := g.githubJSON(ctx, http.MethodPost, "git/blobs", in, &out); err != nil {
|
|
return version{}, err
|
|
} else if res != nil {
|
|
return version{}, githubError(res)
|
|
}
|
|
if out.SHA != gitBlobSHA(data) {
|
|
return version{}, errors.New("GitHub stored a different blob than the one sent")
|
|
}
|
|
*blob = out.SHA
|
|
}
|
|
var commit struct {
|
|
Tree struct {
|
|
SHA string `json:"sha"`
|
|
} `json:"tree"`
|
|
}
|
|
if res, err := g.githubJSON(ctx, http.MethodGet, "git/commits/"+head, nil, &commit); err != nil {
|
|
return version{}, err
|
|
} else if res != nil {
|
|
return version{}, githubError(res)
|
|
}
|
|
if commit.Tree.SHA == "" {
|
|
return version{}, errors.New("GitHub did not return the head commit's tree")
|
|
}
|
|
// A null sha removes the path from the tree.
|
|
type entry struct {
|
|
Path string `json:"path"`
|
|
Mode string `json:"mode"`
|
|
Type string `json:"type"`
|
|
SHA *string `json:"sha"`
|
|
}
|
|
e := entry{Path: g.at(name), Mode: "100644", Type: "blob"}
|
|
message := "magpie: remove " + name
|
|
if !remove {
|
|
e.SHA, message = blob, "magpie: sync "+name
|
|
}
|
|
var tree, made struct {
|
|
SHA string `json:"sha"`
|
|
}
|
|
if res, err := g.githubJSON(ctx, http.MethodPost, "git/trees", map[string]any{"base_tree": commit.Tree.SHA, "tree": []entry{e}}, &tree); err != nil {
|
|
return version{}, err
|
|
} else if res != nil {
|
|
return version{}, githubError(res)
|
|
}
|
|
if res, err := g.githubJSON(ctx, http.MethodPost, "git/commits", map[string]any{"message": message, "tree": tree.SHA, "parents": []string{head}}, &made); err != nil {
|
|
return version{}, err
|
|
} else if res != nil {
|
|
return version{}, githubError(res)
|
|
}
|
|
if made.SHA == "" {
|
|
return version{}, errors.New("GitHub did not return the new commit")
|
|
}
|
|
var moved json.RawMessage
|
|
res, err := g.githubJSON(ctx, http.MethodPatch, "git/refs/heads/"+g.branch, map[string]any{"sha": made.SHA, "force": false}, &moved)
|
|
if err != nil {
|
|
return version{}, err
|
|
}
|
|
if res != nil {
|
|
if res.StatusCode == http.StatusUnprocessableEntity {
|
|
b, _ := io.ReadAll(res.Body)
|
|
if strings.Contains(strings.ToLower(string(b)), "fast forward") {
|
|
return version{}, errBehind
|
|
}
|
|
res.Body = io.NopCloser(bytes.NewReader(b))
|
|
}
|
|
return version{}, githubError(res)
|
|
}
|
|
g.empty = false
|
|
if remove {
|
|
return version{}, nil
|
|
}
|
|
return version{ETag: *blob}, nil
|
|
}
|
|
|
|
// gitBlobSHA is the SHA git names a blob holding b by: the version GitHub
|
|
// reports for the file.
|
|
func gitBlobSHA(b []byte) string {
|
|
h := sha1.New()
|
|
fmt.Fprintf(h, "blob %d\x00", len(b))
|
|
h.Write(b)
|
|
return hex.EncodeToString(h.Sum(nil))
|
|
}
|
|
|
|
// initialize gives an empty repository its first commit, a short note in
|
|
// magpie's folder, so a backup too large for the Contents API can be
|
|
// committed on top of it through the Git Data API. Another computer that
|
|
// initialized it first is just as good.
|
|
func (g *github) initialize(ctx context.Context) error {
|
|
note := []byte("This folder holds magpie's encrypted sync files.\n")
|
|
if _, err := g.contents(ctx, "README.md", note, "", false); err != nil && !errors.Is(err, errChanged) {
|
|
return err
|
|
}
|
|
g.empty = false
|
|
return nil
|
|
}
|
|
|
|
// contents writes through the Contents API, which only an empty repository's
|
|
// first write uses.
|
|
func (g *github) contents(ctx context.Context, name string, data []byte, sha string, remove bool) (version, error) {
|
|
in := map[string]string{"message": "magpie: sync " + name, "content": base64.StdEncoding.EncodeToString(data)}
|
|
// Omitting branch lets the first backup initialize an empty repository.
|
|
if !g.empty {
|
|
in["branch"] = g.branch
|
|
}
|
|
if sha != "" {
|
|
in["sha"] = sha
|
|
}
|
|
method := http.MethodPut
|
|
if remove {
|
|
method = http.MethodDelete
|
|
in["message"] = "magpie: remove " + name
|
|
delete(in, "content")
|
|
}
|
|
body, err := json.Marshal(in)
|
|
if err != nil {
|
|
return version{}, err
|
|
}
|
|
res, err := g.send(ctx, method, "contents/"+g.at(name), body, "application/vnd.github+json", "")
|
|
if err != nil {
|
|
return version{}, err
|
|
}
|
|
defer res.Body.Close()
|
|
if res.StatusCode == http.StatusConflict {
|
|
return version{}, errChanged
|
|
}
|
|
if res.StatusCode == http.StatusRequestEntityTooLarge {
|
|
return version{}, errTooLarge
|
|
}
|
|
if res.StatusCode == http.StatusUnprocessableEntity {
|
|
body, _ := io.ReadAll(io.LimitReader(res.Body, 64<<10))
|
|
// A first write raced another computer creating the same file.
|
|
if strings.Contains(string(body), `\"sha\" wasn't supplied`) {
|
|
return version{}, errChanged
|
|
}
|
|
var e struct{ Message string }
|
|
if json.Unmarshal(body, &e) == nil && strings.Contains(strings.ToLower(e.Message), "too large") {
|
|
return version{}, errTooLarge
|
|
}
|
|
res.Body = io.NopCloser(bytes.NewReader(body))
|
|
}
|
|
if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated {
|
|
return version{}, githubError(res)
|
|
}
|
|
var out struct{ Content *githubContent }
|
|
if err := json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&out); err != nil {
|
|
return version{}, err
|
|
}
|
|
if remove {
|
|
return version{}, nil
|
|
}
|
|
if out.Content == nil || out.Content.SHA == "" {
|
|
return version{}, errors.New("GitHub did not return the version of the committed file")
|
|
}
|
|
g.empty = false
|
|
return version{ETag: out.Content.SHA}, nil
|
|
}
|
|
|
|
func (g *github) put(ctx context.Context, data []byte, sha string) (version, error) {
|
|
return g.commit(ctx, file, data, sha, false)
|
|
}
|
|
|
|
func (g *github) list(ctx context.Context) (map[string]string, error) {
|
|
if err := g.prepare(ctx); err != nil {
|
|
return nil, err
|
|
}
|
|
res, err := g.send(ctx, http.MethodGet, "contents/"+g.at(usageFolder), nil, "application/vnd.github+json", g.branch)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer res.Body.Close()
|
|
if res.StatusCode == http.StatusNotFound {
|
|
return map[string]string{}, nil
|
|
}
|
|
if res.StatusCode != http.StatusOK {
|
|
return nil, githubError(res)
|
|
}
|
|
var entries []githubContent
|
|
if err := json.NewDecoder(io.LimitReader(res.Body, 16<<20)).Decode(&entries); err != nil {
|
|
return nil, err
|
|
}
|
|
if len(entries) >= 1000 {
|
|
return nil, errors.New("the GitHub usage folder reached the Contents API's 1,000-file listing limit")
|
|
}
|
|
out := map[string]string{}
|
|
for _, e := range entries {
|
|
if e.Type == "file" && pathpkg.Base(e.Name) == e.Name &&
|
|
(strings.HasSuffix(e.Name, usageExt) || strings.HasSuffix(e.Name, quotasExt)) {
|
|
if e.SHA == "" {
|
|
return nil, errors.New("GitHub returned a usage file without its version")
|
|
}
|
|
out[e.Name] = e.SHA
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (g *github) read(ctx context.Context, name string) ([]byte, error) {
|
|
c, err := g.content(ctx, pathpkg.Join(usageFolder, name))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if c == nil {
|
|
return nil, fmt.Errorf("the GitHub usage file %s is missing", name)
|
|
}
|
|
return g.bytes(ctx, c)
|
|
}
|
|
|
|
func (g *github) write(ctx context.Context, name string, data []byte) error {
|
|
at := pathpkg.Join(usageFolder, name)
|
|
c, err := g.content(ctx, at)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
sha := ""
|
|
if c != nil {
|
|
sha = c.SHA
|
|
}
|
|
_, err = g.commit(ctx, at, data, sha, false)
|
|
return err
|
|
}
|
|
|
|
func (g *github) remove(ctx context.Context, name string) error {
|
|
at := pathpkg.Join(usageFolder, name)
|
|
c, err := g.content(ctx, at)
|
|
if err != nil || c == nil {
|
|
return err
|
|
}
|
|
_, err = g.commit(ctx, at, nil, c.SHA, true)
|
|
return err
|
|
}
|