-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.go
More file actions
1525 lines (1424 loc) · 55.5 KB
/
Copy pathapp.go
File metadata and controls
1525 lines (1424 loc) · 55.5 KB
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
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
"crypto/rand"
"encoding/base64"
"fmt"
"net"
"os"
"path/filepath"
stdruntime "runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/GeiserX/CashPilot-Desktop/internal/bgservice"
"github.com/GeiserX/CashPilot-Desktop/internal/catalog"
"github.com/GeiserX/CashPilot-Desktop/internal/collectors"
"github.com/GeiserX/CashPilot-Desktop/internal/config"
"github.com/GeiserX/CashPilot-Desktop/internal/exchange"
"github.com/GeiserX/CashPilot-Desktop/internal/runtime"
"github.com/GeiserX/CashPilot-Desktop/internal/services"
"github.com/GeiserX/CashPilot-Desktop/internal/store"
wailsruntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
type App struct {
ctx context.Context
cfg *config.Manager
catalog *catalog.Catalog
store *store.Store
runtime runtime.Provider
native runtime.Provider
services *services.Manager
collectors collectorRegistry
exchange *exchange.Service
trayIcon []byte
fleetAPI *fleetAPIServer
// fleetKey is the fleet bearer token held in memory for the per-request auth
// check. It is loaded once at Startup by ensureFleetAPIKey from the OS keychain
// (0600 file fallback) so the token is never persisted in config.json and the
// keychain is not hit on every heartbeat.
fleetKey string
// Background collection scheduler. collecting is a single-flight guard so
// overlapping collectAll runs (the ticker, a post-deploy kick, a future manual
// refresh) never stack. schedCancel/schedDone are the running loop's stop
// handle, guarded by schedMu because Startup, SaveSettings and Shutdown touch
// them from different goroutines.
collecting atomic.Bool
schedMu sync.Mutex
schedCancel context.CancelFunc
schedDone chan struct{}
// fleetMu serializes the per-worker-key state machine. handleWorkerHeartbeat's
// read(FleetDeviceKeyState) -> classify -> upsert -> set/confirm sequence is not
// a single DB transaction (each call is its own statement), so without this lock
// two concurrent/retried heartbeats for one device could both enroll and race
// the key write (last-writer-wins -> a client holds a key the DB discarded), and
// a reap/delete landing mid-sequence could blank a confirmed device's key. Reap
// and manual delete take the same lock so they cannot interleave with a heartbeat.
fleetMu sync.Mutex
// fleetLimiter throttles the heartbeat/enrollment endpoint per client IP as
// defense-in-depth against floods, mass enrollment (DB growth), and racing the
// enrollment window. Initialised in startFleetAPI.
fleetLimiter *fleetRateLimiter
}
// collectorRegistry is the slice of *collectors.Registry the app depends on: run a
// single service's collector (persisting its earnings record) and report whether a
// slug has a native collector at all. It is an interface so the scheduler tests can
// inject a fake collector without a live store or network.
type collectorRegistry interface {
Collect(ctx context.Context, slug string, credentials map[string]string) (store.EarningsRecord, error)
Supports(slug string) bool
}
func NewApp() *App {
return &App{}
}
// Startup is the Wails OnStartup hook. It brings the app's core engine up via
// startCore — the shared init that both the GUI and the headless --daemon role use.
// The engine init has nothing UI-specific in it (the window/tray/webview setup lives in
// DomReady), so the two roles share one definition of "bring the app up". A fatal core
// failure (config/store/catalog) was already surfaced as an app:error event inside
// startCore and leaves a.ready() failing for every binding, so — exactly as before —
// there is nothing further for the GUI hook to do with the returned error.
func (a *App) Startup(ctx context.Context) {
_ = a.startCore(ctx)
}
// startCore initialises everything the app needs in BOTH roles: config, the local
// store, the embedded catalog, the Docker and native runtime providers (registering the
// native-process supervisor), the collectors, the periodic exchange-rate refresh, the
// loopback fleet API, and the background collection scheduler. It is deliberately free
// of any Wails/UI dependency — the window, tray and webview are set up separately in
// DomReady — so the --daemon path can call it to run the same engine headless.
//
// It returns an error only on a fatal init failure (config/store/catalog); a fleet
// key/listener failure is non-fatal and merely surfaced, matching the original Startup.
// The Wails path ignores the return (the failure is already an app:error event and
// a.ready() reports it); the daemon path logs it and exits.
//
// ctx is stored as a.ctx and drives the exchange refresh, the scheduler and event
// emission: the Wails app context under the GUI, a signal-cancelled context under the
// daemon. Under the daemon that context carries no "events" value, so emitEvent /
// emitError safely no-op (no window/tray code is ever reached).
func (a *App) startCore(ctx context.Context) error {
a.ctx = ctx
cfg, err := config.NewManager()
if err != nil {
a.emitError("config", err)
return err
}
a.cfg = cfg
st, err := store.Open(cfg.DataDir())
if err != nil {
a.emitError("store", err)
return err
}
a.store = st
cat, err := catalog.LoadEmbedded(serviceFiles)
if err != nil {
a.emitError("catalog", err)
return err
}
a.catalog = cat
a.runtime = runtime.NewDockerProvider()
native := runtime.NewNativeProcessProvider(cfg.AppDir())
// Feed the native supervisor's autonomous crashes/respawns into the same runtime_events
// stream HealthScores aggregates, so native earners get the crash/restart accounting the
// Docker path already has. Set on the concrete provider before it is stored behind the
// Provider interface, and before any Deploy (no supervise goroutine exists yet).
native.SetEventRecorder(a.store.RecordEvent)
a.native = native
a.services = services.NewManager(a.runtime, a.catalog, a.store)
a.services.Register(runtime.NativeRuntimeKind, a.native)
a.collectors = collectors.NewRegistry(a.store)
// Exchange rates power the earnings summary. Kick a best-effort initial fetch
// and a periodic refresh; a failed fetch must never fail Startup (the summary
// is stale-graceful and flags stale rates rather than blanking balances).
a.exchange = exchange.NewService()
go func() { _ = a.exchange.Refresh(ctx) }()
go func() {
ticker := time.NewTicker(exchange.CacheTTL)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
_ = a.exchange.Refresh(ctx)
}
}
}()
// A fleet-token problem must NOT disable core earnings collection: surface it and
// continue so the scheduler and retention purge below still start. The fleet
// heartbeat handler fails closed while fleetKey is empty (it returns 503 and
// persists nothing), so continuing here never leaves the worker API open.
if err := a.ensureFleetAPIKey(); err != nil {
a.emitError("fleet-api", err)
}
if err := a.startFleetAPI(); err != nil {
a.emitError("fleet-api", err)
}
// Start background earnings collection so the app is genuinely "passive":
// balances refresh on a timer without the user clicking Collect. This never
// blocks Startup — startScheduler only launches a goroutine.
a.startScheduler(ctx)
return nil
}
func (a *App) DomReady(ctx context.Context) {
// a.ctx is set once in Startup with the same Wails app context; deliberately do
// NOT reassign it here. Binding goroutines (GetAppState -> runtime.Status,
// computeEarningsSummary -> EnsureFresh, CollectService) read a.ctx
// concurrently, so a second write would race with those reads under -race.
// DomReady uses its local ctx parameter directly for the window/tray setup.
wailsruntime.WindowShow(ctx)
PositionMainWindowOnPrimaryScreen()
InstallTrayIcon(a.trayIcon)
}
func (a *App) Shutdown(_ context.Context) {
// Stop the collection loop before closing the store so no in-flight collect
// writes to a database that is about to close.
a.stopScheduler()
if a.fleetAPI != nil {
_ = a.fleetAPI.Close()
}
if a.store != nil {
_ = a.store.Close()
}
}
type AppState struct {
Config config.AppConfig `json:"config"`
Runtime runtime.Status `json:"runtime"`
Services []catalog.Service `json:"services"`
Deployments []store.Deployment `json:"deployments"`
// OutdatedServices lists the slugs of deployed services whose running image no
// longer matches the catalog's current image (the provider changed or re-pinned
// it): deployed and often still "running", but likely earning nothing until
// re-deployed. The frontend badges these; notifications() also alerts on them.
OutdatedServices []string `json:"outdatedServices"`
Earnings []store.EarningsRecord `json:"earnings"`
Guides []runtime.InstallGuide `json:"guides"`
Notifications []Notification `json:"notifications"`
Currencies []string `json:"currencies"`
Summary EarningsSummary `json:"summary"`
Health map[string]store.HealthScore `json:"health"`
// ServiceDetails carries each collector's optional per-service JSON detail blob
// keyed by slug (e.g. the MystNodes per-node earnings breakdown). The frontend
// parses the raw JSON per service; the backend stores and forwards it opaquely.
ServiceDetails map[string]string `json:"serviceDetails"`
// Hostname is this machine's name, so a deploy form can render a {hostname}-defaulted
// field with the real value the deploy path will substitute (instead of the literal
// "cashpilot-{hostname}" the raw catalog default would otherwise show and submit).
Hostname string `json:"hostname"`
}
type Notification struct {
Level string `json:"level"`
Title string `json:"title"`
Message string `json:"message"`
}
// EarningsSummary is the dashboard's converted, aggregated view of earnings.
// Balances stored per service are CUMULATIVE lifetime totals; the summary turns
// them into a single display-currency total plus per-day accrual figures.
type EarningsSummary struct {
DisplayCurrency string `json:"displayCurrency"`
Total float64 `json:"total"`
Today float64 `json:"today"`
Month float64 `json:"month"`
TodayChange float64 `json:"todayChange"`
MonthChange float64 `json:"monthChange"`
Breakdown []ServiceEarning `json:"breakdown"`
Points []PointsBalance `json:"points"`
Daily []DailyPoint `json:"daily"`
RatesStale bool `json:"ratesStale"`
RatesUpdated string `json:"ratesUpdated"`
}
// ServiceEarning is one service's latest balance, both native and converted to
// the display currency, with its payout/cashout progress. Error rows are kept so
// the UI can surface a "needs attention" chip.
type ServiceEarning struct {
Platform string `json:"platform"`
Name string `json:"name"`
Balance float64 `json:"balance"`
Currency string `json:"currency"`
BalanceDisplay float64 `json:"balanceDisplay"`
Convertible bool `json:"convertible"`
Error string `json:"error"`
Cashout CashoutProgress `json:"cashout"`
}
// CashoutProgress describes how close a service is to its minimum payout. It is
// only meaningful (Comparable) when the balance currency matches the cashout
// currency; otherwise the UI hides the progress bar.
type CashoutProgress struct {
MinAmount float64 `json:"minAmount"`
Currency string `json:"currency"`
Percent float64 `json:"percent"`
Eligible bool `json:"eligible"`
Comparable bool `json:"comparable"`
Method string `json:"method"`
DashboardURL string `json:"dashboardUrl"`
Notes string `json:"notes"`
}
// PointsBalance is a non-convertible reward balance (e.g. GRASS points) shown in
// native units and deliberately excluded from fiat totals.
type PointsBalance struct {
Platform string `json:"platform"`
Name string `json:"name"`
Balance float64 `json:"balance"`
Currency string `json:"currency"`
}
// DailyPoint is one day's earnings (accrual) in the display currency, for the
// dashboard chart.
type DailyPoint struct {
Day string `json:"day"`
Amount float64 `json:"amount"`
}
type EnvSetting struct {
Key string `json:"key"`
Label string `json:"label"`
Value string `json:"value"`
Source string `json:"source"`
Secret bool `json:"secret"`
ReadOnly bool `json:"readOnly"`
Help string `json:"help"`
}
type CollectorSetting struct {
Slug string `json:"slug"`
Name string `json:"name"`
Configured bool `json:"configured"`
Collector string `json:"collector"`
}
type SettingsState struct {
Environment []EnvSetting `json:"environment"`
Collectors []CollectorSetting `json:"collectors"`
Config config.AppConfig `json:"config"`
}
type FleetState struct {
Workers int `json:"workers"`
Mobiles int `json:"mobiles"`
Online int `json:"online"`
Services int `json:"services"`
Devices []store.FleetDevice `json:"devices"`
UIURL string `json:"uiUrl"`
LocalAPIURL string `json:"localApiUrl"`
APIKey string `json:"apiKey"`
APIListening bool `json:"apiListening"`
WorkerSnippet string `json:"workerSnippet"`
MobileSnippet string `json:"mobileSnippet"`
}
// Fleet device lifecycle tunables, matching production CashPilot. A worker/mobile that
// stops sending heartbeats is flipped offline once it has been silent longer than
// fleetOfflineAfter (the ~3-missed-heartbeat grace), and a device offline longer than
// fleetReapAfter is removed entirely. collectAll's background sweep applies both to the
// DB; GetFleetState additionally uses fleetOfflineAfter to show a silent device as
// offline immediately, without waiting for the next tick.
const (
fleetOfflineAfter = 180 * time.Second
fleetReapAfter = 1 * time.Hour
// collectConcurrency bounds how many services collectAll collects at once. Each
// Collect is a real network round trip (up to ~90s worst case on a stalled
// provider), so running the batch through a small worker pool turns the cycle's
// cost from the SUM of per-service latencies into roughly the MAX, without
// unbounded fan-out against provider APIs or the (SetMaxOpenConns(1)) store.
collectConcurrency = 6
)
func (a *App) GetAppState() (AppState, error) {
if err := a.ready(); err != nil {
return AppState{}, err
}
runtimeStatus := a.runtime.Status(a.ctx)
// Surface the always-on native runtime alongside Docker's status so the frontend
// can proceed (and message honestly) on Docker OR native. Available keeps its
// Docker-only meaning; this is purely additive.
runtimeStatus.NativeAvailable = a.services.HasNativeRuntime()
// Fetch these once and thread them into the helpers below instead of letting
// each helper re-run its own full-table scan (they were each queried up to 3x
// per GetAppState call before this).
deployments := a.store.ListDeployments()
earnings := a.store.ListLatestEarnings()
return AppState{
Config: a.cfg.Config(),
Runtime: runtimeStatus,
Services: a.catalog.ListVisible(),
Deployments: deployments,
OutdatedServices: a.outdatedServices(deployments),
Earnings: earnings,
Guides: runtime.InstallGuides(),
Notifications: a.notifications(runtimeStatus, earnings, deployments),
Currencies: supportedCurrencies(),
Summary: a.computeEarningsSummary(earnings),
Health: a.store.HealthScores(7),
ServiceDetails: a.store.ListServiceDetails(),
Hostname: runtime.DeviceHostname(),
}, nil
}
// GetEarningsSummary returns the converted, aggregated earnings summary on its
// own so the frontend can refresh it without pulling the whole app state.
func (a *App) GetEarningsSummary() (EarningsSummary, error) {
if err := a.ready(); err != nil {
return EarningsSummary{}, err
}
return a.computeEarningsSummary(a.store.ListLatestEarnings()), nil
}
// computeEarningsSummary converts the per-service CUMULATIVE daily balances into
// a single display-currency total plus per-day accrual figures. Convertible
// currencies (USD, known fiat, priced crypto) are summed; non-convertible reward
// points (e.g. GRASS) are surfaced separately and never summed. It is
// stale-graceful: missing rates simply drop a service from the total and set
// RatesStale, rather than erroring.
func (a *App) computeEarningsSummary(earnings []store.EarningsRecord) EarningsSummary {
disp := "USD"
if a.cfg != nil {
if c := a.cfg.Config().DisplayCurrency; c != "" {
disp = c
}
}
summary := EarningsSummary{
DisplayCurrency: disp,
Breakdown: []ServiceEarning{},
Points: []PointsBalance{},
Daily: []DailyPoint{},
}
if a.exchange == nil || a.store == nil || a.catalog == nil {
return summary
}
a.exchange.EnsureFresh(a.ctx)
now := time.Now().UTC()
dayStr := func(offset int) string { return now.AddDate(0, 0, offset).Format("2006-01-02") }
monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)
beforeMonthStart := monthStart.AddDate(0, 0, -1).Format("2006-01-02")
lastMonthStart := monthStart.AddDate(0, -1, 0)
beforeLastMonthStartTime := lastMonthStart.AddDate(0, 0, -1)
beforeLastMonthStart := beforeLastMonthStartTime.Format("2006-01-02")
// Fetch a window wide enough to reach the day BEFORE last month started (two
// months plus a margin) so the month and last-month baselines are actually in
// the map. A hardcoded window would leave those baselines unreachable; combined
// with per-platform accrual below, an unreachable baseline just degrades to
// "contributes 0", never a garbage cumulative number.
daysBack := int(now.Sub(beforeLastMonthStartTime).Hours()/24) + 7
// Build per-platform day -> cumulative balance maps, the platform's currency,
// and a sorted list of the days it was actually collected.
perPlat := map[string]map[string]float64{}
perCur := map[string]string{}
daysByPlat := map[string][]string{}
for _, b := range a.store.ListDailyBalances(daysBack) {
if perPlat[b.Platform] == nil {
perPlat[b.Platform] = map[string]float64{}
}
if _, seen := perPlat[b.Platform][b.Day]; !seen {
daysByPlat[b.Platform] = append(daysByPlat[b.Platform], b.Day)
}
perPlat[b.Platform][b.Day] = b.Balance
perCur[b.Platform] = b.Currency
}
for plat := range daysByPlat {
sort.Strings(daysByPlat[plat])
}
// asOf carries the cumulative balance forward: the balance on the latest
// collected day on or before `day` (ok=false when nothing was collected on or
// before that day, i.e. there is no established baseline yet).
asOf := func(plat, day string) (float64, bool) {
var val float64
found := false
for _, d := range daysByPlat[plat] {
if d <= day {
val = perPlat[plat][d]
found = true
continue
}
break
}
return val, found
}
// platformDelta is a SINGLE platform's display-currency accrual between two
// days, from its own cumulative balances (not the whole-portfolio total). It
// books 0 unless BOTH endpoints have an established, convertible baseline: a
// platform's first-ever observation (or a baseline that predates the fetch
// window) has no `fromDay` balance, so its whole lifetime cumulative is never
// counted as a single day's earning. Per-platform clamping at 0 keeps one
// platform's dip from cancelling another's gain.
platformDelta := func(plat, fromDay, toDay string) float64 {
fromBal, fromOK := asOf(plat, fromDay)
if !fromOK {
return 0
}
toBal, toOK := asOf(plat, toDay)
if !toOK {
return 0
}
cur := perCur[plat]
fromDisp, ok := a.exchange.ToDisplay(fromBal, cur, disp)
if !ok {
return 0
}
toDisp, ok := a.exchange.ToDisplay(toBal, cur, disp)
if !ok {
return 0
}
return max(0, toDisp-fromDisp)
}
// sumDelta accrues every platform's per-platform delta over one period.
sumDelta := func(fromDay, toDay string) float64 {
var sum float64
for plat := range daysByPlat {
sum += platformDelta(plat, fromDay, toDay)
}
return sum
}
// Total / Points from each platform's LATEST cumulative balance, classified by
// INTENT: a declared reward point (PointsCurrencies) is surfaced natively and
// never summed; any other currency is added to the fiat Total when it can be
// priced right now; a non-points currency that cannot currently be priced (a
// rate outage or a zero rate) is dropped from BOTH and flags the rates stale,
// so it is never mislabeled as a reward point.
var total float64
latestDay := ""
for plat, days := range daysByPlat {
if len(days) == 0 {
continue
}
last := days[len(days)-1]
if last > latestDay {
latestDay = last
}
cur := perCur[plat]
bal := perPlat[plat][last]
if a.exchange.IsPoints(cur) {
summary.Points = append(summary.Points, PointsBalance{
Platform: plat,
Name: a.serviceName(plat),
Balance: bal,
Currency: cur,
})
continue
}
if conv, ok := a.exchange.ToDisplay(bal, cur, disp); ok {
total += conv
continue
}
summary.RatesStale = true
}
summary.Total = total
today := dayStr(0)
if latestDay == "" {
latestDay = today
}
// Today / yesterday accrual = per-platform deltas across the two day pairs.
todayEarned := sumDelta(dayStr(-1), today)
yesterdayEarned := sumDelta(dayStr(-2), dayStr(-1))
summary.Today = todayEarned
if yesterdayEarned > 0 {
summary.TodayChange = (todayEarned - yesterdayEarned) / yesterdayEarned * 100
}
// Month = per-platform accrual since the day before this month started; a
// platform whose baseline is unknown (before first collection or outside the
// window) contributes 0 rather than its whole cumulative balance.
summary.Month = sumDelta(beforeMonthStart, latestDay)
prevMonthEarned := sumDelta(beforeLastMonthStart, beforeMonthStart)
if prevMonthEarned > 0 {
summary.MonthChange = (summary.Month - prevMonthEarned) / prevMonthEarned * 100
}
// Daily = last 30 days of per-day accrual in the display currency.
for i := 29; i >= 0; i-- {
d := now.AddDate(0, 0, -i)
curDay := d.Format("2006-01-02")
prevDay := d.AddDate(0, 0, -1).Format("2006-01-02")
summary.Daily = append(summary.Daily, DailyPoint{
Day: d.Format("Jan 02"),
Amount: sumDelta(prevDay, curDay),
})
}
// Breakdown = every service's latest record, INCLUDING error rows so the UI
// keeps a "needs attention" chip.
for _, rec := range earnings {
se := ServiceEarning{
Platform: rec.Platform,
Name: rec.Platform,
Balance: rec.Balance,
Currency: rec.Currency,
Error: rec.Error,
}
var cash catalog.Cashout
if svc, ok := a.catalog.Get(rec.Platform); ok {
se.Name = svc.Name
cash = svc.Cashout
}
if a.exchange.Convertible(rec.Currency) {
se.Convertible = true
if conv, ok := a.exchange.ToDisplay(rec.Balance, rec.Currency, disp); ok {
se.BalanceDisplay = conv
}
}
cp := CashoutProgress{
MinAmount: cash.MinAmount,
Currency: cash.Currency,
Method: cash.Method,
DashboardURL: cash.DashboardURL,
Notes: cash.Notes,
Comparable: rec.Currency == cash.Currency,
}
if cp.Comparable && cash.MinAmount > 0 {
cp.Percent = max(0, min(100, rec.Balance/cash.MinAmount*100))
}
cp.Eligible = cp.Comparable && cash.MinAmount > 0 && rec.Balance >= cash.MinAmount
se.Cashout = cp
summary.Breakdown = append(summary.Breakdown, se)
}
// Preserve any stale flag already raised above (a non-points currency that
// could not be priced) and OR in the exchange's own staleness.
summary.RatesStale = summary.RatesStale || a.exchange.Stale()
summary.RatesUpdated = a.exchange.Snapshot().LastUpdated
return summary
}
// serviceName resolves a catalog display name for a slug, falling back to the
// slug itself when the service is not in the catalog.
func (a *App) serviceName(slug string) string {
if a.catalog != nil {
if svc, ok := a.catalog.Get(slug); ok {
return svc.Name
}
}
return slug
}
func (a *App) GetSettingsState() (SettingsState, error) {
if err := a.ready(); err != nil {
return SettingsState{}, err
}
cfg := a.cfg.Config()
env := []EnvSetting{
{Key: "CASHPILOT_HOSTNAME_PREFIX", Label: "Hostname Prefix", Value: cfg.HostnamePrefix, Source: "Config", Help: "Containers are named <prefix>-<service> where supported."},
{Key: "CASHPILOT_COLLECT_INTERVAL", Label: "Collect Interval (min)", Value: strconv.Itoa(cfg.CollectIntervalMinutes), Source: "Config", Help: "Minutes between future automatic earnings collection runs."},
{Key: "CASHPILOT_DISPLAY_CURRENCY", Label: "Display Currency", Value: cfg.DisplayCurrency, Source: "Config", Help: "Currency used in the topbar and dashboard summaries."},
{Key: "CASHPILOT_API_KEY", Label: "Fleet API Key", Value: a.fleetKey, Source: "Config", Secret: true, Help: "Bearer token used by external workers and mobile clients."},
{Key: "CASHPILOT_UI_URL", Label: "Desktop API URL", Value: a.fleetUIURL(), Source: "Runtime", ReadOnly: true, Help: "URL that external workers should use for CASHPILOT_UI_URL."},
{Key: "CASHPILOT_FLEET_BIND", Label: "Fleet Bind Address", Value: cfg.FleetBindAddress, Source: "Config", Help: "Default 127.0.0.1 (this machine only). Set to 0.0.0.0 only to accept worker/mobile connections from your LAN — this exposes the API to your network, and (if metrics are enabled) also serves the UNAUTHENTICATED /metrics endpoint — your earnings and health totals — to anyone on your LAN."},
{Key: "CASHPILOT_FLEET_PORT", Label: "Fleet API Port", Value: strconv.Itoa(cfg.FleetPort), Source: "Config", Help: "Port used for external worker heartbeats."},
{Key: "TZ", Label: "System Timezone", Value: cfg.Timezone, Source: "Config", Help: "Timezone passed to future managed workers and mobile sync events."},
{Key: "CASHPILOT_DATA_DIR", Label: "Data Directory", Value: a.cfg.DataDir(), Source: "Read-only", ReadOnly: true, Help: "Directory containing the local SQLite database."},
{Key: "CASHPILOT_RUNTIME_PROVIDER", Label: "Runtime Provider", Value: cfg.RuntimeProvider, Source: "Read-only", ReadOnly: true, Help: "Current Docker-compatible runtime integration."},
}
collectors := make([]CollectorSetting, 0)
for _, svc := range a.catalog.ListVisible() {
if svc.Collector.Type == "" && !svc.ManualOnly {
continue
}
creds, err := a.store.GetCredentials(svc.Slug)
if err != nil {
// A credential blob that fails to decrypt/parse must not be silently
// dropped (which would wrongly show the service as "not configured");
// surface it while keeping the rest of the settings list usable.
a.emitError("credentials", err)
}
collectors = append(collectors, CollectorSetting{
Slug: svc.Slug,
Name: svc.Name,
Configured: a.credsConfigured(svc.Slug, creds),
Collector: svc.Collector.Type,
})
}
return SettingsState{Environment: env, Collectors: collectors, Config: cfg}, nil
}
func (a *App) SaveSettings(values map[string]string) (SettingsState, error) {
if err := a.ready(); err != nil {
return SettingsState{}, err
}
cfg := a.cfg.Config()
previousInterval := cfg.CollectIntervalMinutes
previousFleetPort := cfg.FleetPort
previousFleetBind := cfg.FleetBindAddress
if value := strings.TrimSpace(values["displayCurrency"]); value != "" {
upper := strings.ToUpper(value)
if !isSupportedCurrency(upper) {
return SettingsState{}, fmt.Errorf("unsupported display currency: %s", value)
}
cfg.DisplayCurrency = upper
}
if value := strings.TrimSpace(values["hostnamePrefix"]); value != "" {
cfg.HostnamePrefix = value
}
if value := strings.TrimSpace(values["timezone"]); value != "" {
cfg.Timezone = value
}
if value := strings.TrimSpace(values["fleetBindAddress"]); value != "" {
// Only a parseable IP or "localhost" is a valid bind host (an empty value
// keeps the loopback default via config.Normalize). A bad value stored verbatim
// would silently brick the fleet listener on the next launch, so reject it here.
if value != "localhost" && net.ParseIP(value) == nil {
return SettingsState{}, fmt.Errorf("invalid fleet bind address %q", value)
}
cfg.FleetBindAddress = value
}
if value := strings.TrimSpace(values["collectIntervalMinutes"]); value != "" {
minutes, err := strconv.Atoi(value)
if err != nil || minutes <= 0 {
return SettingsState{}, fmt.Errorf("collect interval must be a positive number")
}
cfg.CollectIntervalMinutes = minutes
}
if value := strings.TrimSpace(values["fleetPort"]); value != "" {
port, err := strconv.Atoi(value)
if err != nil || port <= 0 || port > 65535 {
return SettingsState{}, fmt.Errorf("fleet API port must be between 1 and 65535")
}
cfg.FleetPort = port
}
if err := a.cfg.Save(cfg); err != nil {
return SettingsState{}, err
}
// If the collection cadence changed, restart the ticker so the new interval
// takes effect immediately instead of waiting for the next app launch.
if cfg.CollectIntervalMinutes != previousInterval && a.ctx != nil {
a.runScheduler(a.ctx, a.collectInterval())
}
// The fleet listener binds its port/address once at Startup; changing them here
// does not rebind the already-running server (a live restart is deferred). Surface
// a notice so the UI does not keep advertising a now-dead port to the user until
// the app is restarted.
if cfg.FleetPort != previousFleetPort || cfg.FleetBindAddress != previousFleetBind {
a.emitNotice("fleet-api", "Fleet API port/bind change takes effect after restarting the app.")
}
return a.GetSettingsState()
}
func (a *App) GetFleetState() (FleetState, error) {
if err := a.ready(); err != nil {
return FleetState{}, err
}
cfg := a.cfg.Config()
devices := a.store.ListFleetDevices()
hostname, _ := os.Hostname()
local := store.FleetDevice{
ID: 0,
Name: hostnameOrDefault(hostname),
Kind: "desktop",
Endpoint: "local",
OS: stdruntime.GOOS,
Arch: stdruntime.GOARCH,
Status: "online",
Services: deploymentSlugs(a.store.ListDeployments()),
LastSeen: time.Now().UTC().Format(time.RFC3339),
}
devices = append([]store.FleetDevice{local}, devices...)
workers, mobiles, online := 0, 0, 0
for i := range devices {
// Reflect the offline grace on the read path so opening the Fleet view is
// accurate between scheduler ticks: a device silent longer than
// fleetOfflineAfter shows offline immediately. This adjusts only the returned
// value — the actual DB flip and reap happen in collectAll's background sweep.
devices[i].Status = store.EffectiveFleetStatus(devices[i].Status, devices[i].LastSeen, fleetOfflineAfter)
if devices[i].Kind == "mobile" {
mobiles++
} else {
workers++
}
if devices[i].Status == "online" {
online++
}
}
services := len(a.catalog.ListVisible())
uiURL := a.fleetUIURL()
localAPIURL := fmt.Sprintf("http://127.0.0.1:%d", cfg.FleetPort)
return FleetState{
Workers: workers,
Mobiles: mobiles,
Online: online,
Services: services,
Devices: devices,
UIURL: uiURL,
LocalAPIURL: localAPIURL,
APIKey: a.fleetKey,
APIListening: a.fleetAPI != nil,
WorkerSnippet: fmt.Sprintf("CASHPILOT_UI_URL=%s\nCASHPILOT_API_KEY=%s\nCASHPILOT_WORKER_NAME=%s-worker\nCASHPILOT_WORKER_URL=http://<worker-lan-ip>:8081", uiURL, a.fleetKey, cfg.HostnamePrefix),
MobileSnippet: fmt.Sprintf("CASHPILOT_UI_URL=%s\nCASHPILOT_API_KEY=%s\nDevice type: mobile", uiURL, a.fleetKey),
}, nil
}
func (a *App) AddFleetDevice(values map[string]string) (FleetState, error) {
if err := a.ready(); err != nil {
return FleetState{}, err
}
name := strings.TrimSpace(values["name"])
if name == "" {
return FleetState{}, fmt.Errorf("device name is required")
}
kind := strings.TrimSpace(values["kind"])
if kind != "mobile" && kind != "worker" {
kind = "worker"
}
services := splitList(values["services"])
_, err := a.store.UpsertFleetDevice(store.FleetDevice{
Name: name,
Kind: kind,
Endpoint: strings.TrimSpace(values["endpoint"]),
OS: strings.TrimSpace(values["os"]),
Arch: strings.TrimSpace(values["arch"]),
Status: "offline",
Services: services,
LastSeen: "not connected yet",
})
if err != nil {
return FleetState{}, err
}
return a.GetFleetState()
}
func (a *App) RemoveFleetDevice(id int64) (FleetState, error) {
if err := a.ready(); err != nil {
return FleetState{}, err
}
if id <= 0 {
return FleetState{}, fmt.Errorf("the local desktop device cannot be removed")
}
a.fleetMu.Lock()
err := a.store.DeleteFleetDevice(id)
a.fleetMu.Unlock()
if err != nil {
return FleetState{}, err
}
return a.GetFleetState()
}
func (a *App) CompleteOnboarding() error {
if err := a.ready(); err != nil {
return err
}
cfg := a.cfg.Config()
cfg.FirstRunComplete = true
return a.cfg.Save(cfg)
}
func (a *App) CheckRuntime() (runtime.Status, error) {
if err := a.ready(); err != nil {
return runtime.Status{}, err
}
status := a.runtime.Status(a.ctx)
// Report native availability alongside Docker so onboarding's "Check Again" can
// unblock on the always-on native runtime, not only on Docker. Additive only —
// Available still reflects Docker.
status.NativeAvailable = a.services.HasNativeRuntime()
return status, nil
}
func (a *App) GetRuntimeGuides() []runtime.InstallGuide {
return runtime.InstallGuides()
}
func (a *App) ListServices() ([]catalog.Service, error) {
if err := a.ready(); err != nil {
return nil, err
}
return a.catalog.ListVisible(), nil
}
func (a *App) GetService(slug string) (catalog.Service, error) {
if err := a.ready(); err != nil {
return catalog.Service{}, err
}
svc, ok := a.catalog.Get(slug)
if !ok {
return catalog.Service{}, fmt.Errorf("unknown service: %s", slug)
}
return svc, nil
}
func (a *App) SaveCredentials(slug string, values map[string]string) error {
if err := a.ready(); err != nil {
return err
}
return a.store.SaveCredentials(slug, values)
}
func (a *App) GetCredentials(slug string) (map[string]string, error) {
if err := a.ready(); err != nil {
return nil, err
}
return a.store.GetCredentials(slug)
}
func (a *App) DeployService(slug string, values map[string]string) (store.Deployment, error) {
if err := a.ready(); err != nil {
return store.Deployment{}, err
}
// The credentials this deploy will use: the submitted values (which replace the
// stored blob) when provided, else whatever is already stored.
creds := values
if len(creds) == 0 {
stored, err := a.store.GetCredentials(slug)
if err != nil {
return store.Deployment{}, err
}
creds = stored
}
// Validate BEFORE persisting, so a rejected deploy never leaves invalid/blank creds
// lingering — they could never deploy, yet they would linger and light the
// "Configured" badge for a service that cannot actually start.
if err := a.services.ValidateCredentials(slug, creds); err != nil {
a.emitError("deploy", err)
return store.Deployment{}, err
}
if len(values) > 0 {
if err := a.store.SaveCredentials(slug, values); err != nil {
return store.Deployment{}, err
}
}
deployment, err := a.services.Deploy(a.ctx, slug, creds)
if err != nil {
a.emitError("deploy", err)
return store.Deployment{}, err
}
wailsruntime.EventsEmit(a.ctx, "deployment:changed", deployment)
// Collect this service's balance right away so the dashboard shows a figure
// shortly after deploy instead of waiting for the next scheduled tick. Only
// services with a native collector are worth kicking; the rest would merely
// persist a "not ported yet" error row.
if a.collectors != nil && a.collectors.Supports(slug) {
go a.collectOne(a.ctx, slug)
}
return deployment, nil
}
func (a *App) StopService(slug string) error {
if err := a.ready(); err != nil {
return err
}
if err := a.services.Stop(a.ctx, slug); err != nil {
a.emitError("stop", err)
return err
}
wailsruntime.EventsEmit(a.ctx, "deployment:changed", slug)
return nil
}
func (a *App) StartService(slug string) error {
if err := a.ready(); err != nil {
return err
}
if err := a.services.Start(a.ctx, slug); err != nil {
a.emitError("start", err)
return err
}
wailsruntime.EventsEmit(a.ctx, "deployment:changed", slug)
return nil
}
func (a *App) RestartService(slug string) error {
if err := a.ready(); err != nil {
return err
}
if err := a.services.Restart(a.ctx, slug); err != nil {
a.emitError("restart", err)
return err
}
wailsruntime.EventsEmit(a.ctx, "deployment:changed", slug)
return nil
}
func (a *App) RemoveService(slug string) error {
if err := a.ready(); err != nil {
return err
}
if err := a.services.Remove(a.ctx, slug); err != nil {
a.emitError("remove", err)
return err
}
wailsruntime.EventsEmit(a.ctx, "deployment:changed", slug)
return nil
}
func (a *App) GetLogs(slug string, lines int) (string, error) {
if err := a.ready(); err != nil {
return "", err
}
return a.services.Logs(a.ctx, slug, lines)
}
func (a *App) RefreshDeployments() ([]store.Deployment, error) {
if err := a.ready(); err != nil {
return nil, err
}
return a.services.Refresh(a.ctx)
}
func (a *App) CollectService(slug string) (store.EarningsRecord, error) {
if err := a.ready(); err != nil {
return store.EarningsRecord{}, err
}
creds, err := a.store.GetCredentials(slug)
if err != nil {
return store.EarningsRecord{}, err
}
record, err := a.collectors.Collect(a.ctx, slug, creds)
if err != nil {
a.emitError("collector", err)
return store.EarningsRecord{}, err
}