Skip to content

Commit 7dcfcee

Browse files
authored
feat(reconcile): add a Preference kind (#1762)
1 parent 3c08b2f commit 7dcfcee

7 files changed

Lines changed: 529 additions & 11 deletions

File tree

‎cmd/reconcile.go‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,12 @@ func ReconcileCommand(cliConfig *Config) *cli.Command {
2323
Make platform resources match a desired-state YAML file, through the admin API.
2424
2525
Kinds: PlatformUser (platform admins and members), Permission (custom
26-
permissions), and Role (platform-level roles). Deleting a permission or a
27-
custom role needs an explicit 'delete: true' on its entry; nothing is deleted
28-
by omission, and a predefined role cannot be deleted. Log in as a superuser
29-
(for example the bootstrap service account) with --header.
26+
permissions), Role (platform-level roles), and Preference (platform
27+
settings). Deleting a permission or a custom role needs an explicit
28+
'delete: true' on its entry; nothing is deleted by omission, and a predefined
29+
role cannot be deleted. A preference left out of the file resets to its
30+
default. Log in as a superuser (for example the bootstrap service account)
31+
with --header.
3032
3133
Use "frontier export <kind>" to print the current state in this file format.
3234
`),
@@ -85,6 +87,7 @@ func buildReconcileRegistry(host, header string) (map[string]reconcile.Reconcile
8587
reconcile.KindPlatformUser: reconcile.NewPlatformUserReconciler(adminClient, header),
8688
reconcile.KindPermission: reconcile.NewPermissionReconciler(api, header),
8789
reconcile.KindRole: reconcile.NewRoleReconciler(api, header),
90+
reconcile.KindPreference: reconcile.NewPreferenceReconciler(api, header),
8891
}, nil
8992
}
9093

‎docs/content/docs/reconcile.mdx‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,30 @@ takes those permissions away on the next apply.
150150
Permission references accept any form the server knows: the slug (`compute_order_get`),
151151
`service/resource:verb`, or `service.resource.verb`.
152152

153+
## The Preference kind
154+
155+
`Preference` manages platform settings, like whether new organizations can be created or
156+
what an invite email says. An entry is a trait name and a value.
157+
158+
```yaml
159+
apiVersion: v1
160+
kind: Preference
161+
spec:
162+
- name: disable_orgs_on_create
163+
value: "true"
164+
- name: invite_with_roles
165+
value: "false"
166+
```
167+
168+
- Values are strings. A yes/no setting is `"true"` or `"false"`.
169+
- The name must be a platform trait the server knows. An unknown name fails the plan.
170+
- This kind resets instead of deleting. The file is the full desired state: a preference
171+
you list is set to your value, and a preference you leave out goes back to its default.
172+
There is no `delete` flag, because setting a preference back to its default is what
173+
removal means here.
174+
- Export writes only the preferences whose value differs from the default, so settings at
175+
their default stay out of the file.
176+
153177
## Running it
154178

155179
Log in as a superuser. The bootstrap service user exists for exactly this; its client id
@@ -192,8 +216,8 @@ The kind argument is case-insensitive and accepts a plural, so `platformuser` an
192216

193217
## More kinds
194218

195-
This page covers `PlatformUser`, `Permission`, and `Role`. The design and the rules every
196-
kind follows live in
219+
This page covers `PlatformUser`, `Permission`, `Role`, and `Preference`. The design and
220+
the rules every kind follows live in
197221
[RFC 0001](https://github.com/raystack/frontier/blob/main/docs/rfcs/0001-declarative-reconcile.md),
198222
which also lists the kinds proposed next. The flag reference for both commands is in the
199223
[CLI reference](./reference/cli.md).

‎docs/content/docs/reference/cli.mdx‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@ List of supported environment variables
3333

3434
Export the current state of a kind as a desired-state YAML file, printed to
3535
stdout. The output is the format `frontier reconcile` reads: reconciling it
36-
changes nothing. Supported kinds: `PlatformUser`, `Permission`, `Role`. See the
36+
changes nothing. Supported kinds: `PlatformUser`, `Permission`, `Role`,
37+
`Preference`. See the
3738
[Reconcile guide](../reconcile.md) for the file format and the flow.
3839

3940
```
@@ -247,10 +248,11 @@ View a project
247248
248249
Make platform resources match a desired-state YAML file, through the admin
249250
API. Supported kinds: `PlatformUser` (anyone listed is added, anyone not
250-
listed is removed), `Permission` (custom permissions), and `Role`
251-
(platform-level roles). Deleting a permission or a custom role needs an
252-
explicit `delete: true` on its entry; nothing is deleted by omission, and a
253-
predefined role cannot be deleted. Use
251+
listed is removed), `Permission` (custom permissions), `Role`
252+
(platform-level roles), and `Preference` (platform settings, where a setting
253+
left out of the file resets to its default). Deleting a permission or a custom
254+
role needs an explicit `delete: true` on its entry; nothing is deleted by
255+
omission, and a predefined role cannot be deleted. Use
254256
`frontier export` to print the current state in this file format, and see the
255257
[Reconcile guide](../reconcile.md) for the full flow.
256258

‎internal/reconcile/preference.go‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
package reconcile
2+
3+
import (
4+
"fmt"
5+
"sort"
6+
"strings"
7+
)
8+
9+
// KindPreference is the desired-state document kind for platform preferences.
10+
const KindPreference = "Preference"
11+
12+
const (
13+
opSet opAction = "set"
14+
opReset opAction = "reset"
15+
)
16+
17+
// PreferenceSpec is one desired platform preference. Name is a trait name the
18+
// server knows; value is the string value to set. Preferences are strings end
19+
// to end, so a boolean-like trait is "true" or "false".
20+
type PreferenceSpec struct {
21+
Name string `yaml:"name"`
22+
Value string `yaml:"value"`
23+
}
24+
25+
// preferenceOp is a single planned change. For a reset, value is the trait
26+
// default that gets written back, because the API has no delete.
27+
type preferenceOp struct {
28+
action opAction
29+
name string
30+
value string
31+
}
32+
33+
func (o preferenceOp) String() string {
34+
if o.action == opReset {
35+
return fmt.Sprintf("reset preference %s to default", o.name)
36+
}
37+
return fmt.Sprintf("set preference %s = %s", o.name, o.value)
38+
}
39+
40+
// diffPreferences returns the ops that make the current platform preferences
41+
// match the desired spec. The file is the full desired state: a preference the
42+
// file lists is set to its value, and a preference the file leaves out is reset
43+
// to its trait default. defaults holds every valid platform trait and its
44+
// default, so it is both the source of defaults and the set of known names.
45+
func diffPreferences(desired []PreferenceSpec, current, defaults map[string]string) ([]preferenceOp, error) {
46+
desiredByName := make(map[string]string, len(desired))
47+
for _, s := range desired {
48+
if strings.TrimSpace(s.Name) == "" {
49+
return nil, fmt.Errorf("preference name is required")
50+
}
51+
if _, dup := desiredByName[s.Name]; dup {
52+
return nil, fmt.Errorf("preference %q is listed more than once", s.Name)
53+
}
54+
if _, known := defaults[s.Name]; !known {
55+
return nil, fmt.Errorf("unknown platform preference %q", s.Name)
56+
}
57+
desiredByName[s.Name] = s.Value
58+
}
59+
60+
// serverValue is the value in effect on the server: the stored value, or
61+
// the trait default when nothing is stored. An empty stored value counts as
62+
// unset, matching how the server resolves platform preferences, so a file
63+
// entry equal to the default plans no change against it.
64+
serverValue := func(name string) string {
65+
if v, ok := current[name]; ok && v != "" {
66+
return v
67+
}
68+
return defaults[name]
69+
}
70+
71+
var sets, resets []preferenceOp
72+
for name, value := range desiredByName {
73+
if value != serverValue(name) {
74+
sets = append(sets, preferenceOp{action: opSet, name: name, value: value})
75+
}
76+
}
77+
for name, value := range current {
78+
def, known := defaults[name]
79+
if !known {
80+
// A stored value whose trait no longer exists: leave it alone. The
81+
// file cannot name it (unknown names fail), so nothing manages it.
82+
continue
83+
}
84+
if _, listed := desiredByName[name]; listed {
85+
continue
86+
}
87+
if value != def {
88+
resets = append(resets, preferenceOp{action: opReset, name: name, value: def})
89+
}
90+
}
91+
92+
sort.Slice(sets, func(i, j int) bool { return sets[i].name < sets[j].name })
93+
sort.Slice(resets, func(i, j int) bool { return resets[i].name < resets[j].name })
94+
return append(sets, resets...), nil
95+
}
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
package reconcile
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"sort"
7+
8+
"connectrpc.com/connect"
9+
"github.com/raystack/frontier/internal/bootstrap/schema"
10+
frontierv1beta1 "github.com/raystack/frontier/proto/v1beta1"
11+
)
12+
13+
// PreferenceAPI is the API subset the preference reconciler needs. The reads
14+
// live on different services (platform preferences on AdminService, the trait
15+
// list on FrontierService); the caller provides one value that serves both.
16+
type PreferenceAPI interface {
17+
ListPreferences(context.Context, *connect.Request[frontierv1beta1.ListPreferencesRequest]) (*connect.Response[frontierv1beta1.ListPreferencesResponse], error)
18+
DescribePreferences(context.Context, *connect.Request[frontierv1beta1.DescribePreferencesRequest]) (*connect.Response[frontierv1beta1.DescribePreferencesResponse], error)
19+
CreatePreferences(context.Context, *connect.Request[frontierv1beta1.CreatePreferencesRequest]) (*connect.Response[frontierv1beta1.CreatePreferencesResponse], error)
20+
}
21+
22+
// PreferenceReconciler makes platform preferences match the desired spec. A
23+
// preference is a name and a value; a missing entry resets to the trait
24+
// default, because settings always have a default to fall back to.
25+
type PreferenceReconciler struct {
26+
client PreferenceAPI
27+
header string
28+
}
29+
30+
func NewPreferenceReconciler(client PreferenceAPI, header string) *PreferenceReconciler {
31+
return &PreferenceReconciler{client: client, header: header}
32+
}
33+
34+
func (r *PreferenceReconciler) Kind() string { return KindPreference }
35+
36+
func (r *PreferenceReconciler) Reconcile(ctx context.Context, spec []byte, dryRun bool) (Report, error) {
37+
var specs []PreferenceSpec
38+
if err := decodeSpec(spec, &specs); err != nil {
39+
return Report{}, fmt.Errorf("parse %s spec: %w", KindPreference, err)
40+
}
41+
42+
current, err := r.fetchCurrent(ctx)
43+
if err != nil {
44+
return Report{}, err
45+
}
46+
defaults, err := r.fetchDefaults(ctx)
47+
if err != nil {
48+
return Report{}, err
49+
}
50+
51+
ops, err := diffPreferences(specs, current, defaults)
52+
if err != nil {
53+
return Report{}, err
54+
}
55+
56+
rep := Report{Kind: KindPreference, DryRun: dryRun}
57+
for _, op := range ops {
58+
rep.Planned = append(rep.Planned, op.String())
59+
}
60+
if dryRun {
61+
return rep, nil
62+
}
63+
for _, op := range ops {
64+
if err := r.apply(ctx, op); err != nil {
65+
return rep, fmt.Errorf("apply [%s]: %w", op, err)
66+
}
67+
rep.Applied++
68+
}
69+
return rep, nil
70+
}
71+
72+
// Export returns the platform preferences whose value differs from the trait
73+
// default, sorted by name. Preferences at their default stay out of the file,
74+
// so reconciling an export plans no changes.
75+
func (r *PreferenceReconciler) Export(ctx context.Context) (any, error) {
76+
current, err := r.fetchCurrent(ctx)
77+
if err != nil {
78+
return nil, err
79+
}
80+
defaults, err := r.fetchDefaults(ctx)
81+
if err != nil {
82+
return nil, err
83+
}
84+
85+
specs := make([]PreferenceSpec, 0, len(current))
86+
for name, value := range current {
87+
def, known := defaults[name]
88+
if !known || value == def {
89+
continue
90+
}
91+
specs = append(specs, PreferenceSpec{Name: name, Value: value})
92+
}
93+
sort.Slice(specs, func(i, j int) bool { return specs[i].Name < specs[j].Name })
94+
return specs, nil
95+
}
96+
97+
// fetchCurrent reads the platform preferences that are stored on the server.
98+
// A trait with no stored value does not appear here; it is at its default.
99+
func (r *PreferenceReconciler) fetchCurrent(ctx context.Context) (map[string]string, error) {
100+
resp, err := r.client.ListPreferences(ctx, authReq(&frontierv1beta1.ListPreferencesRequest{}, r.header))
101+
if err != nil {
102+
return nil, fmt.Errorf("list preferences: %w", err)
103+
}
104+
current := map[string]string{}
105+
for _, p := range resp.Msg.GetPreferences() {
106+
current[p.GetName()] = p.GetValue()
107+
}
108+
return current, nil
109+
}
110+
111+
// fetchDefaults reads the platform traits and their defaults. It is both the
112+
// map of defaults and the set of valid platform preference names.
113+
func (r *PreferenceReconciler) fetchDefaults(ctx context.Context) (map[string]string, error) {
114+
resp, err := r.client.DescribePreferences(ctx, authReq(&frontierv1beta1.DescribePreferencesRequest{}, r.header))
115+
if err != nil {
116+
return nil, fmt.Errorf("describe preferences: %w", err)
117+
}
118+
defaults := map[string]string{}
119+
for _, t := range resp.Msg.GetTraits() {
120+
if t.GetResourceType() != schema.PlatformNamespace {
121+
continue
122+
}
123+
defaults[t.GetName()] = t.GetDefault()
124+
}
125+
return defaults, nil
126+
}
127+
128+
func (r *PreferenceReconciler) apply(ctx context.Context, op preferenceOp) error {
129+
_, err := r.client.CreatePreferences(ctx, authReq(&frontierv1beta1.CreatePreferencesRequest{
130+
Preferences: []*frontierv1beta1.PreferenceRequestBody{{Name: op.name, Value: op.value}},
131+
}, r.header))
132+
return err
133+
}

0 commit comments

Comments
 (0)