1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
package marketidentity
import (
"context"
"crypto/tls"
"errors"
"fmt"
"log/slog"
"net/http"
"strings"
apierrors "k8s.io/apimachinery/pkg/api/errors"
commonv1 "github.com/johnandersen777/socialweb-computer-kcp/api/common/v1alpha1"
"github.com/johnandersen777/socialweb-computer-kcp/api/v1alpha1"
"github.com/johnandersen777/socialweb-computer-kcp/internal/atproto/pdsclient"
"github.com/johnandersen777/socialweb-computer-kcp/internal/bus"
ctlruntime "github.com/johnandersen777/socialweb-computer-kcp/internal/controllers/runtime"
vaultctl "github.com/johnandersen777/socialweb-computer-kcp/internal/controllers/vault"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/binding"
"github.com/johnandersen777/socialweb-computer-kcp/internal/marketidentity/atproto"
)
const (
Name = "marketidentity"
Export = "marketidentities"
PdsExport = "applications"
RecordWatchKind = "AtprotoRecordWatch"
VaultExport = "hostprocesses"
VaultKind = "OpenBaoServer"
VaultObjectKind = "Vault"
eventBuffer = 256
)
type Options struct {
Scope func(workspace string) bool
Endpoints atproto.EndpointFunc
Vault atproto.VaultFunc
Resolver *pdsclient.Resolver
HTTPClient *http.Client
Bus *bus.Bus
OAuth atproto.OAuthOptions
PLCURL string
RecordHTTP *http.Client
Log *slog.Logger
}
type known struct {
cluster string
req ctlruntime.Request
identity *v1alpha1.MarketIdentity
}
type Controller struct {
accounts *atproto.Accounts
roots *vaultctl.Roots
log *slog.Logger
identities *binding.Table[known]
events chan ctlruntime.Request
bus *bus.Bus
}
func New(opts Options) *Controller {
log := opts.Log
if log == nil {
log = slog.New(slog.DiscardHandler)
}
log = log.With("component", "marketidentity-controller")
roots := vaultctl.NewRoots(opts.Bus, log)
trust := func(ctx context.Context, workspace string, id *v1alpha1.MarketIdentity) (*tls.Config, error) {
pool, err := roots.Pool(ctx, Self(workspace, id.Name), id.Spec.CARef, nil)
if err != nil || pool == nil {
return nil, err
}
return pool.PublicClientConfig(nil), nil
}
accounts := atproto.New(atproto.Config{Endpoints: opts.Endpoints, Vault: opts.Vault, Resolver: opts.Resolver, HTTPClient: opts.HTTPClient,
TLS: trust, Sessions: sessions(opts.Bus), OAuth: opts.OAuth, PLCURL: opts.PLCURL, RecordHTTP: opts.RecordHTTP, Log: log})
return &Controller{accounts: accounts, roots: roots, log: log, identities: binding.New[known](), events: make(chan ctlruntime.Request, eventBuffer), bus: opts.Bus}
}
func Register(m *ctlruntime.Manager, opts Options) (*Controller, error) {
if err := m.AddToScheme(v1alpha1.AddToScheme); err != nil {
return nil, err
}
ctl := New(opts)
ctl.Provide(opts.Bus)
ctl.wakeOnVault(opts.Bus)
options := []ctlruntime.Option{ctlruntime.Export(Export), ctlruntime.Events(ctl.events), ctlruntime.Gone(ctl.gone),
ctlruntime.Watches(func(_ context.Context, src ctlruntime.Request, obj *v1alpha1.AtprotoRecordWatch) []ctlruntime.Request {
return ctl.users(binding.Key(src.Workspace, RecordWatchKind, obj.Name))
}),
ctlruntime.WatchesIn(PdsExport, func(_ context.Context, src ctlruntime.Request, obj *v1alpha1.Pds) []ctlruntime.Request {
return ctl.users(binding.Key(src.Workspace, atproto.ComponentKind, obj.Name))
}),
ctlruntime.WatchesIn(VaultExport, func(_ context.Context, src ctlruntime.Request, _ *v1alpha1.OpenBaoServer) []ctlruntime.Request {
return ctl.users(binding.Key(src.Workspace, VaultKind))
})}
if opts.Scope != nil {
options = append(options, ctlruntime.InWorkspaces(opts.Scope))
}
if err := ctlruntime.For[*v1alpha1.MarketIdentity](m, Name, ctl, options...); err != nil {
return nil, fmt.Errorf("marketidentity: registering the MarketIdentity controller: %w", err)
}
return ctl, nil
}
func (c *Controller) Reconcile(ctx context.Context, req ctlruntime.Request, object *v1alpha1.MarketIdentity) (ctlruntime.Result, error) {
if !object.DeletionTimestamp.IsZero() {
c.gone(ctx, req)
return ctlruntime.Result{}, nil
}
prior, held := c.identities.Get(req.Workspace, req.Name)
wasReady := held && prior.identity != nil && prior.identity.Status.Phase == v1alpha1.MarketIdentityPhaseReady
c.remember(req, object)
status := object.Status
watch, err := c.associationWatch(ctx, req, object)
if err != nil {
return ctlruntime.Result{}, err
}
atproto.Associate(object, watch, &status)
result, reconcileErr := c.accounts.Reconcile(ctx, req.Workspace, object, status)
refAfter, refErr := c.accounts.ApplyAssociationRef(ctx, object, &result.Status)
if errors.Is(refErr, atproto.ErrAssociationRefStale) && refAfter > 0 {
refErr, refAfter = nil, min(refAfter, ctlruntime.DefaultBackoffMax)
}
reconcileErr = errors.Join(reconcileErr, refErr)
if refAfter > 0 && (result.RequeueAfter == 0 || refAfter < result.RequeueAfter) {
result.RequeueAfter = refAfter
}
next := object.DeepCopy()
next.Status = result.Status
if err := req.ApplyStatus(ctx, next); err != nil {
return ctlruntime.Result{}, errors.Join(reconcileErr, err)
}
c.remember(req, next)
if !wasReady && next.Status.Phase == v1alpha1.MarketIdentityPhaseReady {
c.log.Info("marketidentity_ready_notified", "workspace", req.Workspace, "identity", req.Name)
c.bus.NotifyBound(bus.Key{Workspace: req.Workspace, Kind: GroupKind.Kind, Name: req.Name})
}
if reconcileErr != nil {
return ctlruntime.Result{}, reconcileErr
}
return ctlruntime.Result{RequeueAfter: result.RequeueAfter}, nil
}
func (c *Controller) CompleteBrowserAuthorization(ctx context.Context, workspace, name string, r *http.Request) error {
entry, ok := c.identities.Get(workspace, name)
if !ok || entry.identity == nil {
return fmt.Errorf("marketidentity: the MarketIdentity %s in %s is not reconciled", name, workspace)
}
err := c.accounts.CompleteBrowserAuthorization(ctx, workspace, entry.identity, r)
c.enqueue(ctlruntime.Request{Cluster: entry.cluster, Workspace: workspace, Name: name})
return err
}
func (c *Controller) SignOut(ctx context.Context, workspace, name string) error {
entry, ok := c.identities.Get(workspace, name)
if !ok || entry.identity == nil {
return fmt.Errorf("marketidentity: the MarketIdentity %s in %s is not reconciled", name, workspace)
}
var live v1alpha1.MarketIdentity
if err := entry.req.Get(ctx, "", name, &live); err != nil {
return fmt.Errorf("marketidentity: reading the MarketIdentity %s in %s: %w", name, workspace, err)
}
if err := atproto.SignOutRefusal(live.Spec.Mode); err != nil {
return err
}
next := max(live.Spec.SignOutGeneration, live.Status.SignedOutGeneration) + 1
if err := entry.req.ApplyFieldsAs(ctx, v1alpha1.FieldManagerMarketIdentitySignOut, &live,
map[string]any{"spec": map[string]any{"signOutGeneration": next}}); err != nil {
return fmt.Errorf("marketidentity: requesting the sign out of %s in %s: %w", name, workspace, err)
}
c.log.Info("sign out requested", "workspace", workspace, "identity", name, "signOutGeneration", next)
return nil
}
func (c *Controller) ComponentChanged(workspace, kind, name string) {
for _, r := range c.users(binding.Key(workspace, kind, name)) {
c.enqueue(r)
}
}
func (c *Controller) associationWatch(ctx context.Context, req ctlruntime.Request, object *v1alpha1.MarketIdentity) (*v1alpha1.AtprotoRecordWatch, error) {
name := strings.TrimSpace(object.Spec.AssociationWatch)
if name == "" || object.Spec.Mode != v1alpha1.MarketIdentityModeLocalRepo || object.Spec.Association == v1alpha1.AssociationSkip {
return nil, nil
}
var watch v1alpha1.AtprotoRecordWatch
err := req.Get(ctx, "", name, &watch)
if apierrors.IsNotFound(err) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("marketidentity: reading the association watch %s: %w", name, err)
}
return &watch, nil
}
func (c *Controller) remember(req ctlruntime.Request, object *v1alpha1.MarketIdentity) {
identity := object.DeepCopy()
refs := []string{binding.Key(req.Workspace, VaultKind)}
if name := strings.TrimSpace(object.Spec.AssociationWatch); name != "" {
refs = append(refs, binding.Key(req.Workspace, RecordWatchKind, name))
}
if object.Spec.Mode == v1alpha1.MarketIdentityModeLocalRepo {
refs = append(refs, binding.Key(req.Workspace, atproto.ComponentKind, atproto.ComponentName))
}
c.identities.Set(binding.Target{Cluster: req.Cluster, Workspace: req.Workspace, Name: req.Name}, &known{cluster: req.Cluster, req: req, identity: identity}, refs...)
}
func (c *Controller) gone(_ context.Context, req ctlruntime.Request) {
c.identities.Set(binding.Target{Cluster: req.Cluster, Workspace: req.Workspace, Name: req.Name}, nil)
c.accounts.Forget(req.Workspace, req.Name)
c.roots.Drop(Self(req.Workspace, req.Name))
}
func Self(workspace, name string) commonv1.ObjectRef {
return commonv1.ObjectRef{Group: v1alpha1.GroupName, Kind: "MarketIdentity", Name: name, Workspace: workspace}
}
func (c *Controller) users(ref string) []ctlruntime.Request {
var out []ctlruntime.Request
for _, t := range c.identities.Users(ref) {
out = append(out, ctlruntime.Request{Cluster: t.Cluster, Workspace: t.Workspace, Name: t.Name})
}
return out
}
func (c *Controller) wakeOnVault(b *bus.Bus) {
b.Subscribe(func(key bus.Key) {
if key.Kind != VaultObjectKind {
return
}
reqs := c.users(binding.Key(key.Workspace, VaultKind))
if len(reqs) == 0 {
return
}
go func() {
for _, r := range reqs {
c.events <- r
}
}()
})
}
func (c *Controller) enqueue(r ctlruntime.Request) {
select {
case c.events <- r:
default:
c.log.Warn("the MarketIdentity event queue is full; the event is dropped", "workspace", r.Workspace, "name", r.Name)
}
}