diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..379a8ed21 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# temporal/api is generated from temporal/api_next by make stable-api. +temporal/api/** linguist-generated=true diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f8573cae3..4f31303ea 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,6 +35,7 @@ jobs: - uses: actions/setup-go@7b8cf10d4e4a01d4992d18a89f4d7dc5a3e6d6f4 # v4.3.0 with: go-version: '^1.25' + - uses: arduino/setup-protoc@a8b67ba40b37d35169e222f3bb352603327985b6 # v2.1.0 - name: Install buf run: make buf-install - name: Test generate-stable diff --git a/Makefile b/Makefile index a21bc3f8a..db16f4d2d 100644 --- a/Makefile +++ b/Makefile @@ -53,13 +53,14 @@ stable-api: stable-api-test: printf $(COLOR) "Run generate-stable tests..." @cd cmd/generate-stable-protos/ && go test ./... - printf $(COLOR) "Check that both Buf modules exclude fixture protos..." - files=$$(buf ls-files && buf ls-files --config buf.next.yaml) && ! grep '^cmd/' <<<"$$files" + printf $(COLOR) "Check that each Buf module excludes fixture protos and the other API tree..." + buf ls-files | awk '/^(cmd|temporal\/api_next)\// { print; forbidden = 1 } END { if (forbidden) exit 1 }' + buf ls-files --config buf.next.yaml | awk '/^(cmd|temporal\/api)\// { print; forbidden = 1 } END { if (forbidden) exit 1 }' ##### Compile proto files for go ##### grpc: stable-api buf-lint api-linter resource-id-lint buf-breaking clean go-grpc fix-path -go-grpc: clean $(PROTO_OUT) +go-grpc: clean $(PROTO_OUT) | stable-api printf $(COLOR) "Compile for go-gRPC..." protogen \ --root=$(PROTO_ROOT) \ @@ -79,7 +80,7 @@ fix-path: # We need to rewrite bits of this to support our shorthand payload format # We use both yq and jq here as they preserve comments and the ordering of the original # document -http-api-docs: +http-api-docs: | stable-api protoc -I $(PROTO_ROOT) \ --openapi_out=$(OAPI_OUT) \ --openapi_opt=enum_type=string \ @@ -125,7 +126,7 @@ sync-nexus-annotations: ##### Linters ##### API_LINTER_FMT = 'map(select(.problems != []) | . as $$file | .problems[] | {rule: .rule_doc_uri, location: "\($$file.file_path):\(.location.start_position.line_number)"}) | group_by(.rule) | .[] | .[0].rule + ":\n" + (map("\t" + .location) | join("\n"))' -api-linter: +api-linter: | stable-api printf $(COLOR) "Run api-linter on temporal/api_next..." @api-linter --set-exit-status $(PROTO_IMPORTS) --config $(PROTO_ROOT)/api-linter.yaml --output-format json $(PROTO_FILES_NEXT) | gojq -r $(API_LINTER_FMT) printf $(COLOR) "Run api-linter on temporal/api..." @@ -133,7 +134,7 @@ api-linter: # Every RPC needs a temporal-resource-id request_header annotation for routing, or an entry in # cmd/protoc-gen-resource-id-lint/exemptions.go. -resource-id-lint: resource-id-lint-install +resource-id-lint: resource-id-lint-install | stable-api printf $(COLOR) "Check temporal-resource-id annotations..." protoc $(PROTO_IMPORTS) \ --resource-id-lint_out=. \ @@ -146,16 +147,16 @@ resource-id-lint-install: $(STAMPDIR): mkdir $@ -$(STAMPDIR)/buf-dep-prune: $(STAMPDIR) buf.yaml +$(STAMPDIR)/buf-dep-prune: $(STAMPDIR) buf.yaml | stable-api printf $(COLOR) "Pruning buf module" buf dep prune touch $@ -buf-lint: $(STAMPDIR)/buf-dep-prune +buf-lint: $(STAMPDIR)/buf-dep-prune | stable-api printf $(COLOR) "Run buf linter..." (cd $(PROTO_ROOT) && buf lint) -buf-breaking: +buf-breaking: | stable-api @printf $(COLOR) "Run buf breaking changes check for stable API against main branch..." @(cd $(PROTO_ROOT) && buf breaking --against '$(BUF_BREAKING_AGAINST)') @printf $(COLOR) "Run buf breaking changes check for api_next against main branch..." @@ -163,7 +164,7 @@ buf-breaking: @printf $(COLOR) "Run buf breaking changes check for api_next against previous api_next..." @(cd $(PROTO_ROOT) && bash scripts/check-api-next-breaking.sh '$(BUF_BREAKING_AGAINST)') -nexus-rpc-yaml: nexus-rpc-yaml-install +nexus-rpc-yaml: nexus-rpc-yaml-install | stable-api printf $(COLOR) "Generate nexus/temporal-proto-models-nexusrpc.yaml..." mkdir -p nexus protoc -I $(PROTO_ROOT) \ @@ -180,7 +181,7 @@ nexus-rpc-yaml-install: @cd cmd/protoc-gen-nexus-rpc-yaml && go install . ##### Compile system Nexus WIT files ##### -system-nexus-wit: system-nexus-wit-install nex-gen-install +system-nexus-wit: system-nexus-wit-install nex-gen-install | stable-api printf $(COLOR) "Generate system Nexus WIT..." tmp=$$(mktemp -d); trap 'rm -rf "$$tmp"' EXIT; \ protoc -I $(PROTO_ROOT) --include_imports \ diff --git a/README.md b/README.md index 7042bc4d4..bab1af338 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,24 @@ This repository contains both the protobuf descriptors and OpenAPI documentation Install as git submodule to the project. +## Consumers + +Compile either `temporal/api` (stable) or `temporal/api_next` (preview). Never compile both together. +The trees declare the same proto packages, so compiling both causes duplicate symbols. +The default Buf module in `buf.yaml` excludes `temporal/api_next`. +Use `buf.next.yaml` to compile the preview tree. + ## Contribution -Make your change to the temporal/api_next/proto files, and run `make` to update the openapi definitions. +Edit proto files under `temporal/api_next/`. Run `make stable-api` to regenerate `temporal/api/`, or run +`make` to also update the OpenAPI definitions. Do not edit `temporal/api/` by hand. Commit the regenerated +tree with your changes because CI fails if it is stale. + +Use the `draft` field option or the `draft_message` message option from +[`temporal/api_next/protometa/v1/draft.proto`](temporal/api_next/protometa/v1/draft.proto) to mark draft +declarations. For example, `string user = 7 [(temporal.api.protometa.v1.draft) = "update-user-tagging"];` +is a draft field. The generator removes annotated declarations from the stable tree. + Rust is also required because `make` installs and runs `nex-gen` when regenerating system Nexus WIT files. ## Breaking changes diff --git a/cmd/generate-stable-protos/breaking_test.go b/cmd/generate-stable-protos/breaking_test.go index e961a0cfa..51acebce4 100644 --- a/cmd/generate-stable-protos/breaking_test.go +++ b/cmd/generate-stable-protos/breaking_test.go @@ -9,6 +9,7 @@ import ( ) func TestDraftBreakingReservations(t *testing.T) { + t.Parallel() config, err := filepath.Abs("../../buf.next.yaml") if err != nil { t.Fatal(err) @@ -47,6 +48,7 @@ message Example { %s } {"promoted", "string value = 1;", nil}, } { t.Run(tc.name, func(t *testing.T) { + t.Parallel() after := image(t, tc.field) out, err := exec.Command("buf", "breaking", after, "--against", before, "--config", config).CombinedOutput() if len(tc.want) == 0 { @@ -68,6 +70,7 @@ message Example { %s } } func TestDraftBreakingBootstrap(t *testing.T) { + t.Parallel() root, err := filepath.Abs("../..") if err != nil { t.Fatal(err) @@ -82,6 +85,7 @@ func TestDraftBreakingBootstrap(t *testing.T) { {"invalid draft history naming the bootstrap phrase", "temporal/api_next/no .proto files/example.proto", "invalid proto", false}, } { t.Run(tc.name, func(t *testing.T) { + t.Parallel() baseline := t.TempDir() path := filepath.Join(baseline, tc.path) if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { diff --git a/cmd/generate-stable-protos/comments.go b/cmd/generate-stable-protos/comments.go index 051ffe270..c472c55d8 100644 --- a/cmd/generate-stable-protos/comments.go +++ b/cmd/generate-stable-protos/comments.go @@ -51,14 +51,14 @@ func findDraftComments(f *ir.File, dels []ast.DeclAny) (draftComments, error) { } // checkCommentsAfter rejects comments between a removed declaration and the next code. -// protoc attaches such comments to the removed declaration or to nothing, and the printer -// then keeps them. Only a comment on the declaration's own last line, or the doc block -// directly above the next surviving declaration, may sit there. +// The protoc compiler attaches such comments to the removed declaration or to nothing, +// and the printer then keeps them. Only a comment on the declaration's own last line, +// or the doc block directly above the next surviving declaration, may sit there. func checkCommentsAfter(f *ir.File, dels []ast.DeclAny) error { removed := func(offset int) bool { return slices.ContainsFunc(dels, func(d ast.DeclAny) bool { return d.Span().Start <= offset && offset < d.Span().End }) } - // LeafSpan, because the Span of a brace pair covers its whole body. + // Use LeafSpan because the Span of a brace pair covers its whole body. line := func(tok token.Token) int { return tok.LeafSpan().StartLoc().Line } lastLine := func(c token.Token) int { return line(c) + strings.Count(strings.TrimRight(c.Text(), "\n"), "\n") @@ -81,7 +81,7 @@ func checkCommentsAfter(f *ir.File, dels []ast.DeclAny) error { } } if found && removed(next.LeafSpan().Start) { - continue // these belong to the next removed declaration and are checked through it + continue // These comments are checked with the next removed declaration, to which they belong. } doc := len(gap) if found && !closesScope(next) { @@ -98,8 +98,8 @@ func checkCommentsAfter(f *ir.File, dels []ast.DeclAny) error { return nil } -// closesScope reports whether tok is the closing token of a pair such as "}"; Text -// returns the open token's text for both ends. +// closesScope reports whether tok is the closing token of a pair such as "}". +// Text returns the open token's text for both ends. func closesScope(tok token.Token) bool { if tok.IsLeaf() { return false @@ -134,20 +134,24 @@ func commentWords(stream *token.Stream) map[string]int { if tok.Kind() != token.Comment { continue } - text, block := strings.CutPrefix(tok.Text(), "/*") - if block { - text = strings.TrimSuffix(text, "*/") - } else { - text = strings.TrimPrefix(text, "//") - } - for i, line := range strings.Split(text, "\n") { - if block && i > 0 { - line = strings.TrimPrefix(strings.TrimSpace(line), "*") - } - for _, w := range strings.Fields(line) { - counts[w]++ - } + for _, w := range commentTokenWords(tok.Text()) { + counts[w]++ } } return counts } + +func commentTokenWords(text string) []string { + text, block := strings.CutPrefix(text, "/*") + if !block { + return strings.Fields(strings.TrimPrefix(text, "//")) + } + var words []string + for i, line := range strings.Split(strings.TrimSuffix(text, "*/"), "\n") { + if i > 0 { + line = strings.TrimPrefix(strings.TrimSpace(line), "*") + } + words = append(words, strings.Fields(line)...) + } + return words +} diff --git a/cmd/generate-stable-protos/comments_test.go b/cmd/generate-stable-protos/comments_test.go index 13ba0f956..37e2590bb 100644 --- a/cmd/generate-stable-protos/comments_test.go +++ b/cmd/generate-stable-protos/comments_test.go @@ -12,6 +12,7 @@ import ( // after it that protoc attaches to nothing. The passing case also pins the raw printer // output, which TestStableProjection cannot see because it runs buf format first. func TestDraftCommentOwnership(t *testing.T) { + t.Parallel() const fixture = "temporal/api_next/fixture.proto" const after = `after a removed draft declaration would survive in the stable output; move it directly above a declaration, or delete it` input, err := os.ReadFile(filepath.Join("testdata/comments/input", fixture)) @@ -58,6 +59,7 @@ func TestDraftCommentOwnership(t *testing.T) { }, } { t.Run(tc.name, func(t *testing.T) { + t.Parallel() root, out := t.TempDir(), t.TempDir() if err := os.CopyFS(root, os.DirFS("testdata/comments/input")); err != nil { t.Fatal(err) @@ -68,7 +70,7 @@ func TestDraftCommentOwnership(t *testing.T) { if err := os.WriteFile(filepath.Join(root, fixture), []byte(strings.Replace(string(input), tc.old, tc.new, 1)), 0600); err != nil { t.Fatal(err) } - err := stableProtosGenerator(root, out) + err := stableProtosGenerator(t.Context(), root, out) if tc.want != "" { if err == nil || !strings.Contains(err.Error(), tc.want) { t.Fatalf("want %q, got %v", tc.want, err) diff --git a/cmd/generate-stable-protos/fixtures_test.go b/cmd/generate-stable-protos/fixtures_test.go new file mode 100644 index 000000000..df70164c3 --- /dev/null +++ b/cmd/generate-stable-protos/fixtures_test.go @@ -0,0 +1,136 @@ +package main + +import ( + "encoding/json" + "errors" + "io/fs" + "maps" + "os" + "path/filepath" + "reflect" + "slices" + "strings" + "testing" +) + +// TestFixtures runs the generator on every fixture under testdata. A fixture is a +// directory with an input/ api_next tree, and optionally an expected.json and an +// expected/ tree holding the raw generator output without its generated header. +func TestFixtures(t *testing.T) { + t.Parallel() + for _, fixture := range findFixtures(t) { + t.Run(fixture, func(t *testing.T) { + t.Parallel() + runFixture(t, filepath.Join("testdata", fixture)) + }) + } +} + +// fixtureExpectation is a fixture's expected.json. +type fixtureExpectation struct { + // Error is a substring of the expected generator error; empty means success. + Error string `json:"error"` + // Annotations are the draft annotations the generator must accept. + Annotations draftAnnotations `json:"annotations"` +} + +// findFixtures returns the fixture directories under testdata, relative to it. +func findFixtures(t *testing.T) []string { + t.Helper() + var fixtures []string + if err := filepath.WalkDir("testdata", func(path string, entry fs.DirEntry, err error) error { + if err != nil || !entry.IsDir() { + return err + } + for _, marker := range []string{"input", "expected.json"} { + if _, err := os.Stat(filepath.Join(path, marker)); err == nil { + relative, err := filepath.Rel("testdata", path) + if err != nil { + return err + } + fixtures = append(fixtures, filepath.ToSlash(relative)) + return filepath.SkipDir + } + } + return nil + }); err != nil { + t.Fatal(err) + } + return fixtures +} + +func runFixture(t *testing.T, dir string) { + t.Helper() + var expected fixtureExpectation + if data, err := os.ReadFile(filepath.Join(dir, "expected.json")); err == nil { + if err := json.Unmarshal(data, &expected); err != nil { + t.Fatal(err) + } + } else if !errors.Is(err, fs.ErrNotExist) { + t.Fatal(err) + } + root := filepath.Join(dir, "input") + out := t.TempDir() + + if expected.Error != "" { + sentinel := map[string]string{"retained": "old"} + if err := os.WriteFile(filepath.Join(out, "retained"), []byte("old"), 0o600); err != nil { + t.Fatal(err) + } + err := stableProtosGenerator(t.Context(), root, out) + if err == nil || !strings.Contains(err.Error(), expected.Error) { + t.Fatalf("want error %q, got %v", expected.Error, err) + } + if !reflect.DeepEqual(sentinel, readTree(t, out)) { + t.Fatal("generation failure modified output") + } + return + } + + if err := stableProtosGenerator(t.Context(), root, out); err != nil { + t.Fatal(err) + } + actual := readTree(t, out) + again := t.TempDir() + if err := stableProtosGenerator(t.Context(), root, again); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(actual, readTree(t, again)) { + t.Fatal("generator output is not deterministic") + } + + paths, err := getAPINextPaths(root) + if err != nil { + t.Fatal(err) + } + _, _, annotations, err := loadAPINext(t.Context(), root, paths) + if err != nil { + t.Fatal(err) + } + if !maps.Equal(expected.Annotations, annotations) { + t.Errorf("draft annotations differ\nexpected: %v\nactual: %v", expected.Annotations, annotations) + } + + if _, err := os.Stat(filepath.Join(dir, "expected")); err == nil { + bodies := map[string]string{} + for path, text := range actual { + body, ok := strings.CutPrefix(text, generatedHeader) + if !ok { + t.Fatalf("%s: missing generated header", path) + } + bodies[path] = body + } + golden := readTree(t, filepath.Join(dir, "expected")) + for _, path := range sortedKeys(golden, bodies) { + if golden[path] != bodies[path] { + t.Errorf("%s differs from the golden\nexpected:\n%s\nactual:\n%s", path, golden[path], bodies[path]) + } + } + } +} + +func sortedKeys(a, b map[string]string) []string { + keys := maps.Clone(a) + maps.Copy(keys, b) + return slices.Sorted(maps.Keys(keys)) +} diff --git a/cmd/generate-stable-protos/main.go b/cmd/generate-stable-protos/main.go index 02fedd7cf..cc647934c 100644 --- a/cmd/generate-stable-protos/main.go +++ b/cmd/generate-stable-protos/main.go @@ -6,8 +6,10 @@ import ( "flag" "fmt" "io/fs" + "maps" "os" "path/filepath" + "slices" "sort" "strconv" "strings" @@ -48,14 +50,13 @@ func main() { *outDir = *root } - if err := stableProtosGenerator(*root, *outDir); err != nil { + if err := stableProtosGenerator(context.Background(), *root, *outDir); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } -func stableProtosGenerator(root, outDir string) error { - ctx := context.Background() +func stableProtosGenerator(ctx context.Context, root, outDir string) error { paths, err := getAPINextPaths(root) if err != nil { return err @@ -69,8 +70,8 @@ func stableProtosGenerator(root, outDir string) error { return err } - // import stripping has to happen after the draft-tagged declarations are deleted - // because unused imports are only detectable after it is re-rendered + // Strip unused imports after deleting draft-tagged declarations and re-rendering the protos, + // because only then can we detect which imports are unused. stableProtos, err := organizeImports(ctx, root, strippedOrder, strippedProtos) if err != nil { return err @@ -95,15 +96,16 @@ func stableProtosGenerator(root, outDir string) error { return writeFiles(outDir, stableProtos) } -func stripDrafts(ctx context.Context, root string, paths []string) ([]string, map[string]string, map[string]draftComments, error) { - // first, lower the api_next set into ir +// loadAPINext lowers the api_next corpus, discovers the draft-tag extension set and +// validates every draft annotation, returning the annotations it accepted. +func loadAPINext(ctx context.Context, root string, paths []string) (map[string]*ir.File, draftTags, draftAnnotations, error) { + // First, lower the api_next corpus into IR. results, err := lowerFiles(ctx, baseOpener(root), paths) if err != nil { return nil, nil, nil, fmt.Errorf("lower api_next corpus: %w", err) } - // need to iterate to find the draft proto- also check - // for errors while iterating so it doesnt have to be repeated + // Check for errors while indexing files by path so we can look up the draft proto in one pass. byPath := make(map[string]*ir.File, len(paths)) for i, p := range paths { if results[i].Fatal != nil { @@ -114,7 +116,7 @@ func stripDrafts(ctx context.Context, root string, paths []string) ([]string, ma return nil, nil, nil, fmt.Errorf("internal error: incremental.Run result %d has path %q, expected %q", i, got, p) } for imp := range seq.Values(irFile.Imports()) { - // Draft options reached through a public re-export would leak it into the stable tree. + // A public re-export of the draft options proto would leak it into the stable tree. if imp.Direct && imp.Public && imp.Path() == draftTagsPath { return nil, nil, nil, fmt.Errorf("%s: public import of %s is not supported; import it directly", p, draftTagsPath) } @@ -130,18 +132,28 @@ func stripDrafts(ctx context.Context, root string, paths []string) ([]string, ma if err != nil { return nil, nil, nil, err } + annotations := draftAnnotations{} for _, p := range paths { - if err := validateDraftAnnotations(tags, byPath[p]); err != nil { + accepted, err := validateDraftAnnotations(tags, byPath[p]) + if err != nil { return nil, nil, nil, err } + maps.Copy(annotations, accepted) + } + return byPath, tags, annotations, nil +} + +func stripDrafts(ctx context.Context, root string, paths []string) ([]string, map[string]string, map[string]draftComments, error) { + byPath, tags, _, err := loadAPINext(ctx, root, paths) + if err != nil { + return nil, nil, nil, err } - stableOrder := make([]string, 0, len(paths)) protoTexts := make(map[string]string, len(paths)) comments := make(map[string]draftComments, len(paths)) for _, p := range paths { irFile := byPath[p] - // skip draft.proto itself + // Skip draft.proto itself. if p == draftTagsPath { continue } @@ -163,12 +175,11 @@ func stripDrafts(ctx context.Context, root string, paths []string) ([]string, ma } protoTexts[p] = protoText - stableOrder = append(stableOrder, p) } - return stableOrder, protoTexts, comments, nil + return slices.Sorted(maps.Keys(protoTexts)), protoTexts, comments, nil } -// strip unused imports and rename import to stable (api_next -> api) +// organizeImports removes unused imports and rewrites api_next import paths to their stable api paths. func organizeImports(ctx context.Context, root string, order []string, texts map[string]string) (map[string]string, error) { results, err := lowerFiles(ctx, memOpener(root, texts), order) if err != nil { @@ -204,27 +215,23 @@ func organizeImports(ctx context.Context, root string, order []string, texts map return stableTexts, nil } -// re-lower one more time to ensure there are no compilation issues +// verifyGeneratedProtos lowers the generated protos again to check for compilation errors. func verifyGeneratedProtos(ctx context.Context, root string, stableTexts map[string]string) error { - paths := make([]string, 0, len(stableTexts)) - for p := range stableTexts { - paths = append(paths, p) - } - sort.Strings(paths) + paths := slices.Sorted(maps.Keys(stableTexts)) results, err := lowerFiles(ctx, memOpener(root, stableTexts), paths) if err != nil { return fmt.Errorf("verify stable tree failed: %w", err) } - var jErr error + var errs error for i, r := range results { if r.Fatal != nil { - jErr = errors.Join(jErr, fmt.Errorf("verification failed at file %q: %w", paths[i], r.Fatal)) + errs = errors.Join(errs, fmt.Errorf("verification failed at file %q: %w", paths[i], r.Fatal)) } } - return jErr + return errs } -// lowerFiles lowers paths in one session; each pass must construct its opener once. +// lowerFiles lowers paths in one session. Each pass must construct its opener once. func lowerFiles(ctx context.Context, opener source.Opener, paths []string) ([]incremental.Result[*ir.File], error) { session := &ir.Session{} lowerQueries := make([]incremental.Query[*ir.File], len(paths)) @@ -241,7 +248,9 @@ func lowerFiles(ctx context.Context, opener source.Opener, paths []string) ([]in return results, nil } -// TODO: check if the buf formatter rules can just get pulled into a custom formatter +// printFile formats the file with the legacy formatter. +// +// TODO: Check whether a custom formatter can reuse Buf's formatting rules. func printFile(file *ir.File) (string, error) { return printer.PrintFile(printer.Options{Format: true, Formatting: printer.Legacy()}, file.AST()) } @@ -325,7 +334,7 @@ func rewriteImportPaths(text string) (string, error) { if err := prototext.Unmarshal([]byte("value: "+partSpan.Text()), &part); err != nil { return "", fmt.Errorf("decode import literal: %w", err) } - // The _next suffix can straddle concatenated literals; preserve their comments. + // The _next suffix can straddle concatenated literals. Preserve their comments. from := max(len(stableAPIPrefix)-1-offset, 0) to := min(len(apiNextPrefix)-1-offset, len(part.Value)) offset += len(part.Value) @@ -333,10 +342,22 @@ func rewriteImportPaths(text string) (string, error) { continue } out.WriteString(text[start:partSpan.Start]) - out.WriteString(strconv.Quote(part.Value[:from] + part.Value[to:])) + out.WriteString(quoteLike(partSpan.Text(), part.Value[:from]+part.Value[to:])) start = partSpan.End } } out.WriteString(text[start:]) return out.String(), nil } + +// quoteLike quotes s with the quote character of the literal it replaces. The printer +// sorts imports by their raw text, so changing the quote would reorder them on the next +// run. +func quoteLike(literal, s string) string { + quoted := strconv.Quote(s) + if !strings.HasPrefix(literal, "'") { + return quoted + } + body := strings.ReplaceAll(quoted[1:len(quoted)-1], `\"`, `"`) + return "'" + strings.ReplaceAll(body, "'", `\'`) + "'" +} diff --git a/cmd/generate-stable-protos/main_test.go b/cmd/generate-stable-protos/main_test.go index fa7a6e779..5907d57ae 100644 --- a/cmd/generate-stable-protos/main_test.go +++ b/cmd/generate-stable-protos/main_test.go @@ -1,87 +1,16 @@ package main import ( - "encoding/json" "io/fs" "os" "os/exec" "path/filepath" "reflect" - "strings" "testing" ) -func TestStableProjection(t *testing.T) { - for _, fixture := range []string{"classification/valid", "classification/message-types", "imports"} { - t.Run(fixture, func(t *testing.T) { - expected := readTree(t, filepath.Join("testdata", fixture, "expected")) - for range 2 { - out := t.TempDir() - if err := stableProtosGenerator(filepath.Join("testdata", fixture, "input"), out); err != nil { - t.Fatal(err) - } - formatTree(t, out) - actual := readTree(t, out) - if !reflect.DeepEqual(expected, actual) { - t.Fatalf("projection differs from independently authored fixture\nexpected: %v\nactual: %v", expected, actual) - } - } - }) - } -} - -func TestAnnotationClassification(t *testing.T) { - dirs, err := os.ReadDir("testdata/classification") - if err != nil { - t.Fatal(err) - } - for _, dir := range dirs { - t.Run(dir.Name(), func(t *testing.T) { - fixture := filepath.Join("testdata/classification", dir.Name()) - data, err := os.ReadFile(filepath.Join(fixture, "expected.json")) - if err != nil { - t.Fatal(err) - } - var expected struct { - Error string `json:"error"` - } - if err := json.Unmarshal(data, &expected); err != nil { - t.Fatal(err) - } - err = stableProtosGenerator(filepath.Join(fixture, "input"), t.TempDir()) - if expected.Error == "" { - if err != nil { - t.Fatal(err) - } - return - } - if err == nil || !strings.Contains(err.Error(), expected.Error) { - t.Fatalf("want %q, got %v", expected.Error, err) - } - }) - } -} - -func TestProjectionFailures(t *testing.T) { - for _, fixture := range []string{"dangling", "missing"} { - t.Run(fixture, func(t *testing.T) { - out := t.TempDir() - sentinel := filepath.Join(out, "retained") - if err := os.WriteFile(sentinel, []byte("old"), 0600); err != nil { - t.Fatal(err) - } - before := readTree(t, out) - if err := stableProtosGenerator(filepath.Join("testdata", fixture, "input"), out); err == nil { - t.Fatal("expected invalid input to fail") - } - if !reflect.DeepEqual(before, readTree(t, out)) { - t.Fatal("generation failure modified output") - } - }) - } -} - func TestRewriteImportPaths(t *testing.T) { + t.Parallel() input := `syntax = "proto3"; import public /* before */ 'temporal/api_next/used.proto' /* after */; import "google/protobuf/any.proto"; @@ -90,7 +19,7 @@ option java_package = "temporal/api_next/used.proto"; // import "temporal/api_next/used.proto"; ` expected := `syntax = "proto3"; -import public /* before */ "temporal/api/used.proto" /* after */; +import public /* before */ 'temporal/api/used.proto' /* after */; import "google/protobuf/any.proto"; import "temporal/api" /* internal comment */ "/another.proto"; option java_package = "temporal/api_next/used.proto"; @@ -103,18 +32,17 @@ option java_package = "temporal/api_next/used.proto"; if actual != expected { t.Fatalf("expected %q, got %q", expected, actual) } - if _, err := rewriteImportPaths(`import "unterminated`); err == nil { - t.Fatal("expected invalid syntax to fail") - } } func TestStableReplacement(t *testing.T) { + t.Parallel() script, err := filepath.Abs("../../scripts/stable-api.sh") if err != nil { t.Fatal(err) } for _, failure := range []string{"generation", "formatting", "replacement", "none"} { t.Run(failure, func(t *testing.T) { + t.Parallel() root := t.TempDir() tools := t.TempDir() if err := os.MkdirAll(filepath.Join(root, "temporal/api/nested"), 0755); err != nil { @@ -162,14 +90,6 @@ exec /bin/mv "$@" } } -func formatTree(t *testing.T, root string) { - t.Helper() - cmd := exec.Command("buf", "format", "-w", root) - if output, err := cmd.CombinedOutput(); err != nil { - t.Fatalf("format: %v: %s", err, output) - } -} - func readTree(t *testing.T, root string) map[string]string { t.Helper() files := map[string]string{} @@ -195,3 +115,49 @@ func readTree(t *testing.T, root string) map[string]string { } return files } + +func TestStableAPIBufGuards(t *testing.T) { + t.Parallel() + toolDir := t.TempDir() + for name, script := range map[string]string{ + "go": "exit 0", + "buf": `if [[ "$*" == "ls-files --config buf.next.yaml" ]]; then + printf '%s\n' "$NEXT_FILES" + exit "$NEXT_STATUS" +fi +printf '%s\n' "$DEFAULT_FILES" +exit "$DEFAULT_STATUS"`, + "grep": `if [[ "$FILTER_FAIL" == 1 ]]; then exit 2; fi +exec /usr/bin/grep "$@"`, + "awk": `if [[ "$FILTER_FAIL" == 1 ]]; then exit 2; fi +exec /usr/bin/awk "$@"`, + } { + if err := os.WriteFile(filepath.Join(toolDir, name), []byte("#!/bin/bash\n"+script+"\n"), 0o755); err != nil { + t.Fatal(err) + } + } + for _, tc := range []struct { + name, defaultFiles, nextFiles, defaultStatus, nextStatus, filterFail string + wantFailure bool + }{ + {"clean listings", "temporal/api/service.proto", "temporal/api_next/service.proto", "0", "0", "0", false}, + {"preview file in default listing", "temporal/api_next/service.proto", "", "0", "0", "0", true}, + {"stable file in preview listing", "", "temporal/api/service.proto", "0", "0", "0", true}, + {"fixture in default listing", "cmd/fixture.proto", "", "0", "0", "0", true}, + {"fixture in preview listing", "", "cmd/fixture.proto", "0", "0", "0", true}, + {"default Buf failure", "", "", "2", "0", "0", true}, + {"preview Buf failure", "", "", "0", "2", "0", true}, + {"filter failure", "", "", "0", "0", "1", true}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + cmd := exec.Command("make", "-C", "../..", "stable-api-test", "PATH="+toolDir+string(os.PathListSeparator)+os.Getenv("PATH")) + cmd.Env = append(os.Environ(), "DEFAULT_FILES="+tc.defaultFiles, "NEXT_FILES="+tc.nextFiles, + "DEFAULT_STATUS="+tc.defaultStatus, "NEXT_STATUS="+tc.nextStatus, "FILTER_FAIL="+tc.filterFail) + output, err := cmd.CombinedOutput() + if (err != nil) != tc.wantFailure { + t.Fatalf("want failure %t, got %v\n%s", tc.wantFailure, err, output) + } + }) + } +} diff --git a/cmd/generate-stable-protos/opener.go b/cmd/generate-stable-protos/opener.go index 9f9052ba2..90765f0e4 100644 --- a/cmd/generate-stable-protos/opener.go +++ b/cmd/generate-stable-protos/opener.go @@ -12,10 +12,8 @@ func diskOpener(root string) source.Opener { return &source.FS{FS: os.DirFS(root)} } -// baseOpener is the disk corpus plus well-known types, shared by every pass -// that reads real files unmodified (currently just stripDraftChanges, -// which lowers the authored api_next tree as-is). Construct this once per -// pass and share it across every query in that pass; see the comparability +// baseOpener serves the disk corpus and well-known types. Construct this once +// per pass and share it across every query in that pass. See the comparability // note on memOpener below for why. func baseOpener(root string) source.Opener { return &source.Openers{source.WKTs(), diskOpener(root)} @@ -23,15 +21,13 @@ func baseOpener(root string) source.Opener { // memOpener serves an entire in-memory set of final texts (keyed by their // paths in whatever path space the caller is currently working in) ahead -// of the disk corpus and WKTs. Used by stripUnusedImports (re-lowering -// draft-stripped text) and verifyStrippedProtos (combined cross-file -// verification of the final stable tree). +// of the disk corpus and WKTs. // -// source.Opener implementations must be comparable: an Opener value is -// part of queries.IR's cache key (see queries.IR.Key() in protocompile). +// Implementations of source.Opener must be comparable because an Opener value +// is part of queries.IR's cache key (see queries.IR.Key() in protocompile). // Every constructor in this file therefore returns a pointer, and callers // must call the constructor exactly ONCE per lowering pass and share the -// resulting Opener across every query in that pass -- calling it again +// resulting Opener across every query in that pass. Calling it again // (even with identical contents) yields a distinct pointer, hence a // distinct cache key, forcing protocompile to re-lower the whole corpus. func memOpener(root string, files map[string]string) source.Opener { diff --git a/cmd/generate-stable-protos/tags.go b/cmd/generate-stable-protos/tags.go index 2a35953bf..9fde947e5 100644 --- a/cmd/generate-stable-protos/tags.go +++ b/cmd/generate-stable-protos/tags.go @@ -20,11 +20,15 @@ type draftTags map[ir.FullName]struct{} func getDraftTags(file *ir.File) (draftTags, error) { tags := make(draftTags) extendees := map[string]string{ - "draft": "FieldOptions", "draft_message": "MessageOptions", - "draft_enum": "EnumOptions", "draft_enum_value": "EnumValueOptions", - "draft_service": "ServiceOptions", "draft_method": "MethodOptions", - "draft_file": "FileOptions", "draft_oneof": "OneofOptions", - "draft_extension": "FieldOptions", + "draft": "FieldOptions", + "draft_message": "MessageOptions", + "draft_enum": "EnumOptions", + "draft_enum_value": "EnumValueOptions", + "draft_service": "ServiceOptions", + "draft_method": "MethodOptions", + "draft_file": "FileOptions", + "draft_oneof": "OneofOptions", + "draft_extension": "FieldOptions", } for ext := range seq.Values(file.AllExtensions()) { name, known := extendees[ext.Name()] @@ -51,7 +55,14 @@ func (tags draftTags) has(opts ir.MessageValue) bool { return false } -func validateDraftAnnotations(tags draftTags, f *ir.File) error { +type draftAnnotations map[ir.FullName]draftFeature + +type draftFeature = string + +// validateDraftAnnotations rejects unsupported or malformed draft annotations in f and +// returns the accepted ones. +func validateDraftAnnotations(tags draftTags, f *ir.File) (draftAnnotations, error) { + accepted := draftAnnotations{} check := func(name string, placement string, opts ir.MessageValue) error { for v := range opts.Fields() { if _, ok := tags[v.Field().FullName()]; !ok { @@ -65,11 +76,12 @@ func validateDraftAnnotations(tags draftTags, f *ir.File) error { if !ok || feature == "" || strings.ContainsFunc(feature, unicode.IsSpace) { return fmt.Errorf("%s: draft feature must be nonempty and contain no whitespace", name) } + accepted[ir.FullName(name)] = feature } return nil } if err := check(f.Path(), "file", f.Options()); err != nil { - return err + return nil, err } for t := range seq.Values(f.AllTypes()) { placement := "message" @@ -77,7 +89,7 @@ func validateDraftAnnotations(tags draftTags, f *ir.File) error { placement = "enum" } if err := check(string(t.FullName()), placement, t.Options()); err != nil { - return err + return nil, err } for m := range seq.Values(t.Members()) { placement := "field" @@ -85,43 +97,43 @@ func validateDraftAnnotations(tags draftTags, f *ir.File) error { placement = "enum value" } if err := check(string(m.FullName()), placement, m.Options()); err != nil { - return err + return nil, err } } for o := range seq.Values(t.Oneofs()) { if err := check(string(o.FullName()), "oneof", o.Options()); err != nil { - return err + return nil, err } } } for ext := range seq.Values(f.AllExtensions()) { if err := check(string(ext.FullName()), "extension", ext.Options()); err != nil { - return err + return nil, err } for _, t := range []ir.Type{ext.Element(), ext.Container(), ext.Parent()} { if isDraftType(tags, t) { - return fmt.Errorf("%s: extension references draft type %s unsupported by omission", ext.FullName(), t.FullName()) + return nil, fmt.Errorf("%s: extension references draft type %s unsupported by omission", ext.FullName(), t.FullName()) } } } for s := range seq.Values(f.Services()) { if err := check(string(s.FullName()), "service", s.Options()); err != nil { - return err + return nil, err } for m := range seq.Values(s.Methods()) { if err := check(string(m.FullName()), "method", m.Options()); err != nil { - return err + return nil, err } input, _ := m.Input() output, _ := m.Output() for _, t := range []ir.Type{input, output} { if isDraftType(tags, t) { - return fmt.Errorf("%s: RPC references draft type %s unavailable in the stable API", m.FullName(), t.FullName()) + return nil, fmt.Errorf("%s: RPC references draft type %s unavailable in the stable API", m.FullName(), t.FullName()) } } } } - return nil + return accepted, nil } func isDraftType(tags draftTags, t ir.Type) bool { diff --git a/cmd/generate-stable-protos/testdata/classification/message-types/expected.json b/cmd/generate-stable-protos/testdata/classification/message-types/expected.json index d477392ba..719578c09 100644 --- a/cmd/generate-stable-protos/testdata/classification/message-types/expected.json +++ b/cmd/generate-stable-protos/testdata/classification/message-types/expected.json @@ -1,9 +1,7 @@ { - "fields": { - "fixture.Parent.extra": "feature-c" - }, - "messages": { + "annotations": { "fixture.Draft": "feature-a", - "fixture.Draft.Extra": "feature-b" + "fixture.Draft.Extra": "feature-b", + "fixture.Parent.extra": "feature-c" } } diff --git a/cmd/generate-stable-protos/testdata/classification/message-types/expected/temporal/api/fixture.proto b/cmd/generate-stable-protos/testdata/classification/message-types/expected/temporal/api/fixture.proto index 642d97ba6..444fd3edd 100644 --- a/cmd/generate-stable-protos/testdata/classification/message-types/expected/temporal/api/fixture.proto +++ b/cmd/generate-stable-protos/testdata/classification/message-types/expected/temporal/api/fixture.proto @@ -1,6 +1,3 @@ -// Code generated by generate-stable-protos. DO NOT EDIT. -// @generated - syntax = "proto3"; package fixture; diff --git a/cmd/generate-stable-protos/testdata/classification/message-types/expected/temporal/api/types.proto b/cmd/generate-stable-protos/testdata/classification/message-types/expected/temporal/api/types.proto index 78854f86f..931f0e655 100644 --- a/cmd/generate-stable-protos/testdata/classification/message-types/expected/temporal/api/types.proto +++ b/cmd/generate-stable-protos/testdata/classification/message-types/expected/temporal/api/types.proto @@ -1,6 +1,3 @@ -// Code generated by generate-stable-protos. DO NOT EDIT. -// @generated - syntax = "proto3"; package fixture; diff --git a/cmd/generate-stable-protos/testdata/classification/message/expected.json b/cmd/generate-stable-protos/testdata/classification/message/expected.json index 9410574ea..69c3ac8b8 100644 --- a/cmd/generate-stable-protos/testdata/classification/message/expected.json +++ b/cmd/generate-stable-protos/testdata/classification/message/expected.json @@ -1,5 +1,5 @@ { - "messages": { + "annotations": { "fixture.Example": "feature-a" } } diff --git a/cmd/generate-stable-protos/testdata/classification/valid/expected.json b/cmd/generate-stable-protos/testdata/classification/valid/expected.json index 72cc21fcf..0c140cb07 100644 --- a/cmd/generate-stable-protos/testdata/classification/valid/expected.json +++ b/cmd/generate-stable-protos/testdata/classification/valid/expected.json @@ -1,5 +1,5 @@ { - "fields": { + "annotations": { "fixture.Example.a": "feature-a", "fixture.Example.optional_b": "feature-b", "fixture.Example.draft_choice": "feature-a", diff --git a/cmd/generate-stable-protos/testdata/classification/valid/expected/temporal/api/fixture.proto b/cmd/generate-stable-protos/testdata/classification/valid/expected/temporal/api/fixture.proto index b52868c0c..2c0adb7f4 100644 --- a/cmd/generate-stable-protos/testdata/classification/valid/expected/temporal/api/fixture.proto +++ b/cmd/generate-stable-protos/testdata/classification/valid/expected/temporal/api/fixture.proto @@ -1,6 +1,3 @@ -// Code generated by generate-stable-protos. DO NOT EDIT. -// @generated - syntax = "proto3"; package fixture; diff --git a/cmd/generate-stable-protos/testdata/comments/expected.json b/cmd/generate-stable-protos/testdata/comments/expected.json new file mode 100644 index 000000000..5f0ed611d --- /dev/null +++ b/cmd/generate-stable-protos/testdata/comments/expected.json @@ -0,0 +1,10 @@ +{ + "annotations": { + "fixture.Keeper.b": "b", + "fixture.Keeper.c": "c", + "fixture.Keeper.e": "e", + "fixture.Keeper.f": "f", + "fixture.Keeper.g": "g", + "fixture.Thing": "thing" + } +} diff --git a/cmd/generate-stable-protos/testdata/dangling/expected.json b/cmd/generate-stable-protos/testdata/dangling/expected.json new file mode 100644 index 000000000..451a88a9b --- /dev/null +++ b/cmd/generate-stable-protos/testdata/dangling/expected.json @@ -0,0 +1 @@ +{"error": "cannot find `Missing`"} diff --git a/cmd/generate-stable-protos/testdata/imports/expected.json b/cmd/generate-stable-protos/testdata/imports/expected.json new file mode 100644 index 000000000..e25d2a3bf --- /dev/null +++ b/cmd/generate-stable-protos/testdata/imports/expected.json @@ -0,0 +1,5 @@ +{ + "annotations": { + "fixture.Root.draft": "feature-a" + } +} diff --git a/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/root.proto b/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/root.proto index 07dc23ba0..084261d12 100644 --- a/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/root.proto +++ b/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/root.proto @@ -1,11 +1,7 @@ -// Code generated by generate-stable-protos. DO NOT EDIT. -// @generated - syntax = "proto3"; package fixture; import "temporal/api/used.proto"; - // Keep the literal "temporal/api_next/used.proto" in comments and options. message Root { Used stable = 1 [json_name = "temporal/api_next/used.proto"]; diff --git a/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/unused.proto b/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/unused.proto index 8d1020621..eeeb3e113 100644 --- a/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/unused.proto +++ b/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/unused.proto @@ -1,6 +1,3 @@ -// Code generated by generate-stable-protos. DO NOT EDIT. -// @generated - syntax = "proto3"; package fixture; message Unused {} diff --git a/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/used.proto b/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/used.proto index bf2591135..0cb11575c 100644 --- a/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/used.proto +++ b/cmd/generate-stable-protos/testdata/imports/expected/temporal/api/used.proto @@ -1,6 +1,3 @@ -// Code generated by generate-stable-protos. DO NOT EDIT. -// @generated - syntax = "proto3"; package fixture; message Used {} diff --git a/cmd/generate-stable-protos/testdata/missing/expected.json b/cmd/generate-stable-protos/testdata/missing/expected.json new file mode 100644 index 000000000..fa0da239c --- /dev/null +++ b/cmd/generate-stable-protos/testdata/missing/expected.json @@ -0,0 +1 @@ +{"error": "no such file or directory"} diff --git a/cmd/generate-stable-protos/walk.go b/cmd/generate-stable-protos/walk.go index 98f7659fb..8dbc82aff 100644 --- a/cmd/generate-stable-protos/walk.go +++ b/cmd/generate-stable-protos/walk.go @@ -42,7 +42,7 @@ func walkType(tags draftTags, t ir.Type, dels *[]ast.DeclAny) { } } for nested := range seq.Values(t.Nested()) { - // Synthetic map entries share the field's AST, already handled above. + // Synthetic map entries share the AST of the field handled above. if !nested.IsMapEntry() { walkType(tags, nested, dels) } diff --git a/cmd/generate-stable-protos/walk_test.go b/cmd/generate-stable-protos/walk_test.go index 407897cab..243fdf638 100644 --- a/cmd/generate-stable-protos/walk_test.go +++ b/cmd/generate-stable-protos/walk_test.go @@ -8,6 +8,7 @@ import ( ) func TestDraftSchemaValidation(t *testing.T) { + t.Parallel() schema, err := os.ReadFile("testdata/classification/valid/input/temporal/api_next/protometa/v1/draft.proto") if err != nil { t.Fatal(err) @@ -20,6 +21,7 @@ func TestDraftSchemaValidation(t *testing.T) { {"unrelated extension", string(schema) + "extend google.protobuf.FileOptions { bool draft_notes = 98112; }\n", ""}, } { t.Run(tc.name, func(t *testing.T) { + t.Parallel() root := t.TempDir() path := filepath.Join(root, draftTagsPath) if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { @@ -28,7 +30,7 @@ func TestDraftSchemaValidation(t *testing.T) { if err := os.WriteFile(path, []byte(tc.schema), 0600); err != nil { t.Fatal(err) } - err := stableProtosGenerator(root, t.TempDir()) + err := stableProtosGenerator(t.Context(), root, t.TempDir()) if tc.want == "" { if err != nil { t.Fatal(err) diff --git a/temporal/api_next/update/v1/message.proto b/temporal/api_next/update/v1/message.proto index ff0250df6..7a8da4f74 100644 --- a/temporal/api_next/update/v1/message.proto +++ b/temporal/api_next/update/v1/message.proto @@ -72,7 +72,7 @@ message Request { repeated temporal.api.common.v1.Link links = 5; // Serialization context propagated from the Nexus caller that started this update. temporal.api.nexus.v1.PropagatedSerializationContext propagated_nexus_serialization_context = 6; - // User to be associated with this request. + // User that triggered the update. string user = 7 [(temporal.api.protometa.v1.draft) = "update-user-tagging"]; } @@ -97,6 +97,6 @@ message Acceptance { message Response { Meta meta = 1; Outcome outcome = 2; - // User that triggered the original user. - string user = 6 [(temporal.api.protometa.v1.draft) = "update-user-tagging"]; + // User that triggered the update. + string user = 3 [(temporal.api.protometa.v1.draft) = "update-user-tagging"]; }