Cars: create a car from a manufacturer service, with a per-car data tab

A car can now be imported straight from the account its owner already has
with the manufacturer, and every reading that service exposes shows up on
the car's own tab. MyToyota is the first provider.

API Server — internal/api/vehicleproviders.go adds a generic layer over a
plugin that can enumerate vehicles and read data about them. Adding the
next manufacturer is one vehicleSource adapter plus a line in
vehicleSources(): no new endpoints, no Web App changes.

  GET  /api/vehicle-providers                     providers + connect state
  GET  /api/vehicle-providers/{p}/vehicles        the caller's vehicles
  POST /api/vehicle-providers/{p}/import          create a car from one
  GET  /api/cars/{id}/provider                    live snapshot for the tab
  POST /api/cars/{id}/provider                    link / unlink a car
  POST /api/cars/{id}/provider/sync               re-apply provider data

Two properties shape it. Credentials are always the caller's own, resolved
through the same global -> org -> user cascade as the integration settings,
so a shared car shows provider data only when that vehicle is on the
viewer's account — the owner's credentials are never borrowed. And upstream
shapes are not modelled: these are unofficial APIs, so the layer searches
payloads by key name for the readings worth promoting (odometer, fuel,
battery, range) and flattens the rest to dotted key/value pairs alongside
the raw JSON. A renamed field costs one blank value, not a broken page.

The Toyota gate and its wording now live in toyotaSource, so the older
/api/integrations/toyota/vehicles endpoint and the new ones cannot drift.

Manager.InvokeBatchWith shares one transient plugin instance across a batch
of actions. The tab pulls seven capabilities, and InvokeWith builds a fresh
instance per call — which for a connector that authenticates lazily means a
fresh OAuth login per call. Batching logs in once.

cars gains provider + provider_vehicle_id (schema.go and
setup-pocketbase.mjs both). carPayload deliberately omits them, so an
ordinary car edit can neither reassign the car nor break its link;
carProviderPayload writes the link on its own.

Web App — Dashboard grows an "import from service" button beside "add car",
shown only once an account is connected, opening CarImportModal: pick the
vehicle, choose what to pull (identity / fuel type / dates / odometer, all
on by default), import. ProviderPanel becomes the car's first tab, ahead of
Information, labelled with the service: headline readings, the vehicle
record, one card per capability with its raw response, and an offer to take
the provider's odometer when it is ahead of the stored one. On an unlinked
car the tab instead offers to link it, VIN-matched. Info stays the default
selection — landing on the provider tab would fire a login on every car
page view. Full en/pl/da translations.

Tests cover the payload walking, Toyota normalization, import-selection
defaults, and — through the real handler chain against a stand-in
PocketBase — that every route is registered and that a closed gate is soft
on a listing (200 + a reason the UI can show) but hard on a write (4xx, so
a caller cannot read the reply as a created car).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
tajniak81
2026-08-17 14:13:11 +02:00
co-authored by Claude Opus 5
parent 47a9aef466
commit 358ee68f94
23 changed files with 2983 additions and 43 deletions
+15 -8
View File
@@ -36,9 +36,11 @@ type Plugin interface {
plugin is enabled or its config changes. Prepare clients/tokens here.
- **`HealthCheck`** — probe the upstream and classify: `Health{Status, LatencyMs, Detail}`
where `Status` is `StatusOK` / `StatusDegraded` / `StatusDown`.
- **`Invoke`** — run a named capability. **Part of the contract for the future;
no HTTP endpoint exposes it in v1.** Implement it anyway so the connector is
ready.
- **`Invoke`** — run a named capability. There is no *generic* invoke endpoint yet,
but this is live: the integration routes and the vehicle-provider layer call it
through `Manager.InvokeWith` / `InvokeBatchWith`, so implement it properly. It
must be safe for concurrent use — the live instance is shared across requests,
and `InvokeBatchWith` runs a batch of actions in parallel on one instance.
- **`Shutdown`** — release resources.
### Descriptor & config fields
@@ -139,7 +141,8 @@ func (p *Plugin) HealthCheck(ctx context.Context) plugins.Health {
}
func (p *Plugin) Invoke(ctx context.Context, action string, params json.RawMessage) (json.RawMessage, error) {
// Implement your capabilities; return normalized JSON. (Not yet called in v1.)
// Implement your capabilities; return normalized JSON. Must be safe for
// concurrent use — one instance serves many requests.
return json.RawMessage(`{"ok":true}`), nil
}
@@ -300,8 +303,10 @@ if h := p.HealthCheck(context.Background()); h.Status == "" {
The contract is shaped for these; see [`doc.go`](doc.go):
- **Invocation API** — an endpoint to call `Invoke` from clients, with a normalized
request/response envelope and a provider→internal mapper.
- **Generic invocation API** — an endpoint to call *any* plugin's `Invoke` from a
client, with a normalized request/response envelope. The purpose-built callers
exist (`Manager.InvokeWith` / `InvokeBatchWith`, driven by the integration routes
and `internal/api/vehicleproviders.go`); what is missing is the generic route.
- **Resilience** — retry/backoff, circuit breaker, per-plugin latency/error metrics.
- **Per-tenant credentials _for arbitrary plugins_** — the two built-in connectors
already have them, through the hand-written `/api/integrations/toyota` and
@@ -312,5 +317,7 @@ The contract is shaped for these; see [`doc.go`](doc.go):
- **Audit logging** of plugin access. (Charger *control* commands are already
audited to the `control_audit` collection; this is the wider plugin case.)
Until the invocation API lands, `Invoke` is dormant — plugins are discoverable,
configurable, and health-checked, but not yet callable over HTTP.
Until the generic invocation API lands, `Invoke` is reachable only through the
purpose-built routes: the two integrations' own endpoints, and the vehicle-provider
layer that builds a car from a manufacturer account and feeds the car's provider
tab (see `internal/api/vehicleproviders.go`).
+57
View File
@@ -357,6 +357,63 @@ func (m *Manager) InvokeWith(ctx context.Context, name string, cfg map[string]st
return p.Invoke(ctx, action, payload)
}
// BatchCall is one capability invocation inside an InvokeBatchWith request.
type BatchCall struct {
ID string // caller-chosen id, echoed back on the result
Action string // capability id
Params json.RawMessage // action params; may be nil
}
// BatchResult is the outcome of one BatchCall. Exactly one of Result/Err is set.
type BatchResult struct {
ID string
Result json.RawMessage
Err error
}
// batchConcurrency caps how many calls of one batch are in flight at once, so a
// snapshot of a whole vehicle doesn't arrive at the upstream as a burst.
const batchConcurrency = 4
// InvokeBatchWith runs several capabilities against one caller-resolved config,
// sharing a single transient instance. A connector that authenticates lazily
// (Toyota's OAuth login on first request) would otherwise repeat that login for
// every action, because InvokeWith builds and tears down an instance per call;
// sharing the instance logs in once for the whole batch.
//
// Calls run concurrently, so a plugin's Invoke must be safe for concurrent use —
// which the contract already implies, since the live instance is shared by every
// HTTP request. Results come back in request order, each carrying its own error;
// a non-nil error return means the batch never started (unknown plugin).
func (m *Manager) InvokeBatchWith(ctx context.Context, name string, cfg map[string]string, calls []BatchCall) ([]BatchResult, error) {
m.mu.Lock()
rec := m.records[name]
p := construct(name, m.factories[name], rec)
m.mu.Unlock()
if p == nil {
return nil, errUnknown
}
_ = p.Init(ctx, cfg)
defer func() { _ = p.Shutdown(context.Background()) }()
out := make([]BatchResult, len(calls))
sem := make(chan struct{}, batchConcurrency)
var wg sync.WaitGroup
for i, c := range calls {
wg.Add(1)
go func(i int, c BatchCall) {
defer wg.Done()
sem <- struct{}{}
defer func() { <-sem }()
res, err := p.Invoke(ctx, c.Action, c.Params)
out[i] = BatchResult{ID: c.ID, Result: res, Err: err}
}(i, c)
}
wg.Wait()
return out, nil
}
// RawConfig returns a copy of a plugin's stored (global) config and its enabled
// flag. ok is false for an unknown plugin. This is the top layer (L1) of the
// per-user cascade: the config a superadmin set in the panel, which lower layers