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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
package requester
import (
"cmp"
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/bluesky-social/indigo/atproto/atcrypto"
"github.com/bluesky-social/indigo/atproto/identity"
"k8s.io/utils/ptr"
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/market"
atprotooauth "github.com/johnandersen777/socialweb-computer-kcp/internal/atproto/oauth"
"github.com/johnandersen777/socialweb-computer-kcp/internal/contract/atprotorepo"
contractmarket "github.com/johnandersen777/socialweb-computer-kcp/internal/contract/market"
"github.com/johnandersen777/socialweb-computer-kcp/internal/contract/pds"
"github.com/johnandersen777/socialweb-computer-kcp/internal/contract/policy"
"github.com/johnandersen777/socialweb-computer-kcp/internal/contract/tunnel"
"github.com/johnandersen777/socialweb-computer-kcp/internal/contract/vault"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/supervise"
"github.com/johnandersen777/socialweb-computer-kcp/internal/market/participant"
"github.com/johnandersen777/socialweb-computer-kcp/internal/policyengine/runs"
"github.com/johnandersen777/socialweb-computer-kcp/internal/sshtransport"
)
type IdentityMode string
const (
IdentityModeLocal IdentityMode = "local"
IdentityModeCallback IdentityMode = "callback"
IdentityModeOAuth IdentityMode = "oauth"
)
const (
DefaultVMReadyTimeout = 120 * time.Second
DefaultHostKeysTimeout = 120 * time.Second
DefaultReceiptTimeout = 5 * time.Minute
DefaultReleaseTimeout = 30 * time.Second
heldReleaseAttempts = 6
heldReleaseBackoffMax = 30 * time.Second
transientContractPrefix = "ssh-run-"
heldContractPrefix = "ssh-"
heldRecordTimeout = 10 * time.Second
signerBindVaultWait = 2 * time.Minute
keepVMLabel = "socialweb.computer/ssh-keep-vm"
HeldSessionPolicyTimeout = 30 * time.Second
TransientResumeGiveUp = 2 * time.Minute
DefaultReleaseRetryFirst = 5 * time.Second
DefaultReleaseRetryMax = 5 * time.Minute
DefaultReleaseBound = 24 * time.Hour
DefaultHTTPTimeout = 30 * time.Second
DefaultPolicyWorkflow = v1alpha1.RequesterDefaultPolicy
SessionFullDeniesPerPick = 5
DefaultVMNamePrefix = "compute-"
ServiceAuthTTL = 5 * time.Minute
MaxRecordBids = 20
PolicyGhaLiteNSID = "computer.socialweb.temp.policy.ghalite"
DefaultComputeDisk = "50G"
DefaultComputeCPUs = 2
DefaultComputeMem = "4G"
DefaultExposureWait = 60 * time.Second
IdentityWait = 60 * time.Second
MarketExposureWait = 10 * time.Second
CallbackWait = 5 * time.Minute
PDSExposure = "svc-pds-pds-local"
KindRequester = "Requester"
ownerSessionSigningService = "market_requester"
)
type Placement struct {
Workspace string
Name string
UID string
StateDir string
}
type Config struct {
Spec v1alpha1.RequesterSpec
AtircURL string
Placement
IdentityMode IdentityMode
LocalSigner bool
DID string
Handle string
RepoDID string
MarketDID string
PDSURL string
OAuthScopes []string
OwnerSessions map[string]sshtransport.OwnerSession
PolicyWorkflow string
GuestAuthorizedKeys []string
BidWindow time.Duration
ReceiptTimeout time.Duration
ReceiptPoll time.Duration
SessionCap time.Duration
SessionIdle time.Duration
PolicyTimeout time.Duration
}
type TokenVerifier interface {
VerifyAudience(ctx context.Context, token, audience string) (map[string]any, error)
}
type Guests interface {
Subject(bidderDID, requesterDID, role string) (string, error)
Verifier(issuer string, keys func(ctx context.Context) ([]byte, error)) TokenVerifier
CheckHostKeys(keys []v1alpha1.ComputeVMHostKey) ([]v1alpha1.ComputeVMHostKey, error)
}
type Deps struct {
Intents contractmarket.Intents
Inputs *participant.Inputs
OpenRepo func(ctx context.Context, did string) (atprotorepo.Repo, error)
AwaitRepo func(ctx context.Context, did string)
WatchBinds func() (<-chan struct{}, func())
Policy runs.ResolveFunc
Vault func(ctx context.Context, ref commonv1.SecretRef) (vault.KV, error)
VaultWrite func(ctx context.Context, ref commonv1.SecretRef) (vault.KV, error)
ServiceAuth func(ctx context.Context, identity commonv1.ObjectRef, did string) (pds.ServiceAuth, error)
Guests Guests
ContractEvents contractmarket.ContractEvents
Ingress tunnel.Service
Directory identity.Directory
HTTP *http.Client
Now func() time.Time
Log *slog.Logger
}
type Requester struct {
cfg Config
inboxed sync.Map
synced atomic.Bool
startedAt atomic.Pointer[time.Time]
firstResume atomic.Bool
prunedForeign atomic.Int64
prunedEnded atomic.Int64
deps Deps
log *slog.Logger
did string
handle string
repoDID string
marketDID string
pdsURL string
repoKey atcrypto.PrivateKey
attestationKey atcrypto.PrivateKey
repo *market.RepoStore
signer *market.Signer
identityRef commonv1.ObjectRef
ownerServiceAuth ServiceAuthSource
serviceAuth ServiceAuthSource
atircAuth ServiceAuthSource
market MarketClient
policy *PolicyEvaluator
outbox *participant.Outbox
contracts *participant.Index[v1alpha1.ComputeContract]
foreignContracts sync.Map
syncs *participant.Index[v1alpha1.StateSync]
receipts *participant.Index[market.ResolvedRecord]
contractEvents *participant.Index[v1alpha1.ContractEvent]
creatingInbound sync.Map
bids *bidQueue
mu sync.Mutex
reconcileMu sync.Mutex
pendingMu sync.Mutex
ctx context.Context
started bool
wg sync.WaitGroup
runners map[string]*contractRunner
finished map[string]bool
releaseRevoking sync.Map
releaseRetried sync.Map
bundleLocks sync.Map
atircIndexMu sync.Mutex
atircMintRetrying sync.Map
atircRevokesStarted sync.Map
orphanSweep sync.Once
runnerEnded chan struct{}
waiting map[string]bool
settled map[string]bool
running int
perAccount map[string]int
written map[string][]v1alpha1.ComputeContractEvent
eventMu sync.Mutex
eventSinks map[string]chan MarketEvent
undelivered map[string][]MarketEvent
bidderMu sync.Mutex
bidders map[string]Bidder
secretsMu sync.Mutex
secrets map[string]*secretsState
sealMu sync.Mutex
heldMu sync.Mutex
heldSessions map[string]*heldSession
transientMu sync.Mutex
transient map[string]context.CancelFunc
transientWG sync.WaitGroup
staleSweep sync.Once
ingressMu sync.Mutex
ingressRef *market.StrongRef
ingressScopeSkipped atomic.Bool
}
var _ contractmarket.Observer = (*Requester)(nil)
func IdentityWorkspaces(workspace string) []string {
workspaces := []string{workspace}
if !strings.HasSuffix(workspace, ":app") {
workspaces = append(workspaces, workspace+":app")
}
return workspaces
}
func Configure(spec v1alpha1.RequesterSpec, at Placement) (Config, error) {
at.Workspace = cmp.Or(at.Workspace, "root")
cfg := Config{Spec: spec, Placement: at, IdentityMode: IdentityModeLocal}
if spec.Identity != nil {
cfg.DID = spec.Identity.Did
cfg.Handle = spec.Identity.Handle
}
cfg.RepoDID, cfg.MarketDID = cfg.DID, cfg.DID
callback := spec.PdsRef != nil && spec.PdsRef.Name != ""
if callback {
cfg.IdentityMode = IdentityModeCallback
if did := strings.TrimSpace(spec.PdsDID); did != "" {
cfg.RepoDID, cfg.MarketDID = did, did
}
}
modeText := strings.ToLower(strings.TrimSpace(spec.Mode))
cfg.LocalSigner = modeText == "local" || modeText == "localrepo" || (modeText == "" && !callback)
switch modeText {
case "callback":
cfg.IdentityMode = IdentityModeCallback
case "oauth", "oauthbrowser", "oauthqr":
cfg.IdentityMode = IdentityModeOAuth
}
if cfg.IdentityMode == IdentityModeOAuth {
cfg.RepoDID, cfg.MarketDID = cfg.DID, cfg.DID
}
cfg.PolicyWorkflow = DefaultPolicyWorkflow
if spec.OwnerSessionsFile != "" {
if cfg.IdentityMode == IdentityModeOAuth {
return Config{}, errors.New("requester: ownerSessionsFile and the oauth identity mode exclude each other")
}
owners, did, handle, err := sshtransport.LoadOwnerSessions(spec.OwnerSessionsFile)
if err != nil {
return Config{}, err
}
if want := strings.TrimSpace(cfg.DID); want != "" {
if own, ok := owners[want]; ok {
did, handle = want, own.Identifier
}
}
session := owners[did]
if strings.TrimSpace(session.Service) == "" {
return Config{}, fmt.Errorf("requester: the owner session of %s names no service", did)
}
cfg.OwnerSessions = owners
cfg.DID, cfg.Handle, cfg.RepoDID, cfg.MarketDID = did, handle, did, did
cfg.PDSURL = session.Service
cfg.IdentityMode = IdentityModeCallback
cfg.LocalSigner = false
}
cfg.BidWindow = seconds(spec.BidWindowSeconds)
cfg.ReceiptTimeout = seconds(spec.ReceiptTimeoutSeconds)
cfg.ReceiptPoll = time.Duration(ptr.Deref(spec.ReceiptPollMilliseconds, 0)) * time.Millisecond
cfg.SessionCap = seconds(spec.SessionCapSeconds)
cfg.SessionIdle = seconds(spec.SessionIdleSeconds)
cfg.PolicyTimeout = seconds(spec.PolicyTimeoutSeconds)
cfg.OAuthScopes = append([]string(nil), spec.OAuthScopes...)
if len(cfg.OAuthScopes) == 0 {
cfg.OAuthScopes = append([]string(nil), atprotooauth.RequesterOAuthScope...)
}
if spec.GuestSSHKeysFile != "" {
keys, err := loadGuestSSHKeys(spec.GuestSSHKeysFile)
if err != nil {
return Config{}, err
}
cfg.GuestAuthorizedKeys = keys
}
return cfg, cfg.check()
}
func seconds(value *int32) time.Duration {
return time.Duration(ptr.Deref(value, 0)) * time.Second
}
func (c Config) check() error {
if c.DID == "" && c.Handle == "" && c.IdentityMode != IdentityModeOAuth {
return errors.New("requester: the component names no identity DID or handle")
}
return nil
}
func (c Config) Network() v1alpha1.MarketNetworkValue {
return ptr.Deref(c.Spec.Network, v1alpha1.MarketNetworkValue{})
}
func (c Config) Relays() []string {
return append([]string(nil), c.Spec.Network.Relays()...)
}
func (c Config) DiscoveryRelays() []string {
return c.Spec.Network.DiscoveryRelayURLs()
}
func (c Config) SealedSecrets() bool {
return c.Spec.SecretsFallback == v1alpha1.SecretsFallbackSealed
}
func (c Config) InboundXRPC() bool {
if c.Spec.Comms == nil {
return true
}
switch c.Spec.Comms.Mode {
case "", v1alpha1.MarketCommsModeXRPC, v1alpha1.MarketCommsModeBoth:
return true
}
return false
}
func (c Config) WebRTCIngress() bool {
return c.InboundXRPC() && c.Spec.Ingress != nil && c.Spec.Ingress.ProviderName() == v1alpha1.IngressProviderWebRTC
}
func (c Config) WebRTCIngressOptions() tunnel.ServiceOptions {
opts := tunnel.ServiceOptions{STUN: c.WebRTCSTUN()}
if c.Spec.Ingress != nil && c.Spec.Ingress.WebRTC != nil {
webRTC := c.Spec.Ingress.WebRTC
if seconds := ptr.Deref(webRTC.SessionTTLSeconds, 0); seconds > 0 {
opts.SessionTTL = time.Duration(seconds) * time.Second
}
if sessions := ptr.Deref(webRTC.MaxSessions, 0); sessions > 0 {
opts.MaxSessions = int(sessions)
}
}
return opts
}
func (c Config) WebRTCSTUN() []string {
if c.Spec.Ingress != nil && c.Spec.Ingress.WebRTC != nil {
if urls := cleanedSTUN(c.Spec.Ingress.WebRTC.STUNURLs); len(urls) > 0 {
return urls
}
}
return []string{tunnel.DefaultSTUN}
}
func cleanedSTUN(urls []string) []string {
out := make([]string, 0, len(urls))
for _, raw := range urls {
if value := strings.TrimSpace(raw); value != "" {
out = append(out, value)
}
}
return out
}
func (c Config) dataDir() string {
if c.Spec.Storage != nil && c.Spec.Storage.DataDir != "" {
return c.Spec.Storage.DataDir
}
return c.StateDir
}
func (c Config) stateFile(name string) string {
if dir := c.dataDir(); dir != "" {
return filepath.Join(dir, name)
}
return ""
}
func loadGuestSSHKeys(path string) ([]string, error) {
raw, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("requester: the guest SSH keys file %s: %w", path, err)
}
keys := []string{}
for line := range strings.SplitSeq(string(raw), "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
keys = append(keys, line)
}
return keys, nil
}
func New(cfg Config, deps Deps) (*Requester, error) {
switch {
case deps.Intents == nil:
return nil, errors.New("requester: the market intents handle is required")
case deps.Inputs == nil:
return nil, errors.New("requester: the market inputs are required")
case deps.OpenRepo == nil:
return nil, errors.New("requester: the record store needs a repo handle")
case deps.Guests == nil:
return nil, errors.New("requester: the guest identity checks are required")
case deps.Directory == nil:
return nil, errors.New("requester: the identity directory is required")
}
if deps.HTTP == nil {
deps.HTTP = &http.Client{Timeout: DefaultHTTPTimeout}
}
if deps.Now == nil {
deps.Now = time.Now
}
if deps.Log == nil {
deps.Log = slog.New(slog.DiscardHandler)
}
q := &Requester{
cfg: cfg,
deps: deps,
did: cfg.DID,
handle: cfg.Handle,
repoDID: cfg.RepoDID,
marketDID: cfg.MarketDID,
pdsURL: cfg.PDSURL,
contracts: participant.NewIndex[v1alpha1.ComputeContract](),
syncs: participant.NewIndex[v1alpha1.StateSync](),
receipts: participant.NewIndex[market.ResolvedRecord](),
contractEvents: participant.NewIndex[v1alpha1.ContractEvent](),
bids: newBidQueue(),
runners: map[string]*contractRunner{},
finished: map[string]bool{},
waiting: map[string]bool{},
settled: map[string]bool{},
perAccount: map[string]int{},
written: map[string][]v1alpha1.ComputeContractEvent{},
eventSinks: map[string]chan MarketEvent{},
undelivered: map[string][]MarketEvent{},
bidders: map[string]Bidder{},
secrets: map[string]*secretsState{},
heldSessions: map[string]*heldSession{},
runnerEnded: make(chan struct{}, 1),
}
q.log = deps.Log.With("component", "requester", "did", q.did)
return q, nil
}
func (q *Requester) Start(ctx context.Context) error {
if ctx == nil {
return errors.New("requester: Start needs the run context")
}
q.mu.Lock()
if q.started {
q.mu.Unlock()
return errors.New("requester: the role is already started")
}
q.started = true
startedAt := time.Now()
q.startedAt.Store(&startedAt)
q.ctx = ctx
q.mu.Unlock()
if dir := q.cfg.dataDir(); dir != "" {
if err := os.MkdirAll(dir, 0o700); err != nil {
return fmt.Errorf("requester: state dir: %w", err)
}
}
if q.cfg.IdentityMode == IdentityModeOAuth {
if err := q.resolveOAuthIdentity(ctx); err != nil {
return err
}
q.log = q.deps.Log.With("component", "requester", "did", q.did)
}
if err := q.resolveIdentity(ctx); err != nil {
return err
}
identityMs := time.Since(startedAt).Milliseconds()
if err := q.loadKeys(); err != nil {
return err
}
if len(q.cfg.OwnerSessions) > 0 {
if err := q.authenticateOwnerSession(ctx); err != nil {
return err
}
}
q.signer = market.NewSigner(q.attestationKey, q.marketDID)
repo, err := participant.NewRepoStore(participant.RepoConfig{DID: q.repoDID, Directory: q.deps.Directory, HTTP: q.deps.HTTP, Open: q.openRepo})
if err != nil {
return fmt.Errorf("requester: the record store: %w", err)
}
q.repo = repo
if q.deps.AwaitRepo != nil {
q.deps.AwaitRepo(ctx, q.repoDID)
if err := ctx.Err(); err != nil {
return err
}
}
repoMs := time.Since(startedAt).Milliseconds()
if len(q.cfg.OwnerSessions) > 0 || q.cfg.IdentityMode == IdentityModeOAuth || (q.cfg.IdentityMode == IdentityModeCallback && !q.cfg.LocalSigner) {
if err := q.bindSignerKeyAfterBinds(ctx); err != nil {
return err
}
}
var serviceAuth ServiceAuthSource
switch {
case q.cfg.IdentityMode == IdentityModeOAuth:
serviceAuth = q.oauthServiceAuth()
case !q.cfg.LocalSigner && q.ownerServiceAuth != nil:
serviceAuth = q.ownerServiceAuth
default:
serviceAuth = q.ownerIdentityServiceAuth()
}
q.serviceAuth = serviceAuth
atircAuth, atircSigning, atircReason := q.atircServiceAuth(serviceAuth)
q.atircAuth = atircAuth
q.log.Info("requester_service_auth", "identityMode", q.cfg.IdentityMode, "localSigner", q.cfg.LocalSigner,
"signing", serviceAuthName(serviceAuth), "atircSigning", atircSigning, "atircReason", atircReason)
q.market = &HTTPMarket{
Directory: q.deps.Directory,
Reader: q.repo,
RepoDID: q.repoDID,
Signer: q.signer,
ServiceKey: q.repoKey,
ServiceAuth: serviceAuth,
RelayURLs: q.cfg.DiscoveryRelays(),
BidderDIDs: append([]string(nil), q.cfg.Spec.BidderDIDs...),
OperatorDID: strings.TrimSpace(q.cfg.Spec.OperatorDID),
Ingress: q.ingress(),
IngressRef: q.ingressDescriptor,
IngressWritable: q.ingressWritable,
IngressSTUN: q.cfg.WebRTCSTUN(),
HTTPClient: q.deps.HTTP,
Timeout: q.cfg.BidWindow,
Log: q.log,
StartedAt: startedAt,
}
outbox, err := participant.NewOutbox(q.deps.Intents, q.deps.Now,
&marketInbox{q: q}, inboxAck{name: BidInboxAdapter}, inboxAck{name: InboxAdapter})
if err != nil {
return err
}
q.outbox = outbox
q.policy = &PolicyEvaluator{Runs: q.policyRuns(), Workflow: PolicyWorkflowName(q.cfg.PolicyWorkflow), DID: q.marketDID}
q.log.Info("requester_start_timing", "step", "started", "sinceStartMs", time.Since(startedAt).Milliseconds(),
"identityMs", identityMs, "repoMs", repoMs)
return nil
}
func (q *Requester) sinceStartMs() (int64, bool) {
startedAt := q.startedAt.Load()
if startedAt == nil {
return 0, false
}
return time.Since(*startedAt).Milliseconds(), true
}
func (q *Requester) noteFirstResume(contract string, readMs int64) {
since, ok := q.sinceStartMs()
if !ok || q.firstResume.Swap(true) {
return
}
q.log.Info("requester_start_timing", "step", "firstContractResumed", "contract", contract,
"sinceStartMs", since, "terminationReadMs", readMs)
}
func (q *Requester) Shutdown(ctx context.Context) {
q.endTransientSessions(ctx, "shutdown")
_ = supervise.Join(ctx, q.wg.Wait)
q.keepHeldSessions("shutdown; the next start adopts it until its recorded expiry")
}
func (q *Requester) resolveIdentity(ctx context.Context) error {
if q.pdsURL != "" && q.did != "" {
return nil
}
if q.cfg.Spec.Identity == nil {
return nil
}
ref := q.cfg.Spec.Identity.MarketIdentityRef
if ref == nil || ref.Name == "" {
return nil
}
found, ok := q.deps.Inputs.AwaitIdentity(ctx, IdentityWorkspaces(q.cfg.Workspace), ref.Name, IdentityWait)
if !ok {
return fmt.Errorf("requester: reading its MarketIdentity %s: not found", ref.Name)
}
if did := found.Status.Did; did != "" {
q.did = did
q.repoDID = cmp.Or(q.repoDID, did)
q.marketDID = cmp.Or(q.marketDID, did)
}
if found.Status.PdsURL != "" {
q.pdsURL = found.Status.PdsURL
}
q.handle = cmp.Or(q.handle, found.Status.Handle)
q.noteIdentityRef(ref.Name)
return nil
}
func (q *Requester) noteIdentityRef(name string) {
if q.identityRef.Name != "" {
return
}
for _, ws := range IdentityWorkspaces(q.cfg.Workspace) {
if _, has := q.deps.Inputs.Identity(ws, name); has {
q.identityRef = commonv1.ObjectRef{Name: name, Workspace: ws}
return
}
}
}
func (q *Requester) loadKeys() error {
if q.repoKey == nil {
if keyPath := q.cfg.stateFile("repo-key.json"); keyPath != "" {
signer, err := market.LoadOrCreateSignerFile(keyPath)
if err != nil {
return fmt.Errorf("requester: repo key: %w", err)
}
q.repoKey = signer.PrivateKey
}
}
if q.attestationKey == nil {
if keyPath := q.cfg.stateFile("attestation-key.json"); keyPath != "" {
signer, err := market.LoadOrCreateSignerFile(keyPath)
if err != nil {
return fmt.Errorf("requester: attestation key: %w", err)
}
q.attestationKey = signer.PrivateKey
}
}
if q.attestationKey == nil {
if q.repoKey == nil {
return errors.New("requester: no attestation or repo key")
}
q.attestationKey = q.repoKey
}
return nil
}
func (q *Requester) policyRuns() *runs.Client {
return participant.NewPolicyRuns(participant.PolicyConfig{
Resolve: q.deps.Policy,
Owner: policy.Owner{APIVersion: v1alpha1.GroupVersion.String(), Kind: KindRequester, Name: q.cfg.Name, UID: q.cfg.UID},
Engine: runs.EngineRef(q.cfg.Spec.PolicyEngineRef, q.cfg.Workspace),
Role: "requester",
Prefix: "requester-policy",
Timeout: q.cfg.PolicyTimeout,
Parser: runs.Strict,
Association: q.cfg.Spec.Association,
})
}
func (q *Requester) openRepo(ctx context.Context) (atprotorepo.Repo, error) {
return q.deps.OpenRepo(ctx, q.repoDID)
}
func (q *Requester) marketExposure() string {
if ref := q.cfg.Spec.MarketExposureRef; ref != nil {
return strings.TrimSpace(ref.Name)
}
return ""
}
func (q *Requester) marketAddress() string {
if name := q.marketExposure(); name != "" {
return q.deps.Inputs.Address(name)
}
return ""
}
func (q *Requester) DID() string {
return q.did
}
func (q *Requester) RepoDID() string {
return q.repoDID
}
func (q *Requester) Handle() string {
return q.handle
}
func (q *Requester) Mode() IdentityMode {
return q.cfg.IdentityMode
}
func (q *Requester) Records() *market.RepoStore {
return q.repo
}
func (q *Requester) now() time.Time {
return q.deps.Now()
}
func (q *Requester) nowISO() string {
return market.FormatTime(q.now())
}
func (q *Requester) runContext() context.Context {
q.mu.Lock()
defer q.mu.Unlock()
return q.ctx
}
func (q *Requester) stopping() bool {
return q.runContext().Err() != nil
}
func (q *Requester) callbackDID() string {
return cmp.Or(q.did, q.marketDID)
}
func (q *Requester) submitBidRef(ctx context.Context) (string, error) {
return q.callbackRef(ctx, market.DefaultMarketServiceID)
}
func (q *Requester) submitEventRef(ctx context.Context) (string, error) {
return q.callbackRef(ctx, market.DefaultComputeEventServiceID)
}
var errNoCallback = errors.New("requester: the market Exposure has no address, and in XRPC comms mode no bidder could reach a record without it")
func (q *Requester) callbackRef(ctx context.Context, fragment string) (string, error) {
if !q.cfg.InboundXRPC() {
return "", nil
}
if address := q.marketAddress(); address != "" {
return address, nil
}
xrpcOnly := q.cfg.Spec.Comms != nil && q.cfg.Spec.Comms.Mode == v1alpha1.MarketCommsModeXRPC
if name := q.marketExposure(); name != "" {
deadline := time.Now().Add(CallbackWait)
for attempt := 1; ; attempt++ {
if address := q.deps.Inputs.AwaitAddress(ctx, name, MarketExposureWait, nil); address != "" {
return strings.TrimRight(address, "/"), nil
}
if err := ctx.Err(); err != nil {
return "", err
}
if !xrpcOnly {
break
}
if !time.Now().Before(deadline) {
return "", fmt.Errorf("%w (%s, after %s)", errNoCallback, name, CallbackWait)
}
q.log.Warn("requester_callback_waits", "exposure", name, "attempt", attempt)
}
}
if q.cfg.IdentityMode == IdentityModeOAuth || q.callbackDID() == "" {
if xrpcOnly {
return "", errNoCallback
}
return "", nil
}
return q.callbackDID() + "#" + fragment, nil
}
func (q *Requester) ingress() tunnel.Service {
if !q.cfg.WebRTCIngress() {
return nil
}
return q.deps.Ingress
}
func (q *Requester) ingressDescriptor(ctx context.Context) *market.RecordRef {
if q.ingress() == nil || q.repo == nil {
return nil
}
id := tunnel.ID(q.repoDID)
if id == "" {
return nil
}
q.ingressMu.Lock()
cached := q.ingressRef
q.ingressMu.Unlock()
if cached != nil {
return &market.RecordRef{URI: cached.URI, CID: cached.CID}
}
if !q.ingressWritable(ctx) {
return nil
}
value, err := market.EncodeRecord(market.IngressWebRTC{Kind: tunnel.KindWebRTC, Mode: market.IngressModeListen, ID: id, StunUrls: q.cfg.WebRTCSTUN(), CreatedAt: q.nowISO()})
if err != nil {
q.log.Warn("requester_webrtc_descriptor_failed", "err", err)
return nil
}
ref, err := participant.EnsureRecordAt(ctx, q.repo, q.repoDID, market.IngressWebRTCNSID, "webrtc", value)
if err != nil {
q.log.Warn("requester_webrtc_descriptor_failed", "err", err)
return nil
}
q.ingressMu.Lock()
q.ingressRef = &ref
q.ingressMu.Unlock()
q.log.Info("requester_webrtc_descriptor", "uri", ref.URI, "cid", ref.CID)
return &market.RecordRef{URI: ref.URI, CID: ref.CID}
}
func (q *Requester) ingressWritable(ctx context.Context) bool {
if q.cfg.IdentityMode != IdentityModeOAuth {
return true
}
granted, known, err := q.oauthGrants(ctx)
if err != nil || !known || len(atprotooauth.MissingScopes([]string{atprotooauth.RepoIngressWebRTCCreate}, granted)) == 0 {
q.ingressScopeSkipped.Store(false)
return true
}
if !q.ingressScopeSkipped.Swap(true) {
q.log.Info("requester_webrtc_ingress_skipped", "reason", "the oauth session was not granted "+atprotooauth.RepoIngressWebRTCCreate)
}
return false
}
func (q *Requester) ingressRecords(ctx context.Context) []market.RecordRef {
ref := q.ingressDescriptor(ctx)
if ref == nil {
return nil
}
return []market.RecordRef{*ref}
}
func (q *Requester) IngressRecords(ctx context.Context) []market.StrongRef {
refs := q.ingressRecords(ctx)
out := make([]market.StrongRef, 0, len(refs))
for _, ref := range refs {
out = append(out, market.NewStrongRef(ref.URI, ref.CID))
}
return out
}
func (q *Requester) guestCAPEM() string {
return strings.TrimSpace(q.cfg.Network().CABundle)
}
func (q *Requester) guestKeyDir() string {
return q.cfg.stateFile("guest-keys")
}
func (q *Requester) bundleLock(contract string) *sync.Mutex {
lock, _ := q.bundleLocks.LoadOrStore(contract, &sync.Mutex{})
return lock.(*sync.Mutex)
}