Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- **A new ProxyRack device stayed off the account.** ProxyRack only knows a new UUID about five minutes after its client first connects, and the deploy made its one attempt to add it before that, so the device earned for nobody. A "try again later" answer is now stored and retried, 6 minutes after the deploy and then twice as long each time up to 4 hours; a restart keeps it. After a day the app stops and tells you to add the device by hand. The deploy output says it is still being tried.
- **A copy of ProxyRack reported as the same device as the original.** Only device names built from the hostname got a suffix, so a proxied copy or a second copy on the box reused the original's device UUID and two IPs fought over one ProxyRack device. Ids the catalog marks `per_device` now get a value of their own for each copy, derived the same way as in the web app (same length and case, stable across redeploys); a copy whose id cannot be derived, such as EarnApp's, is refused instead of cloning it.
- **UpRock said you could cash out at $5.** Its minimum is 250 UPT. The catalog now says so, and UPT gets a price from CoinGecko, so the app can compare an UpRock balance with that minimum. USDT and USDC get prices too, so a cash-out recorded in either counts toward the totals.
- **A copy the cap reset could not start stayed stopped for a whole period.** It kept its "stopped by the cap" mark, and nothing tried again until the next reset or a Start by hand. The once-a-minute pass now starts such a copy while the proxy is uncapped, and leaves alone copies you stopped yourself.
Expand Down
49 changes: 41 additions & 8 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ import (
"encoding/base64"
"errors"
"fmt"
"log"
"net"
neturl "net/url"
"os"
"path/filepath"
stdruntime "runtime"
"slices"
"sort"
"strconv"
"strings"
Expand Down Expand Up @@ -101,6 +103,8 @@ type App struct {
usageStop func()
// proxyStop stops the proxied-copies pass (app_proxies.go) and waits for it.
proxyStop func()
// deviceLinkStop stops the device-registration retry pass (app_device_links.go).
deviceLinkStop func()
// activity is the Activity sampler (activity_sampler.go): off until the owner switches it on.
activity activityState
}
Expand All @@ -127,7 +131,7 @@ type collectorRegistry interface {
// collectorRegistry need not implement it.
type deviceRegistry interface {
Unlinked(slug string) []string
RegisterDevice(ctx context.Context, slug string, credentials map[string]string) bool
RegisterDevice(ctx context.Context, slug string, credentials map[string]string) collectors.Registration
}

func NewApp() *App {
Expand Down Expand Up @@ -254,6 +258,8 @@ func (a *App) startCore(ctx context.Context) error {
a.startUsageSampler(ctx)
// Proxied copies: traffic per proxy, the cap, and earners whose tunnel came back.
a.startProxyTicker(ctx)
// Device registrations the provider asked to retry later.
a.startDeviceLinkRetry(ctx)
// What each earner talks to, when the owner switched Activity on.
a.startActivitySampler(ctx)
// Optional, and a no-op unless the user paired this Desktop with a
Expand Down Expand Up @@ -296,6 +302,7 @@ func (a *App) Shutdown(_ context.Context) {
a.stopScheduler()
a.stopUsageSampler()
a.stopProxyTicker()
a.stopDeviceLinkRetry()
a.stopActivitySampler()
a.stopUpstream()
if a.fleetAPI != nil {
Expand Down Expand Up @@ -356,6 +363,9 @@ type AppState struct {
// AddedDevices is, per slug, the device id the last deploy added to the user's
// account itself (ProxyRack with its API key saved), so no manual step is needed.
AddedDevices map[string]string `json:"addedDevices"`
// RetryingDevices is, per slug, the device id the provider did not know yet at
// deploy time and the app keeps trying to add to the account for a day.
RetryingDevices map[string]string `json:"retryingDevices"`
// StateBackups lists the deployed services whose catalog entry marks state as
// irreplaceable, and whether the user has a backup of it.
StateBackups []statebackup.Row `json:"stateBackups"`
Expand Down Expand Up @@ -550,6 +560,7 @@ func (a *App) GetAppState() (AppState, error) {
Scaling: a.services.ScalingLimits(visible),
Copies: a.services.Copies(),
AddedDevices: a.addedDeviceIDs(),
RetryingDevices: a.retryingDeviceIDs(),
StateBackups: a.stateBackups(deployments),
Drift: a.containerDrift(),
Isolation: a.isolationStatus(),
Expand Down Expand Up @@ -670,26 +681,44 @@ func (a *App) addedDeviceIDs() map[string]string {
// registerDevice adds a just-deployed device to the user's account where the
// provider's API can (ProxyRack, with its API key among the credentials). It never
// fails the deploy, which has already happened: anything short of "on the account"
// leaves the manual step in the deploy output.
// leaves the manual step in the deploy output, except a device the provider does
// not know yet, which is stored and retried (app_device_links.go).
func (a *App) registerDevice(slug string, creds map[string]string) {
devicesReg, ok := a.collectors.(deviceRegistry)
svc, inCatalog := a.catalog.Get(slug)
if !ok || !inCatalog || svc.DeviceLink == nil {
return
}
id := strings.TrimSpace(creds[svc.DeviceLink.IDEnv])
a.dropOtherDeviceLinks(slug, id)
ctx, cancel := context.WithTimeout(a.ctx, 20*time.Second)
defer cancel()
added := devicesReg.RegisterDevice(ctx, slug, creds)
a.addedMu.Lock()
defer a.addedMu.Unlock()
if !added {
result := devicesReg.RegisterDevice(ctx, slug, creds)
if result == collectors.RegisterPending && a.store != nil {
now := time.Now()
if err := a.store.SavePendingDeviceLink(slug, id, now, now.Add(deviceLinkFirstRetry)); err != nil {
log.Printf("device links: store %s: %v", slug, err)
}
}
if result == collectors.RegisterAdded && a.store != nil {
_ = a.store.DeletePendingDeviceLink(slug, id)
}
if result != collectors.RegisterAdded {
a.addedMu.Lock()
delete(a.addedDevices, slug)
a.addedMu.Unlock()
return
}
a.setAddedDevice(slug, id)
}

func (a *App) setAddedDevice(slug, id string) {
a.addedMu.Lock()
defer a.addedMu.Unlock()
if a.addedDevices == nil {
a.addedDevices = map[string]string{}
}
a.addedDevices[slug] = strings.TrimSpace(creds[svc.DeviceLink.IDEnv])
a.addedDevices[slug] = id
}

// GetEarningsSummary returns the converted, aggregated earnings summary on its
Expand Down Expand Up @@ -1865,6 +1894,7 @@ func (a *App) notifications(status runtime.Status, earnings []store.EarningsReco
}
}
items = append(items, a.unlinkedDeviceNotifications(deployments)...)
items = append(items, a.deviceLinkGaveUpNotifications()...)
Comment thread
GeiserX marked this conversation as resolved.
Resolved
items = append(items, a.proxyNotifications()...)
items = append(items, a.activityNotifications()...)
if len(deployments) == 0 {
Expand All @@ -1881,9 +1911,12 @@ func (a *App) unlinkedDeviceNotifications(deployments []store.Deployment) []Noti
if !ok || a.catalog == nil {
return nil
}
// A device with a stored registration is being retried, or has its own
// give-up notice (app_device_links.go).
pending := a.pendingDeviceLinkIDs()
var items []Notification
for _, dep := range deployments {
ids := devicesReg.Unlinked(dep.Slug)
ids := slices.DeleteFunc(devicesReg.Unlinked(dep.Slug), func(id string) bool { return pending[dep.Slug][id] })
svc, inCatalog := a.catalog.Get(dep.Slug)
if len(ids) == 0 || !inCatalog || svc.DeviceLink == nil {
continue
Expand Down
232 changes: 232 additions & 0 deletions app_device_links.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
package main

import (
"context"
"log"
neturl "net/url"
"slices"
"strings"
"time"

"github.com/GeiserX/CashPilot-Desktop/internal/collectors"
)

// A registration the provider asked to retry is tried again this long after the
// first refusal, then twice as long each time up to the cap; after the give-up the
// user is told to add the device by hand. The same numbers as the web app.
const (
deviceLinkFirstRetry = 6 * time.Minute
deviceLinkMaxRetry = 4 * time.Hour
deviceLinkGiveUp = 24 * time.Hour
// deviceLinkTick is how often the retry pass looks for a registration that is due.
deviceLinkTick = 3 * time.Minute
)

// deployedDevice says whether slug is deployed here with a device link, and the
// device id its saved credentials hold. An error means the store could not be read,
// which proves nothing either way.
func (a *App) deployedDevice(slug string) (id string, deployed bool, err error) {
if a.store == nil || a.catalog == nil {
return "", false, nil
}
svc, ok := a.catalog.Get(slug)
if !ok || svc.DeviceLink == nil {
return "", false, nil
}
if _, deployed, err = a.store.GetDeployment(slug); err != nil || !deployed {
return "", false, err
}
creds, err := a.store.GetCredentials(slug)
if err != nil {
return "", false, err
}
return strings.TrimSpace(creds[svc.DeviceLink.IDEnv]), true, nil
}

// runsDevice is whether slug is deployed here with deviceID; false when unsure.
func (a *App) runsDevice(slug, deviceID string) bool {
id, deployed, err := a.deployedDevice(slug)
return err == nil && deployed && id == deviceID
}

// dropOtherDeviceLinks forgets slug's pending registrations of any device but id:
// a deploy replaced that device.
func (a *App) dropOtherDeviceLinks(slug, id string) {
if a.store == nil {
return
}
rows, err := a.store.ListPendingDeviceLinks()
if err != nil {
return
}
for _, row := range rows {
if row.Slug == slug && row.DeviceID != id {
_ = a.store.DeletePendingDeviceLink(row.Slug, row.DeviceID)
}
}
}

// pendingDeviceLinkIDs is, per slug, every device id with a stored registration,
// retrying or given up.
func (a *App) pendingDeviceLinkIDs() map[string]map[string]bool {
out := map[string]map[string]bool{}
if a.store == nil {
return out
}
rows, err := a.store.ListPendingDeviceLinks()
if err != nil {
return out
}
for _, row := range rows {
if out[row.Slug] == nil {
out[row.Slug] = map[string]bool{}
}
out[row.Slug][row.DeviceID] = true
}
return out
}

// retryDeviceLinks retries the registrations a provider asked to try again later,
// with backoff, and gives up after a day. A service no longer deployed here is
// forgotten without asking the provider. A row whose id the saved credentials no
// longer hold is left alone: credentials saved without a redeploy leave the old
// device running, and a deploy drops the row itself (dropOtherDeviceLinks).
func (a *App) retryDeviceLinks(ctx context.Context, now time.Time) {
devicesReg, ok := a.collectors.(deviceRegistry)
if !ok || a.store == nil {
return
}
rows, err := a.store.ListPendingDeviceLinks()
if err != nil {
log.Printf("device links: list: %v", err)
return
}
for _, row := range rows {
if ctx.Err() != nil {
return
}
id, deployed, err := a.deployedDevice(row.Slug)
if err != nil {
continue
}
if !deployed {
_ = a.store.DeletePendingDeviceLink(row.Slug, row.DeviceID)
continue
}
if id != row.DeviceID || row.GaveUp || row.NextAt.After(now) {
continue
}
creds, err := a.store.GetCredentials(row.Slug)
if err != nil {
continue
}
callCtx, cancel := context.WithTimeout(ctx, 20*time.Second)
result := devicesReg.RegisterDevice(callCtx, row.Slug, creds)
cancel()
if result == collectors.RegisterAdded {
_ = a.store.DeletePendingDeviceLink(row.Slug, row.DeviceID)
a.store.RecordEvent(row.Slug, "device_linked", row.DeviceID+" added to the account")
// A redeploy during the call may have put another device in its place.
if a.runsDevice(row.Slug, row.DeviceID) {
a.setAddedDevice(row.Slug, row.DeviceID)
}
continue
Comment thread
GeiserX marked this conversation as resolved.
Resolved
}
attempts := row.Attempts + 1
if now.Sub(row.FirstAt) >= deviceLinkGiveUp {
_ = a.store.UpdatePendingDeviceLink(row.Slug, row.DeviceID, attempts, row.NextAt, true)
continue
Comment thread
GeiserX marked this conversation as resolved.
Resolved
}
wait := deviceLinkMaxRetry
if attempts < 16 { // past that the doubling is far over the cap anyway
wait = min(deviceLinkFirstRetry<<attempts, deviceLinkMaxRetry)
}
_ = a.store.UpdatePendingDeviceLink(row.Slug, row.DeviceID, attempts, now.Add(wait), false)
}
}

// startDeviceLinkRetry runs retryDeviceLinks every few minutes until ctx ends.
func (a *App) startDeviceLinkRetry(ctx context.Context) {
if ctx == nil || a.store == nil {
return
}
loopCtx, cancel := context.WithCancel(ctx)
done := make(chan struct{})
a.deviceLinkStop = func() {
cancel()
<-done
}
go func() {
defer close(done)
ticker := time.NewTicker(deviceLinkTick)
defer ticker.Stop()
for {
a.retryDeviceLinks(loopCtx, time.Now())
select {
case <-loopCtx.Done():
return
case <-ticker.C:
}
}
}()
}

// stopDeviceLinkRetry stops the loop and waits for it, so Shutdown never closes the
// store under a retry being written.
func (a *App) stopDeviceLinkRetry() {
if a.deviceLinkStop != nil {
a.deviceLinkStop()
a.deviceLinkStop = nil
}
}

// retryingDeviceIDs is, per slug, the device id the app is still trying to add to
// the account, so the deploy output can say so instead of the manual step.
func (a *App) retryingDeviceIDs() map[string]string {
out := map[string]string{}
if a.store == nil {
return out
}
rows, err := a.store.ListPendingDeviceLinks()
if err != nil {
return out
}
for _, row := range rows {
if !row.GaveUp && a.runsDevice(row.Slug, row.DeviceID) {
out[row.Slug] = row.DeviceID
}
Comment thread
GeiserX marked this conversation as resolved.
Resolved
}
return out
}

// deviceLinkGaveUpNotifications tells the user about every device the provider
// never accepted after a day of retries, that still runs here, and that the
// provider's last check still says is not on the account: a device the user then
// adds by hand stops being reported at the next check. Read from the store, so a
// restart cannot drop one.
func (a *App) deviceLinkGaveUpNotifications() []Notification {
devicesReg, ok := a.collectors.(deviceRegistry)
if !ok || a.store == nil || a.catalog == nil {
return nil
}
rows, err := a.store.ListPendingDeviceLinks()
if err != nil {
return nil
}
var items []Notification
for _, row := range rows {
svc, ok := a.catalog.Get(row.Slug)
if !row.GaveUp || !ok || svc.DeviceLink == nil || !a.runsDevice(row.Slug, row.DeviceID) ||
!slices.Contains(devicesReg.Unlinked(row.Slug), row.DeviceID) {
continue
}
url := strings.ReplaceAll(svc.DeviceLink.URL, "${"+svc.DeviceLink.IDEnv+"}", neturl.PathEscape(row.DeviceID))
items = append(items, Notification{
Level: "warning",
Title: svc.Name + " device not on your account",
Message: strings.TrimSpace(svc.Name + " never accepted the device " + row.DeviceID +
" after a day of retries, so it earns for nobody. " + strings.TrimSpace(svc.DeviceLink.Steps) + " " + url),
})
Comment thread
GeiserX marked this conversation as resolved.
Resolved
}
return items
}
Loading
Loading