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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/bump-spin.yml
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,12 @@ jobs:
RELEASE: ${{ steps.newer.outputs.release }}
run: go tool task spin:bump

- name: Error codes
if: steps.newer.outputs.release != ''
env:
GH_TOKEN: ${{ steps.read.outputs.token }}
run: go tool task contract:spin

- name: Check
if: steps.newer.outputs.release != ''
run: go tool task ci
Expand Down
11 changes: 8 additions & 3 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,13 @@ run is named `spin <release>`, which is how shipset finds it again). The run:
1. stops, successfully, when the release is not newer than the pin (`task spin:newer`);
2. bumps the pin (`task spin:bump`, go-tools' `versions bump spin <release>`), reading the tag's
commit from spin with a read-only token of the release app;
3. runs `task ci` and `task package:all`, which pulls that release's CLI for every platform it has
3. holds `src/cli/contract.ts`'s error codes and actions to errorActions in that release's
`cmd/cli/cmd/errcode.go` (`task contract:spin`, `hack/errcodes`), with the same token: a code
spin added or dropped fails the run, and the contract, the errors module and the fake spin
follow it by hand;
4. runs `task ci` and `task package:all`, which pulls that release's CLI for every platform it has
one for and checks each with cosign;
4. moves `package.json`'s version to the next patch when a tag has it already, commits that and
5. moves `package.json`'s version to the next patch when a tag has it already, commits that and
the pin as the release app (spin-stack-release), force-pushes `spin/next`, and opens the pull
request there, or rewrites the one open (`task spin:propose`, `hack/spinpropose`).

Expand All @@ -44,7 +48,8 @@ CI and Package run on it. Merging it, after checking the CLI's contract against
person's, and it releases the extension: `.github/workflows/tag.yml` tags the merge (below). The
run needs the app's key as the secret `RELEASE_APP_KEY`.

To bump by hand, `go tool task spin:bump RELEASE=<release>` and `go tool task package:all`.
To bump by hand, `go tool task spin:bump RELEASE=<release>`, `go tool task contract:spin` and
`go tool task package:all`.

## Releasing

Expand Down
15 changes: 15 additions & 0 deletions Taskfile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,21 @@ tasks:
- '[ -z "${GH_TOKEN:-}" ] || gh auth setup-git'
- versions bump spin "{{.RELEASE}}"

contract:spin:
desc: Hold src/cli/contract.ts's error codes and actions to errorActions in spin's cmd/cli/cmd/errcode.go at the release versions.yaml pins (hack/errcodes), read from spin's repository over git - with GH_TOKEN as git's credentials when it is set, since spin is private. The Bump spin workflow runs it after the bump, so a release that adds or drops a code is a red bump, not an envelope read as internal.
vars:
SPIN:
sh: versions version spin
cmds:
- '[ -z "${GH_TOKEN:-}" ] || gh auth setup-git'
- |
set -eu
dir=$(mktemp -d)
trap 'rm -rf "$dir"' EXIT
git clone --quiet --depth 1 --branch {{.SPIN}} --filter=blob:none --no-checkout https://github.com/spin-stack/spin "$dir/spin"
git -C "$dir/spin" show HEAD:cmd/cli/cmd/errcode.go > "$dir/errcode.go"
go run ./hack/errcodes -spin "$dir/errcode.go" -contract src/cli/contract.ts

spin:propose:
desc: Commit versions.yaml's spin at RELEASE, with package.json at the next patch when its version is tagged already, push it to spin/next and open or rewrite the pull request there, as the app GH_TOKEN and APP_SLUG name (hack/spinpropose) - the Bump spin workflow's last step, after task ci and task package:all.
requires:
Expand Down
172 changes: 172 additions & 0 deletions hack/errcodes/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
// Command errcodes holds the extension's error codes to the spin CLI's: every code, and the action
// it pairs with, in errorActions of spin's cmd/cli/cmd/errcode.go is ACTION_OF in
// src/cli/contract.ts, and nothing else is. A code spin adds or drops is a failure here, not an
// envelope the extension quietly reads as internal (task contract:spin reads spin's file at the
// release versions.yaml pins):
//
// go run ./hack/errcodes -spin errcode.go -contract src/cli/contract.ts
package main

import (
"errors"
"flag"
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"regexp"
"sort"
"strconv"
"strings"
)

func main() {
spinPath := flag.String("spin", "", "spin's cmd/cli/cmd/errcode.go")
contractPath := flag.String("contract", "src/cli/contract.ts", "the extension's contract")
flag.Parse()
if err := check(*spinPath, *contractPath); err != nil {
fmt.Fprintln(os.Stderr, "errcodes:", err)
os.Exit(1)
}
fmt.Println("errcodes: the contract's codes are spin's")
}

func check(spinPath, contractPath string) error {
spinSrc, err := os.ReadFile(spinPath)
if err != nil {
return err
}
contractSrc, err := os.ReadFile(contractPath)
if err != nil {
return err
}
spin, err := spinActions(spinSrc)
if err != nil {
return fmt.Errorf("%s: %w", spinPath, err)
}
contract, err := contractActions(string(contractSrc))
if err != nil {
return fmt.Errorf("%s: %w", contractPath, err)
}
if d := diff(spin, contract); len(d) > 0 {
return errors.New("the contract is not spin's:\n " + strings.Join(d, "\n "))
}
return nil
}

// spinActions reads errorActions: each key a constant of type errorCode, each value its action.
func spinActions(src []byte) (map[string]string, error) {
f, err := parser.ParseFile(token.NewFileSet(), "errcode.go", src, 0)
if err != nil {
return nil, err
}
codes := map[string]string{}
var table *ast.CompositeLit
for _, decl := range f.Decls {
gen, ok := decl.(*ast.GenDecl)
if !ok {
continue
}
for _, spec := range gen.Specs {
vs, ok := spec.(*ast.ValueSpec)
if !ok {
continue
}
for i, name := range vs.Names {
if i >= len(vs.Values) {
continue
}
switch gen.Tok {
case token.CONST:
if s, ok := stringLit(vs.Values[i]); ok {
codes[name.Name] = s
}
case token.VAR:
if lit, ok := vs.Values[i].(*ast.CompositeLit); ok && name.Name == "errorActions" {
table = lit
}
}
}
}
}
if table == nil {
return nil, errors.New("no errorActions")
}
actions := map[string]string{}
for _, elt := range table.Elts {
kv, ok := elt.(*ast.KeyValueExpr)
if !ok {
return nil, errors.New("errorActions holds an entry that is no key and value")
}
key, ok := kv.Key.(*ast.Ident)
if !ok {
return nil, errors.New("errorActions has a key that is no constant")
}
code, ok := codes[key.Name]
if !ok {
return nil, fmt.Errorf("errorActions names %s, which is no string constant", key.Name)
}
action, ok := stringLit(kv.Value)
if !ok {
return nil, fmt.Errorf("errorActions pairs %s with no string", code)
}
actions[code] = action
}
return actions, nil
}

func stringLit(e ast.Expr) (string, bool) {
lit, ok := e.(*ast.BasicLit)
if !ok || lit.Kind != token.STRING {
return "", false
}
s, err := strconv.Unquote(lit.Value)
return s, err == nil
}

var (
tableStart = regexp.MustCompile(`(?m)^export const ACTION_OF = \{$`)
tableEntry = regexp.MustCompile(`^\s*([a-z_]+): "([a-z_]+)",?$`)
)

// contractActions reads ACTION_OF, one `code: "action",` to a line, up to its closing brace.
func contractActions(src string) (map[string]string, error) {
start := tableStart.FindStringIndex(src)
if start == nil {
return nil, errors.New("no ACTION_OF")
}
actions := map[string]string{}
for _, line := range strings.Split(src[start[1]:], "\n")[1:] {
if strings.HasPrefix(line, "}") {
return actions, nil
}
m := tableEntry.FindStringSubmatch(line)
if m == nil {
return nil, fmt.Errorf("ACTION_OF holds %q, which is no `code: \"action\",`", line)
}
actions[m[1]] = m[2]
}
return nil, errors.New("ACTION_OF does not end")
}

// diff says, sorted, each code one side has and the other lacks, and each the two pair otherwise.
func diff(spin, contract map[string]string) []string {
var out []string
for code, action := range spin {
got, ok := contract[code]
switch {
case !ok:
out = append(out, fmt.Sprintf("spin writes %s (%s), which the contract lacks", code, action))
case got != action:
out = append(out, fmt.Sprintf("%s: spin pairs %s, the contract %s", code, action, got))
}
}
for code := range contract {
if _, ok := spin[code]; !ok {
out = append(out, fmt.Sprintf("the contract has %s, which spin no longer writes", code))
}
}
sort.Strings(out)
return out
}
144 changes: 144 additions & 0 deletions hack/errcodes/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
package main

import (
"os"
"path/filepath"
"strings"
"testing"
)

// spinSrc is errcode.go as spin writes it: the codes, then errorActions.
const spinSrc = `package cmd

type errorCode string

const (
codeNotSignedIn errorCode = "not_signed_in"
// The key this machine logs in with is none the control plane certifies.
codeKeyNotEnrolled errorCode = "key_not_enrolled"
codeInternal errorCode = "internal"
)

const muxPersist = "10m"

var errorActions = map[errorCode]string{
codeNotSignedIn: "login",
codeKeyNotEnrolled: "add_key",
codeInternal: "details",
}
`

const contractSrc = `export type Action = "login" | "add_key" | "details"

export const ACTION_OF = {
not_signed_in: "login",
key_not_enrolled: "add_key",
internal: "details",
} as const satisfies Record<ErrorCode, Action>
`

func TestSpinActions(t *testing.T) {
got, err := spinActions([]byte(spinSrc))
if err != nil {
t.Fatal(err)
}
want := map[string]string{"not_signed_in": "login", "key_not_enrolled": "add_key", "internal": "details"}
if len(got) != len(want) {
t.Fatalf("got %v, want %v", got, want)
}
for k, v := range want {
if got[k] != v {
t.Errorf("%s: got %q, want %q", k, got[k], v)
}
}
}

func TestContractActions(t *testing.T) {
got, err := contractActions(contractSrc)
if err != nil {
t.Fatal(err)
}
if len(got) != 3 || got["key_not_enrolled"] != "add_key" {
t.Fatalf("got %v", got)
}
}

// The contract this repository holds parses: the check is never green for reading nothing.
func TestTheContractParses(t *testing.T) {
src, err := os.ReadFile(filepath.Join("..", "..", "src", "cli", "contract.ts"))
if err != nil {
t.Fatal(err)
}
got, err := contractActions(string(src))
if err != nil {
t.Fatal(err)
}
if got["internal"] != "details" {
t.Fatalf("ACTION_OF read as %v", got)
}
}

func TestDiff(t *testing.T) {
for _, tc := range []struct {
name string
contract string
want []string
}{
{name: "the same", contract: contractSrc},
{
name: "a code spin added",
contract: strings.Replace(contractSrc, " key_not_enrolled: \"add_key\",\n", "", 1),
want: []string{"spin writes key_not_enrolled (add_key), which the contract lacks"},
},
{
name: "a code spin dropped",
contract: strings.Replace(contractSrc, " internal:", " no_key_held: \"add_key\",\n internal:", 1),
want: []string{"the contract has no_key_held, which spin no longer writes"},
},
{
name: "another action",
contract: strings.Replace(contractSrc, `not_signed_in: "login"`, `not_signed_in: "details"`, 1),
want: []string{"not_signed_in: spin pairs login, the contract details"},
},
} {
t.Run(tc.name, func(t *testing.T) {
spin, err := spinActions([]byte(spinSrc))
if err != nil {
t.Fatal(err)
}
contract, err := contractActions(tc.contract)
if err != nil {
t.Fatal(err)
}
got := diff(spin, contract)
if strings.Join(got, "|") != strings.Join(tc.want, "|") {
t.Fatalf("got %q, want %q", got, tc.want)
}
})
}
}

func TestRefused(t *testing.T) {
for _, tc := range []struct{ name, spin, contract, want string }{
{"no table in spin", "package cmd\n", contractSrc, "no errorActions"},
{"a key that is no constant", strings.Replace(spinSrc, "codeInternal: \"details\"", "\"internal\": \"details\"", 1), contractSrc, "no constant"},
{"no table in the contract", spinSrc, "export const X = {}\n", "no ACTION_OF"},
{"an entry that is no pair", spinSrc, strings.Replace(contractSrc, ` internal: "details",`, ` ...MORE,`, 1), "no `code"},
{"a table that does not end", spinSrc, "export const ACTION_OF = {\n internal: \"details\",", "does not end"},
} {
t.Run(tc.name, func(t *testing.T) {
dir := t.TempDir()
spin, contract := filepath.Join(dir, "errcode.go"), filepath.Join(dir, "contract.ts")
if err := os.WriteFile(spin, []byte(tc.spin), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(contract, []byte(tc.contract), 0o600); err != nil {
t.Fatal(err)
}
err := check(spin, contract)
if err == nil || !strings.Contains(err.Error(), tc.want) {
t.Fatalf("got %v, want an error holding %q", err, tc.want)
}
})
}
}
Loading
Loading