tripshare

package
v0.41.22 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package tripshare builds and stores public read-only trip links: a frozen, sanitized copy of a saved trip's plan behind an unguessable token. The design is _shared/share-trip-design.md (approved by DA, conditions S1-S9).

Index

Constants

View Source
const (

	// MinCutM and MaxCutM bound the random cut radius drawn per link.
	MinCutM = 3000.0
	MaxCutM = 6000.0
)
View Source
const (
	// MaxActivePerUser caps the live links an account keeps.
	MaxActivePerUser = 25
	// MaxCreatesPerHour caps how many links an account makes in an hour, counted from the table so every replica agrees.
	MaxCreatesPerHour = 20
	// KeepEndedFor is how long an expired or revoked row stays before the cleanup removes it.
	KeepEndedFor = 30 * 24 * time.Hour
)

Variables

View Source
var (
	// ErrUnsupported is a saved plan that is not a single-day plan with a road line (multi-day, no line).
	ErrUnsupported = errors.New("tripshare: plan cannot be shared")
	// ErrTooShort is a trip with too little route outside the private areas.
	ErrTooShort = errors.New("tripshare: trip too short to share")
)
View Source
var (
	ErrNotFound = errors.New("tripshare: not found")
	ErrCap      = errors.New("tripshare: too many active links")
	ErrRate     = errors.New("tripshare: too many links created")
)
View Source
var MetricEvents = []string{"created", "revoked", "viewed", "miss", "rate_limited", "busy", "refused"}

MetricEvents are the values of rivolt_trip_share_total{event}.

Functions

func Collapse

func Collapse(segs []Segment, m float64) (float64, bool)

Collapse maps a distance along the original line to the shared axis, or false when it falls in a cut.

func DistM

func DistM(aLat, aLon, bLat, bLon float64) float64

DistM is the great-circle distance in metres.

func EffectiveCut

func EffectiveCut(cutM float64, home *Circle) float64

EffectiveCut is the radius used: the drawn one, or the home radius plus homeExtraM when that is larger.

func HashToken

func HashToken(token string) []byte

HashToken is the SHA-256 of the token string, what trip_shares.token_hash holds.

func NearestKept

func NearestKept(segs []Segment, lat, lon, maxM float64) (float64, bool)

NearestKept is the distance along the shared axis of the kept point nearest to (lat, lon), and false when none is within maxM.

func NewToken

func NewToken() (token string, hash []byte, err error)

NewToken returns a fresh token and the hash that is stored in its place. The token is shown to the owner once.

func RandomCut

func RandomCut(r float64) float64

RandomCut draws a cut radius in [MinCutM, MaxCutM] from r, a uniform float in [0,1).

func ValidToken

func ValidToken(s string) bool

ValidToken reports whether s has the shape of a token (so a malformed body is a 400 and never reaches the database).

Types

type Area

type Area struct {
	Label string  `json:"label"`
	Lat   float64 `json:"lat"`
	Lon   float64 `json:"lon"`
}

Area is a place shown only as a region: coordinates rounded to areaStepDeg.

type Circle

type Circle struct {
	Lat, Lon, RadiusM float64
}

Circle is a private place: the start, the destination, a via, an overnight, the saved home.

type ElevOut

type ElevOut struct {
	Points      [][2]int `json:"points"`
	WaypointAtM []*int   `json:"waypoint_at_m"`
}

type Input

type Input struct {
	Title     string
	Plan      json.RawMessage
	DepartAt  string
	PlannedAt time.Time
	// Home is the saved home place, when one is set (RadiusM is its radius).
	Home *Circle
	// CutM is the per-link random radius from RandomCut.
	CutM float64
}

Input is everything Build needs; Plan is the saved plan JSON as stored.

type Link struct {
	ID          uuid.UUID  `json:"id"`
	SavedTripID uuid.UUID  `json:"saved_trip_id"`
	Title       string     `json:"title"`
	CreatedAt   time.Time  `json:"created_at"`
	ExpiresAt   *time.Time `json:"expires_at"`
	RevokedAt   *time.Time `json:"revoked_at"`
}

Link is an owner's view of one link: never the token (shown once at creation) and never the snapshot.

type RouteOut

type RouteOut struct {
	Segments []string `json:"segments"`
}

type Segment

type Segment struct {
	Points [][2]float64 // lat, lon
	// FromM and ToM are where the run starts and ends along the original line.
	FromM, ToM float64
	// CollapsedFromM is where the run starts on the shared axis, which closes the gaps (so the gap lengths, which would give the cut radius
	// away, are not on the wire).
	CollapsedFromM float64
}

Segment is a run of the line outside every circle.

func Cut

func Cut(line [][2]float64, cs []Circle) ([]Segment, float64)

Cut returns the runs of the line that lie outside every circle, in order. Runs of fewer than two points are dropped. The total length of the original line is returned too.

func (Segment) Encode

func (s Segment) Encode() string

Encode is the segment as a polyline6 string.

type Snapshot

type Snapshot struct {
	Version   int       `json:"version"`
	Title     string    `json:"title"`
	PlannedAt time.Time `json:"planned_at"`
	DepartAt  string    `json:"depart_at,omitempty"`
	TZ        string    `json:"tz,omitempty"`
	StartSoC  float64   `json:"start_soc"`
	Totals    Totals    `json:"totals"`
	Start     Area      `json:"start"`
	End       Area      `json:"end"`
	Stops     []Stop    `json:"stops"`
	Route     RouteOut  `json:"route"`
	Elevation *ElevOut  `json:"elevation_profile,omitempty"`
}

Snapshot is what a shared link serves: built field by field from the saved plan (an allowlist, never the stored JSON passed through), so a field added to the plan later is not shared by accident. The wire contract is in _shared/share-trip-design.md.

func Build

func Build(in Input) (*Snapshot, error)

Build makes the snapshot, or ErrUnsupported / ErrTooShort.

type Stop

type Stop struct {
	Kind      string  `json:"kind"` // "charger" or "stop"
	Name      string  `json:"name,omitempty"`
	Lat       float64 `json:"lat"`
	Lon       float64 `json:"lon"`
	AtM       *int    `json:"at_m"`
	ArriveAt  string  `json:"arrive_at,omitempty"`
	DepartAt  string  `json:"depart_at,omitempty"`
	ArriveSoC float64 `json:"arrive_soc"`
	DepartSoC float64 `json:"depart_soc"`
	ChargeS   int     `json:"charge_s,omitempty"`
	MaxKW     float64 `json:"max_kw,omitempty"`
}

type Store

type Store struct {
	Req, Sys *sql.DB
}

Store reads and writes trip_shares. Req is the request pool (tenant row-level security applies: the account's own rows only), Sys the system pool, used for the public lookup, which has no account, and for the cleanup.

func (*Store) Create

func (s *Store) Create(ctx context.Context, uid, savedTripID uuid.UUID, title string, hash []byte, cutM float64, snapshot []byte, expiresAt *time.Time) (Link, error)

Create stores a link for uid and returns it, or ErrCap / ErrRate. The two limits are counted in the same transaction as the insert under a per-account advisory lock, so concurrent creates cannot both slip past a limit.

func (*Store) List

func (s *Store) List(ctx context.Context, uid, savedTripID uuid.UUID) ([]Link, error)

List is uid's links for one saved trip, newest first (ended ones included, so the owner sees what was revoked).

func (*Store) Lookup

func (s *Store) Lookup(ctx context.Context, hash []byte) ([]byte, error)

Lookup is the public read: the snapshot of a live link by its token hash, or ErrNotFound for unknown, expired and revoked alike. It calls the SECURITY DEFINER function on the system pool (the request role cannot execute it).

func (*Store) Revoke

func (s *Store) Revoke(ctx context.Context, uid, id uuid.UUID) error

Revoke ends a link; repeating it is a no-op. ErrNotFound for a link that is not uid's.

func (*Store) Sweep

func (s *Store) Sweep(ctx context.Context) (int64, error)

Sweep deletes rows that ended (expired or revoked) more than KeepEndedFor ago. System pool; idempotent, so every replica may run it.

type Totals

type Totals struct {
	DistanceM  int     `json:"distance_m"`
	DriveS     int     `json:"drive_s"`
	ChargeS    int     `json:"charge_s"`
	ArrivalSoC float64 `json:"arrival_soc"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL