diff --git a/.changeset/registry-quotas-command.md b/.changeset/registry-quotas-command.md new file mode 100644 index 00000000..73bc3ee5 --- /dev/null +++ b/.changeset/registry-quotas-command.md @@ -0,0 +1,5 @@ +--- +"cre-cli": minor +--- + +Add `cre registry quotas [registry-id]`, which shows how many workflows are active against each DON family's limit in every registry available to your organization, and how many owner addresses are linked or pending against the linked-owner limit. Supports `--json`. If part of the quotas cannot be read, the rest is still shown with a warning. `cre registry list` now points to the new command. diff --git a/cmd/registry/list/list.go b/cmd/registry/list/list.go index c5d39865..2d246718 100644 --- a/cmd/registry/list/list.go +++ b/cmd/registry/list/list.go @@ -56,6 +56,8 @@ under the ` + "`deployment-registry`" + ` key to target that registry, e.g.: ui.Code(" user-workflow:") ui.Code(fmt.Sprintf(" deployment-registry: %q", registries[0].ID)) ui.Line() + ui.Dim("Run `cre registry quotas` to see your usage against registry quotas.") + ui.Line() return nil }, diff --git a/cmd/registry/quotas/quotas.go b/cmd/registry/quotas/quotas.go new file mode 100644 index 00000000..010757bc --- /dev/null +++ b/cmd/registry/quotas/quotas.go @@ -0,0 +1,401 @@ +package quotas + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "sort" + "strings" + + "github.com/spf13/cobra" + + "github.com/smartcontractkit/cre-cli/internal/client/graphqlclient" + "github.com/smartcontractkit/cre-cli/internal/client/registryquotaclient" + "github.com/smartcontractkit/cre-cli/internal/registrytype" + "github.com/smartcontractkit/cre-cli/internal/runtime" + "github.com/smartcontractkit/cre-cli/internal/tenantctx" + "github.com/smartcontractkit/cre-cli/internal/ui" + "github.com/smartcontractkit/cre-cli/internal/workflowresolve" +) + +func New(runtimeContext *runtime.Context) *cobra.Command { + var outputFormat string + var jsonFlag bool + + cmd := &cobra.Command{ + Use: "quotas [registry-id]", + Short: "Shows workflow and linked-owner usage against your registry quotas", + Long: `Shows, for each workflow registry available to your organization, how many +workflows are active against the limit of each DON family, and how many owner +addresses are linked against the linked-owner limit. + +Pass a registry ID from ` + "`cre registry list`" + ` to show a single registry. + +Pending link requests count against the linked-owner limit until they expire.`, + Example: ` cre registry quotas + cre registry quotas private + cre registry quotas --json`, + Args: cobra.MaximumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + format, err := workflowresolve.ResolveOutputFormat(outputFormat, jsonFlag) + if err != nil { + return err + } + if runtimeContext.TenantContext == nil { + return fmt.Errorf("user context not available — run `cre login` and retry") + } + registryID := "" + if len(args) == 1 { + registryID = args[0] + } + + h := &Handler{ + client: graphqlclient.New(runtimeContext.Credentials, runtimeContext.EnvironmentSet, runtimeContext.Logger), + tenantContext: runtimeContext.TenantContext, + } + return h.Execute(cmd.Context(), registryID, format) + }, + } + + cmd.Flags().StringVar(&outputFormat, "output", "", `Output format: "json" prints the quotas as JSON to stdout`) + cmd.Flags().BoolVar(&jsonFlag, "json", false, "Output as JSON (shorthand for --output=json)") + return cmd +} + +// Handler fetches registry quotas and renders them against the registries of the +// cached user context. +type Handler struct { + client registryquotaclient.Executor + tenantContext *tenantctx.EnvironmentContext +} + +// NewHandler creates a Handler; it is used by tests to inject a GraphQL client. +func NewHandler(client registryquotaclient.Executor, tenantContext *tenantctx.EnvironmentContext) *Handler { + return &Handler{client: client, tenantContext: tenantContext} +} + +func (h *Handler) Execute(ctx context.Context, registryID, format string) error { + if registryID != "" && findRegistry(h.tenantContext.Registries, registryID) == nil { + return fmt.Errorf("unknown registry %q; valid IDs: %s", registryID, strings.Join(registryIDs(h.tenantContext.Registries), ", ")) + } + + spinner := ui.NewSpinner() + spinner.Start("Fetching registry quotas...") + quotas, err := registryquotaclient.Fetch(ctx, h.client) + spinner.Stop() + + // A partial result is rendered with unreadable parts shown as unavailable; any + // other error means there is nothing to show. + var partial *registryquotaclient.PartialError + if err != nil && !errors.As(err, &partial) { + return err + } + + report := buildReport(h.tenantContext.Registries, quotas, registryID) + if partial != nil { + report.Warnings = append(report.Warnings, partial.Error()) + } + + if format == workflowresolve.OutputFormatJSON { + data, err := json.MarshalIndent(report, "", " ") + if err != nil { + return err + } + fmt.Println(string(data)) + return nil + } + printReport(report) + return nil +} + +// Report is the JSON output of the command. +type Report struct { + Registries []RegistryReport `json:"registries"` + // LinkedOwners covers the whole organization across on-chain registries. Absent + // when no on-chain registry is shown; null when it could not be read. + LinkedOwners *registryquotaclient.LinkedOwners `json:"linkedOwners"` + hasLinkedOwners bool + Warnings []string `json:"warnings,omitempty"` +} + +// MarshalJSON omits linkedOwners when it does not apply, and keeps it as null when it +// applies but could not be read. +func (r Report) MarshalJSON() ([]byte, error) { + type alias Report + if r.hasLinkedOwners { + return json.Marshal(alias(r)) + } + return json.Marshal(struct { + Registries []RegistryReport `json:"registries"` + Warnings []string `json:"warnings,omitempty"` + }{r.Registries, r.Warnings}) +} + +// RegistryReport is one registry with its quota. Workflows is set for off-chain +// registries and Owners for on-chain ones; either is null when it could not be read. +type RegistryReport struct { + ID string `json:"id"` + Label string `json:"label"` + Type string `json:"type"` + ChainSelector string `json:"chainSelector,omitempty"` + Address string `json:"address,omitempty"` + Workflows *[]registryquotaclient.DonFamilyQuota `json:"workflows,omitempty"` + Owners *[]registryquotaclient.OwnerQuota `json:"owners,omitempty"` + // InUserContext is false for a registry the API returned that the cached user + // context does not know about yet. + InUserContext bool `json:"-"` +} + +func buildReport(registries []*tenantctx.Registry, quotas *registryquotaclient.Quotas, registryID string) Report { + report := Report{Registries: []RegistryReport{}} + usedOnChain := make([]bool, len(quotas.OnChainRegistries)) + offChainIdx := 0 + + for _, reg := range registries { + entry := RegistryReport{ID: reg.ID, Label: reg.Label, Type: reg.Type, InUserContext: true} + if reg.ChainSelector != nil { + entry.ChainSelector = *reg.ChainSelector + } + if reg.Address != nil { + entry.Address = *reg.Address + } + + switch registrytype.Type(reg.Type) { + case registrytype.OffChain: + if offChainIdx >= len(quotas.OffChainRegistries) { + continue + } + workflows := quotas.OffChainRegistries[offChainIdx].Workflows + offChainIdx++ + entry.Workflows = &workflows + case registrytype.OnChain: + i := matchOnChain(quotas.OnChainRegistries, entry.ChainSelector, entry.Address) + if i < 0 { + continue + } + usedOnChain[i] = true + owners := quotas.OnChainRegistries[i].Owners + entry.Owners = &owners + default: + continue + } + + if registryID == "" || registryID == reg.ID { + report.Registries = append(report.Registries, entry) + } + } + + // On-chain registries the cached user context does not know about yet. + if registryID == "" { + for i, q := range quotas.OnChainRegistries { + if usedOnChain[i] { + continue + } + owners := q.Owners + report.Registries = append(report.Registries, RegistryReport{ + ID: "onchain:" + string(q.ChainSelector), + Label: fmt.Sprintf("chain %s (%s)", q.ChainSelector, abbreviate(q.Address)), + Type: string(registrytype.OnChain), + ChainSelector: string(q.ChainSelector), + Address: q.Address, + Owners: &owners, + }) + } + } + + for _, r := range report.Registries { + if r.Type == string(registrytype.OnChain) { + report.hasLinkedOwners = true + report.LinkedOwners = quotas.LinkedOwners + break + } + } + return report +} + +func matchOnChain(regs []registryquotaclient.OnChainRegistry, chainSelector, address string) int { + for i, q := range regs { + if !strings.EqualFold(q.Address, address) { + continue + } + if chainSelector != "" && string(q.ChainSelector) != chainSelector { + continue + } + return i + } + return -1 +} + +func findRegistry(registries []*tenantctx.Registry, id string) *tenantctx.Registry { + for _, r := range registries { + if r.ID == id { + return r + } + } + return nil +} + +func registryIDs(registries []*tenantctx.Registry) []string { + ids := make([]string, 0, len(registries)) + for _, r := range registries { + ids = append(ids, r.ID) + } + return ids +} + +func printReport(report Report) { + ui.Line() + ui.Bold("Registry quotas for your organization") + ui.Line() + + if len(report.Registries) == 0 { + ui.Warning("No registry quotas found for this environment") + return + } + + ownerStatus := linkStatusByAddress(report.LinkedOwners) + staleContext := false + for _, r := range report.Registries { + ui.Bold(r.Label) + ui.Dim(fmt.Sprintf("ID: %s", r.ID)) + ui.Dim(fmt.Sprintf("Type: %s", r.Type)) + if r.Address != "" { + ui.Dim(fmt.Sprintf("Addr: %s", r.Address)) + } + if !r.InUserContext { + staleContext = true + } + + switch { + case r.Workflows != nil: + printOffChain(*r.Workflows) + case r.Owners != nil: + printOnChain(*r.Owners, ownerStatus) + } + ui.Line() + } + + if report.hasLinkedOwners { + printLinkedOwners(report.LinkedOwners) + ui.Line() + } + + if staleContext { + ui.Dim("Some registries are missing from your saved user context. Run `cre login` to refresh it.") + ui.Line() + } + for _, w := range report.Warnings { + ui.Warning("Some quotas could not be read: " + w) + } +} + +func printOffChain(workflows []registryquotaclient.DonFamilyQuota) { + if workflows == nil { + ui.Warning("Workflow quota unavailable") + return + } + ui.Print("Workflows by DON family:") + if len(workflows) == 0 { + ui.Dim(" No DON families available to your organization") + return + } + printFamilies(workflows, " ") + if len(workflows) > 1 { + ui.Dim(" Workflows are counted per organization, so every DON family shows the same total.") + } +} + +func printOnChain(owners []registryquotaclient.OwnerQuota, status map[string]string) { + if owners == nil { + ui.Warning("On-chain workflow quota unavailable") + return + } + ui.Print("Workflows by owner and DON family:") + if len(owners) == 0 { + ui.Dim(" No linked owners. Link one with `cre account link-key`.") + return + } + for _, o := range owners { + label := o.Owner + if s, ok := status[strings.ToLower(o.Owner)]; ok { + label = fmt.Sprintf("%s (%s)", o.Owner, s) + } + ui.Print(" " + label) + if len(o.Workflows) == 0 { + ui.Dim(" No DON families available to this owner") + continue + } + printFamilies(o.Workflows, " ") + } +} + +func printFamilies(workflows []registryquotaclient.DonFamilyQuota, indent string) { + sorted := append([]registryquotaclient.DonFamilyQuota(nil), workflows...) + sort.Slice(sorted, func(i, j int) bool { return sorted[i].DonFamily < sorted[j].DonFamily }) + + width := 0 + for _, w := range sorted { + width = max(width, len(w.DonFamily)) + } + for _, w := range sorted { + ui.Print(fmt.Sprintf("%s%-*s %s", indent, width, w.DonFamily, formatUsage(w.Active, w.Limit))) + } +} + +func formatUsage(active, limit int) string { + switch { + case limit == 0: + return fmt.Sprintf("disabled (%d active)", active) + case active > limit: + return fmt.Sprintf("%d / %d active (over limit)", active, limit) + default: + return fmt.Sprintf("%d / %d active, %d remaining", active, limit, limit-active) + } +} + +func printLinkedOwners(lo *registryquotaclient.LinkedOwners) { + ui.Bold("Linked owners (all on-chain registries)") + if lo == nil { + ui.Warning("Linked-owner quota unavailable") + return + } + used := len(lo.Linked) + len(lo.Pending) + summary := fmt.Sprintf("%d / %d used (%d linked, %d pending)", used, lo.Limit, len(lo.Linked), len(lo.Pending)) + if used <= lo.Limit { + summary += fmt.Sprintf(", %d remaining", lo.Limit-used) + } else { + summary += ", over limit" + } + ui.Print(summary) + for _, o := range lo.Linked { + ui.Dim(fmt.Sprintf(" %s linked", o.Address)) + } + for _, o := range lo.Pending { + ui.Dim(fmt.Sprintf(" %s pending", o.Address)) + } + if len(lo.Pending) > 0 { + ui.Dim("Pending link requests count against the limit until they expire.") + } +} + +func linkStatusByAddress(lo *registryquotaclient.LinkedOwners) map[string]string { + status := map[string]string{} + if lo == nil { + return status + } + for _, o := range lo.Linked { + status[strings.ToLower(o.Address)] = "linked" + } + for _, o := range lo.Pending { + status[strings.ToLower(o.Address)] = "pending" + } + return status +} + +func abbreviate(addr string) string { + if len(addr) <= 10 { + return addr + } + return addr[:6] + "..." + addr[len(addr)-4:] +} diff --git a/cmd/registry/quotas/quotas_test.go b/cmd/registry/quotas/quotas_test.go new file mode 100644 index 00000000..63b4620c --- /dev/null +++ b/cmd/registry/quotas/quotas_test.go @@ -0,0 +1,215 @@ +package quotas_test + +import ( + "context" + "encoding/json" + "errors" + "io" + "os" + "strings" + "testing" + + "github.com/machinebox/graphql" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smartcontractkit/cre-cli/cmd/registry/quotas" + "github.com/smartcontractkit/cre-cli/internal/client/registryquotaclient" + "github.com/smartcontractkit/cre-cli/internal/tenantctx" + "github.com/smartcontractkit/cre-cli/internal/workflowresolve" +) + +const ( + registryAddress = "0x4Ac54353FA4Fa961AfcC5ec4B118596d3305E7e5" + chainSelector = "5009297550715157269" + ownerAddress = "0x1111111111111111111111111111111111111111" + pendingAddress = "0x2222222222222222222222222222222222222222" +) + +type fakeExecutor struct { + data string + err error + calls int +} + +func (f *fakeExecutor) Execute(_ context.Context, _ *graphql.Request, resp any) error { + f.calls++ + if f.data != "" { + if err := json.Unmarshal([]byte(f.data), resp); err != nil { + return err + } + } + return f.err +} + +func strPtr(s string) *string { return &s } + +func tenantContext() *tenantctx.EnvironmentContext { + return &tenantctx.EnvironmentContext{Registries: []*tenantctx.Registry{ + { + ID: "onchain:ethereum-mainnet", + Label: "ethereum-mainnet (0x4Ac5...7e5)", + Type: "on-chain", + ChainSelector: strPtr(chainSelector), + // Lower case on purpose: matching must ignore address case. + Address: strPtr(strings.ToLower(registryAddress)), + }, + {ID: "private", Label: "Private (Chainlink-hosted)", Type: "off-chain"}, + }} +} + +const fullData = `{"getRegistryQuotas": { + "offChainRegistries": [{"workflows": [ + {"donFamily": "zone-b", "active": 4, "limit": 0}, + {"donFamily": "zone-a", "active": 4, "limit": 5} + ]}], + "onChainRegistries": [{"chainSelector": "5009297550715157269", "address": "0x4Ac54353FA4Fa961AfcC5ec4B118596d3305E7e5", + "owners": [{"owner": "0x1111111111111111111111111111111111111111", "workflows": [{"donFamily": "zone-a", "active": 4, "limit": 3}]}]}], + "linkedOwners": { + "linked": [{"address": "0x1111111111111111111111111111111111111111", "chainSelector": "5009297550715157269", "workflowRegistryAddress": "0x4Ac54353FA4Fa961AfcC5ec4B118596d3305E7e5"}], + "pending": [{"address": "0x2222222222222222222222222222222222222222", "chainSelector": "5009297550715157269", "workflowRegistryAddress": "0x4Ac54353FA4Fa961AfcC5ec4B118596d3305E7e5"}], + "limit": 3 + } +}}` + +// run executes the handler and returns what it wrote to stdout and stderr. +func run(t *testing.T, exec *fakeExecutor, registryID, format string) (string, string, error) { + t.Helper() + oldOut, oldErr := os.Stdout, os.Stderr + outR, outW, _ := os.Pipe() + errR, errW, _ := os.Pipe() + os.Stdout, os.Stderr = outW, errW + + err := quotas.NewHandler(exec, tenantContext()).Execute(context.Background(), registryID, format) + + outW.Close() + errW.Close() + os.Stdout, os.Stderr = oldOut, oldErr + stdout, _ := io.ReadAll(outR) + stderr, _ := io.ReadAll(errR) + return string(stdout), string(stderr), err +} + +func TestQuotas_Text(t *testing.T) { + stdout, _, err := run(t, &fakeExecutor{data: fullData}, "", "") + require.NoError(t, err) + + for _, want := range []string{ + "Private (Chainlink-hosted)", + "zone-a 4 / 5 active, 1 remaining", + "zone-b disabled (4 active)", + "every DON family shows the same total", + "ethereum-mainnet (0x4Ac5...7e5)", + ownerAddress + " (linked)", + "4 / 3 active (over limit)", + "Linked owners (all on-chain registries)", + "2 / 3 used (1 linked, 1 pending), 1 remaining", + pendingAddress + " pending", + } { + assert.Contains(t, stdout, want) + } + assert.Less(t, strings.Index(stdout, "zone-a"), strings.Index(stdout, "zone-b"), "DON families are sorted") + assert.NotContains(t, stdout, "user context") +} + +func TestQuotas_JSON(t *testing.T) { + stdout, _, err := run(t, &fakeExecutor{data: fullData}, "", workflowresolve.OutputFormatJSON) + require.NoError(t, err) + + var report struct { + Registries []struct { + ID string `json:"id"` + Type string `json:"type"` + Workflows []json.RawMessage `json:"workflows"` + Owners []json.RawMessage `json:"owners"` + } `json:"registries"` + LinkedOwners *struct { + Limit int `json:"limit"` + } `json:"linkedOwners"` + Warnings []string `json:"warnings"` + } + require.NoError(t, json.Unmarshal([]byte(stdout), &report), stdout) + require.Len(t, report.Registries, 2) + assert.Equal(t, "onchain:ethereum-mainnet", report.Registries[0].ID) + assert.Len(t, report.Registries[0].Owners, 1) + assert.Equal(t, "private", report.Registries[1].ID) + assert.Len(t, report.Registries[1].Workflows, 2) + require.NotNil(t, report.LinkedOwners) + assert.Equal(t, 3, report.LinkedOwners.Limit) + assert.Empty(t, report.Warnings) +} + +func TestQuotas_FilterByRegistry(t *testing.T) { + stdout, _, err := run(t, &fakeExecutor{data: fullData}, "private", workflowresolve.OutputFormatJSON) + require.NoError(t, err) + + var report map[string]json.RawMessage + require.NoError(t, json.Unmarshal([]byte(stdout), &report)) + var registries []map[string]any + require.NoError(t, json.Unmarshal(report["registries"], ®istries)) + require.Len(t, registries, 1) + assert.Equal(t, "private", registries[0]["id"]) + _, hasLinked := report["linkedOwners"] + assert.False(t, hasLinked, "linked owners only apply to on-chain registries") +} + +func TestQuotas_UnknownRegistry(t *testing.T) { + exec := &fakeExecutor{data: fullData} + _, _, err := run(t, exec, "nope", "") + require.ErrorContains(t, err, `unknown registry "nope"; valid IDs: onchain:ethereum-mainnet, private`) + assert.Equal(t, 0, exec.calls, "the API is not called for an unknown registry") +} + +func TestQuotas_PartialResult(t *testing.T) { + data := `{"getRegistryQuotas": { + "offChainRegistries": [{"workflows": [{"donFamily": "zone-a", "active": 1, "limit": 3}]}], + "onChainRegistries": [{"chainSelector": "5009297550715157269", "address": "0x4Ac54353FA4Fa961AfcC5ec4B118596d3305E7e5", "owners": null}], + "linkedOwners": null + }}` + exec := &fakeExecutor{data: data, err: errors.New("cre api error: on-chain registry temporarily unavailable")} + + t.Run("text", func(t *testing.T) { + stdout, stderr, err := run(t, exec, "", "") + require.NoError(t, err, "a partial result is not a failure") + assert.Contains(t, stdout, "zone-a 1 / 3 active, 2 remaining") + assert.Contains(t, stderr, "On-chain workflow quota unavailable") + assert.Contains(t, stderr, "Linked-owner quota unavailable") + assert.Contains(t, stderr, "on-chain registry temporarily unavailable") + }) + + t.Run("json keeps unavailable parts as null", func(t *testing.T) { + stdout, _, err := run(t, exec, "", workflowresolve.OutputFormatJSON) + require.NoError(t, err) + + var report map[string]json.RawMessage + require.NoError(t, json.Unmarshal([]byte(stdout), &report)) + assert.JSONEq(t, `null`, string(report["linkedOwners"])) + assert.Contains(t, string(report["registries"]), `"owners": null`) + assert.Contains(t, string(report["warnings"]), "on-chain registry temporarily unavailable") + }) +} + +func TestQuotas_RegistryMissingFromUserContext(t *testing.T) { + data := `{"getRegistryQuotas": { + "offChainRegistries": [], + "onChainRegistries": [ + {"chainSelector": "5009297550715157269", "address": "0x4Ac54353FA4Fa961AfcC5ec4B118596d3305E7e5", "owners": []}, + {"chainSelector": "16015286601757825753", "address": "0x3333333333333333333333333333333333333333", "owners": []} + ], + "linkedOwners": {"linked": [], "pending": [], "limit": 1} + }}` + stdout, _, err := run(t, &fakeExecutor{data: data}, "", "") + require.NoError(t, err) + + assert.Contains(t, stdout, "chain 16015286601757825753 (0x3333...3333)") + assert.Contains(t, stdout, "Run `cre login` to refresh it") + assert.Contains(t, stdout, "No linked owners") + assert.NotContains(t, stdout, "Private (Chainlink-hosted)", "a registry without a quota is not shown") +} + +func TestQuotas_FetchErrors(t *testing.T) { + t.Run("permission denied", func(t *testing.T) { + _, _, err := run(t, &fakeExecutor{err: errors.New("cre api error: unauthorized: user does not have platform:limits:read permission")}, "", "") + require.ErrorIs(t, err, registryquotaclient.ErrPermissionDenied) + }) +} diff --git a/cmd/registry/registry.go b/cmd/registry/registry.go index 440df4fe..e5003ef2 100644 --- a/cmd/registry/registry.go +++ b/cmd/registry/registry.go @@ -4,6 +4,7 @@ import ( "github.com/spf13/cobra" "github.com/smartcontractkit/cre-cli/cmd/registry/list" + "github.com/smartcontractkit/cre-cli/cmd/registry/quotas" "github.com/smartcontractkit/cre-cli/internal/runtime" ) @@ -11,10 +12,11 @@ func New(runtimeContext *runtime.Context) *cobra.Command { registryCmd := &cobra.Command{ Use: "registry", Short: "Manages workflow registries", - Long: `The registry command lets you view and inspect the workflow registries available for your organization.`, + Long: `The registry command lets you view and inspect the workflow registries available for your organization, and your usage against their quotas.`, } registryCmd.AddCommand(list.New(runtimeContext)) + registryCmd.AddCommand(quotas.New(runtimeContext)) return registryCmd } diff --git a/cmd/root.go b/cmd/root.go index e104165d..227e515c 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -596,6 +596,7 @@ func isLoadSettings(cmd *cobra.Command) bool { "cre templates remove": {}, "cre registry": {}, "cre registry list": {}, + "cre registry quotas": {}, "cre": {}, } diff --git a/docs/cre_registry.md b/docs/cre_registry.md index 5f6e2e3e..c8189307 100644 --- a/docs/cre_registry.md +++ b/docs/cre_registry.md @@ -4,7 +4,7 @@ Manages workflow registries ### Synopsis -The registry command lets you view and inspect the workflow registries available for your organization. +The registry command lets you view and inspect the workflow registries available for your organization, and your usage against their quotas. ``` cre registry [optional flags] @@ -33,4 +33,5 @@ cre registry [optional flags] * [cre](cre.md) - CRE CLI tool * [cre registry list](cre_registry_list.md) - Lists available workflow registries for the current environment +* [cre registry quotas](cre_registry_quotas.md) - Shows workflow and linked-owner usage against your registry quotas diff --git a/docs/cre_registry_quotas.md b/docs/cre_registry_quotas.md new file mode 100644 index 00000000..c3ec09b4 --- /dev/null +++ b/docs/cre_registry_quotas.md @@ -0,0 +1,51 @@ +## cre registry quotas + +Shows workflow and linked-owner usage against your registry quotas + +### Synopsis + +Shows, for each workflow registry available to your organization, how many +workflows are active against the limit of each DON family, and how many owner +addresses are linked against the linked-owner limit. + +Pass a registry ID from `cre registry list` to show a single registry. + +Pending link requests count against the linked-owner limit until they expire. + +``` +cre registry quotas [registry-id] [flags] +``` + +### Examples + +``` + cre registry quotas + cre registry quotas private + cre registry quotas --json +``` + +### Options + +``` + -h, --help help for quotas + --json Output as JSON (shorthand for --output=json) + --output string Output format: "json" prints the quotas as JSON to stdout +``` + +### Options inherited from parent commands + +``` + --allow-insecure-rpc Allow non-localhost HTTP RPC URLs (insecure) + --allow-unknown-chains Skip chain-name validation against the chain-selectors registry (for experimental chains) + -e, --env string Path to .env file which contains sensitive info + --non-interactive Fail instead of prompting; requires all inputs via flags + -R, --project-root string Path to the project root + -E, --public-env string Path to .env.public file which contains shared, non-sensitive build config + -T, --target string Use target settings from YAML config + -v, --verbose Run command in VERBOSE mode +``` + +### SEE ALSO + +* [cre registry](cre_registry.md) - Manages workflow registries + diff --git a/internal/client/registryquotaclient/registryquotaclient.go b/internal/client/registryquotaclient/registryquotaclient.go new file mode 100644 index 00000000..37700d24 --- /dev/null +++ b/internal/client/registryquotaclient/registryquotaclient.go @@ -0,0 +1,152 @@ +// Package registryquotaclient fetches registry quotas (workflow and linked-owner usage +// against the effective limits) from the CRE API. +package registryquotaclient + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strconv" + "strings" + + "github.com/machinebox/graphql" +) + +const query = `query GetRegistryQuotas { + getRegistryQuotas { + offChainRegistries { + workflows { donFamily active limit } + } + onChainRegistries { + chainSelector + address + owners { + owner + workflows { donFamily active limit } + } + } + linkedOwners { + linked { address chainSelector workflowRegistryAddress } + pending { address chainSelector workflowRegistryAddress } + limit + } + } +}` + +// ErrPermissionDenied is returned when the caller lacks the platform:limits:read permission. +var ErrPermissionDenied = errors.New("you do not have permission to read registry quotas (requires platform:limits:read)") + +// Executor runs a GraphQL request. It is satisfied by graphqlclient.Client. +type Executor interface { + Execute(ctx context.Context, req *graphql.Request, resp any) error +} + +// Quotas is the getRegistryQuotas result. A nil slice or pointer on a field the +// server resolves separately (OffChainRegistry.Workflows, OnChainRegistry.Owners, +// LinkedOwners) means the server could not read it; an empty slice means there is +// nothing to show. LinkedOwners is also nil when there is no on-chain registry. +type Quotas struct { + OffChainRegistries []OffChainRegistry `json:"offChainRegistries"` + OnChainRegistries []OnChainRegistry `json:"onChainRegistries"` + LinkedOwners *LinkedOwners `json:"linkedOwners"` +} + +type OffChainRegistry struct { + Workflows []DonFamilyQuota `json:"workflows"` +} + +type OnChainRegistry struct { + ChainSelector ChainSelector `json:"chainSelector"` + Address string `json:"address"` + Owners []OwnerQuota `json:"owners"` +} + +type OwnerQuota struct { + Owner string `json:"owner"` + Workflows []DonFamilyQuota `json:"workflows"` +} + +type DonFamilyQuota struct { + DonFamily string `json:"donFamily"` + Active int `json:"active"` + Limit int `json:"limit"` +} + +type LinkedOwners struct { + Linked []LinkedOwner `json:"linked"` + Pending []LinkedOwner `json:"pending"` + Limit int `json:"limit"` +} + +type LinkedOwner struct { + Address string `json:"address"` + ChainSelector ChainSelector `json:"chainSelector"` + WorkflowRegistryAddress string `json:"workflowRegistryAddress"` +} + +// ChainSelector is a chain selector as a decimal string. The API may send it as a +// JSON string or number; it is kept as a string to avoid precision loss. +type ChainSelector string + +func (c *ChainSelector) UnmarshalJSON(raw []byte) error { + if string(raw) == "null" { + *c = "" + return nil + } + var s string + if err := json.Unmarshal(raw, &s); err == nil { + *c = ChainSelector(s) + return nil + } + var n json.Number + if err := json.Unmarshal(raw, &n); err != nil { + return fmt.Errorf("invalid chain selector %s: %w", raw, err) + } + if _, err := strconv.ParseUint(n.String(), 10, 64); err != nil { + return fmt.Errorf("invalid chain selector %s: %w", raw, err) + } + *c = ChainSelector(n.String()) + return nil +} + +// PartialError is returned together with the quotas when the API returned data but +// could not read every part of it. Unreadable parts are nil in the returned Quotas. +type PartialError struct { + Err error +} + +func (e *PartialError) Error() string { return e.Err.Error() } +func (e *PartialError) Unwrap() error { return e.Err } + +// Fetch reads the registry quotas of the caller's organization. +// +// On success it returns the quotas and a nil error. When the API returned data with +// errors, it returns the quotas and a *PartialError. Otherwise it returns nil and an +// error, which is ErrPermissionDenied when the caller lacks the permission. +func Fetch(ctx context.Context, client Executor) (*Quotas, error) { + var resp struct { + GetRegistryQuotas *Quotas `json:"getRegistryQuotas"` + } + err := client.Execute(ctx, graphql.NewRequest(query), &resp) + if err == nil { + if resp.GetRegistryQuotas == nil { + return nil, errors.New("CRE API returned no registry quotas") + } + return resp.GetRegistryQuotas, nil + } + + // The GraphQL client still decodes data when the response also carries errors. + if resp.GetRegistryQuotas != nil { + return resp.GetRegistryQuotas, &PartialError{Err: err} + } + return nil, classify(err) +} + +func classify(err error) error { + msg := err.Error() + if strings.Contains(msg, "platform:limits:read") { + return fmt.Errorf("%w: %w", ErrPermissionDenied, err) + } + return fmt.Errorf("fetch registry quotas: %w", err) +} diff --git a/internal/client/registryquotaclient/registryquotaclient_test.go b/internal/client/registryquotaclient/registryquotaclient_test.go new file mode 100644 index 00000000..ec02c76a --- /dev/null +++ b/internal/client/registryquotaclient/registryquotaclient_test.go @@ -0,0 +1,98 @@ +package registryquotaclient_test + +import ( + "context" + "encoding/json" + "errors" + "testing" + + "github.com/machinebox/graphql" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smartcontractkit/cre-cli/internal/client/registryquotaclient" +) + +// fakeExecutor decodes data into the response like the GraphQL client does, which +// also decodes data when the response carries errors. +type fakeExecutor struct { + data string + err error +} + +func (f *fakeExecutor) Execute(_ context.Context, _ *graphql.Request, resp any) error { + if f.data != "" { + if err := json.Unmarshal([]byte(f.data), resp); err != nil { + return err + } + } + return f.err +} + +const fullData = `{"getRegistryQuotas": { + "offChainRegistries": [{"workflows": [{"donFamily": "zone-a", "active": 1, "limit": 3}]}], + "onChainRegistries": [{"chainSelector": "5009297550715157269", "address": "0x4Ac54353FA4Fa961AfcC5ec4B118596d3305E7e5", + "owners": [{"owner": "0x1111111111111111111111111111111111111111", "workflows": [{"donFamily": "zone-a", "active": 2, "limit": 3}]}]}], + "linkedOwners": {"linked": [{"address": "0x1111111111111111111111111111111111111111", "chainSelector": 5009297550715157269, + "workflowRegistryAddress": "0x4Ac54353FA4Fa961AfcC5ec4B118596d3305E7e5"}], "pending": [], "limit": 1} +}}` + +func TestFetch_Success(t *testing.T) { + q, err := registryquotaclient.Fetch(context.Background(), &fakeExecutor{data: fullData}) + require.NoError(t, err) + + require.Len(t, q.OffChainRegistries, 1) + assert.Equal(t, []registryquotaclient.DonFamilyQuota{{DonFamily: "zone-a", Active: 1, Limit: 3}}, q.OffChainRegistries[0].Workflows) + require.Len(t, q.OnChainRegistries, 1) + assert.Equal(t, registryquotaclient.ChainSelector("5009297550715157269"), q.OnChainRegistries[0].ChainSelector) + require.Len(t, q.OnChainRegistries[0].Owners, 1) + require.NotNil(t, q.LinkedOwners) + assert.Equal(t, 1, q.LinkedOwners.Limit) + assert.Equal(t, registryquotaclient.ChainSelector("5009297550715157269"), q.LinkedOwners.Linked[0].ChainSelector, "numeric selectors keep full precision") + assert.NotNil(t, q.LinkedOwners.Pending) +} + +func TestFetch_PartialData(t *testing.T) { + data := `{"getRegistryQuotas": { + "offChainRegistries": [{"workflows": [{"donFamily": "zone-a", "active": 1, "limit": 3}]}], + "onChainRegistries": [{"chainSelector": "1", "address": "0x4Ac54353FA4Fa961AfcC5ec4B118596d3305E7e5", "owners": null}], + "linkedOwners": null + }}` + q, err := registryquotaclient.Fetch(context.Background(), &fakeExecutor{data: data, err: errors.New("cre api error: on-chain registry temporarily unavailable")}) + + var partial *registryquotaclient.PartialError + require.ErrorAs(t, err, &partial) + require.NotNil(t, q) + assert.NotNil(t, q.OffChainRegistries[0].Workflows) + assert.Nil(t, q.OnChainRegistries[0].Owners, "null owners stay nil so callers can show them as unavailable") + assert.Nil(t, q.LinkedOwners) +} + +func TestFetch_Errors(t *testing.T) { + t.Run("missing permission", func(t *testing.T) { + _, err := registryquotaclient.Fetch(context.Background(), &fakeExecutor{ + data: `{"getRegistryQuotas": null}`, + err: errors.New("cre api error: unauthorized: user does not have platform:limits:read permission"), + }) + require.ErrorIs(t, err, registryquotaclient.ErrPermissionDenied) + }) + + t.Run("other error", func(t *testing.T) { + _, err := registryquotaclient.Fetch(context.Background(), &fakeExecutor{err: errors.New("connection refused")}) + require.ErrorContains(t, err, "fetch registry quotas: connection refused") + assert.NotErrorIs(t, err, registryquotaclient.ErrPermissionDenied) + }) + + t.Run("no data and no error", func(t *testing.T) { + _, err := registryquotaclient.Fetch(context.Background(), &fakeExecutor{data: `{"getRegistryQuotas": null}`}) + require.ErrorContains(t, err, "no registry quotas") + }) +} + +func TestChainSelector_RejectsInvalid(t *testing.T) { + var c registryquotaclient.ChainSelector + require.Error(t, json.Unmarshal([]byte(`-1`), &c)) + require.Error(t, json.Unmarshal([]byte(`true`), &c)) + require.NoError(t, json.Unmarshal([]byte(`null`), &c)) + assert.Equal(t, registryquotaclient.ChainSelector(""), c) +}